create-prisma-php-app 1.2.12 → 1.2.13

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 +1 -312
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,313 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import { execSync } from "child_process";
3
- import fs from "fs";
4
- import { fileURLToPath } from "url";
5
- import path from "path";
6
- import chalk from "chalk";
7
- import prompts from "prompts";
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = path.dirname(__filename);
10
- function configureBrowserSyncCommand(baseDir, projectSettings) {
11
- // Identify the base path dynamically up to and including 'htdocs'
12
- const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");
13
- if (htdocsIndex === -1) {
14
- console.error("Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\");
15
- return ""; // Return an empty string or handle the error as appropriate
16
- }
17
- // Extract the path up to and including 'htdocs\\'
18
- const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(0, htdocsIndex + "\\htdocs\\".length);
19
- // Escape backslashes for the regex pattern
20
- const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
21
- // Remove the base path and replace backslashes with forward slashes for URL compatibility
22
- const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(new RegExp(`^${escapedBasePathToRemove}`), "").replace(/\\/g, "/");
23
- // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
24
- let proxyUrl = `http://localhost/${relativeWebPath}`;
25
- // Ensure the proxy URL does not end with a slash before appending '/public'
26
- proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
27
- // Clean the URL by replacing "//" with "/" but not affecting "http://"
28
- // We replace instances of "//" that are not preceded by ":"
29
- const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
30
- // TypeScript content to write
31
- const bsConfigTsContent = `
32
- const { createProxyMiddleware } = require("http-proxy-middleware");
33
-
34
- module.exports = {
35
- // Use the 'middleware' option to create a proxy that masks the deep URL.
36
- middleware: [
37
- // This middleware intercepts requests to the root and proxies them to the deep path.
38
- createProxyMiddleware("/", {
39
- target:
40
- "${cleanUrl}",
41
- changeOrigin: true,
42
- pathRewrite: {
43
- "^/": "${relativeWebPath}", // Rewrite the path.
44
- },
45
- }),
46
- ],
47
- proxy: "http://localhost:3000", // Proxy the BrowserSync server.
48
- serveStatic: ["src/app"], // Serve static files from this directory.
49
- notify: false,
50
- };`;
51
- // Determine the path and write the bs-config.js
52
- const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
53
- fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
54
- // Return the Browser Sync command string, using the cleaned URL
55
- return `browser-sync start --config settings/bs-config.cjs`;
56
- }
57
- async function updatePackageJson(baseDir, projectSettings, answer) {
58
- const packageJsonPath = path.join(baseDir, "package.json");
59
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
60
- // Use the new function to configure the Browser Sync command
61
- const browserSyncCommand = configureBrowserSyncCommand(baseDir, projectSettings);
62
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { postinstall: "prisma generate" });
63
- if (answer.tailwindcss) {
64
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { tailwind: "tailwindcss -i ./src/app/css/tailwind.css -o ./src/app/css/styles.css --minify --watch", "browser-sync": browserSyncCommand, dev: "npm-run-all --parallel browser-sync tailwind" });
65
- }
66
- else {
67
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { dev: browserSyncCommand });
68
- }
69
- packageJson.type = "module";
70
- packageJson.prisma = {
71
- seed: "node prisma/seed.js",
72
- };
73
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
74
- }
75
- // This function updates the .gitignore file
76
- async function createUpdateGitignoreFile(baseDir, additions) {
77
- const gitignorePath = path.join(baseDir, ".gitignore");
78
- // Check if the .gitignore file exists, create if it doesn't
79
- let gitignoreContent = "";
80
- if (fs.existsSync(gitignorePath)) {
81
- gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
82
- }
83
- additions.forEach((addition) => {
84
- if (!gitignoreContent.includes(addition)) {
85
- gitignoreContent += `\n${addition}`;
86
- }
87
- });
88
- // Ensure there's no leading newline if the file was just created
89
- gitignoreContent = gitignoreContent.trimStart();
90
- fs.writeFileSync(gitignorePath, gitignoreContent);
91
- }
92
- // Recursive copy function
93
- function copyRecursiveSync(src, dest) {
94
- const exists = fs.existsSync(src);
95
- const stats = exists && fs.statSync(src);
96
- const isDirectory = exists && stats && stats.isDirectory(); // Add type guard to check if stats is truthy
97
- if (isDirectory) {
98
- fs.mkdirSync(dest, { recursive: true });
99
- fs.readdirSync(src).forEach((childItemName) => copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName)));
100
- }
101
- else {
102
- fs.copyFileSync(src, dest);
103
- }
104
- }
105
- // Function to execute the recursive copy for entire directories
106
- async function executeCopy(baseDir, directoriesToCopy) {
107
- directoriesToCopy.forEach(({ srcDir, destDir }) => {
108
- const sourcePath = path.join(__dirname, srcDir);
109
- const destPath = path.join(baseDir, destDir);
110
- copyRecursiveSync(sourcePath, destPath);
111
- });
112
- }
113
- function modifyTailwindConfig(baseDir) {
114
- const filePath = path.join(baseDir, "tailwind.config.js");
115
- const newContent = [
116
- "./src/app/**/*.{php,html,js}",
117
- // Add more paths as needed
118
- ];
119
- let configData = fs.readFileSync(filePath, "utf8");
120
- const contentArrayString = newContent
121
- .map((item) => ` "${item}"`)
122
- .join(",\n");
123
- configData = configData.replace(/content: \[\],/g, `content: [\n${contentArrayString}\n],`);
124
- fs.writeFileSync(filePath, configData, "utf8");
125
- console.log(chalk.green("Tailwind configuration updated successfully."));
126
- }
127
- function modifyIndexPHP(baseDir, useTailwind) {
128
- const indexPath = path.join(baseDir, "src", "app", "layout.php");
129
- try {
130
- let indexContent = fs.readFileSync(indexPath, "utf8");
131
- // Tailwind CSS link or CDN script
132
- const tailwindLink = useTailwind
133
- ? ' <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet">'
134
- : ' <script src="https://cdn.tailwindcss.com"></script>';
135
- // Insert before the closing </head> tag
136
- indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
137
- fs.writeFileSync(indexPath, indexContent, "utf8");
138
- // Remove src/css if tailwind is not chosen
139
- if (!useTailwind) {
140
- const cssPath = path.join(baseDir, "src", "app", "css");
141
- fs.rm(cssPath, { recursive: true }, (err) => {
142
- if (err)
143
- throw err;
144
- });
145
- }
146
- console.log(chalk.green(`index.php modified successfully for ${useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"}.`));
147
- }
148
- catch (error) {
149
- console.error(chalk.red("Error modifying index.php:"), error);
150
- }
151
- }
152
- async function createDirectoryStructure(baseDir, answer, projectSettings) {
153
- const filesToCopy = [
154
- { src: "/bootstrap.php", dest: "/bootstrap.php" },
155
- { src: "/.htaccess", dest: "/.htaccess" },
156
- { src: "/../composer.json", dest: "/composer.json" },
157
- { src: "/../composer.lock", dest: "/composer.lock" },
158
- ];
159
- const directoriesToCopy = [
160
- {
161
- srcDir: "/settings",
162
- destDir: "/settings",
163
- },
164
- {
165
- srcDir: "/prisma",
166
- destDir: "/prisma",
167
- },
168
- {
169
- srcDir: "/src",
170
- destDir: "/src",
171
- },
172
- {
173
- srcDir: "/../vendor",
174
- destDir: "/vendor",
175
- },
176
- ];
177
- await executeCopy(baseDir, directoriesToCopy);
178
- await updatePackageJson(baseDir, projectSettings, answer);
179
- filesToCopy.forEach(({ src, dest }) => {
180
- const sourcePath = path.join(__dirname, src);
181
- const destPath = path.join(baseDir, dest);
182
- const code = fs.readFileSync(sourcePath, "utf8");
183
- fs.writeFileSync(destPath, code);
184
- });
185
- if (answer.tailwindcss) {
186
- modifyTailwindConfig(baseDir);
187
- modifyIndexPHP(baseDir, true);
188
- }
189
- else {
190
- modifyIndexPHP(baseDir, false);
191
- }
192
- }
193
- async function getAnswer() {
194
- const questions = [
195
- {
196
- type: "text",
197
- name: "projectName",
198
- message: "What is your project named?",
199
- initial: "my-app",
200
- },
201
- {
202
- type: "toggle",
203
- name: "tailwindcss",
204
- message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
205
- initial: true,
206
- active: "Yes",
207
- inactive: "No",
208
- },
209
- ];
210
- const onCancel = () => {
211
- return false;
212
- };
213
- try {
214
- const response = await prompts(questions, { onCancel });
215
- if (Object.keys(response).length === 0) {
216
- return null;
217
- }
218
- return {
219
- projectName: String(response.projectName).trim().replace(/ /g, "-"),
220
- tailwindcss: response.tailwindcss,
221
- };
222
- }
223
- catch (error) {
224
- console.error(chalk.red("Prompt error:"), error);
225
- return null;
226
- }
227
- }
228
- /**
229
- * Install dependencies in the specified directory.
230
- * @param {string} baseDir - The base directory where to install the dependencies.
231
- * @param {string[]} dependencies - The list of dependencies to install.
232
- * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
233
- */
234
- async function installDependencies(baseDir, dependencies, isDev = false) {
235
- console.log("Initializing new Node.js project...");
236
- // Initialize a package.json if it doesn't exist
237
- execSync("npm init -y", {
238
- stdio: "inherit",
239
- cwd: baseDir,
240
- });
241
- // Log the dependencies being installed
242
- console.log(`${isDev ? "Installing development dependencies" : "Installing dependencies"}:`);
243
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
244
- // Prepare the npm install command with the appropriate flag for dev dependencies
245
- const npmInstallCommand = `npm install ${isDev ? "--save-dev" : ""} ${dependencies.join(" ")}`;
246
- // Execute the npm install command
247
- execSync(npmInstallCommand, {
248
- stdio: "inherit",
249
- cwd: baseDir,
250
- });
251
- }
252
- async function main() {
253
- try {
254
- const answer = await getAnswer();
255
- if (answer === null) {
256
- console.log(chalk.red("Installation cancelled."));
257
- return;
258
- }
259
- execSync(`npm install -g create-prisma-php-app`, { stdio: "inherit" });
260
- // Support for browser-sync
261
- execSync(`npm install -g browser-sync`, { stdio: "inherit" });
262
- // Create the project directory
263
- fs.mkdirSync(answer.projectName);
264
- const projectPath = path.join(process.cwd(), answer.projectName);
265
- process.chdir(answer.projectName);
266
- const dependencies = [
267
- "prisma",
268
- "@prisma/client",
269
- "typescript",
270
- "@types/node",
271
- "ts-node",
272
- "http-proxy-middleware",
273
- ];
274
- if (answer.tailwindcss) {
275
- dependencies.push("npm-run-all", "tailwindcss", "autoprefixer", "postcss");
276
- }
277
- await installDependencies(projectPath, dependencies, true);
278
- execSync(`npx prisma init`, { stdio: "inherit" });
279
- execSync(`npx tsc --init`, { stdio: "inherit" });
280
- if (answer.tailwindcss) {
281
- execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
282
- }
283
- const projectSettings = {
284
- PROJECT_NAME: answer.projectName,
285
- PROJECT_ROOT_PATH: projectPath.replace(/\\/g, "\\\\"),
286
- PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
287
- PHP_GENERATE_CLASS_PATH: "src/lib/prisma/classes",
288
- };
289
- await createDirectoryStructure(projectPath, answer, projectSettings);
290
- if (answer.tailwindcss) {
291
- execSync(`npx tailwindcss -i ./src/app/css/tailwind.css -o ./src/app/css/styles.css --minify`, { stdio: "inherit" });
292
- }
293
- // execSync(`composer install`, { stdio: "inherit" });
294
- // execSync(`composer dump-autoload`, { stdio: "inherit" });
295
- // Create settings file
296
- const settingsPath = path.join(projectPath, "settings", "project-settings.js");
297
- const settingsCode = `export const projectSettings = {
298
- PROJECT_NAME: "${answer.projectName}",
299
- PROJECT_ROOT_PATH: "${projectPath.replace(/\\/g, "\\\\")}",
300
- PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
301
- PHP_GENERATE_CLASS_PATH: "src/lib/prisma/classes",
302
- };`;
303
- fs.writeFileSync(settingsPath, settingsCode);
304
- // Create public directory
305
- fs.mkdirSync(path.join(projectPath, "public"));
306
- console.log(`${chalk.green("Success!")} Prisma PHP project successfully created in ${answer.projectName}!`);
307
- }
308
- catch (error) {
309
- console.error("Error while creating the project:", error);
310
- process.exit(1);
311
- }
312
- }
313
- main();
2
+ import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from"url";import path from"path";import chalk from"chalk";import prompts from"prompts";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);function configureBrowserSyncCommand(e,t){const s=t.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");if(-1===s)return"";const i=t.PROJECT_ROOT_PATH.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=t.PROJECT_ROOT_PATH.replace(new RegExp(`^${i}`),"").replace(/\\/g,"/");let c=`http://localhost/${n}`;c=c.endsWith("/")?c.slice(0,-1):c;const r=`\n const { createProxyMiddleware } = require("http-proxy-middleware");\n\n module.exports = {\n // Use the 'middleware' option to create a proxy that masks the deep URL.\n middleware: [\n // This middleware intercepts requests to the root and proxies them to the deep path.\n createProxyMiddleware("/", {\n target:\n "${c.replace(/(?<!:)(\/\/+)/g,"/")}",\n changeOrigin: true,\n pathRewrite: {\n "^/": "${n}", // Rewrite the path.\n },\n }),\n ],\n proxy: "http://localhost:3000", // Proxy the BrowserSync server.\n serveStatic: ["src/app"], // Serve static files from this directory.\n notify: false,\n };`,a=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(a,r,"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,t,s){const i=path.join(e,"package.json"),n=JSON.parse(fs.readFileSync(i,"utf8")),c=configureBrowserSyncCommand(e,t);n.scripts=Object.assign(Object.assign({},n.scripts),{postinstall:"prisma generate"}),s.tailwindcss?n.scripts=Object.assign(Object.assign({},n.scripts),{tailwind:"tailwindcss -i ./src/app/css/tailwind.css -o ./src/app/css/styles.css --minify --watch","browser-sync":c,dev:"npm-run-all --parallel browser-sync tailwind"}):n.scripts=Object.assign(Object.assign({},n.scripts),{dev:c}),n.type="module",n.prisma={seed:"node prisma/seed.js"},fs.writeFileSync(i,JSON.stringify(n,null,2))}async function createUpdateGitignoreFile(e,t){const s=path.join(e,".gitignore");let i="";fs.existsSync(s)&&(i=fs.readFileSync(s,"utf8")),t.forEach((e=>{i.includes(e)||(i+=`\n${e}`)})),i=i.trimStart(),fs.writeFileSync(s,i)}function copyRecursiveSync(e,t){const s=fs.existsSync(e),i=s&&fs.statSync(e);s&&i&&i.isDirectory()?(fs.mkdirSync(t,{recursive:!0}),fs.readdirSync(e).forEach((s=>copyRecursiveSync(path.join(e,s),path.join(t,s))))):fs.copyFileSync(e,t)}async function executeCopy(e,t){t.forEach((({srcDir:t,destDir:s})=>{copyRecursiveSync(path.join(__dirname,t),path.join(e,s))}))}function modifyTailwindConfig(e){const t=path.join(e,"tailwind.config.js");let s=fs.readFileSync(t,"utf8");const i=["./src/app/**/*.{php,html,js}"].map((e=>` "${e}"`)).join(",\n");s=s.replace(/content: \[\],/g,`content: [\n${i}\n],`),fs.writeFileSync(t,s,"utf8")}function modifyIndexPHP(e,t){const s=path.join(e,"src","app","layout.php");try{let i=fs.readFileSync(s,"utf8");const n=t?' <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet">':' <script src="https://cdn.tailwindcss.com"><\/script>';if(i=i.replace("</head>",`${n}\n</head>`),fs.writeFileSync(s,i,"utf8"),!t){const t=path.join(e,"src","app","css");fs.rm(t,{recursive:!0},(e=>{if(e)throw e}))}}catch(e){}}async function createDirectoryStructure(e,t,s){await executeCopy(e,[{srcDir:"/settings",destDir:"/settings"},{srcDir:"/prisma",destDir:"/prisma"},{srcDir:"/src",destDir:"/src"},{srcDir:"/../vendor",destDir:"/vendor"}]),await updatePackageJson(e,s,t),[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"},{src:"/../composer.lock",dest:"/composer.lock"}].forEach((({src:t,dest:s})=>{const i=path.join(__dirname,t),n=path.join(e,s),c=fs.readFileSync(i,"utf8");fs.writeFileSync(n,c)})),t.tailwindcss?(modifyTailwindConfig(e),modifyIndexPHP(e,!0)):modifyIndexPHP(e,!1)}async function getAnswer(){const e=[{type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"},{type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}],t=()=>!1;try{const s=await prompts(e,{onCancel:t});return 0===Object.keys(s).length?null:{projectName:String(s.projectName).trim().replace(/ /g,"-"),tailwindcss:s.tailwindcss}}catch(e){return null}}async function installDependencies(e,t,s=!1){execSync("npm init -y",{stdio:"inherit",cwd:e}),t.forEach((e=>{}));const i=`npm install ${s?"--save-dev":""} ${t.join(" ")}`;execSync(i,{stdio:"inherit",cwd:e})}async function main(){try{const e=await getAnswer();if(null===e)return;execSync("npm install -g create-prisma-php-app",{stdio:"inherit"}),execSync("npm install -g browser-sync",{stdio:"inherit"}),fs.mkdirSync(e.projectName);const t=path.join(process.cwd(),e.projectName);process.chdir(e.projectName);const s=["prisma","@prisma/client","typescript","@types/node","ts-node","http-proxy-middleware"];e.tailwindcss&&s.push("npm-run-all","tailwindcss","autoprefixer","postcss"),await installDependencies(t,s,!0),execSync("npx prisma init",{stdio:"inherit"}),execSync("npx tsc --init",{stdio:"inherit"}),e.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"});const i={PROJECT_NAME:e.projectName,PROJECT_ROOT_PATH:t.replace(/\\/g,"\\\\"),PHP_ROOT_PATH_EXE:"D:\\\\xampp\\\\php\\\\php.exe",PHP_GENERATE_CLASS_PATH:"src/lib/prisma/classes"};await createDirectoryStructure(t,e,i),e.tailwindcss&&execSync("npx tailwindcss -i ./src/app/css/tailwind.css -o ./src/app/css/styles.css --minify",{stdio:"inherit"});const n=path.join(t,"settings","project-settings.js"),c=`export const projectSettings = {\n PROJECT_NAME: "${e.projectName}",\n PROJECT_ROOT_PATH: "${t.replace(/\\/g,"\\\\")}",\n PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",\n PHP_GENERATE_CLASS_PATH: "src/lib/prisma/classes",\n };`;fs.writeFileSync(n,c),fs.mkdirSync(path.join(t,"public"))}catch(e){process.exit(1)}}main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "1.2.12",
3
+ "version": "1.2.13",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",