zoho-sites-dev-cli 0.0.0-stage → 1.0.1

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 (53) hide show
  1. package/README.md +396 -2
  2. package/bin/zoho-sites-dev-cli.js +108 -0
  3. package/config/default.json +26 -0
  4. package/index.js +6 -0
  5. package/package.json +55 -4
  6. package/src/commands/auth.js +125 -0
  7. package/src/commands/create.js +175 -0
  8. package/src/commands/deploy.js +409 -0
  9. package/src/commands/generate-zip.js +49 -0
  10. package/src/commands/index.js +23 -0
  11. package/src/commands/init-tailwind.js +57 -0
  12. package/src/commands/init.js +449 -0
  13. package/src/commands/install.js +90 -0
  14. package/src/commands/login.js +253 -0
  15. package/src/commands/pull.js +41 -0
  16. package/src/commands/serve.js +163 -0
  17. package/src/compilers/css-compiler.js +230 -0
  18. package/src/compilers/css-ignore-loader.js +33 -0
  19. package/src/compilers/plugins/index.js +12 -0
  20. package/src/compilers/plugins/root-selector-transform-plugin.js +79 -0
  21. package/src/compilers/tailwind-compiler.js +102 -0
  22. package/src/compilers/webpack-compiler.js +512 -0
  23. package/src/compilers/webpack-config.js +103 -0
  24. package/src/config/constants.js +164 -0
  25. package/src/config/environments/audiences.js +19 -0
  26. package/src/config/environments/index.js +78 -0
  27. package/src/config/environments/internal.js +72 -0
  28. package/src/config/environments/production.js +54 -0
  29. package/src/locales/en.json +216 -0
  30. package/src/services/devServer.js +583 -0
  31. package/src/services/oauthService.js +796 -0
  32. package/src/templates/component/fields.json +6 -0
  33. package/src/templates/component/index.js +11 -0
  34. package/src/templates/component/llm.md +9 -0
  35. package/src/templates/component/meta.json +9 -0
  36. package/src/templates/component/styles.css +3 -0
  37. package/src/templates/oauth/complete.html +41 -0
  38. package/src/templates/oauth/error.html +69 -0
  39. package/src/templates/oauth/invalid-request.html +58 -0
  40. package/src/templates/oauth/loading.html +80 -0
  41. package/src/templates/oauth/not-found.html +33 -0
  42. package/src/templates/oauth/success.html +70 -0
  43. package/src/templates/oauth/timeout.html +56 -0
  44. package/src/templates/oauth/token-error.html +57 -0
  45. package/src/utils/cliName.js +35 -0
  46. package/src/utils/configUtil.js +67 -0
  47. package/src/utils/httpUtil.js +351 -0
  48. package/src/utils/i18n.js +222 -0
  49. package/src/utils/loadingUtil.js +190 -0
  50. package/src/utils/secureConfig.js +75 -0
  51. package/src/utils/secureStorage.js +230 -0
  52. package/src/utils/templateLoader.js +89 -0
  53. package/src/utils/urlUtil.js +372 -0
@@ -0,0 +1,583 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const http = require("http");
4
+ const chokidar = require("chokidar");
5
+ const { i18n } = require("../utils/i18n.js");
6
+ const { SERVER_CONFIG, CONTENT_TYPES, WEBPACK_OVERRIDES_FILE } = require("../config/constants.js");
7
+ const WebpackCompiler = require("../compilers/webpack-compiler.js");
8
+
9
+ const { getNamespace } = require("../utils/configUtil.js");
10
+
11
+ /**
12
+ * Check whether targetPath is equal to or nested inside rootPath using path components.
13
+ */
14
+ function isPathWithinRoot(rootPath, targetPath) {
15
+ const relative = path.relative(rootPath, targetPath);
16
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
17
+ }
18
+
19
+ /**
20
+ * Resolve a relative request path within rootDir and verify containment both
21
+ * lexically and after resolving filesystem symlinks.
22
+ * @returns {{ status: "ok", filePath: string } | { status: "forbidden" } | { status: "missing" }}
23
+ */
24
+ function resolveContainedPath(rootDir, relPath) {
25
+ if (!rootDir) {
26
+ return { status: "missing" };
27
+ }
28
+
29
+ const resolvedRoot = path.resolve(rootDir);
30
+ const resolvedTarget = path.resolve(resolvedRoot, relPath || "");
31
+ if (!isPathWithinRoot(resolvedRoot, resolvedTarget)) {
32
+ return { status: "forbidden" };
33
+ }
34
+
35
+ if (!fs.existsSync(resolvedRoot)) {
36
+ return { status: "missing" };
37
+ }
38
+
39
+ let realRoot;
40
+ try {
41
+ realRoot = fs.realpathSync(resolvedRoot);
42
+ } catch (_) {
43
+ return { status: "missing" };
44
+ }
45
+
46
+ if (!fs.existsSync(resolvedTarget)) {
47
+ return { status: "missing" };
48
+ }
49
+
50
+ let realTarget;
51
+ try {
52
+ realTarget = fs.realpathSync(resolvedTarget);
53
+ } catch (_) {
54
+ return { status: "missing" };
55
+ }
56
+
57
+ if (!isPathWithinRoot(realRoot, realTarget)) {
58
+ return { status: "forbidden" };
59
+ }
60
+
61
+ return { status: "ok", filePath: realTarget };
62
+ }
63
+
64
+ /**
65
+ * Create filesystem-backed dev server serving component assets:
66
+ * /:namespace/__widgets/dist/index.js
67
+ * /:namespace/__widgets/dist/styles.css (combined CSS for all components)
68
+ * /:namespace/__widgets/dist/:component/fields.json
69
+ *
70
+ * Components already live on real disk, so this server compiles straight from/to
71
+ * disk (via WebpackCompiler) and serves each rebuild's real output directory —
72
+ * no in-memory filesystem is involved.
73
+ */
74
+ function createWebpackDevServerConfig(portOverride) {
75
+ const namespace = getNamespace();
76
+ const baseDir = process.cwd();
77
+ const compiler = new WebpackCompiler(baseDir, namespace, null, "development", {}, baseDir);
78
+ const cache = { lastBuildStats: null };
79
+
80
+ // Track which root directories currently look like components (have meta.json)
81
+ const isComponentRoot = (absDir) => {
82
+ try {
83
+ return fs.existsSync(path.join(absDir, "meta.json"));
84
+ } catch (_) {
85
+ return false;
86
+ }
87
+ };
88
+
89
+ const listRootDirectories = () => {
90
+ try {
91
+ return fs
92
+ .readdirSync(baseDir, { withFileTypes: true })
93
+ .filter((e) => e.isDirectory())
94
+ .map((e) => path.join(baseDir, e.name));
95
+ } catch (_) {
96
+ return [];
97
+ }
98
+ };
99
+
100
+ const componentRoots = new Set(
101
+ listRootDirectories().filter(isComponentRoot)
102
+ );
103
+
104
+ const rootWebpackOverrides = path.join(baseDir, WEBPACK_OVERRIDES_FILE);
105
+
106
+ // Current build's real output directory (dist), swapped after each successful rebuild
107
+ const getDistDir = () => compiler.outDir;
108
+
109
+ const rebuild = async () => {
110
+ try {
111
+ i18n.info("commands.serve.rebuilding");
112
+
113
+ const { stats } = await compiler.compile(namespace);
114
+ cache.lastBuildStats = stats || null;
115
+
116
+ // Verify styles.css was created
117
+ const distDir = getDistDir();
118
+ const stylesPath = distDir ? path.join(distDir, "styles.css") : null;
119
+ if (stylesPath && fs.existsSync(stylesPath)) {
120
+ const styleSize = fs.statSync(stylesPath).size;
121
+ i18n.info("commands.serve.stylesCompiled", { size: styleSize });
122
+ } else {
123
+ i18n.warning("commands.serve.noStylesFile");
124
+ }
125
+
126
+ i18n.success("commands.serve.buildComplete");
127
+ } catch (error) {
128
+ i18n.error("commands.serve.buildError", { error: error.message });
129
+ }
130
+ };
131
+
132
+ // HTTP server that serves assets from the current build's real dist directory
133
+ const server = http.createServer((req, res) => {
134
+ try {
135
+ const rawUrlPath = (req.url || "/").split("?")[0];
136
+ let urlPath;
137
+ try {
138
+ urlPath = decodeURIComponent(rawUrlPath);
139
+ } catch (_) {
140
+ res.setHeader("Access-Control-Allow-Origin", "*");
141
+ res.statusCode = 400;
142
+ res.end("Bad Request");
143
+ return;
144
+ }
145
+
146
+ if (urlPath.includes("\0")) {
147
+ res.setHeader("Access-Control-Allow-Origin", "*");
148
+ res.statusCode = 400;
149
+ res.end("Bad Request");
150
+ return;
151
+ }
152
+
153
+ const expectedPrefix = `/${namespace}/__widgets/dist`;
154
+ const distDir = getDistDir();
155
+
156
+ // Health check endpoint for debugging
157
+ if (urlPath === `/${namespace}/__widgets/health`) {
158
+ res.setHeader("Access-Control-Allow-Origin", "*");
159
+ res.setHeader("Content-Type", "application/json");
160
+
161
+ const listDistDir = (dirPath) => {
162
+ try {
163
+ if (!dirPath || !fs.existsSync(dirPath)) {
164
+ return null;
165
+ }
166
+ const items = fs.readdirSync(dirPath);
167
+ return items.map((item) => {
168
+ const fullPath = path.join(dirPath, item);
169
+ const stat = fs.statSync(fullPath);
170
+ return {
171
+ name: item,
172
+ type: stat.isDirectory() ? 'directory' : 'file',
173
+ size: stat.isFile() ? stat.size : undefined
174
+ };
175
+ });
176
+ } catch (e) {
177
+ return { error: e.message };
178
+ }
179
+ };
180
+
181
+ const metaJsonPath = distDir ? path.join(distDir, "meta.json") : null;
182
+ const metaJsonExists = !!metaJsonPath && fs.existsSync(metaJsonPath);
183
+ const metaJsonSize = metaJsonExists ? fs.statSync(metaJsonPath).size : 0;
184
+
185
+ // Check component directories for fields.json
186
+ const componentDetails = {};
187
+ const distContents = listDistDir(distDir);
188
+ if (distContents) {
189
+ for (const item of distContents) {
190
+ if (item.type === 'directory') {
191
+ const componentPath = path.join(distDir, item.name);
192
+ const componentFiles = listDistDir(componentPath);
193
+ const fieldsJsonPath = path.join(componentPath, "fields.json");
194
+ const hasFieldsJson = fs.existsSync(fieldsJsonPath);
195
+ componentDetails[item.name] = {
196
+ path: componentPath,
197
+ files: componentFiles,
198
+ hasFieldsJson,
199
+ fieldsJsonSize: hasFieldsJson ? fs.statSync(fieldsJsonPath).size : 0
200
+ };
201
+ }
202
+ }
203
+ }
204
+
205
+ const stylesPath = distDir ? path.join(distDir, "styles.css") : null;
206
+ const stylesExists = !!stylesPath && fs.existsSync(stylesPath);
207
+
208
+ const healthInfo = {
209
+ status: 'ok',
210
+ namespace,
211
+ expectedPrefix,
212
+ dist: {
213
+ distDir,
214
+ distExists: !!distDir && fs.existsSync(distDir),
215
+ distContents,
216
+ stylesExists,
217
+ stylesSize: stylesExists ? fs.statSync(stylesPath).size : 0,
218
+ metaJsonExists,
219
+ metaJsonSize,
220
+ componentDetails
221
+ },
222
+ components: componentRoots.size,
223
+ lastBuildStats: cache.lastBuildStats ? 'available' : 'not available'
224
+ };
225
+
226
+ res.statusCode = 200;
227
+ res.end(JSON.stringify(healthInfo, null, 2));
228
+ return;
229
+ }
230
+
231
+ // Validate URL path starts with expected prefix on a path boundary
232
+ if (urlPath !== expectedPrefix && !urlPath.startsWith(`${expectedPrefix}/`)) {
233
+ // Set CORS headers for 404 responses too
234
+ res.setHeader("Access-Control-Allow-Origin", "*");
235
+ res.setHeader(
236
+ "Access-Control-Allow-Methods",
237
+ "GET, POST, OPTIONS, PUT, PATCH, DELETE"
238
+ );
239
+ res.setHeader(
240
+ "Access-Control-Allow-Headers",
241
+ "X-Requested-With,content-type"
242
+ );
243
+ res.setHeader("Access-Control-Allow-Credentials", "true");
244
+
245
+ res.statusCode = 404;
246
+ res.end("Not Found");
247
+ return;
248
+ }
249
+
250
+ // Get relative path within the dist directory
251
+ const rel = urlPath.slice(expectedPrefix.length).replace(/^\/+/, "");
252
+ const isAssetsRequest = rel === "assets" || rel.startsWith("assets/");
253
+
254
+ // Serve disk-backed `assets/` folder directly at:
255
+ // /:namespace/__widgets/dist/assets/<file path>
256
+ if (isAssetsRequest) {
257
+ const relAssetPath = rel.replace(/^assets\/?/, "");
258
+ const assetsRoot = path.join(baseDir, "assets");
259
+ const resolvedAsset = resolveContainedPath(assetsRoot, relAssetPath);
260
+
261
+ if (resolvedAsset.status === "forbidden") {
262
+ res.setHeader("Access-Control-Allow-Origin", "*");
263
+ res.statusCode = 400;
264
+ res.end("Bad Request");
265
+ return;
266
+ }
267
+
268
+ if (resolvedAsset.status !== "ok" || fs.statSync(resolvedAsset.filePath).isDirectory()) {
269
+ res.setHeader("Access-Control-Allow-Origin", "*");
270
+ res.statusCode = 404;
271
+ res.end("Not Found");
272
+ return;
273
+ }
274
+
275
+ // Set CORS headers
276
+ res.setHeader("Access-Control-Allow-Origin", "*");
277
+ res.setHeader(
278
+ "Access-Control-Allow-Methods",
279
+ "GET, POST, OPTIONS, PUT, PATCH, DELETE"
280
+ );
281
+ res.setHeader(
282
+ "Access-Control-Allow-Headers",
283
+ "X-Requested-With,content-type"
284
+ );
285
+ res.setHeader("Access-Control-Allow-Credentials", "true");
286
+
287
+ // Handle preflight requests
288
+ if (req.method === "OPTIONS") {
289
+ res.statusCode = 200;
290
+ res.end();
291
+ return;
292
+ }
293
+
294
+ const ext = path.extname(resolvedAsset.filePath).toLowerCase();
295
+ const ctype = CONTENT_TYPES[ext] || "application/octet-stream";
296
+ res.setHeader("Content-Type", ctype);
297
+ res.end(fs.readFileSync(resolvedAsset.filePath));
298
+ return;
299
+ }
300
+
301
+ let resolvedDist = resolveContainedPath(distDir, rel || "");
302
+
303
+ if (resolvedDist.status === "forbidden") {
304
+ res.setHeader("Access-Control-Allow-Origin", "*");
305
+ res.statusCode = 400;
306
+ res.end("Bad Request");
307
+ return;
308
+ }
309
+
310
+ // If path is a directory, serve index.js by default (re-validating containment)
311
+ if (resolvedDist.status === "ok" && fs.statSync(resolvedDist.filePath).isDirectory()) {
312
+ resolvedDist = resolveContainedPath(distDir, path.join(rel || "", "index.js"));
313
+ if (resolvedDist.status === "forbidden") {
314
+ res.setHeader("Access-Control-Allow-Origin", "*");
315
+ res.statusCode = 400;
316
+ res.end("Bad Request");
317
+ return;
318
+ }
319
+ }
320
+
321
+ // Check if file exists and is not a directory
322
+ if (resolvedDist.status !== "ok" || fs.statSync(resolvedDist.filePath).isDirectory()) {
323
+ // Set CORS headers for 404 responses too
324
+ res.setHeader("Access-Control-Allow-Origin", "*");
325
+ res.setHeader(
326
+ "Access-Control-Allow-Methods",
327
+ "GET, POST, OPTIONS, PUT, PATCH, DELETE"
328
+ );
329
+ res.setHeader(
330
+ "Access-Control-Allow-Headers",
331
+ "X-Requested-With,content-type"
332
+ );
333
+ res.setHeader("Access-Control-Allow-Credentials", "true");
334
+
335
+ res.statusCode = 404;
336
+ res.end("Not Found");
337
+ return;
338
+ }
339
+
340
+ const distPath = resolvedDist.filePath;
341
+
342
+ // Set CORS headers
343
+ res.setHeader("Access-Control-Allow-Origin", "*");
344
+ res.setHeader(
345
+ "Access-Control-Allow-Methods",
346
+ "GET, POST, OPTIONS, PUT, PATCH, DELETE"
347
+ );
348
+ res.setHeader(
349
+ "Access-Control-Allow-Headers",
350
+ "X-Requested-With,content-type"
351
+ );
352
+ res.setHeader("Access-Control-Allow-Credentials", "true");
353
+
354
+ // Handle preflight requests
355
+ if (req.method === "OPTIONS") {
356
+ res.statusCode = 200;
357
+ res.end();
358
+ return;
359
+ }
360
+
361
+ // Set appropriate content type and serve file
362
+ const ext = path.extname(distPath).toLowerCase();
363
+ const ctype = CONTENT_TYPES[ext] || "application/octet-stream";
364
+ res.setHeader("Content-Type", ctype);
365
+ const content = fs.readFileSync(distPath);
366
+ res.end(content);
367
+ } catch (err) {
368
+ // Set CORS headers for error responses too
369
+ res.setHeader("Access-Control-Allow-Origin", "*");
370
+ res.setHeader(
371
+ "Access-Control-Allow-Methods",
372
+ "GET, POST, OPTIONS, PUT, PATCH, DELETE"
373
+ );
374
+ res.setHeader(
375
+ "Access-Control-Allow-Headers",
376
+ "X-Requested-With,content-type"
377
+ );
378
+ res.setHeader("Access-Control-Allow-Credentials", "true");
379
+
380
+ res.statusCode = 500;
381
+ res.end("Internal Server Error");
382
+ }
383
+ });
384
+
385
+ const parsedPort =
386
+ portOverride !== undefined && portOverride !== null && portOverride !== ""
387
+ ? Number(portOverride)
388
+ : NaN;
389
+ const listenPort =
390
+ Number.isInteger(parsedPort) && parsedPort >= 0
391
+ ? parsedPort
392
+ : SERVER_CONFIG.HTTP_PORT || 8083;
393
+ const listenHost = SERVER_CONFIG.HTTP_HOST || "127.0.0.1";
394
+ server.listen(listenPort, listenHost, () => {
395
+ i18n.info("commands.serve.serverRunning", { port: listenPort, namespace });
396
+ });
397
+
398
+ // Watch and rebuild — components already live on disk, so no mirroring step is
399
+ // needed; we just need to know when to trigger a rebuild.
400
+ const watcher = chokidar.watch(baseDir, {
401
+ ignored: [
402
+ /(^|\/)node_modules(\/|$)/,
403
+ /\/\.git\//,
404
+ /(^|\/)build(\/|$)/,
405
+ /(^|\/)coverage(\/|$)/
406
+ ],
407
+ persistent: true,
408
+ ignoreInitial: true
409
+ });
410
+
411
+ const queue = [];
412
+ let rebuilding = false;
413
+ const enqueueRebuild = () => {
414
+ queue.push(1);
415
+ if (rebuilding) {
416
+ return;
417
+ }
418
+ rebuilding = true;
419
+ (async () => {
420
+ while (queue.length) {
421
+ queue.length = 0;
422
+ await rebuild();
423
+ }
424
+ rebuilding = false;
425
+ })();
426
+ };
427
+
428
+ const getRootOfPath = (absPath) => {
429
+ const rel = path.relative(baseDir, absPath);
430
+ const [rootName] = rel.split(path.sep);
431
+ if (!rootName) {
432
+ return null;
433
+ }
434
+ return path.join(baseDir, rootName);
435
+ };
436
+
437
+ const isMetaJsonAtRoot = (absPath) => {
438
+ const root = getRootOfPath(absPath);
439
+ if (!root) {
440
+ return false;
441
+ }
442
+ return path.join(root, "meta.json") === absPath;
443
+ };
444
+
445
+ // Helper function to handle file add/change events
446
+ const handleFileAddOrChange = (p) => {
447
+ const root = getRootOfPath(p);
448
+ if (!root) {
449
+ return;
450
+ }
451
+
452
+ // Handle webpack config file changes
453
+ if (p === rootWebpackOverrides) {
454
+ enqueueRebuild();
455
+ return;
456
+ }
457
+
458
+ // Handle changes in known component roots
459
+ if (componentRoots.has(root)) {
460
+ enqueueRebuild();
461
+ return;
462
+ }
463
+
464
+ // Handle discovery of new components via meta.json
465
+ if (isMetaJsonAtRoot(p)) {
466
+ componentRoots.add(root);
467
+ enqueueRebuild();
468
+ }
469
+ };
470
+
471
+ // Set up file watchers
472
+ watcher.on("add", handleFileAddOrChange);
473
+ watcher.on("change", handleFileAddOrChange);
474
+
475
+ watcher.on("unlink", (p) => {
476
+ const root = getRootOfPath(p);
477
+ if (!root) {
478
+ return;
479
+ }
480
+ if (isMetaJsonAtRoot(p)) {
481
+ // Component removed
482
+ componentRoots.delete(root);
483
+ enqueueRebuild();
484
+ return;
485
+ }
486
+ if (componentRoots.has(root)) {
487
+ enqueueRebuild();
488
+ }
489
+ });
490
+
491
+ watcher.on("addDir", (p) => {
492
+ const root = getRootOfPath(p);
493
+ if (!root) {
494
+ return;
495
+ }
496
+ if (componentRoots.has(root)) {
497
+ enqueueRebuild();
498
+ }
499
+ });
500
+
501
+ watcher.on("unlinkDir", (p) => {
502
+ const root = getRootOfPath(p);
503
+ if (!root) {
504
+ return;
505
+ }
506
+ if (componentRoots.has(root)) {
507
+ enqueueRebuild();
508
+ }
509
+ });
510
+
511
+ // Perform initial build
512
+ rebuild();
513
+
514
+ const cleanup = () => {
515
+ try {
516
+ watcher.close();
517
+ } catch (_) {}
518
+ try {
519
+ server.close();
520
+ } catch (_) {}
521
+ try {
522
+ if (compiler.outDir) {
523
+ fs.rm(compiler.outDir, { recursive: true, force: true }, () => {});
524
+ }
525
+ } catch (_) {}
526
+ };
527
+
528
+ const getNamespaceComponentsIndexJS = () => {
529
+ try {
530
+ return fs.readFileSync(path.join(getDistDir(), "index.js"), "utf8");
531
+ } catch (_) {
532
+ return "export default {}";
533
+ }
534
+ };
535
+ const getComponentStyles = () => {
536
+ try {
537
+ return fs.readFileSync(path.join(getDistDir(), "styles.css"), "utf8");
538
+ } catch (_) {
539
+ return "";
540
+ }
541
+ };
542
+ const getComponentFields = (componentName) => {
543
+ try {
544
+ return JSON.parse(
545
+ fs.readFileSync(path.join(getDistDir(), componentName, "fields.json"), "utf8") || "{}"
546
+ );
547
+ } catch (_) {
548
+ return {};
549
+ }
550
+ };
551
+ const getAllMetaJson = () => {
552
+ try {
553
+ return JSON.parse(fs.readFileSync(path.join(getDistDir(), "meta.json"), "utf8") || "{}");
554
+ } catch (_) {
555
+ return {};
556
+ }
557
+ };
558
+ const getComponents = () => {
559
+ try {
560
+ return compiler.getComponentDirectories();
561
+ } catch (_) {
562
+ return [];
563
+ }
564
+ };
565
+
566
+ return {
567
+ cache,
568
+ watcher,
569
+ cleanup,
570
+ server,
571
+ getNamespaceComponentsIndexJS,
572
+ getComponentStyles,
573
+ getComponentFields,
574
+ getAllMetaJson,
575
+ getComponents
576
+ };
577
+ }
578
+
579
+ module.exports = {
580
+ createWebpackDevServerConfig,
581
+ isPathWithinRoot,
582
+ resolveContainedPath
583
+ };