create-prisma-php-app 1.22.506 → 1.22.507

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.js CHANGED
@@ -10,420 +10,415 @@ const __filename = fileURLToPath(import.meta.url);
10
10
  const __dirname = path.dirname(__filename);
11
11
  let updateAnswer = null;
12
12
  const nonBackendFiles = [
13
- "favicon.ico",
14
- "\\src\\app\\index.php",
15
- "metadata.php",
16
- "not-found.php",
13
+ "favicon.ico",
14
+ "\\src\\app\\index.php",
15
+ "metadata.php",
16
+ "not-found.php",
17
17
  ];
18
18
  const dockerFiles = [
19
- ".dockerignore",
20
- "docker-compose.yml",
21
- "Dockerfile",
22
- "apache.conf",
19
+ ".dockerignore",
20
+ "docker-compose.yml",
21
+ "Dockerfile",
22
+ "apache.conf",
23
23
  ];
24
24
  function bsConfigUrls(projectRootPath) {
25
- // Identify the base path dynamically up to and including 'htdocs'
26
- const htdocsIndex = projectRootPath.indexOf("\\htdocs\\");
27
- if (htdocsIndex === -1) {
28
- console.error("Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\");
29
- return {
30
- bsTarget: "",
31
- bsPathRewrite: {},
32
- };
33
- }
34
- // Extract the path up to and including 'htdocs\\'
35
- const basePathToRemove = projectRootPath.substring(0, htdocsIndex + "\\htdocs\\".length);
36
- // Escape backslashes for the regex pattern
37
- const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
38
- // Remove the base path and replace backslashes with forward slashes for URL compatibility
39
- const relativeWebPath = projectRootPath
40
- .replace(new RegExp(`^${escapedBasePathToRemove}`), "")
41
- .replace(/\\/g, "/");
42
- // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
43
- let proxyUrl = `http://localhost/${relativeWebPath}`;
44
- // Ensure the proxy URL does not end with a slash before appending '/public'
45
- proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
46
- // Clean the URL by replacing "//" with "/" but not affecting "http://"
47
- // We replace instances of "//" that are not preceded by ":"
48
- const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
49
- const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
50
- // Correct the relativeWebPath to ensure it does not start with a "/"
51
- const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
52
- ? cleanRelativeWebPath.substring(1)
53
- : cleanRelativeWebPath;
25
+ // Identify the base path dynamically up to and including 'htdocs'
26
+ const htdocsIndex = projectRootPath.indexOf("\\htdocs\\");
27
+ if (htdocsIndex === -1) {
28
+ console.error(
29
+ "Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\"
30
+ );
54
31
  return {
55
- bsTarget: `${cleanUrl}/`,
56
- bsPathRewrite: {
57
- "^/": `/${adjustedRelativeWebPath}/`,
58
- },
32
+ bsTarget: "",
33
+ bsPathRewrite: {},
59
34
  };
60
- }
61
- function configureBrowserSyncCommand(baseDir) {
62
- // TypeScript content to write
63
- const bsConfigTsContent = `const { createProxyMiddleware } = require("http-proxy-middleware");
64
- const fs = require("fs");
65
- const chokidar = require("chokidar");
66
- const { execSync } = require("child_process");
67
-
68
- const jsonData = fs.readFileSync("prisma-php.json", "utf8");
69
- const config = JSON.parse(jsonData);
70
-
71
- // Watch for file changes (create, delete, save)
72
- const watcher = chokidar.watch("src/**/*", {
73
- ignored: /(^|[\\/\\\\])\\\../,
74
- persistent: true,
75
- usePolling: true,
76
- interval: 1000,
77
- });
78
-
79
- watcher
80
- .on("add", async (path) => {
81
- execSync("node settings/files-list-config.js");
82
- })
83
- .on("change", async (path) => {
84
- execSync("node settings/files-list-config.js");
85
- })
86
- .on("unlink", async (path) => {
87
- execSync("node settings/files-list-config.js");
88
- });
89
-
90
- module.exports = {
91
- proxy: "http://localhost:3000",
92
- middleware: [
93
- (req, res, next) => {
94
- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
95
- res.setHeader("Pragma", "no-cache");
96
- res.setHeader("Expires", "0");
97
- next();
35
+ }
36
+ // Extract the path up to and including 'htdocs\\'
37
+ const basePathToRemove = projectRootPath.substring(
38
+ 0,
39
+ htdocsIndex + "\\htdocs\\".length
40
+ );
41
+ // Escape backslashes for the regex pattern
42
+ const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
43
+ // Remove the base path and replace backslashes with forward slashes for URL compatibility
44
+ const relativeWebPath = projectRootPath
45
+ .replace(new RegExp(`^${escapedBasePathToRemove}`), "")
46
+ .replace(/\\/g, "/");
47
+ // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
48
+ let proxyUrl = `http://localhost/${relativeWebPath}`;
49
+ // Ensure the proxy URL does not end with a slash before appending '/public'
50
+ proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
51
+ // Clean the URL by replacing "//" with "/" but not affecting "http://"
52
+ // We replace instances of "//" that are not preceded by ":"
53
+ const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
54
+ const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
55
+ // Correct the relativeWebPath to ensure it does not start with a "/"
56
+ const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
57
+ ? cleanRelativeWebPath.substring(1)
58
+ : cleanRelativeWebPath;
59
+ return {
60
+ bsTarget: `${cleanUrl}/`,
61
+ bsPathRewrite: {
62
+ "^/": `/${adjustedRelativeWebPath}/`,
98
63
  },
99
- createProxyMiddleware({
100
- target: config.bsTarget,
101
- changeOrigin: true,
102
- pathRewrite: config.bsPathRewrite,
103
- }),
104
- ],
105
- files: "src/**/*.*",
106
- notify: false,
107
- open: false,
108
- ghostMode: false,
109
- codeSync: true, // Disable synchronization of code changes across clients
110
- watchOptions: {
111
- usePolling: true,
112
- interval: 1000,
113
- },
114
- };`;
115
- // Determine the path and write the bs-config.js
116
- const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
117
- fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
118
- // Return the Browser Sync command string, using the cleaned URL
119
- return `browser-sync start --config settings/bs-config.cjs`;
64
+ };
120
65
  }
121
66
  async function updatePackageJson(baseDir, answer) {
122
- const packageJsonPath = path.join(baseDir, "package.json");
123
- if (checkExcludeFiles(packageJsonPath))
124
- return;
125
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
126
- // Use the new function to configure the Browser Sync command
127
- const browserSyncCommand = configureBrowserSyncCommand(baseDir);
128
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { projectName: "node settings/project-name.cjs" });
129
- let answersToInclude = [];
130
- if (answer.tailwindcss) {
131
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { tailwind: "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch" });
132
- answersToInclude.push("tailwind");
133
- }
134
- if (answer.websocket) {
135
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { websocket: "node ./settings/restart-websocket.cjs" });
136
- answersToInclude.push("websocket");
137
- }
138
- // if (answer.prisma) {
139
- // packageJson.scripts = {
140
- // ...packageJson.scripts,
141
- // postinstall: "prisma generate",
142
- // };
143
- // }
144
- if (answer.docker) {
145
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { docker: "docker-compose up" });
146
- answersToInclude.push("docker");
147
- }
148
- if (answer.swaggerDocs) {
149
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { "create-swagger-docs": "node settings/swagger-setup.js" });
150
- answersToInclude.push("create-swagger-docs");
151
- }
152
- // Initialize with existing scripts
153
- let updatedScripts = Object.assign({}, packageJson.scripts);
154
- // Conditionally add "browser-sync" command
155
- updatedScripts.browserSync = browserSyncCommand;
156
- updatedScripts.npmRunAll =
157
- answersToInclude.length > 0
158
- ? `npm-run-all -p ${answersToInclude.join(" ")}`
159
- : 'echo "No additional scripts to run"';
160
- updatedScripts.dev = `node settings/start-dev.js`;
161
- // Finally, assign the updated scripts back to packageJson
162
- packageJson.scripts = updatedScripts;
163
- packageJson.type = "module";
164
- if (answer.prisma)
165
- packageJson.prisma = {
166
- seed: "node prisma/seed.js",
167
- };
168
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
67
+ const packageJsonPath = path.join(baseDir, "package.json");
68
+ if (checkExcludeFiles(packageJsonPath)) return;
69
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
70
+ packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), {
71
+ projectName: "node settings/project-name.js",
72
+ });
73
+ let answersToInclude = [];
74
+ if (answer.tailwindcss) {
75
+ packageJson.scripts = Object.assign(
76
+ Object.assign({}, packageJson.scripts),
77
+ {
78
+ tailwind:
79
+ "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch",
80
+ }
81
+ );
82
+ answersToInclude.push("tailwind");
83
+ }
84
+ if (answer.websocket) {
85
+ packageJson.scripts = Object.assign(
86
+ Object.assign({}, packageJson.scripts),
87
+ { websocket: "node settings/restart-websocket.js" }
88
+ );
89
+ answersToInclude.push("websocket");
90
+ }
91
+ // if (answer.prisma) {
92
+ // packageJson.scripts = {
93
+ // ...packageJson.scripts,
94
+ // postinstall: "prisma generate",
95
+ // };
96
+ // }
97
+ if (answer.docker) {
98
+ packageJson.scripts = Object.assign(
99
+ Object.assign({}, packageJson.scripts),
100
+ { docker: "docker-compose up" }
101
+ );
102
+ answersToInclude.push("docker");
103
+ }
104
+ if (answer.swaggerDocs) {
105
+ packageJson.scripts = Object.assign(
106
+ Object.assign({}, packageJson.scripts),
107
+ { "create-swagger-docs": "node settings/swagger-config.js" }
108
+ );
109
+ answersToInclude.push("create-swagger-docs");
110
+ }
111
+ // Initialize with existing scripts
112
+ let updatedScripts = Object.assign({}, packageJson.scripts);
113
+ updatedScripts.browserSync = "node settings/bs-config.js";
114
+ updatedScripts.dev = `npm-run-all -s projectName browserSync ${answersToInclude.join(
115
+ " "
116
+ )}`;
117
+ // Finally, assign the updated scripts back to packageJson
118
+ packageJson.scripts = updatedScripts;
119
+ packageJson.type = "module";
120
+ if (answer.prisma)
121
+ packageJson.prisma = {
122
+ seed: "node prisma/seed.js",
123
+ };
124
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
169
125
  }
170
126
  async function updateComposerJson(baseDir, answer) {
171
- const composerJsonPath = path.join(baseDir, "composer.json");
172
- if (checkExcludeFiles(composerJsonPath))
173
- return;
174
- let composerJson;
175
- // Check if the composer.json file exists
176
- if (fs.existsSync(composerJsonPath)) {
177
- // Read the current composer.json content
178
- const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
179
- composerJson = JSON.parse(composerJsonContent);
180
- }
181
- else {
182
- console.error("composer.json does not exist.");
183
- return;
184
- }
185
- // Conditionally add WebSocket dependency
186
- if (answer.websocket) {
187
- composerJson.require = Object.assign(Object.assign({}, composerJson.require), { "cboden/ratchet": "^0.4.4" });
188
- }
189
- if (answer.prisma) {
190
- composerJson.require = Object.assign(Object.assign({}, composerJson.require), { "ramsey/uuid": "5.x-dev", "hidehalo/nanoid-php": "1.x-dev" });
191
- }
192
- // Write the modified composer.json back to the file
193
- fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
194
- console.log("composer.json updated successfully.");
127
+ const composerJsonPath = path.join(baseDir, "composer.json");
128
+ if (checkExcludeFiles(composerJsonPath)) return;
129
+ let composerJson;
130
+ // Check if the composer.json file exists
131
+ if (fs.existsSync(composerJsonPath)) {
132
+ // Read the current composer.json content
133
+ const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
134
+ composerJson = JSON.parse(composerJsonContent);
135
+ } else {
136
+ console.error("composer.json does not exist.");
137
+ return;
138
+ }
139
+ // Conditionally add WebSocket dependency
140
+ if (answer.websocket) {
141
+ composerJson.require = Object.assign(
142
+ Object.assign({}, composerJson.require),
143
+ { "cboden/ratchet": "^0.4.4" }
144
+ );
145
+ }
146
+ if (answer.prisma) {
147
+ composerJson.require = Object.assign(
148
+ Object.assign({}, composerJson.require),
149
+ { "ramsey/uuid": "5.x-dev", "hidehalo/nanoid-php": "1.x-dev" }
150
+ );
151
+ }
152
+ // Write the modified composer.json back to the file
153
+ fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
154
+ console.log("composer.json updated successfully.");
195
155
  }
196
156
  async function updateIndexJsForWebSocket(baseDir, answer) {
197
- if (!answer.websocket) {
198
- return;
199
- }
200
- const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
201
- if (checkExcludeFiles(indexPath))
202
- return;
203
- let indexContent = fs.readFileSync(indexPath, "utf8");
204
- // WebSocket initialization code to be appended
205
- const webSocketCode = `
157
+ if (!answer.websocket) {
158
+ return;
159
+ }
160
+ const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
161
+ if (checkExcludeFiles(indexPath)) return;
162
+ let indexContent = fs.readFileSync(indexPath, "utf8");
163
+ // WebSocket initialization code to be appended
164
+ const webSocketCode = `
206
165
  // WebSocket initialization
207
166
  const ws = new WebSocket("ws://localhost:8080");
208
167
  `;
209
- // Append WebSocket code if user chose to use WebSocket
210
- indexContent += webSocketCode;
211
- fs.writeFileSync(indexPath, indexContent, "utf8");
212
- console.log("WebSocket code added to index.js successfully.");
168
+ // Append WebSocket code if user chose to use WebSocket
169
+ indexContent += webSocketCode;
170
+ fs.writeFileSync(indexPath, indexContent, "utf8");
171
+ console.log("WebSocket code added to index.js successfully.");
213
172
  }
214
173
  // This function updates the .gitignore file
215
174
  async function createUpdateGitignoreFile(baseDir, additions) {
216
- const gitignorePath = path.join(baseDir, ".gitignore");
217
- if (checkExcludeFiles(gitignorePath))
218
- return;
219
- let gitignoreContent = "";
220
- additions.forEach((addition) => {
221
- if (!gitignoreContent.includes(addition)) {
222
- gitignoreContent += `\n${addition}`;
223
- }
224
- });
225
- // Ensure there's no leading newline if the file was just created
226
- gitignoreContent = gitignoreContent.trimStart();
227
- fs.writeFileSync(gitignorePath, gitignoreContent);
175
+ const gitignorePath = path.join(baseDir, ".gitignore");
176
+ if (checkExcludeFiles(gitignorePath)) return;
177
+ let gitignoreContent = "";
178
+ additions.forEach((addition) => {
179
+ if (!gitignoreContent.includes(addition)) {
180
+ gitignoreContent += `\n${addition}`;
181
+ }
182
+ });
183
+ // Ensure there's no leading newline if the file was just created
184
+ gitignoreContent = gitignoreContent.trimStart();
185
+ fs.writeFileSync(gitignorePath, gitignoreContent);
228
186
  }
229
187
  // Recursive copy function
230
188
  function copyRecursiveSync(src, dest, answer) {
231
- var _a;
232
- console.log("🚀 ~ copyRecursiveSync ~ dest:", dest);
233
- console.log("🚀 ~ copyRecursiveSync ~ src:", src);
234
- const exists = fs.existsSync(src);
235
- const stats = exists && fs.statSync(src);
236
- const isDirectory = exists && stats && stats.isDirectory();
237
- if (isDirectory) {
238
- const destLower = dest.toLowerCase();
239
- if (!answer.websocket && destLower.includes("src\\lib\\websocket"))
240
- return;
241
- if (!answer.prisma && destLower.includes("src\\lib\\prisma"))
242
- return;
243
- if ((answer.backendOnly && destLower.includes("src\\app\\js")) ||
244
- (answer.backendOnly && destLower.includes("src\\app\\css")))
245
- return;
246
- if (!answer.swaggerDocs && destLower.includes("src\\app\\swagger-docs"))
247
- return;
248
- const destModified = dest.replace(/\\/g, "/");
249
- if ((_a = updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.excludeFilePath) === null || _a === void 0 ? void 0 : _a.includes(destModified))
250
- return;
251
- if (!fs.existsSync(dest))
252
- fs.mkdirSync(dest, { recursive: true });
253
- fs.readdirSync(src).forEach((childItemName) => {
254
- copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName), answer);
255
- });
189
+ var _a;
190
+ console.log("🚀 ~ copyRecursiveSync ~ dest:", dest);
191
+ console.log("🚀 ~ copyRecursiveSync ~ src:", src);
192
+ const exists = fs.existsSync(src);
193
+ const stats = exists && fs.statSync(src);
194
+ const isDirectory = exists && stats && stats.isDirectory();
195
+ if (isDirectory) {
196
+ const destLower = dest.toLowerCase();
197
+ if (!answer.websocket && destLower.includes("src\\lib\\websocket")) return;
198
+ if (!answer.prisma && destLower.includes("src\\lib\\prisma")) return;
199
+ if (
200
+ (answer.backendOnly && destLower.includes("src\\app\\js")) ||
201
+ (answer.backendOnly && destLower.includes("src\\app\\css"))
202
+ )
203
+ return;
204
+ if (!answer.swaggerDocs && destLower.includes("src\\app\\swagger-docs"))
205
+ return;
206
+ const destModified = dest.replace(/\\/g, "/");
207
+ if (
208
+ (_a =
209
+ updateAnswer === null || updateAnswer === void 0
210
+ ? void 0
211
+ : updateAnswer.excludeFilePath) === null || _a === void 0
212
+ ? void 0
213
+ : _a.includes(destModified)
214
+ )
215
+ return;
216
+ if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
217
+ fs.readdirSync(src).forEach((childItemName) => {
218
+ copyRecursiveSync(
219
+ path.join(src, childItemName),
220
+ path.join(dest, childItemName),
221
+ answer
222
+ );
223
+ });
224
+ } else {
225
+ if (checkExcludeFiles(dest)) return;
226
+ if (
227
+ !answer.tailwindcss &&
228
+ (dest.includes("tailwind.css") || dest.includes("styles.css"))
229
+ )
230
+ return;
231
+ if (
232
+ !answer.websocket &&
233
+ (dest.includes("restart-websocket.cjs") ||
234
+ dest.includes("restart-websocket.bat"))
235
+ )
236
+ return;
237
+ if (!answer.docker && dockerFiles.some((file) => dest.includes(file))) {
238
+ return;
256
239
  }
257
- else {
258
- if (checkExcludeFiles(dest))
259
- return;
260
- if (!answer.tailwindcss &&
261
- (dest.includes("tailwind.css") || dest.includes("styles.css")))
262
- return;
263
- if (!answer.websocket &&
264
- (dest.includes("restart-websocket.cjs") ||
265
- dest.includes("restart-websocket.bat")))
266
- return;
267
- if (!answer.docker && dockerFiles.some((file) => dest.includes(file))) {
268
- return;
269
- }
270
- if (answer.backendOnly &&
271
- nonBackendFiles.some((file) => dest.includes(file))) {
272
- return;
273
- }
274
- if (!answer.backendOnly && dest.includes("route.php"))
275
- return;
276
- if (!answer.swaggerDocs && dest.includes("swagger-setup.js")) {
277
- return;
278
- }
279
- fs.copyFileSync(src, dest, 0);
240
+ if (
241
+ answer.backendOnly &&
242
+ nonBackendFiles.some((file) => dest.includes(file))
243
+ ) {
244
+ return;
245
+ }
246
+ if (!answer.backendOnly && dest.includes("route.php")) return;
247
+ if (!answer.swaggerDocs && dest.includes("swagger-config.js")) {
248
+ return;
280
249
  }
250
+ fs.copyFileSync(src, dest, 0);
251
+ }
281
252
  }
282
253
  // Function to execute the recursive copy for entire directories
283
254
  async function executeCopy(baseDir, directoriesToCopy, answer) {
284
- directoriesToCopy.forEach(({ srcDir, destDir }) => {
285
- const sourcePath = path.join(__dirname, srcDir);
286
- const destPath = path.join(baseDir, destDir);
287
- copyRecursiveSync(sourcePath, destPath, answer);
288
- });
255
+ directoriesToCopy.forEach(({ src: srcDir, dest: destDir }) => {
256
+ const sourcePath = path.join(__dirname, srcDir);
257
+ const destPath = path.join(baseDir, destDir);
258
+ copyRecursiveSync(sourcePath, destPath, answer);
259
+ });
289
260
  }
290
261
  function createOrUpdateTailwindConfig(baseDir) {
291
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ baseDir:", baseDir);
292
- const filePath = path.join(baseDir, "tailwind.config.js");
293
- if (checkExcludeFiles(filePath))
294
- return;
295
- const newContent = [
296
- "./src/**/*.{html,js,php}",
297
- // Add more paths as needed
298
- ];
299
- let configData = fs.readFileSync(filePath, "utf8");
300
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ configData:", configData);
301
- const contentArrayString = newContent
302
- .map((item) => ` "${item}"`)
303
- .join(",\n");
304
- configData = configData.replace(/content: \[\],/g, `content: [\n${contentArrayString}\n],`);
305
- fs.writeFileSync(filePath, configData, { flag: "w" });
306
- console.log(chalk.green("Tailwind configuration updated successfully."));
262
+ console.log("🚀 ~ createOrUpdateTailwindConfig ~ baseDir:", baseDir);
263
+ const filePath = path.join(baseDir, "tailwind.config.js");
264
+ if (checkExcludeFiles(filePath)) return;
265
+ const newContent = [
266
+ "./src/**/*.{html,js,php}",
267
+ // Add more paths as needed
268
+ ];
269
+ let configData = fs.readFileSync(filePath, "utf8");
270
+ console.log("🚀 ~ createOrUpdateTailwindConfig ~ configData:", configData);
271
+ const contentArrayString = newContent
272
+ .map((item) => ` "${item}"`)
273
+ .join(",\n");
274
+ configData = configData.replace(
275
+ /content: \[\],/g,
276
+ `content: [\n${contentArrayString}\n],`
277
+ );
278
+ fs.writeFileSync(filePath, configData, { flag: "w" });
279
+ console.log(chalk.green("Tailwind configuration updated successfully."));
307
280
  }
308
281
  function modifyPostcssConfig(baseDir) {
309
- const filePath = path.join(baseDir, "postcss.config.js");
310
- if (checkExcludeFiles(filePath))
311
- return;
312
- const newContent = `export default {
282
+ const filePath = path.join(baseDir, "postcss.config.js");
283
+ if (checkExcludeFiles(filePath)) return;
284
+ const newContent = `export default {
313
285
  plugins: {
314
286
  tailwindcss: {},
315
287
  autoprefixer: {},
316
288
  cssnano: {},
317
289
  },
318
290
  };`;
319
- fs.writeFileSync(filePath, newContent, { flag: "w" });
320
- console.log(chalk.green("postcss.config.js updated successfully."));
291
+ fs.writeFileSync(filePath, newContent, { flag: "w" });
292
+ console.log(chalk.green("postcss.config.js updated successfully."));
321
293
  }
322
294
  function modifyLayoutPHP(baseDir, answer) {
323
- const layoutPath = path.join(baseDir, "src", "app", "layout.php");
324
- if (checkExcludeFiles(layoutPath))
325
- return;
326
- try {
327
- let indexContent = fs.readFileSync(layoutPath, "utf8");
328
- let stylesAndLinks = "";
329
- if (!answer.backendOnly) {
330
- stylesAndLinks = `\n <link href="<?= $baseUrl; ?>/css/index.css" rel="stylesheet">\n <script src="<?= $baseUrl; ?>/js/index.js"></script>`;
331
- }
332
- // Tailwind CSS link or CDN script
333
- let tailwindLink = "";
334
- if (!answer.backendOnly) {
335
- tailwindLink = answer.tailwindcss
336
- ? ` <link href="<?= $baseUrl; ?>/css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
337
- : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
338
- }
339
- // Insert before the closing </head> tag
340
- const breakLine = tailwindLink.length > 0 ? "\n" : "";
341
- indexContent = indexContent.replace("</head>", `${tailwindLink}${breakLine} <!-- Dynamic Head -->
342
- <?= implode("\\n", $mainLayoutHead); ?>
343
- </head>`);
344
- fs.writeFileSync(layoutPath, indexContent, { flag: "w" });
345
- console.log(chalk.green(`layout.php modified successfully for ${answer.tailwindcss ? "local Tailwind CSS" : "Tailwind CSS CDN"}.`));
295
+ const layoutPath = path.join(baseDir, "src", "app", "layout.php");
296
+ if (checkExcludeFiles(layoutPath)) return;
297
+ try {
298
+ let indexContent = fs.readFileSync(layoutPath, "utf8");
299
+ let stylesAndLinks = "";
300
+ if (!answer.backendOnly) {
301
+ stylesAndLinks = `\n <link href="<?= $baseUrl; ?>/css/index.css" rel="stylesheet">\n <script src="<?= $baseUrl; ?>/js/index.js"></script>`;
346
302
  }
347
- catch (error) {
348
- console.error(chalk.red("Error modifying layout.php:"), error);
303
+ // Tailwind CSS link or CDN script
304
+ let tailwindLink = "";
305
+ if (!answer.backendOnly) {
306
+ tailwindLink = answer.tailwindcss
307
+ ? ` <link href="<?= $baseUrl; ?>/css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
308
+ : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
349
309
  }
310
+ // Insert before the closing </head> tag
311
+ const breakLine = tailwindLink.length > 0 ? "\n" : "";
312
+ indexContent = indexContent.replace(
313
+ "</head>",
314
+ `${tailwindLink}${breakLine} <!-- Dynamic Head -->
315
+ <?= implode("\\n", $mainLayoutHead); ?>
316
+ </head>`
317
+ );
318
+ fs.writeFileSync(layoutPath, indexContent, { flag: "w" });
319
+ console.log(
320
+ chalk.green(
321
+ `layout.php modified successfully for ${
322
+ answer.tailwindcss ? "local Tailwind CSS" : "Tailwind CSS CDN"
323
+ }.`
324
+ )
325
+ );
326
+ } catch (error) {
327
+ console.error(chalk.red("Error modifying layout.php:"), error);
328
+ }
350
329
  }
351
330
  // This function updates or creates the .env file
352
331
  async function createOrUpdateEnvFile(baseDir, content) {
353
- const envPath = path.join(baseDir, ".env");
354
- if (checkExcludeFiles(envPath))
355
- return;
356
- console.log("🚀 ~ content:", content);
357
- fs.writeFileSync(envPath, content, { flag: "w" });
332
+ const envPath = path.join(baseDir, ".env");
333
+ if (checkExcludeFiles(envPath)) return;
334
+ console.log("🚀 ~ content:", content);
335
+ fs.writeFileSync(envPath, content, { flag: "w" });
358
336
  }
359
337
  function checkExcludeFiles(destPath) {
360
- var _a, _b;
361
- if (!(updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate))
362
- return false;
363
- return ((_b = (_a = updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.excludeFilePath) === null || _a === void 0 ? void 0 : _a.includes(destPath.replace(/\\/g, "/"))) !== null && _b !== void 0 ? _b : false);
338
+ var _a, _b;
339
+ if (
340
+ !(updateAnswer === null || updateAnswer === void 0
341
+ ? void 0
342
+ : updateAnswer.isUpdate)
343
+ )
344
+ return false;
345
+ return (_b =
346
+ (_a =
347
+ updateAnswer === null || updateAnswer === void 0
348
+ ? void 0
349
+ : updateAnswer.excludeFilePath) === null || _a === void 0
350
+ ? void 0
351
+ : _a.includes(destPath.replace(/\\/g, "/"))) !== null && _b !== void 0
352
+ ? _b
353
+ : false;
364
354
  }
365
355
  async function createDirectoryStructure(baseDir, answer) {
366
- console.log("🚀 ~ baseDir:", baseDir);
367
- console.log("🚀 ~ answer:", answer);
368
- const filesToCopy = [
369
- { src: "/bootstrap.php", dest: "/bootstrap.php" },
370
- { src: "/.htaccess", dest: "/.htaccess" },
371
- { src: "/../composer.json", dest: "/composer.json" },
372
- ];
373
- if (updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate) {
374
- filesToCopy.push({ src: "/tsconfig.json", dest: "/tsconfig.json" });
375
- if (updateAnswer.tailwindcss) {
376
- filesToCopy.push({ src: "/postcss.config.js", dest: "/postcss.config.js" }, { src: "/tailwind.config.js", dest: "/tailwind.config.js" });
377
- }
378
- }
379
- const directoriesToCopy = [
380
- {
381
- srcDir: "/settings",
382
- destDir: "/settings",
383
- },
384
- {
385
- srcDir: "/src",
386
- destDir: "/src",
387
- },
388
- ];
389
- if (answer.backendOnly && answer.swaggerDocs) {
390
- directoriesToCopy.push({
391
- srcDir: "/swagger-docs-layout.php",
392
- destDir: "/src/app/layout.php",
393
- });
394
- }
395
- if (answer.prisma) {
396
- directoriesToCopy.push({
397
- srcDir: "/prisma",
398
- destDir: "/prisma",
399
- });
400
- }
401
- if (answer.docker) {
402
- directoriesToCopy.push({ srcDir: "/.dockerignore", destDir: "/.dockerignore" }, { srcDir: "/docker-compose.yml", destDir: "/docker-compose.yml" }, { srcDir: "/Dockerfile", destDir: "/Dockerfile" }, { srcDir: "/apache.conf", destDir: "/apache.conf" });
403
- }
404
- console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
405
- filesToCopy.forEach(({ src, dest }) => {
406
- const sourcePath = path.join(__dirname, src);
407
- const destPath = path.join(baseDir, dest);
408
- if (checkExcludeFiles(destPath))
409
- return;
410
- const code = fs.readFileSync(sourcePath, "utf8");
411
- fs.writeFileSync(destPath, code, { flag: "w" });
356
+ console.log("🚀 ~ baseDir:", baseDir);
357
+ console.log("🚀 ~ answer:", answer);
358
+ const filesToCopy = [
359
+ { src: "/bootstrap.php", dest: "/bootstrap.php" },
360
+ { src: "/.htaccess", dest: "/.htaccess" },
361
+ { src: "/../composer.json", dest: "/composer.json" },
362
+ { src: "/tsconfig.json", dest: "/tsconfig.json" },
363
+ ];
364
+ if (answer.tailwindcss) {
365
+ filesToCopy.push(
366
+ { src: "/postcss.config.js", dest: "/postcss.config.js" },
367
+ { src: "/tailwind.config.js", dest: "/tailwind.config.js" }
368
+ );
369
+ }
370
+ const directoriesToCopy = [
371
+ {
372
+ src: "/settings",
373
+ dest: "/settings",
374
+ },
375
+ {
376
+ src: "/src",
377
+ dest: "/src",
378
+ },
379
+ ];
380
+ if (answer.backendOnly && answer.swaggerDocs) {
381
+ directoriesToCopy.push({
382
+ src: "/swagger-docs-layout.php",
383
+ dest: "/src/app/layout.php",
412
384
  });
413
- await executeCopy(baseDir, directoriesToCopy, answer);
414
- await updatePackageJson(baseDir, answer);
415
- await updateComposerJson(baseDir, answer);
416
- if (!answer.backendOnly) {
417
- await updateIndexJsForWebSocket(baseDir, answer);
418
- }
419
- if (answer.tailwindcss) {
420
- createOrUpdateTailwindConfig(baseDir);
421
- modifyPostcssConfig(baseDir);
422
- }
423
- if (answer.tailwindcss || !answer.backendOnly || answer.swaggerDocs) {
424
- modifyLayoutPHP(baseDir, answer);
425
- }
426
- const prismaPHPEnvContent = `# Prisma PHP Auth Secret Key For development only - Change this in production
385
+ }
386
+ if (answer.prisma) {
387
+ directoriesToCopy.push({
388
+ src: "/prisma",
389
+ dest: "/prisma",
390
+ });
391
+ }
392
+ if (answer.docker) {
393
+ directoriesToCopy.push(
394
+ { src: "/.dockerignore", dest: "/.dockerignore" },
395
+ { src: "/docker-compose.yml", dest: "/docker-compose.yml" },
396
+ { src: "/Dockerfile", dest: "/Dockerfile" },
397
+ { src: "/apache.conf", dest: "/apache.conf" }
398
+ );
399
+ }
400
+ console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
401
+ filesToCopy.forEach(({ src, dest }) => {
402
+ const sourcePath = path.join(__dirname, src);
403
+ const destPath = path.join(baseDir, dest);
404
+ if (checkExcludeFiles(destPath)) return;
405
+ const code = fs.readFileSync(sourcePath, "utf8");
406
+ fs.writeFileSync(destPath, code, { flag: "w" });
407
+ });
408
+ await executeCopy(baseDir, directoriesToCopy, answer);
409
+ await updatePackageJson(baseDir, answer);
410
+ await updateComposerJson(baseDir, answer);
411
+ if (!answer.backendOnly) {
412
+ await updateIndexJsForWebSocket(baseDir, answer);
413
+ }
414
+ if (answer.tailwindcss) {
415
+ createOrUpdateTailwindConfig(baseDir);
416
+ modifyPostcssConfig(baseDir);
417
+ }
418
+ if (answer.tailwindcss || !answer.backendOnly || answer.swaggerDocs) {
419
+ modifyLayoutPHP(baseDir, answer);
420
+ }
421
+ const prismaPHPEnvContent = `# Prisma PHP Auth Secret Key For development only - Change this in production
427
422
  AUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4=
428
423
 
429
424
  # PHPMailer
@@ -438,172 +433,205 @@ AUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4=
438
433
  # SHOW ERRORS - Set to true to show errors in the browser for development only - Change this in production to false
439
434
  SHOW_ERRORS=true
440
435
 
441
- # ChatGPT API Key
442
- # CHATGPT_API_KEY=sk-your-api-key
443
-
444
436
  # APP TIMEZONE - Set your application timezone - Default is "UTC"
445
437
  APP_TIMEZONE="UTC"
446
438
 
447
439
  # APP ENV - Set your application environment - Default is "development" - Change this in production to "production"
448
440
  APP_ENV=development`;
449
- if (answer.prisma) {
450
- const prismaEnvContent = `# Environment variables declared in this file are automatically made available to Prisma.
441
+ if (answer.prisma) {
442
+ const prismaEnvContent = `# Environment variables declared in this file are automatically made available to Prisma.
451
443
  # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
452
444
 
453
445
  # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
454
446
  # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
455
447
 
456
448
  DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"`;
457
- const envContent = `${prismaEnvContent}\n\n${prismaPHPEnvContent}`;
458
- await createOrUpdateEnvFile(baseDir, envContent);
459
- }
460
- else {
461
- await createOrUpdateEnvFile(baseDir, prismaPHPEnvContent);
462
- }
463
- // Add vendor to .gitignore
464
- await createUpdateGitignoreFile(baseDir, ["vendor", ".env", "node_modules"]);
449
+ const envContent = `${prismaEnvContent}\n\n${prismaPHPEnvContent}`;
450
+ await createOrUpdateEnvFile(baseDir, envContent);
451
+ } else {
452
+ await createOrUpdateEnvFile(baseDir, prismaPHPEnvContent);
453
+ }
454
+ // Add vendor to .gitignore
455
+ await createUpdateGitignoreFile(baseDir, ["vendor", ".env", "node_modules"]);
465
456
  }
466
457
  async function getAnswer(predefinedAnswers = {}) {
467
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
468
- console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
469
- const questionsArray = [];
470
- if (!predefinedAnswers.projectName) {
471
- questionsArray.push({
472
- type: "text",
473
- name: "projectName",
474
- message: "What is your project named?",
475
- initial: "my-app",
476
- });
458
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
459
+ console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
460
+ const questionsArray = [];
461
+ if (!predefinedAnswers.projectName) {
462
+ questionsArray.push({
463
+ type: "text",
464
+ name: "projectName",
465
+ message: "What is your project named?",
466
+ initial: "my-app",
467
+ });
468
+ }
469
+ if (!predefinedAnswers.backendOnly) {
470
+ questionsArray.push({
471
+ type: "toggle",
472
+ name: "backendOnly",
473
+ message: "Would you like to create a backend-only project?",
474
+ initial: false,
475
+ active: "Yes",
476
+ inactive: "No",
477
+ });
478
+ }
479
+ // Execute the initial questionsArray first
480
+ const onCancel = () => {
481
+ console.log(chalk.red("Operation cancelled by the user."));
482
+ process.exit(0);
483
+ };
484
+ const initialResponse = await prompts(questionsArray, { onCancel });
485
+ console.log("🚀 ~ initialResponse:", initialResponse);
486
+ const nonBackendOnlyQuestionsArray = [];
487
+ if (initialResponse.backendOnly || predefinedAnswers.backendOnly) {
488
+ // If it's a backend-only project, skip Tailwind CSS, but ask other questions
489
+ if (!predefinedAnswers.swaggerDocs) {
490
+ nonBackendOnlyQuestionsArray.push({
491
+ type: "toggle",
492
+ name: "swaggerDocs",
493
+ message: `Would you like to use ${chalk.blue("Swagger Docs")}?`,
494
+ initial: false,
495
+ active: "Yes",
496
+ inactive: "No",
497
+ });
477
498
  }
478
- if (!predefinedAnswers.backendOnly) {
479
- questionsArray.push({
480
- type: "toggle",
481
- name: "backendOnly",
482
- message: "Would you like to create a backend-only project?",
483
- initial: false,
484
- active: "Yes",
485
- inactive: "No",
486
- });
499
+ if (!predefinedAnswers.websocket) {
500
+ nonBackendOnlyQuestionsArray.push({
501
+ type: "toggle",
502
+ name: "websocket",
503
+ message: `Would you like to use ${chalk.blue("Websocket")}?`,
504
+ initial: true,
505
+ active: "Yes",
506
+ inactive: "No",
507
+ });
487
508
  }
488
- // Execute the initial questionsArray first
489
- const onCancel = () => {
490
- console.log(chalk.red("Operation cancelled by the user."));
491
- process.exit(0);
492
- };
493
- const initialResponse = await prompts(questionsArray, { onCancel });
494
- console.log("🚀 ~ initialResponse:", initialResponse);
495
- const nonBackendOnlyQuestionsArray = [];
496
- if (initialResponse.backendOnly || predefinedAnswers.backendOnly) {
497
- // If it's a backend-only project, skip Tailwind CSS, but ask other questions
498
- if (!predefinedAnswers.swaggerDocs) {
499
- nonBackendOnlyQuestionsArray.push({
500
- type: "toggle",
501
- name: "swaggerDocs",
502
- message: `Would you like to use ${chalk.blue("Swagger Docs")}?`,
503
- initial: false,
504
- active: "Yes",
505
- inactive: "No",
506
- });
507
- }
508
- if (!predefinedAnswers.websocket) {
509
- nonBackendOnlyQuestionsArray.push({
510
- type: "toggle",
511
- name: "websocket",
512
- message: `Would you like to use ${chalk.blue("Websocket")}?`,
513
- initial: true,
514
- active: "Yes",
515
- inactive: "No",
516
- });
517
- }
518
- if (!predefinedAnswers.prisma) {
519
- nonBackendOnlyQuestionsArray.push({
520
- type: "toggle",
521
- name: "prisma",
522
- message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
523
- initial: true,
524
- active: "Yes",
525
- inactive: "No",
526
- });
527
- }
528
- if (!predefinedAnswers.docker) {
529
- nonBackendOnlyQuestionsArray.push({
530
- type: "toggle",
531
- name: "docker",
532
- message: `Would you like to use ${chalk.blue("Docker")}?`,
533
- initial: false,
534
- active: "Yes",
535
- inactive: "No",
536
- });
537
- }
509
+ if (!predefinedAnswers.prisma) {
510
+ nonBackendOnlyQuestionsArray.push({
511
+ type: "toggle",
512
+ name: "prisma",
513
+ message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
514
+ initial: true,
515
+ active: "Yes",
516
+ inactive: "No",
517
+ });
538
518
  }
539
- else {
540
- // If it's not a backend-only project, ask Tailwind CSS as well
541
- if (!predefinedAnswers.swaggerDocs) {
542
- nonBackendOnlyQuestionsArray.push({
543
- type: "toggle",
544
- name: "swaggerDocs",
545
- message: `Would you like to use ${chalk.blue("Swagger Docs")}?`,
546
- initial: false,
547
- active: "Yes",
548
- inactive: "No",
549
- });
550
- }
551
- if (!predefinedAnswers.tailwindcss) {
552
- nonBackendOnlyQuestionsArray.push({
553
- type: "toggle",
554
- name: "tailwindcss",
555
- message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
556
- initial: true,
557
- active: "Yes",
558
- inactive: "No",
559
- });
560
- }
561
- if (!predefinedAnswers.websocket) {
562
- nonBackendOnlyQuestionsArray.push({
563
- type: "toggle",
564
- name: "websocket",
565
- message: `Would you like to use ${chalk.blue("Websocket")}?`,
566
- initial: true,
567
- active: "Yes",
568
- inactive: "No",
569
- });
570
- }
571
- if (!predefinedAnswers.prisma) {
572
- nonBackendOnlyQuestionsArray.push({
573
- type: "toggle",
574
- name: "prisma",
575
- message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
576
- initial: true,
577
- active: "Yes",
578
- inactive: "No",
579
- });
580
- }
581
- if (!predefinedAnswers.docker) {
582
- nonBackendOnlyQuestionsArray.push({
583
- type: "toggle",
584
- name: "docker",
585
- message: `Would you like to use ${chalk.blue("Docker")}?`,
586
- initial: false,
587
- active: "Yes",
588
- inactive: "No",
589
- });
590
- }
519
+ if (!predefinedAnswers.docker) {
520
+ nonBackendOnlyQuestionsArray.push({
521
+ type: "toggle",
522
+ name: "docker",
523
+ message: `Would you like to use ${chalk.blue("Docker")}?`,
524
+ initial: false,
525
+ active: "Yes",
526
+ inactive: "No",
527
+ });
591
528
  }
592
- const nonBackendOnlyResponse = await prompts(nonBackendOnlyQuestionsArray, {
593
- onCancel,
594
- });
595
- console.log("🚀 ~ nonBackendOnlyResponse:", nonBackendOnlyResponse);
596
- return {
597
- projectName: initialResponse.projectName
598
- ? String(initialResponse.projectName).trim().replace(/ /g, "-")
599
- : (_a = predefinedAnswers.projectName) !== null && _a !== void 0 ? _a : "my-app",
600
- backendOnly: (_c = (_b = initialResponse.backendOnly) !== null && _b !== void 0 ? _b : predefinedAnswers.backendOnly) !== null && _c !== void 0 ? _c : false,
601
- swaggerDocs: (_e = (_d = nonBackendOnlyResponse.swaggerDocs) !== null && _d !== void 0 ? _d : predefinedAnswers.swaggerDocs) !== null && _e !== void 0 ? _e : false,
602
- tailwindcss: (_g = (_f = nonBackendOnlyResponse.tailwindcss) !== null && _f !== void 0 ? _f : predefinedAnswers.tailwindcss) !== null && _g !== void 0 ? _g : false,
603
- websocket: (_j = (_h = nonBackendOnlyResponse.websocket) !== null && _h !== void 0 ? _h : predefinedAnswers.websocket) !== null && _j !== void 0 ? _j : false,
604
- prisma: (_l = (_k = nonBackendOnlyResponse.prisma) !== null && _k !== void 0 ? _k : predefinedAnswers.prisma) !== null && _l !== void 0 ? _l : false,
605
- docker: (_o = (_m = nonBackendOnlyResponse.docker) !== null && _m !== void 0 ? _m : predefinedAnswers.docker) !== null && _o !== void 0 ? _o : false,
606
- };
529
+ } else {
530
+ // If it's not a backend-only project, ask Tailwind CSS as well
531
+ if (!predefinedAnswers.swaggerDocs) {
532
+ nonBackendOnlyQuestionsArray.push({
533
+ type: "toggle",
534
+ name: "swaggerDocs",
535
+ message: `Would you like to use ${chalk.blue("Swagger Docs")}?`,
536
+ initial: false,
537
+ active: "Yes",
538
+ inactive: "No",
539
+ });
540
+ }
541
+ if (!predefinedAnswers.tailwindcss) {
542
+ nonBackendOnlyQuestionsArray.push({
543
+ type: "toggle",
544
+ name: "tailwindcss",
545
+ message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
546
+ initial: true,
547
+ active: "Yes",
548
+ inactive: "No",
549
+ });
550
+ }
551
+ if (!predefinedAnswers.websocket) {
552
+ nonBackendOnlyQuestionsArray.push({
553
+ type: "toggle",
554
+ name: "websocket",
555
+ message: `Would you like to use ${chalk.blue("Websocket")}?`,
556
+ initial: true,
557
+ active: "Yes",
558
+ inactive: "No",
559
+ });
560
+ }
561
+ if (!predefinedAnswers.prisma) {
562
+ nonBackendOnlyQuestionsArray.push({
563
+ type: "toggle",
564
+ name: "prisma",
565
+ message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
566
+ initial: true,
567
+ active: "Yes",
568
+ inactive: "No",
569
+ });
570
+ }
571
+ if (!predefinedAnswers.docker) {
572
+ nonBackendOnlyQuestionsArray.push({
573
+ type: "toggle",
574
+ name: "docker",
575
+ message: `Would you like to use ${chalk.blue("Docker")}?`,
576
+ initial: false,
577
+ active: "Yes",
578
+ inactive: "No",
579
+ });
580
+ }
581
+ }
582
+ const nonBackendOnlyResponse = await prompts(nonBackendOnlyQuestionsArray, {
583
+ onCancel,
584
+ });
585
+ console.log("🚀 ~ nonBackendOnlyResponse:", nonBackendOnlyResponse);
586
+ return {
587
+ projectName: initialResponse.projectName
588
+ ? String(initialResponse.projectName).trim().replace(/ /g, "-")
589
+ : (_a = predefinedAnswers.projectName) !== null && _a !== void 0
590
+ ? _a
591
+ : "my-app",
592
+ backendOnly:
593
+ (_c =
594
+ (_b = initialResponse.backendOnly) !== null && _b !== void 0
595
+ ? _b
596
+ : predefinedAnswers.backendOnly) !== null && _c !== void 0
597
+ ? _c
598
+ : false,
599
+ swaggerDocs:
600
+ (_e =
601
+ (_d = nonBackendOnlyResponse.swaggerDocs) !== null && _d !== void 0
602
+ ? _d
603
+ : predefinedAnswers.swaggerDocs) !== null && _e !== void 0
604
+ ? _e
605
+ : false,
606
+ tailwindcss:
607
+ (_g =
608
+ (_f = nonBackendOnlyResponse.tailwindcss) !== null && _f !== void 0
609
+ ? _f
610
+ : predefinedAnswers.tailwindcss) !== null && _g !== void 0
611
+ ? _g
612
+ : false,
613
+ websocket:
614
+ (_j =
615
+ (_h = nonBackendOnlyResponse.websocket) !== null && _h !== void 0
616
+ ? _h
617
+ : predefinedAnswers.websocket) !== null && _j !== void 0
618
+ ? _j
619
+ : false,
620
+ prisma:
621
+ (_l =
622
+ (_k = nonBackendOnlyResponse.prisma) !== null && _k !== void 0
623
+ ? _k
624
+ : predefinedAnswers.prisma) !== null && _l !== void 0
625
+ ? _l
626
+ : false,
627
+ docker:
628
+ (_o =
629
+ (_m = nonBackendOnlyResponse.docker) !== null && _m !== void 0
630
+ ? _m
631
+ : predefinedAnswers.docker) !== null && _o !== void 0
632
+ ? _o
633
+ : false,
634
+ };
607
635
  }
608
636
  /**
609
637
  * Install dependencies in the specified directory.
@@ -612,352 +640,460 @@ async function getAnswer(predefinedAnswers = {}) {
612
640
  * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
613
641
  */
614
642
  async function installDependencies(baseDir, dependencies, isDev = false) {
615
- console.log("Initializing new Node.js project...");
616
- // Initialize a package.json if it doesn't exist
617
- if (!fs.existsSync(path.join(baseDir, "package.json")))
618
- execSync("npm init -y", {
619
- stdio: "inherit",
620
- cwd: baseDir,
621
- });
622
- // Log the dependencies being installed
623
- console.log(`${isDev ? "Installing development dependencies" : "Installing dependencies"}:`);
624
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
625
- // Prepare the npm install command with the appropriate flag for dev dependencies
626
- const npmInstallCommand = `npm install ${isDev ? "--save-dev" : ""} ${dependencies.join(" ")}`;
627
- // Execute the npm install command
628
- execSync(npmInstallCommand, {
629
- stdio: "inherit",
630
- cwd: baseDir,
643
+ console.log("Initializing new Node.js project...");
644
+ // Initialize a package.json if it doesn't exist
645
+ if (!fs.existsSync(path.join(baseDir, "package.json")))
646
+ execSync("npm init -y", {
647
+ stdio: "inherit",
648
+ cwd: baseDir,
631
649
  });
650
+ // Log the dependencies being installed
651
+ console.log(
652
+ `${
653
+ isDev ? "Installing development dependencies" : "Installing dependencies"
654
+ }:`
655
+ );
656
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
657
+ // Prepare the npm install command with the appropriate flag for dev dependencies
658
+ const npmInstallCommand = `npm install ${
659
+ isDev ? "--save-dev" : ""
660
+ } ${dependencies.join(" ")}`;
661
+ // Execute the npm install command
662
+ execSync(npmInstallCommand, {
663
+ stdio: "inherit",
664
+ cwd: baseDir,
665
+ });
632
666
  }
633
667
  async function uninstallDependencies(baseDir, dependencies, isDev = false) {
634
- console.log("Uninstalling dependencies:");
635
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
636
- // Prepare the npm uninstall command with the appropriate flag for dev dependencies
637
- const npmUninstallCommand = `npm uninstall ${isDev ? "--save-dev" : "--save"} ${dependencies.join(" ")}`;
638
- // Execute the npm uninstall command
639
- execSync(npmUninstallCommand, {
640
- stdio: "inherit",
641
- cwd: baseDir,
642
- });
668
+ console.log("Uninstalling dependencies:");
669
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
670
+ // Prepare the npm uninstall command with the appropriate flag for dev dependencies
671
+ const npmUninstallCommand = `npm uninstall ${
672
+ isDev ? "--save-dev" : "--save"
673
+ } ${dependencies.join(" ")}`;
674
+ // Execute the npm uninstall command
675
+ execSync(npmUninstallCommand, {
676
+ stdio: "inherit",
677
+ cwd: baseDir,
678
+ });
643
679
  }
644
680
  function fetchPackageVersion(packageName) {
645
- return new Promise((resolve, reject) => {
646
- https
647
- .get(`https://registry.npmjs.org/${packageName}`, (res) => {
648
- let data = "";
649
- res.on("data", (chunk) => (data += chunk));
650
- res.on("end", () => {
651
- try {
652
- const parsed = JSON.parse(data);
653
- resolve(parsed["dist-tags"].latest);
654
- }
655
- catch (error) {
656
- reject(new Error("Failed to parse JSON response"));
657
- }
658
- });
659
- })
660
- .on("error", (err) => reject(err));
661
- });
681
+ return new Promise((resolve, reject) => {
682
+ https
683
+ .get(`https://registry.npmjs.org/${packageName}`, (res) => {
684
+ let data = "";
685
+ res.on("data", (chunk) => (data += chunk));
686
+ res.on("end", () => {
687
+ try {
688
+ const parsed = JSON.parse(data);
689
+ resolve(parsed["dist-tags"].latest);
690
+ } catch (error) {
691
+ reject(new Error("Failed to parse JSON response"));
692
+ }
693
+ });
694
+ })
695
+ .on("error", (err) => reject(err));
696
+ });
662
697
  }
663
698
  const readJsonFile = (filePath) => {
664
- const jsonData = fs.readFileSync(filePath, "utf8");
665
- return JSON.parse(jsonData);
699
+ const jsonData = fs.readFileSync(filePath, "utf8");
700
+ return JSON.parse(jsonData);
666
701
  };
667
702
  function compareVersions(installedVersion, currentVersion) {
668
- const installedVersionArray = installedVersion.split(".").map(Number);
669
- const currentVersionArray = currentVersion.split(".").map(Number);
670
- for (let i = 0; i < installedVersionArray.length; i++) {
671
- if (installedVersionArray[i] > currentVersionArray[i]) {
672
- return 1;
673
- }
674
- else if (installedVersionArray[i] < currentVersionArray[i]) {
675
- return -1;
676
- }
703
+ const installedVersionArray = installedVersion.split(".").map(Number);
704
+ const currentVersionArray = currentVersion.split(".").map(Number);
705
+ for (let i = 0; i < installedVersionArray.length; i++) {
706
+ if (installedVersionArray[i] > currentVersionArray[i]) {
707
+ return 1;
708
+ } else if (installedVersionArray[i] < currentVersionArray[i]) {
709
+ return -1;
677
710
  }
678
- return 0;
711
+ }
712
+ return 0;
679
713
  }
680
714
  function getInstalledPackageVersion(packageName) {
681
- try {
682
- const output = execSync(`npm list -g ${packageName} --depth=0`).toString();
683
- const versionMatch = output.match(new RegExp(`${packageName}@(\\d+\\.\\d+\\.\\d+)`));
684
- if (versionMatch) {
685
- return versionMatch[1];
686
- }
687
- else {
688
- console.error(`Package ${packageName} is not installed`);
689
- return null;
690
- }
691
- }
692
- catch (error) {
693
- console.error(error instanceof Error ? error.message : String(error));
694
- return null;
715
+ try {
716
+ const output = execSync(`npm list -g ${packageName} --depth=0`).toString();
717
+ const versionMatch = output.match(
718
+ new RegExp(`${packageName}@(\\d+\\.\\d+\\.\\d+)`)
719
+ );
720
+ if (versionMatch) {
721
+ return versionMatch[1];
722
+ } else {
723
+ console.error(`Package ${packageName} is not installed`);
724
+ return null;
695
725
  }
726
+ } catch (error) {
727
+ console.error(error instanceof Error ? error.message : String(error));
728
+ return null;
729
+ }
696
730
  }
697
731
  async function main() {
698
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
699
- try {
700
- const args = process.argv.slice(2);
701
- let projectName = args[0];
702
- let answer = null;
703
- if (projectName) {
704
- let useBackendOnly = args.includes("--backend-only");
705
- let useSwaggerDocs = args.includes("--swagger-docs");
706
- let useTailwind = args.includes("--tailwindcss");
707
- let useWebsocket = args.includes("--websocket");
708
- let usePrisma = args.includes("--prisma");
709
- let useDocker = args.includes("--docker");
710
- const predefinedAnswers = {
711
- projectName,
712
- backendOnly: useBackendOnly,
713
- swaggerDocs: useSwaggerDocs,
714
- tailwindcss: useTailwind,
715
- websocket: useWebsocket,
716
- prisma: usePrisma,
717
- docker: useDocker,
718
- };
719
- console.log("🚀 ~ main ~ predefinedAnswers:", predefinedAnswers);
720
- answer = await getAnswer(predefinedAnswers);
721
- if (answer === null) {
722
- console.log(chalk.red("Installation cancelled."));
723
- return;
724
- }
725
- const currentDir = process.cwd();
726
- const configPath = path.join(currentDir, "prisma-php.json");
727
- const localSettings = readJsonFile(configPath);
728
- let excludeFiles = [];
729
- (_a = localSettings.excludeFiles) === null || _a === void 0 ? void 0 : _a.map((file) => {
730
- const filePath = path.join(currentDir, file);
731
- if (fs.existsSync(filePath))
732
- excludeFiles.push(filePath.replace(/\\/g, "/"));
733
- });
734
- updateAnswer = {
735
- projectName,
736
- backendOnly: (_b = answer === null || answer === void 0 ? void 0 : answer.backendOnly) !== null && _b !== void 0 ? _b : false,
737
- swaggerDocs: (_c = answer === null || answer === void 0 ? void 0 : answer.swaggerDocs) !== null && _c !== void 0 ? _c : false,
738
- tailwindcss: (_d = answer === null || answer === void 0 ? void 0 : answer.tailwindcss) !== null && _d !== void 0 ? _d : false,
739
- websocket: (_e = answer === null || answer === void 0 ? void 0 : answer.websocket) !== null && _e !== void 0 ? _e : false,
740
- prisma: (_f = answer === null || answer === void 0 ? void 0 : answer.prisma) !== null && _f !== void 0 ? _f : false,
741
- docker: (_g = answer === null || answer === void 0 ? void 0 : answer.docker) !== null && _g !== void 0 ? _g : false,
742
- isUpdate: true,
743
- excludeFiles: (_h = localSettings.excludeFiles) !== null && _h !== void 0 ? _h : [],
744
- excludeFilePath: excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
745
- filePath: currentDir,
746
- };
747
- }
748
- else {
749
- answer = await getAnswer();
750
- }
751
- if (answer === null) {
752
- console.warn(chalk.red("Installation cancelled."));
753
- return;
754
- }
755
- const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion("create-prisma-php-app");
756
- const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion("create-prisma-php-app");
757
- if (isCreatePrismaPhpAppInstalled) {
758
- if (compareVersions(isCreatePrismaPhpAppInstalled, latestVersionOfCreatePrismaPhpApp) === -1) {
759
- execSync(`npm uninstall -g create-prisma-php-app`, {
760
- stdio: "inherit",
761
- });
762
- execSync(`npm install -g create-prisma-php-app`, {
763
- stdio: "inherit",
764
- });
765
- }
766
- }
767
- else {
768
- execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
769
- }
770
- const latestVersionOfBrowserSync = await fetchPackageVersion("browser-sync");
771
- const isBrowserSyncInstalled = getInstalledPackageVersion("browser-sync");
772
- if (isBrowserSyncInstalled) {
773
- if (compareVersions(isBrowserSyncInstalled, latestVersionOfBrowserSync) ===
774
- -1) {
775
- execSync(`npm uninstall -g browser-sync`, {
776
- stdio: "inherit",
777
- });
778
- execSync(`npm install -g browser-sync`, {
779
- stdio: "inherit",
780
- });
781
- }
782
- }
783
- else {
784
- execSync("npm install -g browser-sync", { stdio: "inherit" });
732
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
733
+ try {
734
+ const args = process.argv.slice(2);
735
+ let projectName = args[0];
736
+ let answer = null;
737
+ if (projectName) {
738
+ let useBackendOnly = args.includes("--backend-only");
739
+ let useSwaggerDocs = args.includes("--swagger-docs");
740
+ let useTailwind = args.includes("--tailwindcss");
741
+ let useWebsocket = args.includes("--websocket");
742
+ let usePrisma = args.includes("--prisma");
743
+ let useDocker = args.includes("--docker");
744
+ const predefinedAnswers = {
745
+ projectName,
746
+ backendOnly: useBackendOnly,
747
+ swaggerDocs: useSwaggerDocs,
748
+ tailwindcss: useTailwind,
749
+ websocket: useWebsocket,
750
+ prisma: usePrisma,
751
+ docker: useDocker,
752
+ };
753
+ console.log("🚀 ~ main ~ predefinedAnswers:", predefinedAnswers);
754
+ answer = await getAnswer(predefinedAnswers);
755
+ if (answer === null) {
756
+ console.log(chalk.red("Installation cancelled."));
757
+ return;
758
+ }
759
+ const currentDir = process.cwd();
760
+ const configPath = path.join(currentDir, "prisma-php.json");
761
+ const localSettings = readJsonFile(configPath);
762
+ let excludeFiles = [];
763
+ (_a = localSettings.excludeFiles) === null || _a === void 0
764
+ ? void 0
765
+ : _a.map((file) => {
766
+ const filePath = path.join(currentDir, file);
767
+ if (fs.existsSync(filePath))
768
+ excludeFiles.push(filePath.replace(/\\/g, "/"));
769
+ });
770
+ updateAnswer = {
771
+ projectName,
772
+ backendOnly:
773
+ (_b =
774
+ answer === null || answer === void 0
775
+ ? void 0
776
+ : answer.backendOnly) !== null && _b !== void 0
777
+ ? _b
778
+ : false,
779
+ swaggerDocs:
780
+ (_c =
781
+ answer === null || answer === void 0
782
+ ? void 0
783
+ : answer.swaggerDocs) !== null && _c !== void 0
784
+ ? _c
785
+ : false,
786
+ tailwindcss:
787
+ (_d =
788
+ answer === null || answer === void 0
789
+ ? void 0
790
+ : answer.tailwindcss) !== null && _d !== void 0
791
+ ? _d
792
+ : false,
793
+ websocket:
794
+ (_e =
795
+ answer === null || answer === void 0
796
+ ? void 0
797
+ : answer.websocket) !== null && _e !== void 0
798
+ ? _e
799
+ : false,
800
+ prisma:
801
+ (_f =
802
+ answer === null || answer === void 0 ? void 0 : answer.prisma) !==
803
+ null && _f !== void 0
804
+ ? _f
805
+ : false,
806
+ docker:
807
+ (_g =
808
+ answer === null || answer === void 0 ? void 0 : answer.docker) !==
809
+ null && _g !== void 0
810
+ ? _g
811
+ : false,
812
+ isUpdate: true,
813
+ excludeFiles:
814
+ (_h = localSettings.excludeFiles) !== null && _h !== void 0 ? _h : [],
815
+ excludeFilePath:
816
+ excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
817
+ filePath: currentDir,
818
+ };
819
+ } else {
820
+ answer = await getAnswer();
821
+ }
822
+ if (answer === null) {
823
+ console.warn(chalk.red("Installation cancelled."));
824
+ return;
825
+ }
826
+ const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
827
+ "create-prisma-php-app"
828
+ );
829
+ const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
830
+ "create-prisma-php-app"
831
+ );
832
+ if (isCreatePrismaPhpAppInstalled) {
833
+ if (
834
+ compareVersions(
835
+ isCreatePrismaPhpAppInstalled,
836
+ latestVersionOfCreatePrismaPhpApp
837
+ ) === -1
838
+ ) {
839
+ execSync(`npm uninstall -g create-prisma-php-app`, {
840
+ stdio: "inherit",
841
+ });
842
+ execSync(`npm install -g create-prisma-php-app`, {
843
+ stdio: "inherit",
844
+ });
845
+ }
846
+ } else {
847
+ execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
848
+ }
849
+ // Create the project directory
850
+ if (!projectName) fs.mkdirSync(answer.projectName);
851
+ const currentDir = process.cwd();
852
+ let projectPath = projectName
853
+ ? currentDir
854
+ : path.join(currentDir, answer.projectName);
855
+ if (!projectName) process.chdir(answer.projectName);
856
+ const dependencies = [
857
+ "typescript",
858
+ "@types/node",
859
+ "ts-node",
860
+ "http-proxy-middleware",
861
+ "chalk",
862
+ "npm-run-all",
863
+ "browser-sync",
864
+ ];
865
+ if (answer.swaggerDocs) {
866
+ dependencies.push("swagger-jsdoc");
867
+ }
868
+ if (answer.tailwindcss) {
869
+ dependencies.push(
870
+ "tailwindcss",
871
+ "autoprefixer",
872
+ "postcss",
873
+ "postcss-cli",
874
+ "cssnano"
875
+ );
876
+ }
877
+ if (answer.websocket) {
878
+ dependencies.push("chokidar-cli");
879
+ }
880
+ if (answer.prisma) {
881
+ dependencies.push("prisma", "@prisma/client");
882
+ }
883
+ await installDependencies(projectPath, dependencies, true);
884
+ if (!projectName) {
885
+ execSync(`npx tsc --init`, { stdio: "inherit" });
886
+ }
887
+ if (answer.tailwindcss)
888
+ execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
889
+ if (answer.prisma) {
890
+ if (!fs.existsSync(path.join(projectPath, "prisma")))
891
+ execSync(`npx prisma init`, { stdio: "inherit" });
892
+ }
893
+ await createDirectoryStructure(projectPath, answer);
894
+ const publicDirPath = path.join(projectPath, "public");
895
+ if (!fs.existsSync(publicDirPath)) {
896
+ fs.mkdirSync(publicDirPath);
897
+ }
898
+ if (answer.swaggerDocs) {
899
+ const swaggerDocsPath = path.join(
900
+ projectPath,
901
+ "src",
902
+ "app",
903
+ "swagger-docs"
904
+ );
905
+ // Check if the directory exists, if not, create it
906
+ if (!fs.existsSync(swaggerDocsPath)) {
907
+ fs.mkdirSync(swaggerDocsPath, { recursive: true }); // 'recursive: true' creates parent directories if they don't exist
908
+ }
909
+ // Clone the Git repository into the swagger-docs directory
910
+ execSync(
911
+ `git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`,
912
+ { stdio: "inherit" }
913
+ );
914
+ }
915
+ if (
916
+ updateAnswer === null || updateAnswer === void 0
917
+ ? void 0
918
+ : updateAnswer.isUpdate
919
+ ) {
920
+ const updateUninstallDependencies = [];
921
+ if (updateAnswer.backendOnly) {
922
+ nonBackendFiles.forEach((file) => {
923
+ const filePath = path.join(projectPath, "src", "app", file);
924
+ if (fs.existsSync(filePath)) {
925
+ fs.unlinkSync(filePath); // Delete each file if it exists
926
+ console.log(`${file} was deleted successfully.`);
927
+ } else {
928
+ console.log(`${file} does not exist.`);
929
+ }
930
+ });
931
+ const backendOnlyFolders = ["js", "css"];
932
+ backendOnlyFolders.forEach((folder) => {
933
+ const folderPath = path.join(projectPath, "src", "app", folder);
934
+ if (fs.existsSync(folderPath)) {
935
+ fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
936
+ console.log(`${folder} was deleted successfully.`);
937
+ } else {
938
+ console.log(`${folder} does not exist.`);
939
+ }
940
+ });
941
+ }
942
+ if (!updateAnswer.swaggerDocs) {
943
+ const swaggerDocsFolder = path.join(
944
+ projectPath,
945
+ "src",
946
+ "app",
947
+ "swagger-docs"
948
+ );
949
+ if (fs.existsSync(swaggerDocsFolder)) {
950
+ fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
951
+ console.log(`swagger-docs was deleted successfully.`);
785
952
  }
786
- // Create the project directory
787
- if (!projectName)
788
- fs.mkdirSync(answer.projectName);
789
- const currentDir = process.cwd();
790
- let projectPath = projectName
791
- ? currentDir
792
- : path.join(currentDir, answer.projectName);
793
- if (!projectName)
794
- process.chdir(answer.projectName);
795
- const dependencies = [
796
- "typescript",
797
- "@types/node",
798
- "ts-node",
799
- "http-proxy-middleware@^3.0.0",
800
- "chalk",
801
- "npm-run-all",
953
+ const swaggerFiles = ["swagger-setup.js"];
954
+ swaggerFiles.forEach((file) => {
955
+ const filePath = path.join(projectPath, "settings", file);
956
+ if (fs.existsSync(filePath)) {
957
+ fs.unlinkSync(filePath); // Delete each file if it exists
958
+ console.log(`${file} was deleted successfully.`);
959
+ } else {
960
+ console.log(`${file} does not exist.`);
961
+ }
962
+ });
963
+ updateUninstallDependencies.push("swagger-jsdoc");
964
+ }
965
+ if (!updateAnswer.tailwindcss) {
966
+ const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
967
+ tailwindFiles.forEach((file) => {
968
+ const filePath = path.join(projectPath, file);
969
+ if (fs.existsSync(filePath)) {
970
+ fs.unlinkSync(filePath); // Delete each file if it exists
971
+ console.log(`${file} was deleted successfully.`);
972
+ } else {
973
+ console.log(`${file} does not exist.`);
974
+ }
975
+ });
976
+ updateUninstallDependencies.push(
977
+ "tailwindcss",
978
+ "autoprefixer",
979
+ "postcss",
980
+ "postcss-cli",
981
+ "cssnano"
982
+ );
983
+ }
984
+ if (!updateAnswer.websocket) {
985
+ const websocketFiles = [
986
+ "restart-websocket.js",
987
+ "restart-websocket.bat",
802
988
  ];
803
- if (answer.swaggerDocs) {
804
- dependencies.push("swagger-jsdoc");
805
- }
806
- if (answer.tailwindcss) {
807
- dependencies.push("tailwindcss", "autoprefixer", "postcss", "postcss-cli", "cssnano");
808
- }
809
- if (answer.websocket) {
810
- dependencies.push("chokidar-cli");
811
- }
812
- if (answer.prisma) {
813
- dependencies.push("prisma", "@prisma/client");
814
- }
815
- await installDependencies(projectPath, dependencies, true);
816
- if (!projectName) {
817
- execSync(`npx tsc --init`, { stdio: "inherit" });
818
- }
819
- if (answer.tailwindcss)
820
- execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
821
- if (answer.prisma) {
822
- if (!fs.existsSync(path.join(projectPath, "prisma")))
823
- execSync(`npx prisma init`, { stdio: "inherit" });
824
- }
825
- await createDirectoryStructure(projectPath, answer);
826
- const publicDirPath = path.join(projectPath, "public");
827
- if (!fs.existsSync(publicDirPath)) {
828
- fs.mkdirSync(publicDirPath);
829
- }
830
- if (answer.swaggerDocs) {
831
- const swaggerDocsPath = path.join(projectPath, "src", "app", "swagger-docs");
832
- // Check if the directory exists, if not, create it
833
- if (!fs.existsSync(swaggerDocsPath)) {
834
- fs.mkdirSync(swaggerDocsPath, { recursive: true }); // 'recursive: true' creates parent directories if they don't exist
835
- }
836
- // Clone the Git repository into the swagger-docs directory
837
- execSync(`git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`, { stdio: "inherit" });
838
- }
839
- if (updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate) {
840
- const updateUninstallDependencies = [];
841
- if (updateAnswer.backendOnly) {
842
- nonBackendFiles.forEach((file) => {
843
- const filePath = path.join(projectPath, "src", "app", file);
844
- if (fs.existsSync(filePath)) {
845
- fs.unlinkSync(filePath); // Delete each file if it exists
846
- console.log(`${file} was deleted successfully.`);
847
- }
848
- else {
849
- console.log(`${file} does not exist.`);
850
- }
851
- });
852
- const backendOnlyFolders = ["js", "css"];
853
- backendOnlyFolders.forEach((folder) => {
854
- const folderPath = path.join(projectPath, "src", "app", folder);
855
- if (fs.existsSync(folderPath)) {
856
- fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
857
- console.log(`${folder} was deleted successfully.`);
858
- }
859
- else {
860
- console.log(`${folder} does not exist.`);
861
- }
862
- });
863
- }
864
- if (!updateAnswer.swaggerDocs) {
865
- const swaggerDocsFolder = path.join(projectPath, "src", "app", "swagger-docs");
866
- if (fs.existsSync(swaggerDocsFolder)) {
867
- fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
868
- console.log(`swagger-docs was deleted successfully.`);
869
- }
870
- const swaggerFiles = ["swagger-setup.js"];
871
- swaggerFiles.forEach((file) => {
872
- const filePath = path.join(projectPath, "settings", file);
873
- if (fs.existsSync(filePath)) {
874
- fs.unlinkSync(filePath); // Delete each file if it exists
875
- console.log(`${file} was deleted successfully.`);
876
- }
877
- else {
878
- console.log(`${file} does not exist.`);
879
- }
880
- });
881
- updateUninstallDependencies.push("swagger-jsdoc");
882
- }
883
- if (!updateAnswer.tailwindcss) {
884
- const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
885
- tailwindFiles.forEach((file) => {
886
- const filePath = path.join(projectPath, file);
887
- if (fs.existsSync(filePath)) {
888
- fs.unlinkSync(filePath); // Delete each file if it exists
889
- console.log(`${file} was deleted successfully.`);
890
- }
891
- else {
892
- console.log(`${file} does not exist.`);
893
- }
894
- });
895
- updateUninstallDependencies.push("tailwindcss", "autoprefixer", "postcss", "postcss-cli", "cssnano");
896
- }
897
- if (!updateAnswer.websocket) {
898
- updateUninstallDependencies.push("chokidar-cli");
899
- }
900
- if (!updateAnswer.prisma) {
901
- updateUninstallDependencies.push("prisma", "@prisma/client");
902
- }
903
- if (!updateAnswer.docker) {
904
- const dockerFiles = [
905
- ".dockerignore",
906
- "docker-compose.yml",
907
- "Dockerfile",
908
- "apache.conf",
909
- ];
910
- dockerFiles.forEach((file) => {
911
- const filePath = path.join(projectPath, file);
912
- if (fs.existsSync(filePath)) {
913
- fs.unlinkSync(filePath); // Delete each file if it exists
914
- console.log(`${file} was deleted successfully.`);
915
- }
916
- else {
917
- console.log(`${file} does not exist.`);
918
- }
919
- });
920
- }
921
- if (updateUninstallDependencies.length > 0) {
922
- await uninstallDependencies(projectPath, updateUninstallDependencies, true);
923
- }
989
+ websocketFiles.forEach((file) => {
990
+ const filePath = path.join(projectPath, "settings", file);
991
+ if (fs.existsSync(filePath)) {
992
+ fs.unlinkSync(filePath); // Delete each file if it exists
993
+ console.log(`${file} was deleted successfully.`);
994
+ } else {
995
+ console.log(`${file} does not exist.`);
996
+ }
997
+ });
998
+ const websocketFolder = path.join(
999
+ projectPath,
1000
+ "src",
1001
+ "Lib",
1002
+ "Websocket"
1003
+ );
1004
+ if (fs.existsSync(websocketFolder)) {
1005
+ fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
1006
+ console.log(`Websocket folder was deleted successfully.`);
924
1007
  }
925
- const projectPathModified = projectPath.replace(/\\/g, "\\");
926
- const bsConfig = bsConfigUrls(projectPathModified);
927
- const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
928
- const prismaPhpConfig = {
929
- projectName: answer.projectName,
930
- projectRootPath: projectPathModified,
931
- phpEnvironment: "XAMPP",
932
- phpRootPathExe: "C:\\xampp\\php\\php.exe",
933
- phpGenerateClassPath,
934
- bsTarget: bsConfig.bsTarget,
935
- bsPathRewrite: bsConfig.bsPathRewrite,
936
- backendOnly: answer.backendOnly,
937
- swaggerDocs: answer.swaggerDocs,
938
- tailwindcss: answer.tailwindcss,
939
- websocket: answer.websocket,
940
- prisma: answer.prisma,
941
- docker: answer.docker,
942
- version: latestVersionOfCreatePrismaPhpApp,
943
- excludeFiles: (_j = updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.excludeFiles) !== null && _j !== void 0 ? _j : [],
944
- };
945
- fs.writeFileSync(path.join(projectPath, "prisma-php.json"), JSON.stringify(prismaPhpConfig, null, 2), { flag: "w" });
946
- if (updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate) {
947
- execSync(`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update`, {
948
- stdio: "inherit",
949
- });
1008
+ updateUninstallDependencies.push("chokidar-cli");
1009
+ }
1010
+ if (!updateAnswer.prisma) {
1011
+ updateUninstallDependencies.push("prisma", "@prisma/client");
1012
+ }
1013
+ if (!updateAnswer.docker) {
1014
+ const dockerFiles = [
1015
+ ".dockerignore",
1016
+ "docker-compose.yml",
1017
+ "Dockerfile",
1018
+ "apache.conf",
1019
+ ];
1020
+ dockerFiles.forEach((file) => {
1021
+ const filePath = path.join(projectPath, file);
1022
+ if (fs.existsSync(filePath)) {
1023
+ fs.unlinkSync(filePath); // Delete each file if it exists
1024
+ console.log(`${file} was deleted successfully.`);
1025
+ } else {
1026
+ console.log(`${file} does not exist.`);
1027
+ }
1028
+ });
1029
+ }
1030
+ if (updateUninstallDependencies.length > 0) {
1031
+ await uninstallDependencies(
1032
+ projectPath,
1033
+ updateUninstallDependencies,
1034
+ true
1035
+ );
1036
+ }
1037
+ }
1038
+ const projectPathModified = projectPath.replace(/\\/g, "\\");
1039
+ const bsConfig = bsConfigUrls(projectPathModified);
1040
+ const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
1041
+ const prismaPhpConfig = {
1042
+ projectName: answer.projectName,
1043
+ projectRootPath: projectPathModified,
1044
+ phpEnvironment: "XAMPP",
1045
+ phpRootPathExe: "C:\\xampp\\php\\php.exe",
1046
+ phpGenerateClassPath,
1047
+ bsTarget: bsConfig.bsTarget,
1048
+ bsPathRewrite: bsConfig.bsPathRewrite,
1049
+ backendOnly: answer.backendOnly,
1050
+ swaggerDocs: answer.swaggerDocs,
1051
+ tailwindcss: answer.tailwindcss,
1052
+ websocket: answer.websocket,
1053
+ prisma: answer.prisma,
1054
+ docker: answer.docker,
1055
+ ngrok: false,
1056
+ version: latestVersionOfCreatePrismaPhpApp,
1057
+ excludeFiles:
1058
+ (_j =
1059
+ updateAnswer === null || updateAnswer === void 0
1060
+ ? void 0
1061
+ : updateAnswer.excludeFiles) !== null && _j !== void 0
1062
+ ? _j
1063
+ : [],
1064
+ };
1065
+ fs.writeFileSync(
1066
+ path.join(projectPath, "prisma-php.json"),
1067
+ JSON.stringify(prismaPhpConfig, null, 2),
1068
+ { flag: "w" }
1069
+ );
1070
+ if (
1071
+ updateAnswer === null || updateAnswer === void 0
1072
+ ? void 0
1073
+ : updateAnswer.isUpdate
1074
+ ) {
1075
+ execSync(
1076
+ `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update`,
1077
+ {
1078
+ stdio: "inherit",
950
1079
  }
951
- else {
952
- execSync(`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`, {
953
- stdio: "inherit",
954
- });
1080
+ );
1081
+ } else {
1082
+ execSync(
1083
+ `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`,
1084
+ {
1085
+ stdio: "inherit",
955
1086
  }
956
- console.log(`${chalk.green("Success!")} Prisma PHP project successfully created in ${answer.projectName}!`);
957
- }
958
- catch (error) {
959
- console.error("Error while creating the project:", error);
960
- process.exit(1);
1087
+ );
961
1088
  }
1089
+ console.log(
1090
+ `${chalk.green("Success!")} Prisma PHP project successfully created in ${
1091
+ answer.projectName
1092
+ }!`
1093
+ );
1094
+ } catch (error) {
1095
+ console.error("Error while creating the project:", error);
1096
+ process.exit(1);
1097
+ }
962
1098
  }
963
1099
  main();