create-prisma-php-app 1.11.536 → 1.11.537

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +726 -601
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -10,43 +10,51 @@ const __filename = fileURLToPath(import.meta.url);
10
10
  const __dirname = path.dirname(__filename);
11
11
  let updateAnswer = null;
12
12
  function bsConfigUrls(projectSettings) {
13
- // Identify the base path dynamically up to and including 'htdocs'
14
- const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");
15
- if (htdocsIndex === -1) {
16
- console.error("Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\");
17
- return {
18
- bsTarget: "",
19
- bsPathRewrite: {},
20
- };
21
- }
22
- // Extract the path up to and including 'htdocs\\'
23
- const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(0, htdocsIndex + "\\htdocs\\".length);
24
- // Escape backslashes for the regex pattern
25
- const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
26
- // Remove the base path and replace backslashes with forward slashes for URL compatibility
27
- const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(new RegExp(`^${escapedBasePathToRemove}`), "").replace(/\\/g, "/");
28
- // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
29
- let proxyUrl = `http://localhost/${relativeWebPath}`;
30
- // Ensure the proxy URL does not end with a slash before appending '/public'
31
- proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
32
- // Clean the URL by replacing "//" with "/" but not affecting "http://"
33
- // We replace instances of "//" that are not preceded by ":"
34
- const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
35
- const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
36
- // Correct the relativeWebPath to ensure it does not start with a "/"
37
- const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
38
- ? cleanRelativeWebPath.substring(1)
39
- : cleanRelativeWebPath;
13
+ // Identify the base path dynamically up to and including 'htdocs'
14
+ const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");
15
+ if (htdocsIndex === -1) {
16
+ console.error(
17
+ "Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\"
18
+ );
40
19
  return {
41
- bsTarget: `${cleanUrl}/`,
42
- bsPathRewrite: {
43
- "^/": `/${adjustedRelativeWebPath}/`,
44
- },
20
+ bsTarget: "",
21
+ bsPathRewrite: {},
45
22
  };
23
+ }
24
+ // Extract the path up to and including 'htdocs\\'
25
+ const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(
26
+ 0,
27
+ htdocsIndex + "\\htdocs\\".length
28
+ );
29
+ // Escape backslashes for the regex pattern
30
+ const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
31
+ // Remove the base path and replace backslashes with forward slashes for URL compatibility
32
+ const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(
33
+ new RegExp(`^${escapedBasePathToRemove}`),
34
+ ""
35
+ ).replace(/\\/g, "/");
36
+ // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
37
+ let proxyUrl = `http://localhost/${relativeWebPath}`;
38
+ // Ensure the proxy URL does not end with a slash before appending '/public'
39
+ proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
40
+ // Clean the URL by replacing "//" with "/" but not affecting "http://"
41
+ // We replace instances of "//" that are not preceded by ":"
42
+ const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
43
+ const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
44
+ // Correct the relativeWebPath to ensure it does not start with a "/"
45
+ const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
46
+ ? cleanRelativeWebPath.substring(1)
47
+ : cleanRelativeWebPath;
48
+ return {
49
+ bsTarget: `${cleanUrl}/`,
50
+ bsPathRewrite: {
51
+ "^/": `/${adjustedRelativeWebPath}/`,
52
+ },
53
+ };
46
54
  }
47
55
  function configureBrowserSyncCommand(baseDir) {
48
- // TypeScript content to write
49
- const bsConfigTsContent = `const { createProxyMiddleware } = require("http-proxy-middleware");
56
+ // TypeScript content to write
57
+ const bsConfigTsContent = `const { createProxyMiddleware } = require("http-proxy-middleware");
50
58
  const fs = require("fs");
51
59
 
52
60
  const jsonData = fs.readFileSync("prisma-php.json", "utf8");
@@ -72,291 +80,341 @@ module.exports = {
72
80
  open: false,
73
81
  ghostMode: false,
74
82
  };`;
75
- // Determine the path and write the bs-config.js
76
- const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
77
- fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
78
- // Return the Browser Sync command string, using the cleaned URL
79
- return `browser-sync start --config settings/bs-config.cjs`;
83
+ // Determine the path and write the bs-config.js
84
+ const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
85
+ fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
86
+ // Return the Browser Sync command string, using the cleaned URL
87
+ return `browser-sync start --config settings/bs-config.cjs`;
80
88
  }
81
89
  async function updatePackageJson(baseDir, answer) {
82
- const packageJsonPath = path.join(baseDir, "package.json");
83
- if (checkExcludeFiles(packageJsonPath))
84
- return;
85
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
86
- // Use the new function to configure the Browser Sync command
87
- const browserSyncCommand = configureBrowserSyncCommand(baseDir);
88
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { projectName: "node settings/project-name.cjs" });
89
- let answersToInclude = [];
90
- if (answer.tailwindcss) {
91
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { tailwind: "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch" });
92
- answersToInclude.push("tailwind");
93
- }
94
- if (answer.websocket) {
95
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { websocket: "node ./settings/restart-websocket.cjs" });
96
- answersToInclude.push("websocket");
97
- }
98
- // if (answer.prisma) {
99
- // packageJson.scripts = {
100
- // ...packageJson.scripts,
101
- // postinstall: "prisma generate",
102
- // };
103
- // }
104
- // Initialize with existing scripts
105
- const updatedScripts = Object.assign({}, packageJson.scripts);
106
- // Conditionally add "browser-sync" command
107
- updatedScripts["browser-sync"] = browserSyncCommand;
108
- // Conditionally set the "dev" command
109
- updatedScripts.dev =
110
- answersToInclude.length > 0
111
- ? `npm-run-all --parallel projectName browser-sync ${answersToInclude.join(" ")}`
112
- : `npm-run-all --parallel projectName browser-sync`;
113
- // Finally, assign the updated scripts back to packageJson
114
- packageJson.scripts = updatedScripts;
115
- packageJson.type = "module";
116
- if (answer.prisma)
117
- packageJson.prisma = {
118
- seed: "node prisma/seed.js",
119
- };
120
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
90
+ const packageJsonPath = path.join(baseDir, "package.json");
91
+ if (checkExcludeFiles(packageJsonPath)) return;
92
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
93
+ // Use the new function to configure the Browser Sync command
94
+ const browserSyncCommand = configureBrowserSyncCommand(baseDir);
95
+ packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), {
96
+ projectName: "node settings/project-name.cjs",
97
+ });
98
+ let answersToInclude = [];
99
+ if (answer.tailwindcss) {
100
+ packageJson.scripts = Object.assign(
101
+ Object.assign({}, packageJson.scripts),
102
+ {
103
+ tailwind:
104
+ "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch",
105
+ }
106
+ );
107
+ answersToInclude.push("tailwind");
108
+ }
109
+ if (answer.websocket) {
110
+ packageJson.scripts = Object.assign(
111
+ Object.assign({}, packageJson.scripts),
112
+ { websocket: "node ./settings/restart-websocket.cjs" }
113
+ );
114
+ answersToInclude.push("websocket");
115
+ }
116
+ // if (answer.prisma) {
117
+ // packageJson.scripts = {
118
+ // ...packageJson.scripts,
119
+ // postinstall: "prisma generate",
120
+ // };
121
+ // }
122
+ // Initialize with existing scripts
123
+ const updatedScripts = Object.assign({}, packageJson.scripts);
124
+ // Conditionally add "browser-sync" command
125
+ updatedScripts["browser-sync"] = browserSyncCommand;
126
+ // Conditionally set the "dev" command
127
+ updatedScripts.dev =
128
+ answersToInclude.length > 0
129
+ ? `npm-run-all --parallel projectName browser-sync ${answersToInclude.join(
130
+ " "
131
+ )}`
132
+ : `npm-run-all --parallel projectName browser-sync`;
133
+ // Finally, assign the updated scripts back to packageJson
134
+ packageJson.scripts = updatedScripts;
135
+ packageJson.type = "module";
136
+ if (answer.prisma)
137
+ packageJson.prisma = {
138
+ seed: "node prisma/seed.js",
139
+ };
140
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
121
141
  }
122
142
  async function updateComposerJson(baseDir, answer) {
123
- const composerJsonPath = path.join(baseDir, "composer.json");
124
- if (checkExcludeFiles(composerJsonPath))
125
- return;
126
- let composerJson;
127
- // Check if the composer.json file exists
128
- if (fs.existsSync(composerJsonPath)) {
129
- // Read the current composer.json content
130
- const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
131
- composerJson = JSON.parse(composerJsonContent);
132
- }
133
- else {
134
- console.error("composer.json does not exist.");
135
- return;
136
- }
137
- // Conditionally add WebSocket dependency
138
- if (answer.websocket) {
139
- composerJson.require = Object.assign(Object.assign({}, composerJson.require), { "cboden/ratchet": "^0.4.4" });
140
- }
141
- if (answer.prisma) {
142
- composerJson.require = Object.assign(Object.assign({}, composerJson.require), { "ramsey/uuid": "5.x-dev", "hidehalo/nanoid-php": "1.x-dev" });
143
- }
144
- // Write the modified composer.json back to the file
145
- fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
146
- console.log("composer.json updated successfully.");
143
+ const composerJsonPath = path.join(baseDir, "composer.json");
144
+ if (checkExcludeFiles(composerJsonPath)) return;
145
+ let composerJson;
146
+ // Check if the composer.json file exists
147
+ if (fs.existsSync(composerJsonPath)) {
148
+ // Read the current composer.json content
149
+ const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
150
+ composerJson = JSON.parse(composerJsonContent);
151
+ } else {
152
+ console.error("composer.json does not exist.");
153
+ return;
154
+ }
155
+ // Conditionally add WebSocket dependency
156
+ if (answer.websocket) {
157
+ composerJson.require = Object.assign(
158
+ Object.assign({}, composerJson.require),
159
+ { "cboden/ratchet": "^0.4.4" }
160
+ );
161
+ }
162
+ if (answer.prisma) {
163
+ composerJson.require = Object.assign(
164
+ Object.assign({}, composerJson.require),
165
+ { "ramsey/uuid": "5.x-dev", "hidehalo/nanoid-php": "1.x-dev" }
166
+ );
167
+ }
168
+ // Write the modified composer.json back to the file
169
+ fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
170
+ console.log("composer.json updated successfully.");
147
171
  }
148
172
  async function updateIndexJsForWebSocket(baseDir, answer) {
149
- if (!answer.websocket) {
150
- return;
151
- }
152
- const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
153
- if (checkExcludeFiles(indexPath))
154
- return;
155
- let indexContent = fs.readFileSync(indexPath, "utf8");
156
- // WebSocket initialization code to be appended
157
- const webSocketCode = `
173
+ if (!answer.websocket) {
174
+ return;
175
+ }
176
+ const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
177
+ if (checkExcludeFiles(indexPath)) return;
178
+ let indexContent = fs.readFileSync(indexPath, "utf8");
179
+ // WebSocket initialization code to be appended
180
+ const webSocketCode = `
158
181
  // WebSocket initialization
159
182
  const ws = new WebSocket("ws://localhost:8080");
160
183
  `;
161
- // Append WebSocket code if user chose to use WebSocket
162
- indexContent += webSocketCode;
163
- fs.writeFileSync(indexPath, indexContent, "utf8");
164
- console.log("WebSocket code added to index.js successfully.");
184
+ // Append WebSocket code if user chose to use WebSocket
185
+ indexContent += webSocketCode;
186
+ fs.writeFileSync(indexPath, indexContent, "utf8");
187
+ console.log("WebSocket code added to index.js successfully.");
165
188
  }
166
189
  // This function updates the .gitignore file
167
190
  async function createUpdateGitignoreFile(baseDir, additions) {
168
- const gitignorePath = path.join(baseDir, ".gitignore");
169
- if (checkExcludeFiles(gitignorePath))
170
- return;
171
- // Check if the .gitignore file exists, create if it doesn't
172
- let gitignoreContent = "";
173
- if (fs.existsSync(gitignorePath)) {
174
- gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
191
+ const gitignorePath = path.join(baseDir, ".gitignore");
192
+ if (checkExcludeFiles(gitignorePath)) return;
193
+ // Check if the .gitignore file exists, create if it doesn't
194
+ let gitignoreContent = "";
195
+ if (fs.existsSync(gitignorePath)) {
196
+ gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
197
+ }
198
+ additions.forEach((addition) => {
199
+ if (!gitignoreContent.includes(addition)) {
200
+ gitignoreContent += `\n${addition}`;
175
201
  }
176
- additions.forEach((addition) => {
177
- if (!gitignoreContent.includes(addition)) {
178
- gitignoreContent += `\n${addition}`;
179
- }
180
- });
181
- // Ensure there's no leading newline if the file was just created
182
- gitignoreContent = gitignoreContent.trimStart();
183
- fs.writeFileSync(gitignorePath, gitignoreContent);
202
+ });
203
+ // Ensure there's no leading newline if the file was just created
204
+ gitignoreContent = gitignoreContent.trimStart();
205
+ fs.writeFileSync(gitignorePath, gitignoreContent);
184
206
  }
185
207
  // Recursive copy function
186
208
  function copyRecursiveSync(src, dest, answer) {
187
- console.log("🚀 ~ copyRecursiveSync ~ dest:", dest);
188
- console.log("🚀 ~ copyRecursiveSync ~ src:", src);
189
- const exists = fs.existsSync(src);
190
- const stats = exists && fs.statSync(src);
191
- const isDirectory = exists && stats && stats.isDirectory();
192
- if (isDirectory) {
193
- if (!fs.existsSync(dest))
194
- fs.mkdirSync(dest, { recursive: true });
195
- fs.readdirSync(src).forEach((childItemName) => {
196
- copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName), answer);
197
- });
198
- }
199
- else {
200
- if (checkExcludeFiles(dest))
201
- return;
202
- if (!answer.tailwindcss &&
203
- (dest.includes("tailwind.css") || dest.includes("styles.css")))
204
- return;
205
- if (!answer.websocket &&
206
- (dest.includes("restart-websocket.cjs") ||
207
- dest.includes("restart-websocket.bat")))
208
- return;
209
- fs.copyFileSync(src, dest, 0);
210
- }
209
+ console.log("🚀 ~ copyRecursiveSync ~ dest:", dest);
210
+ console.log("🚀 ~ copyRecursiveSync ~ src:", src);
211
+ const exists = fs.existsSync(src);
212
+ const stats = exists && fs.statSync(src);
213
+ const isDirectory = exists && stats && stats.isDirectory();
214
+ if (isDirectory) {
215
+ if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
216
+ fs.readdirSync(src).forEach((childItemName) => {
217
+ copyRecursiveSync(
218
+ path.join(src, childItemName),
219
+ path.join(dest, childItemName),
220
+ answer
221
+ );
222
+ });
223
+ } else {
224
+ if (checkExcludeFiles(dest)) return;
225
+ if (
226
+ !answer.tailwindcss &&
227
+ (dest.includes("tailwind.css") || dest.includes("styles.css"))
228
+ )
229
+ return;
230
+ if (
231
+ !answer.websocket &&
232
+ (dest.includes("restart-websocket.cjs") ||
233
+ dest.includes("restart-websocket.bat"))
234
+ )
235
+ return;
236
+ fs.copyFileSync(src, dest, 0);
237
+ }
211
238
  }
212
239
  // Function to execute the recursive copy for entire directories
213
240
  async function executeCopy(baseDir, directoriesToCopy, answer) {
214
- directoriesToCopy.forEach(({ srcDir, destDir }) => {
215
- const sourcePath = path.join(__dirname, srcDir);
216
- const destPath = path.join(baseDir, destDir);
217
- const destLower = destPath.toLowerCase();
218
- if (!answer.websocket &&
219
- (destLower.includes("src\\lib\\websocket") ||
220
- destLower.includes("src/lib/websocket")))
221
- return;
222
- // if (!answer.prisma && dest.toLowerCase().includes("Prisma")) return;
223
- copyRecursiveSync(sourcePath, destPath, answer);
224
- });
241
+ directoriesToCopy.forEach(({ srcDir, destDir }) => {
242
+ const sourcePath = path.join(__dirname, srcDir);
243
+ const destPath = path.join(baseDir, destDir);
244
+ const destLower = destPath.toLowerCase();
245
+ console.log("🚀 ~ directoriesToCopy.forEach ~ destLower:", destLower);
246
+ const destIncludeWebsocket = destLower.includes("src\\\\lib\\\\websocket");
247
+ console.log(
248
+ "🚀 ~ directoriesToCopy.forEach ~ destIncludeWebsocket:",
249
+ destIncludeWebsocket
250
+ );
251
+ if (
252
+ !answer.websocket &&
253
+ (destLower.includes("src\\\\lib\\\\websocket") ||
254
+ destLower.includes("src/lib/websocket"))
255
+ )
256
+ return;
257
+ // if (!answer.prisma && dest.toLowerCase().includes("Prisma")) return;
258
+ copyRecursiveSync(sourcePath, destPath, answer);
259
+ });
225
260
  }
226
261
  function createOrUpdateTailwindConfig(baseDir) {
227
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ baseDir:", baseDir);
228
- const filePath = path.join(baseDir, "tailwind.config.js");
229
- if (checkExcludeFiles(filePath))
230
- return;
231
- const newContent = [
232
- "./src/app/**/*.{html,js,php}",
233
- // Add more paths as needed
234
- ];
235
- let configData = fs.readFileSync(filePath, "utf8");
236
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ configData:", configData);
237
- const contentArrayString = newContent
238
- .map((item) => ` "${item}"`)
239
- .join(",\n");
240
- configData = configData.replace(/content: \[\],/g, `content: [\n${contentArrayString}\n],`);
241
- fs.writeFileSync(filePath, configData, { flag: "w" });
242
- 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/app/**/*.{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."));
243
280
  }
244
281
  function modifyPostcssConfig(baseDir) {
245
- const filePath = path.join(baseDir, "postcss.config.js");
246
- if (checkExcludeFiles(filePath))
247
- return;
248
- const newContent = `export default {
282
+ const filePath = path.join(baseDir, "postcss.config.js");
283
+ if (checkExcludeFiles(filePath)) return;
284
+ const newContent = `export default {
249
285
  plugins: {
250
286
  tailwindcss: {},
251
287
  autoprefixer: {},
252
288
  cssnano: {},
253
289
  },
254
290
  };`;
255
- fs.writeFileSync(filePath, newContent, { flag: "w" });
256
- 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."));
257
293
  }
258
294
  function modifyLayoutPHP(baseDir, useTailwind) {
259
- const layoutPath = path.join(baseDir, "src", "app", "layout.php");
260
- if (checkExcludeFiles(layoutPath))
261
- return;
262
- try {
263
- let indexContent = fs.readFileSync(layoutPath, "utf8");
264
- const stylesAndLinks = `\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"></script>\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">`;
265
- // Tailwind CSS link or CDN script
266
- const tailwindLink = useTailwind
267
- ? ` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
268
- : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
269
- // Insert before the closing </head> tag
270
- indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
271
- fs.writeFileSync(layoutPath, indexContent, { flag: "w" });
272
- console.log(chalk.green(`index.php modified successfully for ${useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"}.`));
273
- }
274
- catch (error) {
275
- console.error(chalk.red("Error modifying index.php:"), error);
276
- }
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
+ const stylesAndLinks = `\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"></script>\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">`;
300
+ // Tailwind CSS link or CDN script
301
+ const tailwindLink = useTailwind
302
+ ? ` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
303
+ : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
304
+ // Insert before the closing </head> tag
305
+ indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
306
+ fs.writeFileSync(layoutPath, indexContent, { flag: "w" });
307
+ console.log(
308
+ chalk.green(
309
+ `index.php modified successfully for ${
310
+ useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"
311
+ }.`
312
+ )
313
+ );
314
+ } catch (error) {
315
+ console.error(chalk.red("Error modifying index.php:"), error);
316
+ }
277
317
  }
278
318
  // This function updates or creates the .env file
279
319
  async function createOrUpdateEnvFile(baseDir, content) {
280
- const envPath = path.join(baseDir, ".env");
281
- if (checkExcludeFiles(envPath))
282
- return;
283
- let envContent = fs.existsSync(envPath)
284
- ? fs.readFileSync(envPath, "utf8")
285
- : "";
286
- // Check if the content already exists in the .env file
287
- if (!envContent.includes(content)) {
288
- envContent += `${envContent !== "" ? "\n\n" : ""}${content}`;
289
- fs.writeFileSync(envPath, envContent, { flag: "w" });
290
- }
291
- else {
292
- console.log(".env file already contains the content.");
293
- }
320
+ const envPath = path.join(baseDir, ".env");
321
+ if (checkExcludeFiles(envPath)) return;
322
+ let envContent = fs.existsSync(envPath)
323
+ ? fs.readFileSync(envPath, "utf8")
324
+ : "";
325
+ // Check if the content already exists in the .env file
326
+ if (!envContent.includes(content)) {
327
+ envContent += `${envContent !== "" ? "\n\n" : ""}${content}`;
328
+ fs.writeFileSync(envPath, envContent, { flag: "w" });
329
+ } else {
330
+ console.log(".env file already contains the content.");
331
+ }
294
332
  }
295
333
  function checkExcludeFiles(destPath) {
296
- var _a, _b;
297
- if (!(updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate))
298
- return false;
299
- 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);
334
+ var _a, _b;
335
+ if (
336
+ !(updateAnswer === null || updateAnswer === void 0
337
+ ? void 0
338
+ : updateAnswer.isUpdate)
339
+ )
340
+ return false;
341
+ return (_b =
342
+ (_a =
343
+ updateAnswer === null || updateAnswer === void 0
344
+ ? void 0
345
+ : updateAnswer.excludeFilePath) === null || _a === void 0
346
+ ? void 0
347
+ : _a.includes(destPath.replace(/\\/g, "/"))) !== null && _b !== void 0
348
+ ? _b
349
+ : false;
300
350
  }
301
351
  async function createDirectoryStructure(baseDir, answer) {
302
- console.log("🚀 ~ baseDir:", baseDir);
303
- console.log("🚀 ~ answer:", answer);
304
- const filesToCopy = [
305
- { src: "/bootstrap.php", dest: "/bootstrap.php" },
306
- { src: "/.htaccess", dest: "/.htaccess" },
307
- { src: "/../composer.json", dest: "/composer.json" },
308
- ];
309
- if (updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate) {
310
- filesToCopy.push({ src: "/.env", dest: "/.env" }, { src: "/tsconfig.json", dest: "/tsconfig.json" });
311
- if (updateAnswer.tailwindcss) {
312
- filesToCopy.push({ src: "/postcss.config.js", dest: "/postcss.config.js" }, { src: "/tailwind.config.js", dest: "/tailwind.config.js" });
313
- }
352
+ console.log("🚀 ~ baseDir:", baseDir);
353
+ console.log("🚀 ~ answer:", answer);
354
+ const filesToCopy = [
355
+ { src: "/bootstrap.php", dest: "/bootstrap.php" },
356
+ { src: "/.htaccess", dest: "/.htaccess" },
357
+ { src: "/../composer.json", dest: "/composer.json" },
358
+ ];
359
+ if (
360
+ updateAnswer === null || updateAnswer === void 0
361
+ ? void 0
362
+ : updateAnswer.isUpdate
363
+ ) {
364
+ filesToCopy.push(
365
+ { src: "/.env", dest: "/.env" },
366
+ { src: "/tsconfig.json", dest: "/tsconfig.json" }
367
+ );
368
+ if (updateAnswer.tailwindcss) {
369
+ filesToCopy.push(
370
+ { src: "/postcss.config.js", dest: "/postcss.config.js" },
371
+ { src: "/tailwind.config.js", dest: "/tailwind.config.js" }
372
+ );
314
373
  }
315
- const directoriesToCopy = [
316
- {
317
- srcDir: "/settings",
318
- destDir: "/settings",
319
- },
320
- {
321
- srcDir: "/src",
322
- destDir: "/src",
323
- },
324
- ];
325
- if (answer.prisma) {
326
- directoriesToCopy.push({
327
- srcDir: "/prisma",
328
- destDir: "/prisma",
329
- });
330
- }
331
- console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
332
- filesToCopy.forEach(({ src, dest }) => {
333
- const sourcePath = path.join(__dirname, src);
334
- const destPath = path.join(baseDir, dest);
335
- if (checkExcludeFiles(destPath))
336
- return;
337
- const code = fs.readFileSync(sourcePath, "utf8");
338
- fs.writeFileSync(destPath, code, { flag: "w" });
374
+ }
375
+ const directoriesToCopy = [
376
+ {
377
+ srcDir: "/settings",
378
+ destDir: "/settings",
379
+ },
380
+ {
381
+ srcDir: "/src",
382
+ destDir: "/src",
383
+ },
384
+ ];
385
+ if (answer.prisma) {
386
+ directoriesToCopy.push({
387
+ srcDir: "/prisma",
388
+ destDir: "/prisma",
339
389
  });
340
- await executeCopy(baseDir, directoriesToCopy, answer);
341
- await updatePackageJson(baseDir, answer);
342
- await updateComposerJson(baseDir, answer);
343
- await updateIndexJsForWebSocket(baseDir, answer);
344
- if (answer.tailwindcss) {
345
- createOrUpdateTailwindConfig(baseDir);
346
- modifyLayoutPHP(baseDir, true);
347
- modifyPostcssConfig(baseDir);
348
- }
349
- else {
350
- modifyLayoutPHP(baseDir, false);
351
- }
352
- const prismaEnvContent = `# Environment variables declared in this file are automatically made available to Prisma.
390
+ }
391
+ console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
392
+ filesToCopy.forEach(({ src, dest }) => {
393
+ const sourcePath = path.join(__dirname, src);
394
+ const destPath = path.join(baseDir, dest);
395
+ if (checkExcludeFiles(destPath)) return;
396
+ const code = fs.readFileSync(sourcePath, "utf8");
397
+ fs.writeFileSync(destPath, code, { flag: "w" });
398
+ });
399
+ await executeCopy(baseDir, directoriesToCopy, answer);
400
+ await updatePackageJson(baseDir, answer);
401
+ await updateComposerJson(baseDir, answer);
402
+ await updateIndexJsForWebSocket(baseDir, answer);
403
+ if (answer.tailwindcss) {
404
+ createOrUpdateTailwindConfig(baseDir);
405
+ modifyLayoutPHP(baseDir, true);
406
+ modifyPostcssConfig(baseDir);
407
+ } else {
408
+ modifyLayoutPHP(baseDir, false);
409
+ }
410
+ const prismaEnvContent = `# Environment variables declared in this file are automatically made available to Prisma.
353
411
  # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
354
412
 
355
413
  # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
356
414
  # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
357
415
 
358
416
  DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"`;
359
- const prismaPHPEnvContent = `# Prisma PHP Auth Secret Key For development only - Change this in production
417
+ const prismaPHPEnvContent = `# Prisma PHP Auth Secret Key For development only - Change this in production
360
418
  AUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4=
361
419
 
362
420
  # PHPMailer
@@ -367,84 +425,93 @@ AUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4=
367
425
  # SMTP_ENCRYPTION=ssl or tls
368
426
  # MAIL_FROM=john.doe@gmail.com
369
427
  # MAIL_FROM_NAME="John Doe"`;
370
- let envContent = prismaPHPEnvContent;
371
- if (answer.prisma) {
372
- envContent = `${prismaEnvContent}\n\n${prismaPHPEnvContent}`;
373
- await createOrUpdateEnvFile(baseDir, envContent);
374
- }
375
- else {
376
- await createOrUpdateEnvFile(baseDir, envContent);
377
- }
378
- // Add vendor to .gitignore
379
- await createUpdateGitignoreFile(baseDir, ["vendor", ".env", "node_modules"]);
428
+ let envContent = prismaPHPEnvContent;
429
+ if (answer.prisma) {
430
+ envContent = `${prismaEnvContent}\n\n${prismaPHPEnvContent}`;
431
+ await createOrUpdateEnvFile(baseDir, envContent);
432
+ } else {
433
+ await createOrUpdateEnvFile(baseDir, envContent);
434
+ }
435
+ // Add vendor to .gitignore
436
+ await createUpdateGitignoreFile(baseDir, ["vendor", ".env", "node_modules"]);
380
437
  }
381
438
  async function getAnswer(predefinedAnswers = {}) {
382
- var _a, _b, _c, _d;
383
- console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
384
- const questionsArray = [];
385
- if (!predefinedAnswers.projectName) {
386
- questionsArray.push({
387
- type: "text",
388
- name: "projectName",
389
- message: "What is your project named?",
390
- initial: "my-app",
391
- });
392
- }
393
- if (!predefinedAnswers.tailwindcss) {
394
- questionsArray.push({
395
- type: "toggle",
396
- name: "tailwindcss",
397
- message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
398
- initial: true,
399
- active: "Yes",
400
- inactive: "No",
401
- });
402
- }
403
- if (!predefinedAnswers.websocket) {
404
- questionsArray.push({
405
- type: "toggle",
406
- name: "websocket",
407
- message: `Would you like to use ${chalk.blue("Websocket")}?`,
408
- initial: true,
409
- active: "Yes",
410
- inactive: "No",
411
- });
412
- }
413
- if (!predefinedAnswers.prisma) {
414
- questionsArray.push({
415
- type: "toggle",
416
- name: "prisma",
417
- message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
418
- initial: true,
419
- active: "Yes",
420
- inactive: "No",
421
- });
439
+ var _a, _b, _c, _d;
440
+ console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
441
+ const questionsArray = [];
442
+ if (!predefinedAnswers.projectName) {
443
+ questionsArray.push({
444
+ type: "text",
445
+ name: "projectName",
446
+ message: "What is your project named?",
447
+ initial: "my-app",
448
+ });
449
+ }
450
+ if (!predefinedAnswers.tailwindcss) {
451
+ questionsArray.push({
452
+ type: "toggle",
453
+ name: "tailwindcss",
454
+ message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
455
+ initial: true,
456
+ active: "Yes",
457
+ inactive: "No",
458
+ });
459
+ }
460
+ if (!predefinedAnswers.websocket) {
461
+ questionsArray.push({
462
+ type: "toggle",
463
+ name: "websocket",
464
+ message: `Would you like to use ${chalk.blue("Websocket")}?`,
465
+ initial: true,
466
+ active: "Yes",
467
+ inactive: "No",
468
+ });
469
+ }
470
+ if (!predefinedAnswers.prisma) {
471
+ questionsArray.push({
472
+ type: "toggle",
473
+ name: "prisma",
474
+ message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
475
+ initial: true,
476
+ active: "Yes",
477
+ inactive: "No",
478
+ });
479
+ }
480
+ const questions = questionsArray;
481
+ console.log("🚀 ~ questions:", questions);
482
+ const onCancel = () => {
483
+ console.log(chalk.red("Operation cancelled by the user."));
484
+ process.exit(0);
485
+ };
486
+ try {
487
+ const response = await prompts(questions, { onCancel });
488
+ console.log("🚀 ~ response:", response);
489
+ if (Object.keys(response).length === 0) {
490
+ return null;
422
491
  }
423
- const questions = questionsArray;
424
- console.log("🚀 ~ questions:", questions);
425
- const onCancel = () => {
426
- console.log(chalk.red("Operation cancelled by the user."));
427
- process.exit(0);
492
+ return {
493
+ projectName: response.projectName
494
+ ? String(response.projectName).trim().replace(/ /g, "-")
495
+ : (_a = predefinedAnswers.projectName) !== null && _a !== void 0
496
+ ? _a
497
+ : "my-app",
498
+ tailwindcss:
499
+ (_b = response.tailwindcss) !== null && _b !== void 0
500
+ ? _b
501
+ : predefinedAnswers.tailwindcss,
502
+ websocket:
503
+ (_c = response.websocket) !== null && _c !== void 0
504
+ ? _c
505
+ : predefinedAnswers.websocket,
506
+ prisma:
507
+ (_d = response.prisma) !== null && _d !== void 0
508
+ ? _d
509
+ : predefinedAnswers.prisma,
428
510
  };
429
- try {
430
- const response = await prompts(questions, { onCancel });
431
- console.log("🚀 ~ response:", response);
432
- if (Object.keys(response).length === 0) {
433
- return null;
434
- }
435
- return {
436
- projectName: response.projectName
437
- ? String(response.projectName).trim().replace(/ /g, "-")
438
- : (_a = predefinedAnswers.projectName) !== null && _a !== void 0 ? _a : "my-app",
439
- tailwindcss: (_b = response.tailwindcss) !== null && _b !== void 0 ? _b : predefinedAnswers.tailwindcss,
440
- websocket: (_c = response.websocket) !== null && _c !== void 0 ? _c : predefinedAnswers.websocket,
441
- prisma: (_d = response.prisma) !== null && _d !== void 0 ? _d : predefinedAnswers.prisma,
442
- };
443
- }
444
- catch (error) {
445
- console.error(chalk.red("Prompt error:"), error);
446
- return null;
447
- }
511
+ } catch (error) {
512
+ console.error(chalk.red("Prompt error:"), error);
513
+ return null;
514
+ }
448
515
  }
449
516
  /**
450
517
  * Install dependencies in the specified directory.
@@ -453,271 +520,329 @@ async function getAnswer(predefinedAnswers = {}) {
453
520
  * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
454
521
  */
455
522
  async function installDependencies(baseDir, dependencies, isDev = false) {
456
- console.log("Initializing new Node.js project...");
457
- // Initialize a package.json if it doesn't exist
458
- if (!fs.existsSync(path.join(baseDir, "package.json")))
459
- execSync("npm init -y", {
460
- stdio: "inherit",
461
- cwd: baseDir,
462
- });
463
- // Log the dependencies being installed
464
- console.log(`${isDev ? "Installing development dependencies" : "Installing dependencies"}:`);
465
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
466
- // Prepare the npm install command with the appropriate flag for dev dependencies
467
- const npmInstallCommand = `npm install ${isDev ? "--save-dev" : ""} ${dependencies.join(" ")}`;
468
- // Execute the npm install command
469
- execSync(npmInstallCommand, {
470
- stdio: "inherit",
471
- cwd: baseDir,
523
+ console.log("Initializing new Node.js project...");
524
+ // Initialize a package.json if it doesn't exist
525
+ if (!fs.existsSync(path.join(baseDir, "package.json")))
526
+ execSync("npm init -y", {
527
+ stdio: "inherit",
528
+ cwd: baseDir,
472
529
  });
530
+ // Log the dependencies being installed
531
+ console.log(
532
+ `${
533
+ isDev ? "Installing development dependencies" : "Installing dependencies"
534
+ }:`
535
+ );
536
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
537
+ // Prepare the npm install command with the appropriate flag for dev dependencies
538
+ const npmInstallCommand = `npm install ${
539
+ isDev ? "--save-dev" : ""
540
+ } ${dependencies.join(" ")}`;
541
+ // Execute the npm install command
542
+ execSync(npmInstallCommand, {
543
+ stdio: "inherit",
544
+ cwd: baseDir,
545
+ });
473
546
  }
474
547
  async function uninstallDependencies(baseDir, dependencies, isDev = false) {
475
- console.log("Uninstalling dependencies:");
476
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
477
- // Prepare the npm uninstall command with the appropriate flag for dev dependencies
478
- const npmUninstallCommand = `npm uninstall ${isDev ? "--save-dev" : "--save"} ${dependencies.join(" ")}`;
479
- // Execute the npm uninstall command
480
- execSync(npmUninstallCommand, {
481
- stdio: "inherit",
482
- cwd: baseDir,
483
- });
548
+ console.log("Uninstalling dependencies:");
549
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
550
+ // Prepare the npm uninstall command with the appropriate flag for dev dependencies
551
+ const npmUninstallCommand = `npm uninstall ${
552
+ isDev ? "--save-dev" : "--save"
553
+ } ${dependencies.join(" ")}`;
554
+ // Execute the npm uninstall command
555
+ execSync(npmUninstallCommand, {
556
+ stdio: "inherit",
557
+ cwd: baseDir,
558
+ });
484
559
  }
485
560
  function fetchPackageVersion(packageName) {
486
- return new Promise((resolve, reject) => {
487
- https
488
- .get(`https://registry.npmjs.org/${packageName}`, (res) => {
489
- let data = "";
490
- res.on("data", (chunk) => (data += chunk));
491
- res.on("end", () => {
492
- try {
493
- const parsed = JSON.parse(data);
494
- resolve(parsed["dist-tags"].latest);
495
- }
496
- catch (error) {
497
- reject(new Error("Failed to parse JSON response"));
498
- }
499
- });
500
- })
501
- .on("error", (err) => reject(err));
502
- });
561
+ return new Promise((resolve, reject) => {
562
+ https
563
+ .get(`https://registry.npmjs.org/${packageName}`, (res) => {
564
+ let data = "";
565
+ res.on("data", (chunk) => (data += chunk));
566
+ res.on("end", () => {
567
+ try {
568
+ const parsed = JSON.parse(data);
569
+ resolve(parsed["dist-tags"].latest);
570
+ } catch (error) {
571
+ reject(new Error("Failed to parse JSON response"));
572
+ }
573
+ });
574
+ })
575
+ .on("error", (err) => reject(err));
576
+ });
503
577
  }
504
578
  const readJsonFile = (filePath) => {
505
- const jsonData = fs.readFileSync(filePath, "utf8");
506
- return JSON.parse(jsonData);
579
+ const jsonData = fs.readFileSync(filePath, "utf8");
580
+ return JSON.parse(jsonData);
507
581
  };
508
582
  async function main() {
509
- var _a, _b, _c, _d, _e, _f;
510
- try {
511
- const args = process.argv.slice(2);
512
- let projectName = args[0];
513
- let answer = null;
514
- if (projectName) {
515
- let useTailwind = args.includes("--tailwindcss");
516
- let useWebsocket = args.includes("--websocket");
517
- let usePrisma = args.includes("--prisma");
518
- const predefinedAnswers = {
519
- projectName,
520
- tailwindcss: useTailwind,
521
- websocket: useWebsocket,
522
- prisma: usePrisma,
523
- };
524
- console.log("🚀 ~ main ~ predefinedAnswers:", predefinedAnswers);
525
- answer = await getAnswer(predefinedAnswers);
526
- if (answer === null) {
527
- console.log(chalk.red("Installation cancelled."));
528
- return;
529
- }
530
- const currentDir = process.cwd();
531
- const configPath = path.join(currentDir, "prisma-php.json");
532
- const localSettings = readJsonFile(configPath);
533
- let excludeFiles = [];
534
- (_a = localSettings.excludeFiles) === null || _a === void 0 ? void 0 : _a.map((file) => {
535
- const filePath = path.join(currentDir, file);
536
- if (fs.existsSync(filePath))
537
- excludeFiles.push(filePath.replace(/\\/g, "/"));
538
- });
539
- updateAnswer = {
540
- projectName,
541
- tailwindcss: (_b = answer === null || answer === void 0 ? void 0 : answer.tailwindcss) !== null && _b !== void 0 ? _b : false,
542
- websocket: (_c = answer === null || answer === void 0 ? void 0 : answer.websocket) !== null && _c !== void 0 ? _c : false,
543
- prisma: (_d = answer === null || answer === void 0 ? void 0 : answer.prisma) !== null && _d !== void 0 ? _d : false,
544
- isUpdate: true,
545
- excludeFiles: (_e = localSettings.excludeFiles) !== null && _e !== void 0 ? _e : [],
546
- excludeFilePath: excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
547
- filePath: currentDir,
548
- };
549
- }
550
- else {
551
- answer = await getAnswer();
552
- }
553
- if (answer === null) {
554
- console.log(chalk.red("Installation cancelled."));
555
- return;
556
- }
557
- execSync(`npm install -g create-prisma-php-app`, { stdio: "inherit" }); // TODO: Uncomment this line before publishing the package
558
- // Support for browser-sync
559
- execSync(`npm install -g browser-sync`, { stdio: "inherit" });
560
- // Create the project directory
561
- if (!projectName)
562
- fs.mkdirSync(answer.projectName);
563
- const currentDir = process.cwd();
564
- let projectPath = projectName
565
- ? currentDir
566
- : path.join(currentDir, answer.projectName);
567
- if (!projectName)
568
- process.chdir(answer.projectName);
569
- const dependencies = [
570
- "typescript",
571
- "@types/node",
572
- "ts-node",
573
- "http-proxy-middleware@^3.0.0",
574
- "npm-run-all",
575
- ];
576
- if (answer.tailwindcss) {
577
- dependencies.push("tailwindcss", "autoprefixer", "postcss", "postcss-cli", "cssnano");
578
- }
579
- if (answer.websocket) {
580
- dependencies.push("chokidar-cli");
581
- }
582
- if (answer.prisma) {
583
- dependencies.push("prisma", "@prisma/client");
584
- }
585
- await installDependencies(projectPath, dependencies, true);
586
- if (!projectName) {
587
- execSync(`npx tsc --init`, { stdio: "inherit" });
588
- }
589
- if (answer.tailwindcss)
590
- execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
591
- if (answer.prisma) {
592
- if (!fs.existsSync(path.join(projectPath, "prisma")))
593
- execSync(`npx prisma init`, { stdio: "inherit" });
594
- }
595
- await createDirectoryStructure(projectPath, answer);
596
- const publicDirPath = path.join(projectPath, "public");
597
- if (!fs.existsSync(publicDirPath)) {
598
- fs.mkdirSync(publicDirPath);
599
- }
600
- // if (!answer.tailwindcss) {
601
- // const cssPath = path.join(projectPath, "src", "app", "css");
602
- // const tailwindFiles = ["tailwind.css", "styles.css"];
603
- // tailwindFiles.forEach((file) => {
604
- // const filePath = path.join(cssPath, file);
605
- // if (fs.existsSync(filePath)) {
606
- // fs.unlinkSync(filePath); // Delete each file if it exists
607
- // console.log(`${file} was deleted successfully.`);
608
- // } else {
609
- // console.log(`${file} does not exist.`);
610
- // }
611
- // });
612
- // }
613
- // Update websocket if not chosen by the user
614
- // if (!answer.websocket) {
615
- // const wsPath = path.join(projectPath, "src", "Lib", "Websocket");
616
- // // Check if the websocket directory exists
617
- // if (fs.existsSync(wsPath)) {
618
- // // Use fs.rmSync with recursive option set to true to delete the directory and its contents
619
- // fs.rmSync(wsPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
620
- // console.log("Websocket directory was deleted successfully.");
621
- // } else {
622
- // console.log("Websocket directory does not exist.");
623
- // }
624
- // // Update settings directory if websocket is not chosen
625
- // const settingsPath = path.join(projectPath, "settings");
626
- // const websocketFiles = ["restart-websocket.cjs", "restart-websocket.bat"];
627
- // websocketFiles.forEach((file) => {
628
- // const filePath = path.join(settingsPath, file);
629
- // if (fs.existsSync(filePath)) {
630
- // fs.unlinkSync(filePath); // Delete each file if it exists
631
- // console.log(`${file} was deleted successfully.`);
632
- // } else {
633
- // console.log(`${file} does not exist.`);
634
- // }
635
- // });
636
- // }
637
- if (!answer.prisma) {
638
- const prismaPath = path.join(projectPath, "prisma");
639
- const prismClassPath = path.join(projectPath, "src", "Lib", "Prisma");
640
- // Check if the prisma directory exists
641
- if (fs.existsSync(prismaPath)) {
642
- // Use fs.rmSync with recursive option set to true to delete the directory and its contents
643
- fs.rmSync(prismaPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
644
- console.log("Prisma directory was deleted successfully.");
645
- }
646
- else {
647
- console.log("Prisma directory does not exist.");
648
- }
649
- // Check if the prisma class directory exists
650
- if (fs.existsSync(prismClassPath)) {
651
- // Use fs.rmSync with recursive option set to true to delete the directory and its contents
652
- fs.rmSync(prismClassPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
653
- console.log("Prisma class directory was deleted successfully.");
654
- }
655
- else {
656
- console.log("Prisma class directory does not exist.");
657
- }
658
- }
659
- if (updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate) {
660
- const updateUninstallDependencies = [];
661
- if (!updateAnswer.tailwindcss) {
662
- const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
663
- tailwindFiles.forEach((file) => {
664
- const filePath = path.join(projectPath, file);
665
- if (fs.existsSync(filePath)) {
666
- fs.unlinkSync(filePath); // Delete each file if it exists
667
- console.log(`${file} was deleted successfully.`);
668
- }
669
- else {
670
- console.log(`${file} does not exist.`);
671
- }
672
- });
673
- updateUninstallDependencies.push("tailwindcss", "autoprefixer", "postcss", "postcss-cli", "cssnano");
674
- }
675
- if (!updateAnswer.websocket) {
676
- updateUninstallDependencies.push("chokidar-cli");
677
- }
678
- if (!updateAnswer.prisma) {
679
- updateUninstallDependencies.push("prisma", "@prisma/client");
680
- }
681
- if (updateUninstallDependencies.length > 0) {
682
- await uninstallDependencies(projectPath, updateUninstallDependencies, true);
683
- }
684
- }
685
- const version = await fetchPackageVersion("create-prisma-php-app");
686
- const projectPathModified = projectPath.replace(/\\/g, "\\");
687
- const PHP_GENERATE_CLASS_PATH = answer.prisma
688
- ? "src/Lib/Prisma/Classes"
689
- : "";
690
- const projectSettings = {
691
- PROJECT_NAME: answer.projectName,
692
- PROJECT_ROOT_PATH: projectPathModified,
693
- PHP_ROOT_PATH_EXE: "C:\\\\xampp\\\\php\\\\php.exe",
694
- PHP_GENERATE_CLASS_PATH,
695
- };
696
- const bsConfig = bsConfigUrls(projectSettings);
697
- const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
698
- const prismaPhpConfig = {
699
- projectName: answer.projectName,
700
- projectRootPath: projectPathModified,
701
- phpEnvironment: "XAMPP",
702
- phpRootPathExe: "C:\\xampp\\php\\php.exe",
703
- phpGenerateClassPath,
704
- bsTarget: bsConfig.bsTarget,
705
- bsPathRewrite: bsConfig.bsPathRewrite,
706
- tailwindcss: answer.tailwindcss,
707
- websocket: answer.websocket,
708
- prisma: answer.prisma,
709
- version,
710
- excludeFiles: (_f = updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.excludeFiles) !== null && _f !== void 0 ? _f : [],
711
- };
712
- fs.writeFileSync(path.join(projectPath, "prisma-php.json"), JSON.stringify(prismaPhpConfig, null, 2), { flag: "w" });
713
- execSync(`D:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`, {
714
- stdio: "inherit",
715
- });
716
- console.log(`${chalk.green("Success!")} Prisma PHP project successfully created in ${answer.projectName}!`);
583
+ var _a, _b, _c, _d, _e, _f;
584
+ try {
585
+ const args = process.argv.slice(2);
586
+ let projectName = args[0];
587
+ let answer = null;
588
+ if (projectName) {
589
+ let useTailwind = args.includes("--tailwindcss");
590
+ let useWebsocket = args.includes("--websocket");
591
+ let usePrisma = args.includes("--prisma");
592
+ const predefinedAnswers = {
593
+ projectName,
594
+ tailwindcss: useTailwind,
595
+ websocket: useWebsocket,
596
+ prisma: usePrisma,
597
+ };
598
+ console.log("🚀 ~ main ~ predefinedAnswers:", predefinedAnswers);
599
+ answer = await getAnswer(predefinedAnswers);
600
+ if (answer === null) {
601
+ console.log(chalk.red("Installation cancelled."));
602
+ return;
603
+ }
604
+ const currentDir = process.cwd();
605
+ const configPath = path.join(currentDir, "prisma-php.json");
606
+ const localSettings = readJsonFile(configPath);
607
+ let excludeFiles = [];
608
+ (_a = localSettings.excludeFiles) === null || _a === void 0
609
+ ? void 0
610
+ : _a.map((file) => {
611
+ const filePath = path.join(currentDir, file);
612
+ if (fs.existsSync(filePath))
613
+ excludeFiles.push(filePath.replace(/\\/g, "/"));
614
+ });
615
+ updateAnswer = {
616
+ projectName,
617
+ tailwindcss:
618
+ (_b =
619
+ answer === null || answer === void 0
620
+ ? void 0
621
+ : answer.tailwindcss) !== null && _b !== void 0
622
+ ? _b
623
+ : false,
624
+ websocket:
625
+ (_c =
626
+ answer === null || answer === void 0
627
+ ? void 0
628
+ : answer.websocket) !== null && _c !== void 0
629
+ ? _c
630
+ : false,
631
+ prisma:
632
+ (_d =
633
+ answer === null || answer === void 0 ? void 0 : answer.prisma) !==
634
+ null && _d !== void 0
635
+ ? _d
636
+ : false,
637
+ isUpdate: true,
638
+ excludeFiles:
639
+ (_e = localSettings.excludeFiles) !== null && _e !== void 0 ? _e : [],
640
+ excludeFilePath:
641
+ excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
642
+ filePath: currentDir,
643
+ };
644
+ } else {
645
+ answer = await getAnswer();
646
+ }
647
+ if (answer === null) {
648
+ console.log(chalk.red("Installation cancelled."));
649
+ return;
650
+ }
651
+ execSync(`npm install -g create-prisma-php-app`, { stdio: "inherit" }); // TODO: Uncomment this line before publishing the package
652
+ // Support for browser-sync
653
+ execSync(`npm install -g browser-sync`, { stdio: "inherit" });
654
+ // Create the project directory
655
+ if (!projectName) fs.mkdirSync(answer.projectName);
656
+ const currentDir = process.cwd();
657
+ let projectPath = projectName
658
+ ? currentDir
659
+ : path.join(currentDir, answer.projectName);
660
+ if (!projectName) process.chdir(answer.projectName);
661
+ const dependencies = [
662
+ "typescript",
663
+ "@types/node",
664
+ "ts-node",
665
+ "http-proxy-middleware@^3.0.0",
666
+ "npm-run-all",
667
+ ];
668
+ if (answer.tailwindcss) {
669
+ dependencies.push(
670
+ "tailwindcss",
671
+ "autoprefixer",
672
+ "postcss",
673
+ "postcss-cli",
674
+ "cssnano"
675
+ );
676
+ }
677
+ if (answer.websocket) {
678
+ dependencies.push("chokidar-cli");
679
+ }
680
+ if (answer.prisma) {
681
+ dependencies.push("prisma", "@prisma/client");
717
682
  }
718
- catch (error) {
719
- console.error("Error while creating the project:", error);
720
- process.exit(1);
683
+ await installDependencies(projectPath, dependencies, true);
684
+ if (!projectName) {
685
+ execSync(`npx tsc --init`, { stdio: "inherit" });
721
686
  }
687
+ if (answer.tailwindcss)
688
+ execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
689
+ if (answer.prisma) {
690
+ if (!fs.existsSync(path.join(projectPath, "prisma")))
691
+ execSync(`npx prisma init`, { stdio: "inherit" });
692
+ }
693
+ await createDirectoryStructure(projectPath, answer);
694
+ const publicDirPath = path.join(projectPath, "public");
695
+ if (!fs.existsSync(publicDirPath)) {
696
+ fs.mkdirSync(publicDirPath);
697
+ }
698
+ // if (!answer.tailwindcss) {
699
+ // const cssPath = path.join(projectPath, "src", "app", "css");
700
+ // const tailwindFiles = ["tailwind.css", "styles.css"];
701
+ // tailwindFiles.forEach((file) => {
702
+ // const filePath = path.join(cssPath, file);
703
+ // if (fs.existsSync(filePath)) {
704
+ // fs.unlinkSync(filePath); // Delete each file if it exists
705
+ // console.log(`${file} was deleted successfully.`);
706
+ // } else {
707
+ // console.log(`${file} does not exist.`);
708
+ // }
709
+ // });
710
+ // }
711
+ // Update websocket if not chosen by the user
712
+ // if (!answer.websocket) {
713
+ // const wsPath = path.join(projectPath, "src", "Lib", "Websocket");
714
+ // // Check if the websocket directory exists
715
+ // if (fs.existsSync(wsPath)) {
716
+ // // Use fs.rmSync with recursive option set to true to delete the directory and its contents
717
+ // fs.rmSync(wsPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
718
+ // console.log("Websocket directory was deleted successfully.");
719
+ // } else {
720
+ // console.log("Websocket directory does not exist.");
721
+ // }
722
+ // // Update settings directory if websocket is not chosen
723
+ // const settingsPath = path.join(projectPath, "settings");
724
+ // const websocketFiles = ["restart-websocket.cjs", "restart-websocket.bat"];
725
+ // websocketFiles.forEach((file) => {
726
+ // const filePath = path.join(settingsPath, file);
727
+ // if (fs.existsSync(filePath)) {
728
+ // fs.unlinkSync(filePath); // Delete each file if it exists
729
+ // console.log(`${file} was deleted successfully.`);
730
+ // } else {
731
+ // console.log(`${file} does not exist.`);
732
+ // }
733
+ // });
734
+ // }
735
+ if (!answer.prisma) {
736
+ const prismaPath = path.join(projectPath, "prisma");
737
+ const prismClassPath = path.join(projectPath, "src", "Lib", "Prisma");
738
+ // Check if the prisma directory exists
739
+ if (fs.existsSync(prismaPath)) {
740
+ // Use fs.rmSync with recursive option set to true to delete the directory and its contents
741
+ fs.rmSync(prismaPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
742
+ console.log("Prisma directory was deleted successfully.");
743
+ } else {
744
+ console.log("Prisma directory does not exist.");
745
+ }
746
+ // Check if the prisma class directory exists
747
+ if (fs.existsSync(prismClassPath)) {
748
+ // Use fs.rmSync with recursive option set to true to delete the directory and its contents
749
+ fs.rmSync(prismClassPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
750
+ console.log("Prisma class directory was deleted successfully.");
751
+ } else {
752
+ console.log("Prisma class directory does not exist.");
753
+ }
754
+ }
755
+ if (
756
+ updateAnswer === null || updateAnswer === void 0
757
+ ? void 0
758
+ : updateAnswer.isUpdate
759
+ ) {
760
+ const updateUninstallDependencies = [];
761
+ if (!updateAnswer.tailwindcss) {
762
+ const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
763
+ tailwindFiles.forEach((file) => {
764
+ const filePath = path.join(projectPath, file);
765
+ if (fs.existsSync(filePath)) {
766
+ fs.unlinkSync(filePath); // Delete each file if it exists
767
+ console.log(`${file} was deleted successfully.`);
768
+ } else {
769
+ console.log(`${file} does not exist.`);
770
+ }
771
+ });
772
+ updateUninstallDependencies.push(
773
+ "tailwindcss",
774
+ "autoprefixer",
775
+ "postcss",
776
+ "postcss-cli",
777
+ "cssnano"
778
+ );
779
+ }
780
+ if (!updateAnswer.websocket) {
781
+ updateUninstallDependencies.push("chokidar-cli");
782
+ }
783
+ if (!updateAnswer.prisma) {
784
+ updateUninstallDependencies.push("prisma", "@prisma/client");
785
+ }
786
+ if (updateUninstallDependencies.length > 0) {
787
+ await uninstallDependencies(
788
+ projectPath,
789
+ updateUninstallDependencies,
790
+ true
791
+ );
792
+ }
793
+ }
794
+ const version = await fetchPackageVersion("create-prisma-php-app");
795
+ const projectPathModified = projectPath.replace(/\\/g, "\\");
796
+ const PHP_GENERATE_CLASS_PATH = answer.prisma
797
+ ? "src/Lib/Prisma/Classes"
798
+ : "";
799
+ const projectSettings = {
800
+ PROJECT_NAME: answer.projectName,
801
+ PROJECT_ROOT_PATH: projectPathModified,
802
+ PHP_ROOT_PATH_EXE: "C:\\\\xampp\\\\php\\\\php.exe",
803
+ PHP_GENERATE_CLASS_PATH,
804
+ };
805
+ const bsConfig = bsConfigUrls(projectSettings);
806
+ const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
807
+ const prismaPhpConfig = {
808
+ projectName: answer.projectName,
809
+ projectRootPath: projectPathModified,
810
+ phpEnvironment: "XAMPP",
811
+ phpRootPathExe: "C:\\xampp\\php\\php.exe",
812
+ phpGenerateClassPath,
813
+ bsTarget: bsConfig.bsTarget,
814
+ bsPathRewrite: bsConfig.bsPathRewrite,
815
+ tailwindcss: answer.tailwindcss,
816
+ websocket: answer.websocket,
817
+ prisma: answer.prisma,
818
+ version,
819
+ excludeFiles:
820
+ (_f =
821
+ updateAnswer === null || updateAnswer === void 0
822
+ ? void 0
823
+ : updateAnswer.excludeFiles) !== null && _f !== void 0
824
+ ? _f
825
+ : [],
826
+ };
827
+ fs.writeFileSync(
828
+ path.join(projectPath, "prisma-php.json"),
829
+ JSON.stringify(prismaPhpConfig, null, 2),
830
+ { flag: "w" }
831
+ );
832
+ execSync(
833
+ `D:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`,
834
+ {
835
+ stdio: "inherit",
836
+ }
837
+ );
838
+ console.log(
839
+ `${chalk.green("Success!")} Prisma PHP project successfully created in ${
840
+ answer.projectName
841
+ }!`
842
+ );
843
+ } catch (error) {
844
+ console.error("Error while creating the project:", error);
845
+ process.exit(1);
846
+ }
722
847
  }
723
848
  main();