create-prisma-php-app 1.22.507 → 1.23.0

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import chalk from"chalk";import{spawn}from"child_process";import fs from"fs";import path from"path";import prompts from"prompts";import{fileURLToPath}from"url";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename),args=process.argv.slice(2),readJsonFile=e=>{const t=fs.readFileSync(e,"utf8");return JSON.parse(t)},executeCommand=(e,t=[],o={})=>new Promise(((r,a)=>{const s=spawn(e,t,Object.assign({stdio:"inherit",shell:!0},o));s.on("error",(e=>{a(e)})),s.on("close",(e=>{0===e?r():a(new Error(`Process exited with code ${e}`))}))}));async function getAnswer(){const e=[{type:"toggle",name:"shouldProceed",message:`This command will update the ${chalk.blue("create-prisma-php-app")} package and overwrite all default files. ${chalk.blue("Do you want to proceed")}?`,initial:!1,active:"Yes",inactive:"No"}],t=await prompts(e,{onCancel:()=>{process.exit(0)}});return 0===Object.keys(t).length?null:t}const commandsToExecute={generateClass:"npx php generate class",update:"npx php update project"};
2
+ import chalk from"chalk";import{spawn}from"child_process";import fs from"fs";import path from"path";import prompts from"prompts";import{fileURLToPath}from"url";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename),args=process.argv.slice(2),readJsonFile=e=>{const t=fs.readFileSync(e,"utf8");return JSON.parse(t)},executeCommand=(e,t=[],o={})=>new Promise(((r,a)=>{const s=spawn(e,t,{stdio:"inherit",shell:!0,...o});s.on("error",(e=>{a(e)})),s.on("close",(e=>{0===e?r():a(new Error(`Process exited with code ${e}`))}))}));async function getAnswer(){const e=[{type:"toggle",name:"shouldProceed",message:`This command will update the ${chalk.blue("create-prisma-php-app")} package and overwrite all default files. ${chalk.blue("Do you want to proceed")}?`,initial:!1,active:"Yes",inactive:"No"}],t=await prompts(e,{onCancel:()=>{process.exit(0)}});return 0===Object.keys(t).length?null:t}const commandsToExecute={generateClass:"npx php generate class",update:"npx php update project"};
3
3
  const main = async () => {
4
4
  if (args.length === 0) {
5
5
  console.log("No command provided.");
@@ -14,9 +14,7 @@ const main = async () => {
14
14
  if (formattedCommand === commandsToExecute.update) {
15
15
  try {
16
16
  const answer = await getAnswer();
17
- if (
18
- !(answer === null || answer === void 0 ? void 0 : answer.shouldProceed)
19
- ) {
17
+ if (!answer?.shouldProceed) {
20
18
  console.log(chalk.red("Operation cancelled by the user."));
21
19
  return;
22
20
  }
@@ -0,0 +1,87 @@
1
+ import { createProxyMiddleware } from "http-proxy-middleware";
2
+ import { writeFileSync } from "fs";
3
+ import chokidar from "chokidar";
4
+ import browserSync, { BrowserSyncInstance } from "browser-sync";
5
+ import prismaPhpConfig from "../prisma-php.json";
6
+ import { generateFileListJson } from "./files-list.js";
7
+ import { join } from "path";
8
+ import { getFileMeta } from "./utils.js";
9
+
10
+ const { __dirname } = getFileMeta();
11
+
12
+ const bs: BrowserSyncInstance = browserSync.create();
13
+
14
+ // Watch for file changes (create, delete, save)
15
+ const watcher = chokidar.watch("src/app/**/*", {
16
+ ignored: /(^|[\/\\])\../, // Ignore dotfiles
17
+ persistent: true,
18
+ usePolling: true,
19
+ interval: 1000,
20
+ });
21
+
22
+ // Perform specific actions for file events
23
+ watcher
24
+ .on("add", () => {
25
+ generateFileListJson();
26
+ })
27
+ .on("change", () => {
28
+ generateFileListJson();
29
+ })
30
+ .on("unlink", () => {
31
+ generateFileListJson();
32
+ });
33
+
34
+ // BrowserSync initialization
35
+ bs.init(
36
+ {
37
+ proxy: "http://localhost:3000",
38
+ middleware: [
39
+ (_: any, res: any, next: any) => {
40
+ res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
41
+ res.setHeader("Pragma", "no-cache");
42
+ res.setHeader("Expires", "0");
43
+ next();
44
+ },
45
+ createProxyMiddleware({
46
+ target: prismaPhpConfig.bsTarget,
47
+ changeOrigin: true,
48
+ pathRewrite: {},
49
+ }),
50
+ ],
51
+ files: "src/**/*.*",
52
+ notify: false,
53
+ open: false,
54
+ ghostMode: false,
55
+ codeSync: true, // Disable synchronization of code changes across clients
56
+ watchOptions: {
57
+ usePolling: true,
58
+ interval: 1000,
59
+ },
60
+ },
61
+ (err, bsInstance) => {
62
+ if (err) {
63
+ console.error("BrowserSync failed to start:", err);
64
+ return;
65
+ }
66
+
67
+ // Retrieve the active URLs from the BrowserSync instance
68
+ const options = bsInstance.getOption("urls");
69
+ const localUrl = options.get("local");
70
+ const externalUrl = options.get("external");
71
+ const uiUrl = options.get("ui");
72
+ const uiExternalUrl = options.get("ui-external");
73
+
74
+ // Construct the URLs dynamically
75
+ const urls = {
76
+ local: localUrl,
77
+ external: externalUrl,
78
+ ui: uiUrl,
79
+ uiExternal: uiExternalUrl,
80
+ };
81
+
82
+ writeFileSync(
83
+ join(__dirname, "bs-config.json"),
84
+ JSON.stringify(urls, null, 2)
85
+ );
86
+ }
87
+ );
@@ -0,0 +1,51 @@
1
+ import { existsSync, readdirSync, statSync, writeFileSync } from "fs";
2
+ import { join, sep, relative } from "path";
3
+ import { getFileMeta } from "./utils.js";
4
+
5
+ const { __dirname } = getFileMeta();
6
+
7
+ // Define the directory and JSON file paths correctly
8
+ const dirPath = "src/app"; // Directory path
9
+ const jsonFilePath = "settings/files-list.json"; // Path to the JSON file
10
+
11
+ // Function to get all files in the directory
12
+ const getAllFiles = (dirPath: string): string[] => {
13
+ const files: string[] = [];
14
+
15
+ // Check if directory exists before reading
16
+ if (!existsSync(dirPath)) {
17
+ console.error(`Directory not found: ${dirPath}`);
18
+ return files; // Return an empty array if the directory doesn't exist
19
+ }
20
+
21
+ const items = readdirSync(dirPath);
22
+ items.forEach((item) => {
23
+ const fullPath = join(dirPath, item);
24
+ if (statSync(fullPath).isDirectory()) {
25
+ files.push(...getAllFiles(fullPath)); // Recursive call for subdirectories
26
+ } else {
27
+ // Generate the relative path and ensure it starts with ./src
28
+ const relativePath = `.${sep}${relative(
29
+ join(__dirname, ".."),
30
+ fullPath
31
+ )}`;
32
+ // Replace only the root backslashes with forward slashes and leave inner ones
33
+ files.push(relativePath.replace(/\\/g, "/").replace(/^\.\.\//, ""));
34
+ }
35
+ });
36
+
37
+ return files;
38
+ };
39
+
40
+ // Function to generate the files-list.json
41
+ export const generateFileListJson = async (): Promise<void> => {
42
+ const files = getAllFiles(dirPath);
43
+
44
+ // If files exist, generate JSON file
45
+ if (files.length > 0) {
46
+ writeFileSync(jsonFilePath, JSON.stringify(files, null, 2));
47
+ // console.log(`File list has been saved to: ${jsonFilePath}`);
48
+ } else {
49
+ console.error("No files found to save in the JSON file.");
50
+ }
51
+ };
@@ -0,0 +1,86 @@
1
+ import { writeFile } from "fs";
2
+ import { join, basename, dirname, normalize, sep } from "path";
3
+ import prismaPhpConfig from "../prisma-php.json";
4
+ import { getFileMeta } from "./utils.js";
5
+
6
+ const { __dirname } = getFileMeta();
7
+
8
+ const newProjectName = basename(join(__dirname, ".."));
9
+
10
+ // Function to update the project name and paths in the JSON config
11
+ function updateProjectNameInConfig(
12
+ filePath: string,
13
+ newProjectName: string
14
+ ): void {
15
+ const filePathDir = dirname(filePath);
16
+
17
+ // Update the projectName directly in the imported config
18
+ prismaPhpConfig.projectName = newProjectName;
19
+
20
+ // Update other paths
21
+ prismaPhpConfig.projectRootPath = filePathDir;
22
+
23
+ const targetPath = getTargetPath(filePathDir, prismaPhpConfig.phpEnvironment);
24
+
25
+ prismaPhpConfig.bsTarget = `http://localhost${targetPath}`;
26
+ prismaPhpConfig.bsPathRewrite["^/"] = targetPath;
27
+
28
+ // Save the updated config back to the JSON file
29
+ writeFile(
30
+ filePath,
31
+ JSON.stringify(prismaPhpConfig, null, 2),
32
+ "utf8",
33
+ (err) => {
34
+ if (err) {
35
+ console.error("Error writing the updated JSON file:", err);
36
+ return;
37
+ }
38
+ console.log(
39
+ "The project name, PHP path, and other paths have been updated successfully."
40
+ );
41
+ }
42
+ );
43
+ }
44
+
45
+ // Function to determine the target path for browser-sync
46
+ function getTargetPath(fullPath: string, environment: string): string {
47
+ const normalizedPath = normalize(fullPath);
48
+ const webDirectories: { [key: string]: string } = {
49
+ XAMPP: join("htdocs"),
50
+ WAMP: join("www"),
51
+ MAMP: join("htdocs"),
52
+ LAMP: join("var", "www", "html"),
53
+ LEMP: join("usr", "share", "nginx", "html"),
54
+ AMPPS: join("www"),
55
+ UniformServer: join("www"),
56
+ EasyPHP: join("data", "localweb"),
57
+ };
58
+
59
+ const webDir = webDirectories[environment.toUpperCase()];
60
+ if (!webDir) {
61
+ throw new Error(`Unsupported environment: ${environment}`);
62
+ }
63
+
64
+ const indexOfWebDir = normalizedPath
65
+ .toLowerCase()
66
+ .indexOf(normalize(webDir).toLowerCase());
67
+ if (indexOfWebDir === -1) {
68
+ throw new Error(`Web directory not found in path: ${webDir}`);
69
+ }
70
+
71
+ const startIndex = indexOfWebDir + webDir.length;
72
+ const subPath = normalizedPath.slice(startIndex);
73
+ const safeSeparatorRegex = new RegExp(
74
+ sep.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"),
75
+ "g"
76
+ );
77
+ const finalPath = subPath.replace(safeSeparatorRegex, "/") + "/";
78
+
79
+ return finalPath;
80
+ }
81
+
82
+ // Path to your JSON configuration file (for saving changes)
83
+ const configFilePath = join(__dirname, "..", "prisma-php.json");
84
+
85
+ // Run the function with your config file path and the new project name
86
+ updateProjectNameInConfig(configFilePath, newProjectName);
@@ -86,7 +86,7 @@ $scriptName = dirname($_SERVER['SCRIPT_NAME']);
86
86
  /**
87
87
  * @var string $baseUrl - The base URL of the request.
88
88
  */
89
- $baseUrl = $_prismaPHPSettings['ngrok'] ? 'src/app' : $protocol . $domainName . "$scriptName/src/app";
89
+ $baseUrl = '/src/app';
90
90
  /**
91
91
  * @var string $documentUrl - The document URL of the request.
92
92
  */
@@ -0,0 +1,57 @@
1
+ import { spawn, ChildProcess } from "child_process";
2
+ import { join } from "path";
3
+ import chokidar from "chokidar";
4
+ import { getFileMeta } from "./utils.js";
5
+
6
+ const { __dirname } = getFileMeta();
7
+
8
+ // Define paths
9
+ const phpPath = "php"; // Adjust if necessary to include the full path to PHP
10
+ const serverScriptPath = join(
11
+ __dirname,
12
+ "..",
13
+ "src",
14
+ "Lib",
15
+ "Websocket",
16
+ "server.php"
17
+ );
18
+
19
+ // Hold the server process
20
+ let serverProcess: ChildProcess | null = null;
21
+
22
+ const restartServer = (): void => {
23
+ // If a server process already exists, kill it
24
+ if (serverProcess) {
25
+ console.log("Stopping WebSocket server...");
26
+ serverProcess.kill("SIGINT"); // Adjust the signal as necessary for your environment
27
+ serverProcess = null;
28
+ }
29
+
30
+ // Start a new WebSocket server process
31
+ console.log("Starting WebSocket server...");
32
+ serverProcess = spawn(phpPath, [serverScriptPath]);
33
+
34
+ serverProcess.stdout?.on("data", (data: Buffer) => {
35
+ console.log(`WebSocket Server: ${data.toString()}`);
36
+ });
37
+
38
+ serverProcess.stderr?.on("data", (data: Buffer) => {
39
+ console.error(`WebSocket Server Error: ${data.toString()}`);
40
+ });
41
+
42
+ serverProcess.on("close", (code: number) => {
43
+ console.log(`WebSocket server process exited with code ${code}`);
44
+ });
45
+ };
46
+
47
+ // Initial start
48
+ restartServer();
49
+
50
+ // Watch for changes and restart the server
51
+ chokidar
52
+ .watch(join(__dirname, "..", "src", "Lib", "Websocket", "**", "*"))
53
+ .on("change", (path: string) => {
54
+ const fileChanged = path.split("\\").pop();
55
+ console.log(`File changed: src/Lib/Websocket/${fileChanged}`);
56
+ restartServer();
57
+ });
@@ -0,0 +1,66 @@
1
+ import swaggerJsdoc from "swagger-jsdoc";
2
+ import { writeFileSync } from "fs";
3
+ import { join } from "path";
4
+ import chalk from "chalk";
5
+ import { getFileMeta } from "./utils.js";
6
+ import bsConnectionInfo from "./bs-config.json";
7
+
8
+ const { __dirname } = getFileMeta();
9
+
10
+ export async function swaggerConfig(): Promise<void> {
11
+ const outputPath = join(
12
+ __dirname,
13
+ "../src/app/swagger-docs/apis/pphp-swagger.json"
14
+ );
15
+
16
+ const options = {
17
+ definition: {
18
+ openapi: "3.0.0",
19
+ info: {
20
+ title: "Prisma PHP API Documentation",
21
+ version: "1.0.0",
22
+ description: "API documentation for the Prisma PHP project",
23
+ },
24
+ servers: [
25
+ {
26
+ url: bsConnectionInfo.local, // For Development
27
+ description: "Development Server",
28
+ },
29
+ {
30
+ url: "your-production-domain", // For Production
31
+ description: "Production Server",
32
+ },
33
+ ],
34
+ components: {
35
+ securitySchemes: {
36
+ bearerAuth: {
37
+ type: "http",
38
+ scheme: "bearer",
39
+ bearerFormat: "JWT",
40
+ },
41
+ },
42
+ },
43
+ security: [
44
+ {
45
+ bearerAuth: [],
46
+ },
47
+ ],
48
+ },
49
+ apis: [join(__dirname, "../src/app/swagger-docs/apis/**/*.js")], // Adjust to match JavaScript file paths
50
+ };
51
+
52
+ // Generate the Swagger specification
53
+ const swaggerSpec = JSON.stringify(swaggerJsdoc(options), null, 2);
54
+
55
+ // Always generate the swagger.json file
56
+ try {
57
+ writeFileSync(outputPath, swaggerSpec, "utf-8");
58
+ console.log(
59
+ `Swagger JSON has been generated and saved to ${chalk.blue(
60
+ "src/app/swagger-docs/pphp-swagger.json"
61
+ )}`
62
+ );
63
+ } catch (error) {
64
+ console.error("Error saving Swagger JSON:", error);
65
+ }
66
+ }
@@ -0,0 +1,14 @@
1
+ import { fileURLToPath } from "url";
2
+ import { dirname } from "path";
3
+
4
+ /**
5
+ * Retrieves the file metadata including the filename and directory name.
6
+ *
7
+ * @param importMetaUrl - The URL of the module's import.meta.url.
8
+ * @returns An object containing the filename (`__filename`) and directory name (`__dirname`).
9
+ */
10
+ export function getFileMeta() {
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = dirname(__filename);
13
+ return { __filename, __dirname };
14
+ }
@@ -25,9 +25,9 @@
25
25
  // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
26
 
27
27
  /* Modules */
28
- "module": "NodeNext" /* Specify what module code is generated. */,
28
+ "module": "ESNext" /* Specify what module code is generated. */,
29
29
  // "rootDir": "./", /* Specify the root folder within your source files. */
30
- // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
30
+ "moduleResolution": "Node", /* Specify how TypeScript looks up a file from a given module specifier. */
31
31
  // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
32
  // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
33
  // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
@@ -74,7 +74,7 @@
74
74
  // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75
75
 
76
76
  /* Interop Constraints */
77
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
77
+ "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78
78
  // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79
79
  // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80
80
  "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
@@ -91,8 +91,8 @@
91
91
  // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92
92
  // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93
93
  // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
94
+ "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95
+ "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96
96
  // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97
97
  // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98
98
  // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "1.22.507",
3
+ "version": "1.23.0",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -1,75 +0,0 @@
1
- import { createProxyMiddleware } from "http-proxy-middleware";
2
- import { readFileSync, writeFileSync } from "fs";
3
- import chokidar from "chokidar";
4
- import browserSync from "browser-sync";
5
- // import prismaPhpConfig from "../prisma-php.json" assert { type: "json" };
6
- import { generateFileListJson } from "./files-list.js";
7
- import { join, dirname } from "path";
8
- import { fileURLToPath } from "url";
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = dirname(__filename);
11
- const bs = browserSync.create();
12
- const prismaPhpConfig = JSON.parse(readFileSync(join(__dirname, "..", "prisma-php.json")).toString("utf-8"));
13
- // Watch for file changes (create, delete, save)
14
- const watcher = chokidar.watch("src/app/**/*", {
15
- ignored: /(^|[\/\\])\../, // Ignore dotfiles
16
- persistent: true,
17
- usePolling: true,
18
- interval: 1000,
19
- });
20
- // Perform specific actions for file events
21
- watcher
22
- .on("add", (path) => {
23
- generateFileListJson();
24
- })
25
- .on("change", (path) => {
26
- generateFileListJson();
27
- })
28
- .on("unlink", (path) => {
29
- generateFileListJson();
30
- });
31
- // BrowserSync initialization
32
- bs.init({
33
- proxy: "http://localhost:3000",
34
- middleware: [
35
- (req, res, next) => {
36
- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
37
- res.setHeader("Pragma", "no-cache");
38
- res.setHeader("Expires", "0");
39
- next();
40
- },
41
- createProxyMiddleware({
42
- target: prismaPhpConfig.bsTarget,
43
- changeOrigin: true,
44
- pathRewrite: prismaPhpConfig.ngrok ? {} : prismaPhpConfig.bsPathRewrite,
45
- }),
46
- ],
47
- files: "src/**/*.*",
48
- notify: false,
49
- open: false,
50
- ghostMode: false,
51
- codeSync: true, // Disable synchronization of code changes across clients
52
- watchOptions: {
53
- usePolling: true,
54
- interval: 1000,
55
- },
56
- }, (err, bsInstance) => {
57
- if (err) {
58
- console.error("BrowserSync failed to start:", err);
59
- return;
60
- }
61
- // Retrieve the active URLs from the BrowserSync instance
62
- const options = bsInstance.getOption("urls");
63
- const localUrl = options.get("local");
64
- const externalUrl = options.get("external");
65
- const uiUrl = options.get("ui");
66
- const uiExternalUrl = options.get("ui-external");
67
- // Construct the URLs dynamically
68
- const urls = {
69
- local: localUrl,
70
- external: externalUrl,
71
- ui: uiUrl,
72
- uiExternal: uiExternalUrl,
73
- };
74
- writeFileSync(join(__dirname, "bs-config.json"), JSON.stringify(urls, null, 2));
75
- });
@@ -1,43 +0,0 @@
1
- import fs from "fs";
2
- import { join, sep, relative, dirname } from "path";
3
- import { fileURLToPath } from "url";
4
- const __filename = fileURLToPath(import.meta.url);
5
- const __dirname = dirname(__filename);
6
- // Define the directory and JSON file paths correctly
7
- const dirPath = "src/app"; // Directory path
8
- const jsonFilePath = "settings/files-list.json"; // Path to the JSON file
9
- // Function to get all files in the directory
10
- const getAllFiles = (dirPath) => {
11
- const files = [];
12
- // Check if directory exists before reading
13
- if (!fs.existsSync(dirPath)) {
14
- console.error(`Directory not found: ${dirPath}`);
15
- return files; // Return an empty array if the directory doesn't exist
16
- }
17
- const items = fs.readdirSync(dirPath);
18
- items.forEach((item) => {
19
- const fullPath = join(dirPath, item);
20
- if (fs.statSync(fullPath).isDirectory()) {
21
- files.push(...getAllFiles(fullPath)); // Recursive call for subdirectories
22
- }
23
- else {
24
- // Generate the relative path and ensure it starts with ./src
25
- const relativePath = `.${sep}${relative(join(__dirname, ".."), fullPath)}`;
26
- // Replace only the root backslashes with forward slashes and leave inner ones
27
- files.push(relativePath.replace(/\\/g, "/").replace(/^\.\.\//, ""));
28
- }
29
- });
30
- return files;
31
- };
32
- // Function to generate the files-list.json
33
- export const generateFileListJson = () => {
34
- const files = getAllFiles(dirPath);
35
- // If files exist, generate JSON file
36
- if (files.length > 0) {
37
- fs.writeFileSync(jsonFilePath, JSON.stringify(files, null, 2));
38
- // console.log(`File list has been saved to: ${jsonFilePath}`);
39
- }
40
- else {
41
- console.error("No files found to save in the JSON file.");
42
- }
43
- };
@@ -1,60 +0,0 @@
1
- import fs, { readFileSync } from "fs";
2
- import { join, basename, dirname, normalize, sep } from "path";
3
- import { fileURLToPath } from "url";
4
- // import prismaPhpConfig from "../prisma-php.json" assert { type: "json" };
5
- const __filename = fileURLToPath(import.meta.url);
6
- const __dirname = dirname(__filename);
7
- const prismaPhpConfig = JSON.parse(readFileSync(join(__dirname, "..", "prisma-php.json")).toString("utf-8"));
8
- const newProjectName = basename(join(__dirname, ".."));
9
- // Function to update the project name and paths in the JSON config
10
- function updateProjectNameInConfig(filePath, newProjectName) {
11
- const filePathDir = dirname(filePath);
12
- // Update the projectName directly in the imported config
13
- prismaPhpConfig.projectName = newProjectName;
14
- // Update other paths
15
- prismaPhpConfig.projectRootPath = filePathDir;
16
- const targetPath = getTargetPath(filePathDir, prismaPhpConfig.phpEnvironment);
17
- prismaPhpConfig.bsTarget = `http://localhost${targetPath}`;
18
- prismaPhpConfig.bsPathRewrite["^/"] = targetPath;
19
- // Save the updated config back to the JSON file
20
- fs.writeFile(filePath, JSON.stringify(prismaPhpConfig, null, 2), "utf8", (err) => {
21
- if (err) {
22
- console.error("Error writing the updated JSON file:", err);
23
- return;
24
- }
25
- console.log("The project name, PHP path, and other paths have been updated successfully.");
26
- });
27
- }
28
- // Function to determine the target path for browser-sync
29
- function getTargetPath(fullPath, environment) {
30
- const normalizedPath = normalize(fullPath);
31
- const webDirectories = {
32
- XAMPP: join("htdocs"),
33
- WAMP: join("www"),
34
- MAMP: join("htdocs"),
35
- LAMP: join("var", "www", "html"),
36
- LEMP: join("usr", "share", "nginx", "html"),
37
- AMPPS: join("www"),
38
- UniformServer: join("www"),
39
- EasyPHP: join("data", "localweb"),
40
- };
41
- const webDir = webDirectories[environment.toUpperCase()];
42
- if (!webDir) {
43
- throw new Error(`Unsupported environment: ${environment}`);
44
- }
45
- const indexOfWebDir = normalizedPath
46
- .toLowerCase()
47
- .indexOf(normalize(webDir).toLowerCase());
48
- if (indexOfWebDir === -1) {
49
- throw new Error(`Web directory not found in path: ${webDir}`);
50
- }
51
- const startIndex = indexOfWebDir + webDir.length;
52
- const subPath = normalizedPath.slice(startIndex);
53
- const safeSeparatorRegex = new RegExp(sep.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"), "g");
54
- const finalPath = subPath.replace(safeSeparatorRegex, "/") + "/";
55
- return finalPath;
56
- }
57
- // Path to your JSON configuration file (for saving changes)
58
- const configFilePath = join(__dirname, "..", "prisma-php.json");
59
- // Run the function with your config file path and the new project name
60
- updateProjectNameInConfig(configFilePath, newProjectName);
@@ -1,40 +0,0 @@
1
- import { spawn } from "child_process";
2
- import path, { dirname } from "path";
3
- import chokidar from "chokidar";
4
- import { fileURLToPath } from "url";
5
- const __filename = fileURLToPath(import.meta.url);
6
- const __dirname = dirname(__filename);
7
- // Define paths
8
- const phpPath = "php"; // Adjust if necessary to include the full path to PHP
9
- const serverScriptPath = path.join(__dirname, "..", "src", "Lib", "Websocket", "server.php");
10
- // Hold the server process
11
- let serverProcess = null;
12
- const restartServer = () => {
13
- // If a server process already exists, kill it
14
- if (serverProcess) {
15
- console.log("Stopping WebSocket server...");
16
- serverProcess.kill("SIGINT"); // Adjust the signal as necessary for your environment
17
- serverProcess = null;
18
- }
19
- // Start a new WebSocket server process
20
- console.log("Starting WebSocket server...");
21
- serverProcess = spawn(phpPath, [serverScriptPath]);
22
- serverProcess.stdout?.on("data", (data) => {
23
- console.log(`WebSocket Server: ${data.toString()}`);
24
- });
25
- serverProcess.stderr?.on("data", (data) => {
26
- console.error(`WebSocket Server Error: ${data.toString()}`);
27
- });
28
- serverProcess.on("close", (code) => {
29
- console.log(`WebSocket server process exited with code ${code}`);
30
- });
31
- };
32
- // Initial start
33
- restartServer();
34
- // Watch for changes and restart the server
35
- chokidar
36
- .watch(path.join(__dirname, "..", "src", "Lib", "Websocket", "**", "*"))
37
- .on("change", (path) => {
38
- console.log(`File changed: ${path}`);
39
- restartServer();
40
- });