create-prisma-php-app 1.11.500 → 1.11.501

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