create-prisma-php-app 1.6.57 → 1.6.59

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