create-prisma-php-app 1.6.31 → 1.6.33

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 +446 -500
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -9,40 +9,32 @@ import https from "https";
9
9
  const __filename = fileURLToPath(import.meta.url);
10
10
  const __dirname = path.dirname(__filename);
11
11
  function configureBrowserSyncCommand(baseDir, projectSettings) {
12
- // Identify the base path dynamically up to and including 'htdocs'
13
- const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");
14
- if (htdocsIndex === -1) {
15
- console.error(
16
- "Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\"
17
- );
18
- return ""; // Return an empty string or handle the error as appropriate
19
- }
20
- // Extract the path up to and including 'htdocs\\'
21
- const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(
22
- 0,
23
- htdocsIndex + "\\htdocs\\".length
24
- );
25
- // Escape backslashes for the regex pattern
26
- const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
27
- // Remove the base path and replace backslashes with forward slashes for URL compatibility
28
- const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(
29
- new RegExp(`^${escapedBasePathToRemove}`),
30
- ""
31
- ).replace(/\\/g, "/");
32
- // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
33
- let proxyUrl = `http://localhost/${relativeWebPath}`;
34
- // Ensure the proxy URL does not end with a slash before appending '/public'
35
- proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
36
- // Clean the URL by replacing "//" with "/" but not affecting "http://"
37
- // We replace instances of "//" that are not preceded by ":"
38
- const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
39
- const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
40
- // Correct the relativeWebPath to ensure it does not start with a "/"
41
- const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
42
- ? cleanRelativeWebPath.substring(1)
43
- : cleanRelativeWebPath;
44
- // TypeScript content to write
45
- const bsConfigTsContent = `
12
+ // Identify the base path dynamically up to and including 'htdocs'
13
+ const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");
14
+ if (htdocsIndex === -1) {
15
+ console.error("Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\");
16
+ return ""; // Return an empty string or handle the error as appropriate
17
+ }
18
+ // Extract the path up to and including 'htdocs\\'
19
+ const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(0, htdocsIndex + "\\htdocs\\".length);
20
+ // Escape backslashes for the regex pattern
21
+ const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
22
+ // Remove the base path and replace backslashes with forward slashes for URL compatibility
23
+ const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(new RegExp(`^${escapedBasePathToRemove}`), "").replace(/\\/g, "/");
24
+ // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
25
+ let proxyUrl = `http://localhost/${relativeWebPath}`;
26
+ // Ensure the proxy URL does not end with a slash before appending '/public'
27
+ proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
28
+ // Clean the URL by replacing "//" with "/" but not affecting "http://"
29
+ // We replace instances of "//" that are not preceded by ":"
30
+ const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
31
+ const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
32
+ // Correct the relativeWebPath to ensure it does not start with a "/"
33
+ const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
34
+ ? cleanRelativeWebPath.substring(1)
35
+ : cleanRelativeWebPath;
36
+ // TypeScript content to write
37
+ const bsConfigTsContent = `
46
38
  const { createProxyMiddleware } = require("http-proxy-middleware");
47
39
 
48
40
  module.exports = {
@@ -72,261 +64,237 @@ function configureBrowserSyncCommand(baseDir, projectSettings) {
72
64
  open: false,
73
65
  ghostMode: false,
74
66
  };`;
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`;
67
+ // Determine the path and write the bs-config.js
68
+ const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
69
+ fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
70
+ // Return the Browser Sync command string, using the cleaned URL
71
+ return `browser-sync start --config settings/bs-config.cjs`;
80
72
  }
81
73
  async function updatePackageJson(baseDir, projectSettings, answer) {
82
- const packageJsonPath = path.join(baseDir, "package.json");
83
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
84
- // Use the new function to configure the Browser Sync command
85
- const browserSyncCommand = configureBrowserSyncCommand(
86
- baseDir,
87
- projectSettings
88
- );
89
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), {
90
- postinstall: "prisma generate",
91
- });
92
- let answersToInclude = [];
93
- if (answer.tailwindcss) {
94
- packageJson.scripts = Object.assign(
95
- Object.assign({}, packageJson.scripts),
96
- {
97
- tailwind:
98
- "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch",
99
- }
100
- );
101
- answersToInclude.push("tailwind");
102
- }
103
- if (answer.websocket) {
104
- packageJson.scripts = Object.assign(
105
- Object.assign({}, packageJson.scripts),
106
- { websocket: "node ./settings/restartWebsocket.cjs" }
107
- );
108
- answersToInclude.push("websocket");
109
- }
110
- // Initialize with existing scripts
111
- const updatedScripts = Object.assign({}, packageJson.scripts);
112
- // Conditionally add "browser-sync" command
113
- if (answersToInclude.length > 0) {
114
- updatedScripts["browser-sync"] = browserSyncCommand;
115
- }
116
- // Conditionally set the "dev" command
117
- updatedScripts.dev =
118
- answersToInclude.length > 0
119
- ? `npm-run-all --parallel browser-sync ${answersToInclude.join(" ")}`
120
- : browserSyncCommand;
121
- // Finally, assign the updated scripts back to packageJson
122
- packageJson.scripts = updatedScripts;
123
- packageJson.type = "module";
124
- packageJson.prisma = {
125
- seed: "node prisma/seed.js",
126
- };
127
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
74
+ const packageJsonPath = path.join(baseDir, "package.json");
75
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
76
+ // Use the new function to configure the Browser Sync command
77
+ const browserSyncCommand = configureBrowserSyncCommand(baseDir, projectSettings);
78
+ packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { postinstall: "prisma generate" });
79
+ let answersToInclude = [];
80
+ if (answer.tailwindcss) {
81
+ packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { tailwind: "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch" });
82
+ answersToInclude.push("tailwind");
83
+ }
84
+ if (answer.websocket) {
85
+ packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { websocket: "node ./settings/restartWebsocket.cjs" });
86
+ answersToInclude.push("websocket");
87
+ }
88
+ // Initialize with existing scripts
89
+ const updatedScripts = Object.assign({}, packageJson.scripts);
90
+ // Conditionally add "browser-sync" command
91
+ if (answersToInclude.length > 0) {
92
+ updatedScripts["browser-sync"] = browserSyncCommand;
93
+ }
94
+ // Conditionally set the "dev" command
95
+ updatedScripts.dev =
96
+ answersToInclude.length > 0
97
+ ? `npm-run-all --parallel browser-sync ${answersToInclude.join(" ")}`
98
+ : browserSyncCommand;
99
+ // Finally, assign the updated scripts back to packageJson
100
+ packageJson.scripts = updatedScripts;
101
+ packageJson.type = "module";
102
+ packageJson.prisma = {
103
+ seed: "node prisma/seed.js",
104
+ };
105
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
128
106
  }
129
107
  async function updateComposerJson(baseDir, answer) {
130
- if (!answer.websocket) return;
131
- const composerJsonPath = path.join(baseDir, "composer.json");
132
- let composerJson;
133
- // Check if the composer.json file exists
134
- if (fs.existsSync(composerJsonPath)) {
135
- // Read the current composer.json content
136
- const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
137
- composerJson = JSON.parse(composerJsonContent);
138
- } else {
139
- console.error("composer.json does not exist.");
140
- return;
141
- }
142
- // Conditionally add WebSocket dependency
143
- if (answer.websocket) {
144
- composerJson.require = Object.assign(
145
- Object.assign({}, composerJson.require),
146
- { "cboden/ratchet": "^0.4.4" }
147
- );
148
- }
149
- // Write the modified composer.json back to the file
150
- fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
151
- console.log("composer.json updated successfully.");
108
+ if (!answer.websocket)
109
+ return;
110
+ const composerJsonPath = path.join(baseDir, "composer.json");
111
+ let composerJson;
112
+ // Check if the composer.json file exists
113
+ if (fs.existsSync(composerJsonPath)) {
114
+ // Read the current composer.json content
115
+ const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
116
+ composerJson = JSON.parse(composerJsonContent);
117
+ }
118
+ else {
119
+ console.error("composer.json does not exist.");
120
+ return;
121
+ }
122
+ // Conditionally add WebSocket dependency
123
+ if (answer.websocket) {
124
+ composerJson.require = Object.assign(Object.assign({}, composerJson.require), { "cboden/ratchet": "^0.4.4" });
125
+ }
126
+ // Write the modified composer.json back to the file
127
+ fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
128
+ console.log("composer.json updated successfully.");
152
129
  }
153
130
  async function updateIndexJsForWebSocket(baseDir, answer) {
154
- if (!answer.websocket) {
155
- return;
156
- }
157
- const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
158
- let indexContent = fs.readFileSync(indexPath, "utf8");
159
- // WebSocket initialization code to be appended
160
- const webSocketCode = `
131
+ if (!answer.websocket) {
132
+ return;
133
+ }
134
+ const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
135
+ let indexContent = fs.readFileSync(indexPath, "utf8");
136
+ // WebSocket initialization code to be appended
137
+ const webSocketCode = `
161
138
  // WebSocket initialization
162
139
  const ws = new WebSocket("ws://localhost:8080");
163
140
  `;
164
- // Append WebSocket code if user chose to use WebSocket
165
- indexContent += webSocketCode;
166
- fs.writeFileSync(indexPath, indexContent, "utf8");
167
- console.log("WebSocket code added to index.js successfully.");
141
+ // Append WebSocket code if user chose to use WebSocket
142
+ indexContent += webSocketCode;
143
+ fs.writeFileSync(indexPath, indexContent, "utf8");
144
+ console.log("WebSocket code added to index.js successfully.");
168
145
  }
169
146
  // This function updates the .gitignore file
170
147
  async function createUpdateGitignoreFile(baseDir, additions) {
171
- const gitignorePath = path.join(baseDir, ".gitignore");
172
- // Check if the .gitignore file exists, create if it doesn't
173
- let gitignoreContent = "";
174
- if (fs.existsSync(gitignorePath)) {
175
- gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
176
- }
177
- additions.forEach((addition) => {
178
- if (!gitignoreContent.includes(addition)) {
179
- gitignoreContent += `\n${addition}`;
148
+ const gitignorePath = path.join(baseDir, ".gitignore");
149
+ // Check if the .gitignore file exists, create if it doesn't
150
+ let gitignoreContent = "";
151
+ if (fs.existsSync(gitignorePath)) {
152
+ gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
180
153
  }
181
- });
182
- // Ensure there's no leading newline if the file was just created
183
- gitignoreContent = gitignoreContent.trimStart();
184
- fs.writeFileSync(gitignorePath, gitignoreContent);
154
+ additions.forEach((addition) => {
155
+ if (!gitignoreContent.includes(addition)) {
156
+ gitignoreContent += `\n${addition}`;
157
+ }
158
+ });
159
+ // Ensure there's no leading newline if the file was just created
160
+ gitignoreContent = gitignoreContent.trimStart();
161
+ fs.writeFileSync(gitignorePath, gitignoreContent);
185
162
  }
186
163
  // Recursive copy function
187
164
  function copyRecursiveSync(src, dest) {
188
- const exists = fs.existsSync(src);
189
- const stats = exists && fs.statSync(src);
190
- const isDirectory = exists && stats && stats.isDirectory();
191
- console.log("🚀 ~ copyRecursiveSync ~ isDirectory:", isDirectory);
192
- if (isDirectory) {
193
- if (fs.existsSync(dest)) {
194
- fs.rmSync(dest, { recursive: true, force: true }); // Remove the directory if it exists
165
+ const exists = fs.existsSync(src);
166
+ const stats = exists && fs.statSync(src);
167
+ const isDirectory = exists && stats && stats.isDirectory();
168
+ console.log("🚀 ~ copyRecursiveSync ~ isDirectory:", isDirectory);
169
+ if (isDirectory) {
170
+ if (fs.existsSync(dest)) {
171
+ fs.rmSync(dest, { recursive: true, force: true }); // Remove the directory if it exists
172
+ }
173
+ fs.mkdirSync(dest, { recursive: true }); // Recreate the directory
174
+ fs.readdirSync(src).forEach((childItemName) => {
175
+ copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName));
176
+ });
177
+ }
178
+ else {
179
+ fs.copyFileSync(src, dest); // This line ensures files are overwritten
195
180
  }
196
- fs.mkdirSync(dest, { recursive: true }); // Recreate the directory
197
- fs.readdirSync(src).forEach((childItemName) => {
198
- copyRecursiveSync(
199
- path.join(src, childItemName),
200
- path.join(dest, childItemName)
201
- );
202
- });
203
- } else {
204
- fs.copyFileSync(src, dest); // This line ensures files are overwritten
205
- }
206
181
  }
207
182
  // Function to execute the recursive copy for entire directories
208
183
  async function executeCopy(baseDir, directoriesToCopy) {
209
- directoriesToCopy.forEach(({ srcDir, destDir }) => {
210
- const sourcePath = path.join(__dirname, srcDir);
211
- const destPath = path.join(baseDir, destDir);
212
- copyRecursiveSync(sourcePath, destPath);
213
- });
184
+ directoriesToCopy.forEach(({ srcDir, destDir }) => {
185
+ const sourcePath = path.join(__dirname, srcDir);
186
+ const destPath = path.join(baseDir, destDir);
187
+ copyRecursiveSync(sourcePath, destPath);
188
+ });
214
189
  }
215
190
  function modifyTailwindConfig(baseDir) {
216
- const filePath = path.join(baseDir, "tailwind.config.js");
217
- const newContent = [
218
- "./src/app/**/*.{html,js,php}",
219
- // Add more paths as needed
220
- ];
221
- let configData = fs.readFileSync(filePath, "utf8");
222
- const contentArrayString = newContent
223
- .map((item) => ` "${item}"`)
224
- .join(",\n");
225
- configData = configData.replace(
226
- /content: \[\],/g,
227
- `content: [\n${contentArrayString}\n],`
228
- );
229
- fs.writeFileSync(filePath, configData, "utf8");
230
- console.log(chalk.green("Tailwind configuration updated successfully."));
191
+ const filePath = path.join(baseDir, "tailwind.config.js");
192
+ const newContent = [
193
+ "./src/app/**/*.{html,js,php}",
194
+ // Add more paths as needed
195
+ ];
196
+ let configData = fs.readFileSync(filePath, "utf8");
197
+ const contentArrayString = newContent
198
+ .map((item) => ` "${item}"`)
199
+ .join(",\n");
200
+ configData = configData.replace(/content: \[\],/g, `content: [\n${contentArrayString}\n],`);
201
+ fs.writeFileSync(filePath, configData, "utf8");
202
+ console.log(chalk.green("Tailwind configuration updated successfully."));
231
203
  }
232
204
  function modifyPostcssConfig(baseDir) {
233
- const filePath = path.join(baseDir, "postcss.config.js");
234
- const newContent = `export default {
205
+ const filePath = path.join(baseDir, "postcss.config.js");
206
+ const newContent = `export default {
235
207
  plugins: {
236
208
  tailwindcss: {},
237
209
  autoprefixer: {},
238
210
  cssnano: {},
239
211
  },
240
212
  };`;
241
- fs.writeFileSync(filePath, newContent, "utf8");
242
- console.log(chalk.green("postcss.config.js updated successfully."));
213
+ fs.writeFileSync(filePath, newContent, "utf8");
214
+ console.log(chalk.green("postcss.config.js updated successfully."));
243
215
  }
244
216
  function modifyIndexPHP(baseDir, useTailwind) {
245
- const indexPath = path.join(baseDir, "src", "app", "layout.php");
246
- try {
247
- let indexContent = fs.readFileSync(indexPath, "utf8");
248
- const stylesAndLinks = `\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"></script>`;
249
- // Tailwind CSS link or CDN script
250
- const tailwindLink = useTailwind
251
- ? ` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
252
- : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
253
- // Insert before the closing </head> tag
254
- indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
255
- fs.writeFileSync(indexPath, indexContent, "utf8");
256
- console.log(
257
- chalk.green(
258
- `index.php modified successfully for ${
259
- useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"
260
- }.`
261
- )
262
- );
263
- } catch (error) {
264
- console.error(chalk.red("Error modifying index.php:"), error);
265
- }
217
+ const indexPath = path.join(baseDir, "src", "app", "layout.php");
218
+ try {
219
+ let indexContent = fs.readFileSync(indexPath, "utf8");
220
+ const stylesAndLinks = `\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"></script>`;
221
+ // Tailwind CSS link or CDN script
222
+ const tailwindLink = useTailwind
223
+ ? ` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
224
+ : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
225
+ // Insert before the closing </head> tag
226
+ indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
227
+ fs.writeFileSync(indexPath, indexContent, "utf8");
228
+ console.log(chalk.green(`index.php modified successfully for ${useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"}.`));
229
+ }
230
+ catch (error) {
231
+ console.error(chalk.red("Error modifying index.php:"), error);
232
+ }
266
233
  }
267
234
  // This function updates or creates the .env file
268
235
  async function updateOrCreateEnvFile(baseDir, content) {
269
- const envPath = path.join(baseDir, ".env");
270
- let envContent = fs.existsSync(envPath)
271
- ? fs.readFileSync(envPath, "utf8")
272
- : "";
273
- envContent += `${envContent !== "" ? "\n\n" : ""}${content}`;
274
- fs.writeFileSync(envPath, envContent);
236
+ const envPath = path.join(baseDir, ".env");
237
+ let envContent = fs.existsSync(envPath)
238
+ ? fs.readFileSync(envPath, "utf8")
239
+ : "";
240
+ envContent += `${envContent !== "" ? "\n\n" : ""}${content}`;
241
+ fs.writeFileSync(envPath, envContent);
275
242
  }
276
243
  async function createDirectoryStructure(baseDir, answer, projectSettings) {
277
- console.log("🚀 ~ baseDir:", baseDir);
278
- console.log("🚀 ~ answer:", answer);
279
- console.log("🚀 ~ projectSettings:", projectSettings);
280
- const filesToCopy = [
281
- { src: "/bootstrap.php", dest: "/bootstrap.php" },
282
- { src: "/.htaccess", dest: "/.htaccess" },
283
- { src: "/../composer.json", dest: "/composer.json" },
284
- ];
285
- // if (answer.websocket) {
286
- // filesToCopy.push({
287
- // src: "/../composer-websocket.lock",
288
- // dest: "/composer.lock",
289
- // });
290
- // } else {
291
- // filesToCopy.push({ src: "/../composer.lock", dest: "/composer.lock" });
292
- // }
293
- const directoriesToCopy = [
294
- {
295
- srcDir: "/settings",
296
- destDir: "/settings",
297
- },
298
- {
299
- srcDir: "/prisma",
300
- destDir: "/prisma",
301
- },
302
- {
303
- srcDir: "/src",
304
- destDir: "/src",
305
- },
306
- {
307
- srcDir: "/../vendor",
308
- destDir: "/vendor",
309
- },
310
- ];
311
- console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
312
- filesToCopy.forEach(({ src, dest }) => {
313
- const sourcePath = path.join(__dirname, src);
314
- const destPath = path.join(baseDir, dest);
315
- const code = fs.readFileSync(sourcePath, "utf8");
316
- fs.writeFileSync(destPath, code, { flag: "w" });
317
- });
318
- await executeCopy(baseDir, directoriesToCopy);
319
- await updatePackageJson(baseDir, projectSettings, answer);
320
- await updateComposerJson(baseDir, answer);
321
- await updateIndexJsForWebSocket(baseDir, answer);
322
- if (answer.tailwindcss) {
323
- modifyTailwindConfig(baseDir);
324
- modifyIndexPHP(baseDir, true);
325
- modifyPostcssConfig(baseDir);
326
- } else {
327
- modifyIndexPHP(baseDir, false);
328
- }
329
- const envContent = `# PHPMailer
244
+ console.log("🚀 ~ baseDir:", baseDir);
245
+ console.log("🚀 ~ answer:", answer);
246
+ console.log("🚀 ~ projectSettings:", projectSettings);
247
+ const filesToCopy = [
248
+ { src: "/bootstrap.php", dest: "/bootstrap.php" },
249
+ { src: "/.htaccess", dest: "/.htaccess" },
250
+ { src: "/../composer.json", dest: "/composer.json" },
251
+ ];
252
+ // if (answer.websocket) {
253
+ // filesToCopy.push({
254
+ // src: "/../composer-websocket.lock",
255
+ // dest: "/composer.lock",
256
+ // });
257
+ // } else {
258
+ // filesToCopy.push({ src: "/../composer.lock", dest: "/composer.lock" });
259
+ // }
260
+ const directoriesToCopy = [
261
+ {
262
+ srcDir: "/settings",
263
+ destDir: "/settings",
264
+ },
265
+ {
266
+ srcDir: "/prisma",
267
+ destDir: "/prisma",
268
+ },
269
+ {
270
+ srcDir: "/src",
271
+ destDir: "/src",
272
+ },
273
+ {
274
+ srcDir: "/../vendor",
275
+ destDir: "/vendor",
276
+ },
277
+ ];
278
+ console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
279
+ filesToCopy.forEach(({ src, dest }) => {
280
+ const sourcePath = path.join(__dirname, src);
281
+ const destPath = path.join(baseDir, dest);
282
+ const code = fs.readFileSync(sourcePath, "utf8");
283
+ fs.writeFileSync(destPath, code, { flag: "w" });
284
+ });
285
+ await executeCopy(baseDir, directoriesToCopy);
286
+ await updatePackageJson(baseDir, projectSettings, answer);
287
+ await updateComposerJson(baseDir, answer);
288
+ await updateIndexJsForWebSocket(baseDir, answer);
289
+ if (answer.tailwindcss) {
290
+ modifyTailwindConfig(baseDir);
291
+ modifyIndexPHP(baseDir, true);
292
+ modifyPostcssConfig(baseDir);
293
+ }
294
+ else {
295
+ modifyIndexPHP(baseDir, false);
296
+ }
297
+ const envContent = `# PHPMailer
330
298
  SMTP_HOST=
331
299
  SMTP_USERNAME=
332
300
  SMTP_PASSWORD=
@@ -334,70 +302,64 @@ SMTP_PORT=
334
302
  SMTP_ENCRYPTION=ssl
335
303
  MAIL_FROM=
336
304
  MAIL_FROM_NAME=""`;
337
- await updateOrCreateEnvFile(baseDir, envContent);
338
- // Add vendor to .gitignore
339
- await createUpdateGitignoreFile(baseDir, ["vendor"]);
305
+ await updateOrCreateEnvFile(baseDir, envContent);
306
+ // Add vendor to .gitignore
307
+ await createUpdateGitignoreFile(baseDir, ["vendor"]);
340
308
  }
341
309
  async function getAnswer(predefinedAnswers = {}) {
342
- var _a, _b, _c;
343
- console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
344
- const questions = [];
345
- if (!predefinedAnswers.projectName) {
346
- questions.push({
347
- type: "text",
348
- name: "projectName",
349
- message: "What is your project named?",
350
- initial: "my-app",
351
- });
352
- }
353
- if (!predefinedAnswers.tailwindcss) {
354
- questions.push({
355
- type: "toggle",
356
- name: "tailwindcss",
357
- message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
358
- initial: true,
359
- active: "Yes",
360
- inactive: "No",
361
- });
362
- }
363
- if (!predefinedAnswers.websocket) {
364
- questions.push({
365
- type: "toggle",
366
- name: "websocket",
367
- message: `Would you like to use ${chalk.blue("Websocket")}?`,
368
- initial: true,
369
- active: "Yes",
370
- inactive: "No",
371
- });
372
- }
373
- console.log("🚀 ~ questions:", questions);
374
- const onCancel = () => {
375
- return false;
376
- };
377
- try {
378
- const response = await prompts(questions, { onCancel });
379
- if (Object.keys(response).length === 0) {
380
- return null;
310
+ var _a, _b, _c;
311
+ console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
312
+ const questions = [];
313
+ if (!predefinedAnswers.projectName) {
314
+ questions.push({
315
+ type: "text",
316
+ name: "projectName",
317
+ message: "What is your project named?",
318
+ initial: "my-app",
319
+ });
381
320
  }
382
- return {
383
- projectName: response.projectName
384
- ? String(response.projectName).trim().replace(/ /g, "-")
385
- : (_a = predefinedAnswers.projectName) !== null && _a !== void 0
386
- ? _a
387
- : "my-app",
388
- tailwindcss:
389
- (_b = response.tailwindcss) !== null && _b !== void 0
390
- ? _b
391
- : predefinedAnswers.tailwindcss,
392
- websocket:
393
- (_c = response.websocket) !== null && _c !== void 0
394
- ? _c
395
- : predefinedAnswers.websocket,
321
+ if (!predefinedAnswers.tailwindcss) {
322
+ questions.push({
323
+ type: "toggle",
324
+ name: "tailwindcss",
325
+ message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
326
+ initial: true,
327
+ active: "Yes",
328
+ inactive: "No",
329
+ });
330
+ }
331
+ if (!predefinedAnswers.websocket) {
332
+ questions.push({
333
+ type: "toggle",
334
+ name: "websocket",
335
+ message: `Would you like to use ${chalk.blue("Websocket")}?`,
336
+ initial: true,
337
+ active: "Yes",
338
+ inactive: "No",
339
+ });
340
+ }
341
+ console.log("🚀 ~ questions:", questions);
342
+ const onCancel = () => {
343
+ return false;
396
344
  };
397
- } catch (error) {
398
- console.error(chalk.red("Prompt error:"), error);
399
- return null;
400
- }
345
+ try {
346
+ const response = await prompts(questions, { onCancel });
347
+ console.log("🚀 ~ response:", response);
348
+ if (Object.keys(response).length === 0 && !predefinedAnswers.projectName) {
349
+ return null;
350
+ }
351
+ return {
352
+ projectName: response.projectName
353
+ ? String(response.projectName).trim().replace(/ /g, "-")
354
+ : (_a = predefinedAnswers.projectName) !== null && _a !== void 0 ? _a : "my-app",
355
+ tailwindcss: (_b = response.tailwindcss) !== null && _b !== void 0 ? _b : predefinedAnswers.tailwindcss,
356
+ websocket: (_c = response.websocket) !== null && _c !== void 0 ? _c : predefinedAnswers.websocket,
357
+ };
358
+ }
359
+ catch (error) {
360
+ console.error(chalk.red("Prompt error:"), error);
361
+ return null;
362
+ }
401
363
  }
402
364
  /**
403
365
  * Install dependencies in the specified directory.
@@ -406,206 +368,190 @@ async function getAnswer(predefinedAnswers = {}) {
406
368
  * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
407
369
  */
408
370
  async function installDependencies(baseDir, dependencies, isDev = false) {
409
- console.log("Initializing new Node.js project...");
410
- // Initialize a package.json if it doesn't exist
411
- if (!fs.existsSync(path.join(baseDir, "package.json")))
412
- execSync("npm init -y", {
413
- stdio: "inherit",
414
- cwd: baseDir,
371
+ console.log("Initializing new Node.js project...");
372
+ // Initialize a package.json if it doesn't exist
373
+ if (!fs.existsSync(path.join(baseDir, "package.json")))
374
+ execSync("npm init -y", {
375
+ stdio: "inherit",
376
+ cwd: baseDir,
377
+ });
378
+ // Log the dependencies being installed
379
+ console.log(`${isDev ? "Installing development dependencies" : "Installing dependencies"}:`);
380
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
381
+ // Prepare the npm install command with the appropriate flag for dev dependencies
382
+ const npmInstallCommand = `npm install ${isDev ? "--save-dev" : ""} ${dependencies.join(" ")}`;
383
+ // Execute the npm install command
384
+ execSync(npmInstallCommand, {
385
+ stdio: "inherit",
386
+ cwd: baseDir,
415
387
  });
416
- // Log the dependencies being installed
417
- console.log(
418
- `${
419
- isDev ? "Installing development dependencies" : "Installing dependencies"
420
- }:`
421
- );
422
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
423
- // Prepare the npm install command with the appropriate flag for dev dependencies
424
- const npmInstallCommand = `npm install ${
425
- isDev ? "--save-dev" : ""
426
- } ${dependencies.join(" ")}`;
427
- // Execute the npm install command
428
- execSync(npmInstallCommand, {
429
- stdio: "inherit",
430
- cwd: baseDir,
431
- });
432
388
  }
433
389
  function fetchPackageVersion(packageName) {
434
- return new Promise((resolve, reject) => {
435
- https
436
- .get(`https://registry.npmjs.org/${packageName}`, (res) => {
437
- let data = "";
438
- res.on("data", (chunk) => (data += chunk));
439
- res.on("end", () => {
440
- try {
441
- const parsed = JSON.parse(data);
442
- resolve(parsed["dist-tags"].latest);
443
- } catch (error) {
444
- reject(new Error("Failed to parse JSON response"));
445
- }
446
- });
447
- })
448
- .on("error", (err) => reject(err));
449
- });
390
+ return new Promise((resolve, reject) => {
391
+ https
392
+ .get(`https://registry.npmjs.org/${packageName}`, (res) => {
393
+ let data = "";
394
+ res.on("data", (chunk) => (data += chunk));
395
+ res.on("end", () => {
396
+ try {
397
+ const parsed = JSON.parse(data);
398
+ resolve(parsed["dist-tags"].latest);
399
+ }
400
+ catch (error) {
401
+ reject(new Error("Failed to parse JSON response"));
402
+ }
403
+ });
404
+ })
405
+ .on("error", (err) => reject(err));
406
+ });
450
407
  }
451
408
  async function main() {
452
- try {
453
- const args = process.argv.slice(2);
454
- let projectName = args[0];
455
- console.log("🚀 ~ main ~ projectName:", projectName);
456
- let answer = null;
457
- if (projectName) {
458
- let useTailwind = args.includes("--tailwind");
459
- let useWebsocket = args.includes("--websocket");
460
- const predefinedAnswers = {
461
- projectName,
462
- tailwindcss: useTailwind,
463
- websocket: useWebsocket,
464
- };
465
- answer = await getAnswer(predefinedAnswers);
466
- console.log("🚀 ~ main ~ answer:", answer);
467
- } else {
468
- answer = await getAnswer();
469
- }
470
- if (answer === null) {
471
- console.log(chalk.red("Installation cancelled."));
472
- return;
473
- }
474
- // execSync(`npm install -g create-prisma-php-app`, { stdio: "inherit" }); // TODO: Uncomment this line before publishing the package
475
- execSync(`npm install -g create-prisma-php-app@alpha-update-command`, {
476
- stdio: "inherit",
477
- }); // TODO: Uncomment this line before publishing the package
478
- // Support for browser-sync
479
- execSync(`npm install -g browser-sync`, { stdio: "inherit" });
480
- // Create the project directory
481
- if (!projectName) fs.mkdirSync(answer.projectName);
482
- const currentDir = process.cwd();
483
- console.log("🚀 ~ main ~ currentDir:", currentDir);
484
- let projectPath = projectName
485
- ? currentDir
486
- : path.join(currentDir, answer.projectName);
487
- console.log("🚀 ~ main ~ projectPath:", projectPath);
488
- if (!projectName) process.chdir(answer.projectName);
489
- const dependencies = [
490
- "prisma",
491
- "@prisma/client",
492
- "typescript",
493
- "@types/node",
494
- "ts-node",
495
- "http-proxy-middleware",
496
- ];
497
- if (answer.tailwindcss) {
498
- dependencies.push(
499
- "tailwindcss",
500
- "autoprefixer",
501
- "postcss",
502
- "postcss-cli",
503
- "cssnano"
504
- );
505
- }
506
- if (answer.websocket) {
507
- dependencies.push("chokidar-cli");
508
- }
509
- if (answer.tailwindcss || answer.websocket) {
510
- dependencies.push("npm-run-all");
511
- }
512
- await installDependencies(projectPath, dependencies, true);
513
- if (!projectName) {
514
- execSync(`npx prisma init`, { stdio: "inherit" });
515
- execSync(`npx tsc --init`, { stdio: "inherit" });
516
- }
517
- if (answer.tailwindcss) {
518
- execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
519
- }
520
- const projectSettings = {
521
- PROJECT_NAME: answer.projectName,
522
- PROJECT_ROOT_PATH: projectPath.replace(/\\/g, "\\\\"),
523
- PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
524
- PHP_GENERATE_CLASS_PATH: "src/lib/prisma/classes",
525
- };
526
- await createDirectoryStructure(projectPath, answer, projectSettings);
527
- // if (answer.tailwindcss) {
528
- // execSync(
529
- // `npx tailwindcss -i ./src/app/css/tailwind.css -o ./src/app/css/styles.css --minify`,
530
- // { stdio: "inherit" }
531
- // );
532
- // }
533
- // execSync(`composer install`, { stdio: "inherit" });
534
- // execSync(`composer dump-autoload`, { stdio: "inherit" });
535
- // Create settings file
536
- const settingsPath = path.join(
537
- projectPath,
538
- "settings",
539
- "project-settings.js"
540
- );
541
- const settingsCode = `export const projectSettings = {
409
+ try {
410
+ const args = process.argv.slice(2);
411
+ let projectName = args[0];
412
+ console.log("🚀 ~ main ~ projectName:", projectName);
413
+ let answer = null;
414
+ if (projectName) {
415
+ let useTailwind = args.includes("--tailwindcss");
416
+ let useWebsocket = args.includes("--websocket");
417
+ const predefinedAnswers = {
418
+ projectName,
419
+ tailwindcss: useTailwind,
420
+ websocket: useWebsocket,
421
+ };
422
+ answer = await getAnswer(predefinedAnswers);
423
+ console.log("🚀 ~ main ~ answer:", answer);
424
+ }
425
+ else {
426
+ answer = await getAnswer();
427
+ }
428
+ if (answer === null) {
429
+ console.log(chalk.red("Installation cancelled."));
430
+ return;
431
+ }
432
+ // execSync(`npm install -g create-prisma-php-app`, { stdio: "inherit" }); // TODO: Uncomment this line before publishing the package
433
+ execSync(`npm install -g create-prisma-php-app@alpha-update-command`, {
434
+ stdio: "inherit",
435
+ }); // TODO: Uncomment this line before publishing the package
436
+ // Support for browser-sync
437
+ execSync(`npm install -g browser-sync`, { stdio: "inherit" });
438
+ // Create the project directory
439
+ if (!projectName)
440
+ fs.mkdirSync(answer.projectName);
441
+ const currentDir = process.cwd();
442
+ console.log("🚀 ~ main ~ currentDir:", currentDir);
443
+ let projectPath = projectName
444
+ ? currentDir
445
+ : path.join(currentDir, answer.projectName);
446
+ console.log("🚀 ~ main ~ projectPath:", projectPath);
447
+ if (!projectName)
448
+ process.chdir(answer.projectName);
449
+ const dependencies = [
450
+ "prisma",
451
+ "@prisma/client",
452
+ "typescript",
453
+ "@types/node",
454
+ "ts-node",
455
+ "http-proxy-middleware",
456
+ ];
457
+ if (answer.tailwindcss) {
458
+ dependencies.push("tailwindcss", "autoprefixer", "postcss", "postcss-cli", "cssnano");
459
+ }
460
+ if (answer.websocket) {
461
+ dependencies.push("chokidar-cli");
462
+ }
463
+ if (answer.tailwindcss || answer.websocket) {
464
+ dependencies.push("npm-run-all");
465
+ }
466
+ await installDependencies(projectPath, dependencies, true);
467
+ if (!projectName) {
468
+ execSync(`npx prisma init`, { stdio: "inherit" });
469
+ execSync(`npx tsc --init`, { stdio: "inherit" });
470
+ }
471
+ if (answer.tailwindcss) {
472
+ execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
473
+ }
474
+ const projectSettings = {
475
+ PROJECT_NAME: answer.projectName,
476
+ PROJECT_ROOT_PATH: projectPath.replace(/\\/g, "\\\\"),
477
+ PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
478
+ PHP_GENERATE_CLASS_PATH: "src/lib/prisma/classes",
479
+ };
480
+ await createDirectoryStructure(projectPath, answer, projectSettings);
481
+ // if (answer.tailwindcss) {
482
+ // execSync(
483
+ // `npx tailwindcss -i ./src/app/css/tailwind.css -o ./src/app/css/styles.css --minify`,
484
+ // { stdio: "inherit" }
485
+ // );
486
+ // }
487
+ // execSync(`composer install`, { stdio: "inherit" });
488
+ // execSync(`composer dump-autoload`, { stdio: "inherit" });
489
+ // Create settings file
490
+ const settingsPath = path.join(projectPath, "settings", "project-settings.js");
491
+ const settingsCode = `export const projectSettings = {
542
492
  PROJECT_NAME: "${answer.projectName}",
543
493
  PROJECT_ROOT_PATH: "${projectPath.replace(/\\/g, "\\\\")}",
544
494
  PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
545
495
  PHP_GENERATE_CLASS_PATH: "src/lib/prisma/classes",
546
496
  };`;
547
- fs.writeFileSync(settingsPath, settingsCode, { flag: "w" });
548
- const publicDirPath = path.join(projectPath, "public");
549
- if (!fs.existsSync(publicDirPath)) {
550
- fs.mkdirSync(publicDirPath);
551
- }
552
- if (!answer.tailwindcss) {
553
- const cssPath = path.join(projectPath, "src", "app", "css");
554
- const tailwindFiles = ["tailwind.css", "styles.css"];
555
- tailwindFiles.forEach((file) => {
556
- const filePath = path.join(cssPath, file);
557
- if (fs.existsSync(filePath)) {
558
- fs.unlinkSync(filePath); // Delete each file if it exists
559
- console.log(`${file} was deleted successfully.`);
560
- } else {
561
- console.log(`${file} does not exist.`);
497
+ fs.writeFileSync(settingsPath, settingsCode, { flag: "w" });
498
+ const publicDirPath = path.join(projectPath, "public");
499
+ if (!fs.existsSync(publicDirPath)) {
500
+ fs.mkdirSync(publicDirPath);
562
501
  }
563
- });
564
- }
565
- // Update websocket if not chosen by the user
566
- if (!answer.websocket) {
567
- const wsPath = path.join(projectPath, "src", "lib", "websocket");
568
- // Check if the websocket directory exists
569
- if (fs.existsSync(wsPath)) {
570
- // Use fs.rmSync with recursive option set to true to delete the directory and its contents
571
- fs.rmSync(wsPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
572
- console.log("Websocket directory was deleted successfully.");
573
- } else {
574
- console.log("Websocket directory does not exist.");
575
- }
576
- // Update settings directory if websocket is not chosen
577
- const settingsPath = path.join(projectPath, "settings");
578
- const websocketFiles = ["restartWebsocket.cjs", "restart_websocket.bat"];
579
- websocketFiles.forEach((file) => {
580
- const filePath = path.join(settingsPath, file);
581
- if (fs.existsSync(filePath)) {
582
- fs.unlinkSync(filePath); // Delete each file if it exists
583
- console.log(`${file} was deleted successfully.`);
584
- } else {
585
- console.log(`${file} does not exist.`);
502
+ if (!answer.tailwindcss) {
503
+ const cssPath = path.join(projectPath, "src", "app", "css");
504
+ const tailwindFiles = ["tailwind.css", "styles.css"];
505
+ tailwindFiles.forEach((file) => {
506
+ const filePath = path.join(cssPath, file);
507
+ if (fs.existsSync(filePath)) {
508
+ fs.unlinkSync(filePath); // Delete each file if it exists
509
+ console.log(`${file} was deleted successfully.`);
510
+ }
511
+ else {
512
+ console.log(`${file} does not exist.`);
513
+ }
514
+ });
515
+ }
516
+ // Update websocket if not chosen by the user
517
+ if (!answer.websocket) {
518
+ const wsPath = path.join(projectPath, "src", "lib", "websocket");
519
+ // Check if the websocket directory exists
520
+ if (fs.existsSync(wsPath)) {
521
+ // Use fs.rmSync with recursive option set to true to delete the directory and its contents
522
+ fs.rmSync(wsPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
523
+ console.log("Websocket directory was deleted successfully.");
524
+ }
525
+ else {
526
+ console.log("Websocket directory does not exist.");
527
+ }
528
+ // Update settings directory if websocket is not chosen
529
+ const settingsPath = path.join(projectPath, "settings");
530
+ const websocketFiles = ["restartWebsocket.cjs", "restart_websocket.bat"];
531
+ websocketFiles.forEach((file) => {
532
+ const filePath = path.join(settingsPath, file);
533
+ if (fs.existsSync(filePath)) {
534
+ fs.unlinkSync(filePath); // Delete each file if it exists
535
+ console.log(`${file} was deleted successfully.`);
536
+ }
537
+ else {
538
+ console.log(`${file} does not exist.`);
539
+ }
540
+ });
586
541
  }
587
- });
542
+ const version = await fetchPackageVersion("create-prisma-php-app");
543
+ const prismaPhpConfig = {
544
+ projectName: answer.projectName,
545
+ tailwindcss: answer.tailwindcss,
546
+ websocket: answer.websocket,
547
+ version,
548
+ };
549
+ fs.writeFileSync(path.join(projectPath, "prisma-php.json"), JSON.stringify(prismaPhpConfig, null, 2), { flag: "w" });
550
+ console.log(`${chalk.green("Success!")} Prisma PHP project successfully created in ${answer.projectName}!`);
551
+ }
552
+ catch (error) {
553
+ console.error("Error while creating the project:", error);
554
+ process.exit(1);
588
555
  }
589
- const version = await fetchPackageVersion("create-prisma-php-app");
590
- const prismaPhpConfig = {
591
- projectName: answer.projectName,
592
- tailwindcss: answer.tailwindcss,
593
- websocket: answer.websocket,
594
- version,
595
- };
596
- fs.writeFileSync(
597
- path.join(projectPath, "prisma-php.json"),
598
- JSON.stringify(prismaPhpConfig, null, 2),
599
- { flag: "w" }
600
- );
601
- console.log(
602
- `${chalk.green("Success!")} Prisma PHP project successfully created in ${
603
- answer.projectName
604
- }!`
605
- );
606
- } catch (error) {
607
- console.error("Error while creating the project:", error);
608
- process.exit(1);
609
- }
610
556
  }
611
557
  main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "1.6.31",
3
+ "version": "1.6.33",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",