@hubspot/cms-dev-server 0.4.0 → 0.4.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.
package/dist/run.js CHANGED
@@ -1,8 +1,1958 @@
1
1
  #!/usr/bin/env node
2
- import { getDevServerCommandLineOptions } from './lib/cli.js';
3
- import createDevServer from './createDevServer.js';
4
- const { webRoot, hubspotCliConfigPathOption, hubspotCliAccountNameOption, sslEnabledOption, storybook, } = getDevServerCommandLineOptions(process.argv);
2
+
3
+ // src/lib/cli.ts
4
+ import { resolve } from "path";
5
+ function getDevServerCommandLineOptions(argv) {
6
+ const args = [...argv];
7
+ const webRoot2 = args[2];
8
+ let hubspotCliConfigPathOption2;
9
+ let hubspotCliAccountNameOption2;
10
+ const configOptionIndex = args.findIndex(
11
+ (arg) => arg === "-c" || arg === "--config"
12
+ );
13
+ if (configOptionIndex > 0 && args.length > configOptionIndex) {
14
+ hubspotCliConfigPathOption2 = resolve(args[configOptionIndex + 1]);
15
+ args.splice(configOptionIndex, 2);
16
+ }
17
+ const accountOptionIndex = args.findIndex(
18
+ (arg) => arg === "-a" || arg === "--account"
19
+ );
20
+ if (accountOptionIndex > 0 && args.length > accountOptionIndex) {
21
+ hubspotCliAccountNameOption2 = args[accountOptionIndex + 1];
22
+ args.splice(accountOptionIndex, 2);
23
+ }
24
+ const sslEnabledOption2 = args.includes("--ssl") && !args.includes("--no-ssl");
25
+ const storybook2 = args.findIndex((arg) => arg === "--storybook") > 0;
26
+ return {
27
+ hubspotCliConfigPathOption: hubspotCliConfigPathOption2,
28
+ hubspotCliAccountNameOption: hubspotCliAccountNameOption2,
29
+ sslEnabledOption: sslEnabledOption2,
30
+ storybook: storybook2,
31
+ webRoot: webRoot2
32
+ };
33
+ }
34
+
35
+ // src/createDevServer.ts
36
+ import path7 from "path";
37
+ import url2 from "url";
38
+ import express2 from "express";
39
+ import http3 from "http";
40
+ import bodyParser from "body-parser";
41
+ import { spawn } from "child_process";
42
+ import { normalizePath as normalizePath4 } from "vite";
43
+
44
+ // src/routes/createDevServerRoutes.ts
45
+ import { Router } from "express";
46
+ import { createProxyMiddleware } from "http-proxy-middleware";
47
+
48
+ // src/routes/partial.ts
49
+ import path4 from "path";
50
+ import { normalizePath as normalizePath2 } from "vite";
51
+
52
+ // src/lib/fullOriginalUrlFromRequest.ts
53
+ function fullOriginalUrlFromRequest(request2) {
54
+ return `${request2.protocol}://${request2.get("host")}${request2.originalUrl}`;
55
+ }
56
+
57
+ // ../cms-js-internal/dist/index.js
58
+ import path from "path";
59
+ import stream from "stream";
60
+ import { renderToPipeableStream } from "react-dom/server";
61
+ import {
62
+ ServerRenderContext,
63
+ createServerRenderContext
64
+ } from "@hubspot/cms-components";
65
+ import { jsx } from "react/jsx-runtime";
66
+ import path2 from "path";
67
+ import { existsSync, readdirSync, lstatSync } from "fs";
68
+ import { join as joinPosix } from "path/posix";
69
+ import { basename } from "path";
70
+ import { cloneElement } from "react";
71
+ import { renderToStaticMarkup } from "react-dom/server";
72
+ var writeIslandDataToJsGlobal = (tweakedIslandsArray, indent = 0) => {
73
+ const indentString = new Array(indent).fill(" ").join("");
74
+ return `window.__islands = ${JSON.stringify(
75
+ tweakedIslandsArray.map(
76
+ ({
77
+ id,
78
+ moduleName,
79
+ moduleId,
80
+ props,
81
+ hydrateOn,
82
+ clientOnly,
83
+ priority,
84
+ url: url3
85
+ }) => {
86
+ return {
87
+ id,
88
+ moduleName,
89
+ moduleId,
90
+ props,
91
+ hydrateOn,
92
+ clientOnly,
93
+ priority,
94
+ url: url3
95
+ };
96
+ }
97
+ ),
98
+ null,
99
+ 2
100
+ ).replace(/\n/gm, `
101
+ ${indentString}`)};`;
102
+ };
103
+ function getIslandUrls(roots, viteDevServer) {
104
+ return roots.map((island) => {
105
+ const islandModule = viteDevServer.moduleGraph.getModuleById(
106
+ island.moduleId
107
+ );
108
+ if (!islandModule) {
109
+ throw new Error(`Unknown island moduleId: ${island.moduleId}`);
110
+ }
111
+ const tweakedIsland = {
112
+ ...island,
113
+ url: islandModule.url
114
+ };
115
+ return tweakedIsland;
116
+ });
117
+ }
118
+ var createIslandsGlobalJsForClientInDev = (roots, viteDevServer, indent) => {
119
+ return writeIslandDataToJsGlobal(getIslandUrls(roots, viteDevServer), indent);
120
+ };
121
+ var viteRoot;
122
+ var viteCommand;
123
+ function resolveIslandPlugin() {
124
+ return {
125
+ enforce: "pre",
126
+ name: "resolve-islands",
127
+ configResolved(config) {
128
+ viteRoot = config.root;
129
+ viteCommand = config.command;
130
+ },
131
+ load(id) {
132
+ if (id.endsWith("?island")) {
133
+ const [idWithNoParam] = id.split("?");
134
+ const componentExtension = path.extname(idWithNoParam);
135
+ const componentFilenameWithNoExtension = path.basename(
136
+ idWithNoParam,
137
+ componentExtension
138
+ );
139
+ const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
140
+ return `
141
+ const moduleId = '${viteCommand === "serve" ? idWithNoParam : modulePath}';
142
+
143
+ const lazyComponent = () => import('${idWithNoParam}');
144
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
145
+ lazyComponent.moduleId = moduleId;
146
+
147
+ export default lazyComponent;
148
+ `;
149
+ }
150
+ return null;
151
+ }
152
+ };
153
+ }
154
+ var promiseForNewWritableStream = () => {
155
+ const chunks = [];
156
+ const writableStream = new stream.Writable();
157
+ writableStream._write = (chunk, encoding, done) => {
158
+ chunks.push(Buffer.from(chunk));
159
+ done();
160
+ };
161
+ const streamDonePromise = new Promise((resolve3, reject) => {
162
+ writableStream.on("error", (error) => {
163
+ reject(error);
164
+ });
165
+ writableStream._final = (done) => {
166
+ resolve3(Buffer.concat(chunks).toString("utf8"));
167
+ done();
168
+ };
169
+ });
170
+ return { streamDonePromise, writableStream };
171
+ };
172
+ var renderStreamToPromise = async (reactElements) => {
173
+ const { streamDonePromise, writableStream } = promiseForNewWritableStream();
174
+ const {
175
+ pipe
176
+ /* abort */
177
+ } = renderToPipeableStream(reactElements, {
178
+ onShellReady() {
179
+ },
180
+ onAllReady() {
181
+ pipe(writableStream);
182
+ }
183
+ // We will log the error sent to the writable, any need to do something in these callbacks?
184
+ // onShellError(error) {},
185
+ // onError(error) {},
186
+ });
187
+ return streamDonePromise;
188
+ };
189
+ var scriptTagToLogServerMessages = (messagesForBrowser, groupLabel) => {
190
+ if (!messagesForBrowser) {
191
+ return "";
192
+ }
193
+ const consoleLines = [];
194
+ for (const message of messagesForBrowser) {
195
+ const funcString = message.level === "error" ? "console.error" : "console.warn";
196
+ const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
197
+ consoleLines.push(` ${funcString}(${argString});`);
198
+ }
199
+ let groupStart = "";
200
+ let groupEnd = "";
201
+ if (groupLabel !== null) {
202
+ groupStart = `
203
+ console.group(${JSON.stringify(groupLabel)});`;
204
+ groupEnd = ` console.groupEnd()
205
+ `;
206
+ }
207
+ return `<script>${groupStart}
208
+ ${consoleLines.join("\n")}
209
+ ${groupEnd}</script>
210
+ `;
211
+ };
212
+ async function renderOnServer(elements, pageUrl, environmentConfig, debugName) {
213
+ const renderContext = createServerRenderContext(pageUrl, environmentConfig);
214
+ let html = await renderStreamToPromise(
215
+ /* @__PURE__ */ jsx(ServerRenderContext.Provider, { value: renderContext, children: elements })
216
+ );
217
+ if (renderContext.messagesForBrowser.length > 0) {
218
+ html = `${html}${scriptTagToLogServerMessages(
219
+ renderContext.messagesForBrowser,
220
+ `Server messages rendering: ${debugName}`
221
+ )}`;
222
+ }
223
+ return { html, renderContext };
224
+ }
225
+ var COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
226
+ var ENTRY_POINTS_PATH = "components/partials/";
227
+ var MODULE_FOLDER_PATH = "components/modules/";
228
+ var getComponentExtension = (componentPath) => {
229
+ const filteredExtensions = COMPONENT_EXTENSIONS.filter(
230
+ (ext) => componentPath.endsWith(ext)
231
+ );
232
+ if (filteredExtensions.length === 1) {
233
+ return filteredExtensions[0];
234
+ }
235
+ return void 0;
236
+ };
237
+ var hasComponentExtension = (componentPath) => {
238
+ return !!getComponentExtension(componentPath);
239
+ };
240
+ var isStorybookStory = (componentPath) => {
241
+ return !!path2.basename(componentPath, path2.extname(componentPath)).endsWith(".stories");
242
+ };
243
+ var removeComponentExtension = (componentPath) => {
244
+ const ext = getComponentExtension(componentPath);
245
+ if (ext == null) {
246
+ return componentPath;
247
+ }
248
+ return componentPath.slice(0, -1 * ext.length);
249
+ };
250
+ var findAllComponentsIn = (webRoot2, componentsFolder, includeSubdirIndexJS) => {
251
+ const fullComponentsFolderPath = joinPosix(webRoot2, componentsFolder);
252
+ const componentsByName = {};
253
+ if (!existsSync(fullComponentsFolderPath)) {
254
+ return componentsByName;
255
+ }
256
+ readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
257
+ const fullPath = joinPosix(fullComponentsFolderPath, fileOrFolderName);
258
+ const subdirPath = joinPosix(componentsFolder, fileOrFolderName);
259
+ const isDirectory = lstatSync(fullPath).isDirectory();
260
+ if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
261
+ const subdirPathNoExtension = removeComponentExtension(subdirPath);
262
+ componentsByName[subdirPathNoExtension] = subdirPath;
263
+ } else if (isDirectory && includeSubdirIndexJS) {
264
+ for (const potentialExtension of COMPONENT_EXTENSIONS) {
265
+ const potentialIndexModule = joinPosix(
266
+ subdirPath,
267
+ `index${potentialExtension}`
268
+ );
269
+ const fullPotentialPath = joinPosix(
270
+ fullPath,
271
+ `index${potentialExtension}`
272
+ );
273
+ if (existsSync(fullPotentialPath)) {
274
+ const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
275
+ componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
276
+ break;
277
+ }
278
+ }
279
+ }
280
+ });
281
+ return componentsByName;
282
+ };
283
+ var findAllComponentsIn_default = findAllComponentsIn;
284
+ function findAllModulesInRoot(webRoot2) {
285
+ const allModuleComponents = findAllComponentsIn_default(
286
+ webRoot2,
287
+ "./components/modules",
288
+ true
289
+ );
290
+ const moduleNames = Object.keys(allModuleComponents).map(
291
+ (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
292
+ );
293
+ const moduleSubpaths = Object.keys(allModuleComponents);
294
+ return { moduleNames, moduleSubpaths };
295
+ }
296
+ function findAllPartialsInRoot(webRoot2) {
297
+ const allPartialComponents = findAllComponentsIn_default(
298
+ webRoot2,
299
+ "./components/partials",
300
+ false
301
+ );
302
+ const partialSubpaths = Object.keys(allPartialComponents);
303
+ const partialNames = partialSubpaths.map(
304
+ (partialSubpath) => basename(partialSubpath)
305
+ );
306
+ return { partialNames, partialSubpaths };
307
+ }
308
+ function getServerGlobalsToInject(environmentConfig, hsServerPageUrl) {
309
+ const globals = [
310
+ `window.__hsEnvConfig = ${JSON.stringify(environmentConfig.toJSON())};`
311
+ ];
312
+ if (hsServerPageUrl) {
313
+ globals.push(`window.__hsServerPageUrl = '${hsServerPageUrl}';`);
314
+ }
315
+ return `
316
+ <script type="text/javascript">
317
+ ${globals.join("\n ")}
318
+ </script>
319
+ `;
320
+ }
321
+ function setIn(object, nestedKeysArray, value) {
322
+ let curr = object;
323
+ const finalKey = nestedKeysArray.pop();
324
+ for (let index = 0; index < nestedKeysArray.length; index++) {
325
+ const currentKey = nestedKeysArray[index];
326
+ const nextKey = nestedKeysArray[index + 1];
327
+ if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {
328
+ if (curr[currentKey] === void 0) {
329
+ curr[currentKey] = [];
330
+ }
331
+ }
332
+ if (curr[currentKey] === void 0) {
333
+ curr[currentKey] = {};
334
+ }
335
+ curr = curr[currentKey];
336
+ }
337
+ if (value !== void 0) {
338
+ curr[finalKey] = value;
339
+ }
340
+ }
341
+ function renderFieldsToJson(fields) {
342
+ let moduleJson;
343
+ const outputCallback = (callbackJson) => {
344
+ moduleJson = callbackJson;
345
+ };
346
+ renderToStaticMarkup(
347
+ cloneElement(fields, {
348
+ outputCallback
349
+ })
350
+ );
351
+ return moduleJson;
352
+ }
353
+
354
+ // src/lib/moduleGraph.ts
355
+ var findFullPathInModuleGraph = (modulePathNoExtension, moduleGraph) => {
356
+ for (const extension of COMPONENT_EXTENSIONS) {
357
+ const pathToTry = `${modulePathNoExtension}${extension}`;
358
+ if (moduleGraph.fileToModulesMap.has(pathToTry)) {
359
+ return pathToTry;
360
+ }
361
+ }
362
+ };
363
+
364
+ // src/lib/packagePath.ts
365
+ import path3 from "path";
366
+ import url from "url";
367
+ import { normalizePath } from "vite";
368
+ function packagePath(metaUrl, projectPath) {
369
+ if (true) {
370
+ return path3.resolve(path3.dirname(url.fileURLToPath(metaUrl)), projectPath);
371
+ }
372
+ const parentDirPath = normalizePath(path3.dirname(url.fileURLToPath(metaUrl)));
373
+ const subPath = parentDirPath.replace(/^.+cms-dev-server\/src\//, "");
374
+ const subPathParentDirs = subPath.split("/").map(() => "..");
375
+ return path3.resolve(
376
+ path3.dirname(url.fileURLToPath(metaUrl)),
377
+ path3.join(...subPathParentDirs, projectPath)
378
+ );
379
+ }
380
+
381
+ // src/lib/renderComponentWithCSS.ts
382
+ async function renderComponentWithCSS(viteServer, componentPath, Component, props, pageUrl, environmentConfig) {
383
+ const internalSsrPath = packagePath(import.meta.url, "internalSsr");
384
+ const { renderComponentOnServer, collectCssInDev } = await viteServer.ssrLoadModule(internalSsrPath);
385
+ let componentPathWithExtension;
386
+ let componentPathNoExtension;
387
+ if (hasComponentExtension(componentPath)) {
388
+ componentPathWithExtension = componentPath;
389
+ componentPathNoExtension = removeComponentExtension(componentPath);
390
+ } else {
391
+ componentPathNoExtension = componentPath;
392
+ }
393
+ const { html, renderContext } = await renderComponentOnServer(
394
+ Component,
395
+ props,
396
+ pageUrl,
397
+ environmentConfig
398
+ );
399
+ if (!componentPathWithExtension) {
400
+ componentPathWithExtension = findFullPathInModuleGraph(
401
+ componentPathNoExtension,
402
+ viteServer.moduleGraph
403
+ );
404
+ if (!componentPathWithExtension) {
405
+ throw new Error(
406
+ `Couldn't find full path to component: ${componentPathNoExtension}`
407
+ );
408
+ }
409
+ }
410
+ const cssNeeded = collectCssInDev(componentPathWithExtension, viteServer);
411
+ return { html, cssNeeded, renderContext };
412
+ }
413
+ var renderComponentWithCSS_default = renderComponentWithCSS;
414
+
415
+ // src/lib/renderHelpers.ts
416
+ function getByteSizeOf(props) {
417
+ return Buffer.from(JSON.stringify(props)).length;
418
+ }
419
+ function formatBytesToString(bytes) {
420
+ if (bytes > 1e6) {
421
+ return ["\x1B[31m", `${(bytes / 1e6).toFixed(2)}mb`, `\x1B[0m`];
422
+ } else if (bytes > 1e4) {
423
+ return ["\x1B[33m", `${(bytes / 1e3).toFixed(2)}kb`, `\x1B[0m`];
424
+ } else {
425
+ return ["\x1B[32m", `${(bytes / 1e3).toFixed(2)}kb`, `\x1B[0m`];
426
+ }
427
+ }
428
+ var getPropsInfo = (props, reportOptions = { showNestedKeySizeIfGreater: null }, recursionDepth = 0) => {
429
+ if (recursionDepth > 8) {
430
+ return [];
431
+ }
432
+ const propsSizeInBytes = getByteSizeOf(props);
433
+ const result = formatBytesToString(propsSizeInBytes);
434
+ if (!Array.isArray(props) && Object.keys(props).length > 0 && reportOptions.showNestedKeySizeIfGreater != null && propsSizeInBytes > reportOptions.showNestedKeySizeIfGreater) {
435
+ for (const [key, value] of Object.entries(props)) {
436
+ const size = getPropsInfo(value, reportOptions, recursionDepth + 1);
437
+ if (Array.isArray(value)) {
438
+ result.push("\n", `${key}[${value.length}]`, ...size);
439
+ } else {
440
+ result.push("\n", key, ...size);
441
+ }
442
+ }
443
+ }
444
+ return result.flat();
445
+ };
446
+ var logPartialInfo = (partialPath, props) => {
447
+ console.log("Rendering partial", partialPath);
448
+ console.group();
449
+ console.log(
450
+ "Props size: ",
451
+ ...getPropsInfo(props, { showNestedKeySizeIfGreater: 1e6 })
452
+ );
453
+ console.groupEnd();
454
+ };
455
+
456
+ // src/lib/renderPartial.ts
457
+ async function renderPartial(viteServer, partialPath, props, pageUrl, environmentConfig) {
458
+ logPartialInfo(partialPath, props);
459
+ const componentModule = await viteServer.ssrLoadModule(partialPath);
460
+ if (!componentModule) {
461
+ throw new Error(`Couldn't find partial: ${partialPath}`);
462
+ }
463
+ const Component = componentModule.default;
464
+ if (!Component) {
465
+ throw new Error(`Couldn't find default export on partial: ${partialPath}`);
466
+ }
467
+ return renderComponentWithCSS_default(
468
+ viteServer,
469
+ partialPath,
470
+ Component,
471
+ props,
472
+ pageUrl,
473
+ environmentConfig
474
+ );
475
+ }
476
+ var renderPartial_default = renderPartial;
477
+
478
+ // src/lib/templates.ts
479
+ import { promises as fsPromises } from "fs";
480
+ var { readFile } = fsPromises;
481
+ var generateIslandSetupScriptBlock = () => {
482
+ return `<script type="module">
483
+ import { initConfigSingletonFromJSON } from '@hubspot/cms-components/config';
484
+ initConfigSingletonFromJSON(window.__hsEnvConfig);
485
+ </script>
486
+ <script type="module">
487
+ import { setupIslandHydration } from '@hubspot/cms-components/island-runtime';
488
+ setupIslandHydration();
489
+ </script>
490
+ `;
491
+ };
492
+ var createdPlainHtmlTemplate = async (baseTemplatePath, title, globalScriptBlock) => {
493
+ const htmlTemplateBase = await readFile(baseTemplatePath, "utf-8");
494
+ return htmlTemplateBase.replace("<!--title-->", title).replace(
495
+ "<!--bodyend-->",
496
+ `
497
+ ${globalScriptBlock}
498
+ <!--bodyend-->`
499
+ );
500
+ };
501
+ var createIslandHtmlTemplate = async (baseTemplatePath, title, globalScriptBlock) => {
502
+ let htmlTemplate = await createdPlainHtmlTemplate(
503
+ baseTemplatePath,
504
+ title,
505
+ globalScriptBlock
506
+ );
507
+ htmlTemplate = htmlTemplate.replace(
508
+ "<!--bodyend-->",
509
+ `
510
+ ${generateIslandSetupScriptBlock()}
511
+ <!-- ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK -->
512
+ <!--islandsglobal-->
513
+ `
514
+ );
515
+ return htmlTemplate;
516
+ };
517
+ var createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url3, title, renderContext, viteServer) => {
518
+ let htmlTemplate;
519
+ if (renderContext.islands.length) {
520
+ const globalScriptBlock = getServerGlobalsToInject(
521
+ renderContext.environmentConfig,
522
+ renderContext.pageUrl
523
+ );
524
+ htmlTemplate = await createIslandHtmlTemplate(
525
+ baseTemplatePath,
526
+ title,
527
+ globalScriptBlock
528
+ );
529
+ htmlTemplate = htmlTemplate.replace(
530
+ "<!--islandsglobal-->",
531
+ `<script>
532
+ ${createIslandsGlobalJsForClientInDev(renderContext.islands, viteServer, 4)}
533
+ </script>
534
+ `
535
+ );
536
+ } else {
537
+ const globalScriptBlock = getServerGlobalsToInject(
538
+ renderContext.environmentConfig
539
+ );
540
+ htmlTemplate = await createdPlainHtmlTemplate(
541
+ baseTemplatePath,
542
+ title,
543
+ globalScriptBlock
544
+ );
545
+ }
546
+ return viteServer.transformIndexHtml(url3, htmlTemplate);
547
+ };
548
+ var getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer) => {
549
+ const internalSsrPath = packagePath(import.meta.url, "internalSsr");
550
+ const { createIslandsGlobalJsForClientInDev: createIslandsGlobalJsForClientInDev2 } = await viteServer.ssrLoadModule(internalSsrPath);
551
+ const islandRuntimeScript = await viteServer.transformIndexHtml(
552
+ "/",
553
+ generateIslandSetupScriptBlock()
554
+ );
555
+ return `${islandRuntimeScript}
556
+ <script>${createIslandsGlobalJsForClientInDev2(
557
+ sortedIslandRoots,
558
+ viteServer,
559
+ 4
560
+ )}</script>
561
+ `;
562
+ };
563
+
564
+ // src/routes/partial.ts
565
+ import { buildStaticEnvConfig } from "@hubspot/cms-components/config";
566
+ var partialRouteHandler = async (request2, response) => {
567
+ const { authedPortalId, authedEnv, authedHublet, webRoot: webRoot2, viteServer } = request2.app.locals;
568
+ const partialName = request2.params.partial;
569
+ const baseTemplatePath = packagePath(
570
+ import.meta.url,
571
+ "html/baseTemplate.html"
572
+ );
573
+ const partialPath = normalizePath2(
574
+ path4.resolve(webRoot2, "components/partials/", partialName)
575
+ );
576
+ const environmentConfig = buildStaticEnvConfig(
577
+ authedPortalId,
578
+ authedHublet,
579
+ authedEnv,
580
+ false
581
+ );
582
+ try {
583
+ const {
584
+ html: renderedHtml,
585
+ cssNeeded,
586
+ renderContext
587
+ } = await renderPartial_default(
588
+ viteServer,
589
+ partialPath,
590
+ {},
591
+ fullOriginalUrlFromRequest(request2),
592
+ environmentConfig
593
+ );
594
+ const htmlShell = await createHtmlShellDependingOnRenderContext(
595
+ baseTemplatePath,
596
+ request2.originalUrl,
597
+ `Partial: ${partialPath}`,
598
+ renderContext,
599
+ viteServer
600
+ );
601
+ const html = htmlShell.replace("<!--headend-->", cssNeeded).replace(`<!--ssr-outlet-->`, renderedHtml);
602
+ response.status(200).set({ "Content-Type": "text/html" }).end(html);
603
+ } catch (e) {
604
+ console.error(e);
605
+ viteServer.ssrFixStacktrace(e);
606
+ response.status(500).end(`Error rendering partial (${partialName})
607
+
608
+ ${e.stack}`);
609
+ }
610
+ };
611
+ var partial_default = partialRouteHandler;
612
+
613
+ // src/components/PartialsList.tsx
614
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
615
+ function EmptyPartialsList({ webRoot: webRoot2 }) {
616
+ return /* @__PURE__ */ jsxs("p", { children: [
617
+ "No partials in ",
618
+ /* @__PURE__ */ jsxs("code", { children: [
619
+ webRoot2,
620
+ "components/partials"
621
+ ] })
622
+ ] });
623
+ }
624
+ function PartialLinkInLI({ partialName }) {
625
+ return /* @__PURE__ */ jsx2("li", { children: /* @__PURE__ */ jsx2("a", { href: `/partial/${partialName}`, children: partialName }) });
626
+ }
627
+ function PartialsList({ webRoot: webRoot2, partialNames }) {
628
+ if (partialNames.length === 0) {
629
+ return /* @__PURE__ */ jsx2(EmptyPartialsList, { webRoot: webRoot2 });
630
+ }
631
+ return /* @__PURE__ */ jsx2("ul", { children: partialNames.map((partialName) => /* @__PURE__ */ jsx2(PartialLinkInLI, { partialName }, partialName)) });
632
+ }
633
+
634
+ // src/routes/linksToAllPartialsRouteHandler.tsx
635
+ import { jsx as jsx3 } from "react/jsx-runtime";
636
+ var linksToAllPartialRouteHandler = async (request2, response) => {
637
+ const { webRoot: webRoot2 } = request2.app.locals;
638
+ const { partialNames } = findAllPartialsInRoot(webRoot2);
639
+ const { html: responseHtml } = await renderOnServer(
640
+ /* @__PURE__ */ jsx3(PartialsList, { webRoot: webRoot2, partialNames }),
641
+ null,
642
+ null
643
+ );
644
+ response.status(200).set({ "Content-Type": "text/html" }).end(responseHtml);
645
+ };
646
+ var linksToAllPartialsRouteHandler_default = linksToAllPartialRouteHandler;
647
+
648
+ // src/components/ModulesList.tsx
649
+ import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
650
+ function EmptyModulesList({ webRoot: webRoot2 }) {
651
+ return /* @__PURE__ */ jsxs2("p", { children: [
652
+ "No modules in ",
653
+ /* @__PURE__ */ jsxs2("code", { children: [
654
+ webRoot2,
655
+ "components/modules"
656
+ ] })
657
+ ] });
658
+ }
659
+ function ModuleLinkInLI({ moduleName }) {
660
+ return /* @__PURE__ */ jsx4("li", { children: /* @__PURE__ */ jsx4("a", { href: `/module/${moduleName}`, children: moduleName }) });
661
+ }
662
+ function ModulesList({ webRoot: webRoot2, moduleNames }) {
663
+ if (moduleNames.length === 0) {
664
+ return /* @__PURE__ */ jsx4(EmptyModulesList, { webRoot: webRoot2 });
665
+ }
666
+ return /* @__PURE__ */ jsx4("ul", { children: moduleNames.map((moduleName) => /* @__PURE__ */ jsx4(ModuleLinkInLI, { moduleName }, moduleName)) });
667
+ }
668
+ var ModulesList_default = ModulesList;
669
+
670
+ // src/routes/linksToAllModulesRouteHandler.tsx
671
+ import { jsx as jsx5 } from "react/jsx-runtime";
672
+ var linksToAllModuleRouteHandler = async (request2, response) => {
673
+ const { webRoot: webRoot2 } = request2.app.locals;
674
+ const { moduleNames } = findAllModulesInRoot(webRoot2);
675
+ const { html: responseHtml } = await renderOnServer(
676
+ /* @__PURE__ */ jsx5(ModulesList_default, { webRoot: webRoot2, moduleNames }),
677
+ null,
678
+ null
679
+ );
680
+ response.status(200).set({ "Content-Type": "text/html" }).end(responseHtml);
681
+ };
682
+ var linksToAllModulesRouteHandler_default = linksToAllModuleRouteHandler;
683
+
684
+ // src/routes/module.ts
685
+ import { buildStaticEnvConfig as buildStaticEnvConfig2 } from "@hubspot/cms-components/config";
686
+ import path5 from "path";
687
+ import { normalizePath as normalizePath3 } from "vite";
688
+
689
+ // src/lib/renderModule.ts
690
+ import { join as joinPosix2 } from "path/posix";
691
+ import { traverseFieldsJSON } from "@hubspot/cms-components/fields";
692
+ var lookForModuleInFolder = async (modulePath, viteServer) => {
693
+ let componentModule;
694
+ const insideFolderPath = joinPosix2(modulePath, "index");
695
+ try {
696
+ componentModule = await viteServer.ssrLoadModule(insideFolderPath);
697
+ } catch (e) {
698
+ if (!e.message.includes("Failed to load url")) {
699
+ throw e;
700
+ }
701
+ }
702
+ return [componentModule, insideFolderPath];
703
+ };
704
+ async function renderModule(viteServer, requestedModulePath, fieldOverrides = {}, pageUrl, environmentConfig) {
705
+ console.log("Rendering module", requestedModulePath);
706
+ let componentModule;
707
+ let foundPath;
708
+ if (!hasComponentExtension(requestedModulePath)) {
709
+ [componentModule, foundPath] = await lookForModuleInFolder(
710
+ requestedModulePath,
711
+ viteServer
712
+ );
713
+ }
714
+ if (!componentModule) {
715
+ componentModule = await viteServer.ssrLoadModule(requestedModulePath);
716
+ foundPath = componentModule ? requestedModulePath : void 0;
717
+ }
718
+ if (!componentModule) {
719
+ throw new Error(`Couldn't find module: ${requestedModulePath}`);
720
+ }
721
+ const Component = componentModule.Component;
722
+ const fields = componentModule.fields;
723
+ const meta = componentModule.meta;
724
+ if (!Component) {
725
+ throw new Error(
726
+ `Module does not have a named Component export: ${foundPath}`
727
+ );
728
+ } else if (!fields) {
729
+ throw new Error(`Module does not have a named fields export: ${foundPath}`);
730
+ } else if (!meta) {
731
+ throw new Error(`Module does not have a named meta export: ${foundPath}`);
732
+ }
733
+ const fieldsJSON = renderFieldsToJson(fields);
734
+ const props = getPropsForModule(fieldsJSON, fieldOverrides);
735
+ return renderComponentWithCSS_default(
736
+ viteServer,
737
+ foundPath,
738
+ Component,
739
+ props,
740
+ pageUrl,
741
+ environmentConfig
742
+ );
743
+ }
744
+ function getPropsForModule(fieldsJSON, fieldOverrides = {}) {
745
+ const props = {};
746
+ traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value) => {
747
+ setIn(props, fieldPathArray, value);
748
+ });
749
+ return props;
750
+ }
751
+ var renderModule_default = renderModule;
752
+
753
+ // src/routes/module.ts
754
+ var moduleRouteHandler = async (request2, response) => {
755
+ const { authedPortalId, authedEnv, authedHublet, webRoot: webRoot2, viteServer } = request2.app.locals;
756
+ const moduleName = request2.params.moduleName;
757
+ const baseTemplatePath = packagePath(
758
+ import.meta.url,
759
+ "html/baseTemplate.html"
760
+ );
761
+ const modulePath = normalizePath3(
762
+ path5.resolve(webRoot2, "components/modules/", moduleName)
763
+ );
764
+ let fieldOverrides = null;
765
+ if (request2.query.fields) {
766
+ try {
767
+ if (typeof request2.query.fields === "string") {
768
+ fieldOverrides = JSON.parse(request2.query.fields);
769
+ }
770
+ } catch (e) {
771
+ console.error(
772
+ `Error parsing field param for module ${moduleName}: ${request2.query.fields}`
773
+ );
774
+ }
775
+ }
776
+ const environmentConfig = buildStaticEnvConfig2(
777
+ authedPortalId,
778
+ authedHublet,
779
+ authedEnv,
780
+ false
781
+ );
782
+ try {
783
+ const {
784
+ html: renderedHtml,
785
+ cssNeeded,
786
+ renderContext
787
+ } = await renderModule_default(
788
+ viteServer,
789
+ modulePath,
790
+ fieldOverrides,
791
+ fullOriginalUrlFromRequest(request2),
792
+ environmentConfig
793
+ );
794
+ const htmlShell = await createHtmlShellDependingOnRenderContext(
795
+ baseTemplatePath,
796
+ request2.originalUrl,
797
+ `Module: ${modulePath}`,
798
+ renderContext,
799
+ viteServer
800
+ );
801
+ const html = htmlShell.replace("<!--headend-->", cssNeeded).replace(`<!--ssr-outlet-->`, renderedHtml);
802
+ response.status(200).set({ "Content-Type": "text/html" }).end(html);
803
+ } catch (e) {
804
+ console.error(e);
805
+ viteServer.ssrFixStacktrace(e);
806
+ response.status(500).end(`Error rendering module (${moduleName})
807
+
808
+ ${e.stack}`);
809
+ }
810
+ };
811
+ var module_default = moduleRouteHandler;
812
+
813
+ // src/proxyPage/fetchContentMetadata.ts
814
+ import http from "http";
815
+ import https from "https";
816
+ async function fetchContentMetadata(url3, redirects = 0, originalUrl) {
817
+ if (redirects > 5) {
818
+ throw new Error(
819
+ `Hit too many redirects to HEAD requests for ${originalUrl}`
820
+ );
821
+ }
822
+ return new Promise((resolve3, reject) => {
823
+ const protocolAPI = url3.startsWith("https://") ? https : http;
824
+ protocolAPI.request(
825
+ url3,
826
+ {
827
+ method: "HEAD",
828
+ headers: {
829
+ // Keep this user agent, so we don't get 403s from the request
830
+ ["User-Agent"]: "cms-dev-server"
831
+ }
832
+ },
833
+ async (res) => {
834
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
835
+ console.log(`Redirecting to ${res.headers.location} (from ${url3})`);
836
+ return resolve3(
837
+ fetchContentMetadata(
838
+ res.headers.location,
839
+ redirects + 1,
840
+ originalUrl ?? url3
841
+ )
842
+ );
843
+ }
844
+ const portalIdHeader = res.headers["x-hs-hub-id"];
845
+ const contentId = res.headers["x-hs-content-id"];
846
+ if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
847
+ return reject(
848
+ new Error(
849
+ `There were multiple hub ID or content ID headers in the HEAD request to ${url3}`
850
+ )
851
+ );
852
+ } else {
853
+ const portalId = parseInt(portalIdHeader, 10);
854
+ if (res.statusCode !== 200) {
855
+ return reject(
856
+ new Error(
857
+ `${res.statusCode} ${res.statusMessage} - Unable to obtain HEAD information from ${url3}. ${res.statusCode === 429 && res.headers["retry-after"] ? `Retry after ${res.headers["retry-after"]} seconds.` : ""}`
858
+ )
859
+ );
860
+ } else if (!portalId || !contentId) {
861
+ return reject(
862
+ new Error(
863
+ `Missing hub ID or content ID headers on HEAD request to ${url3}`
864
+ )
865
+ );
866
+ } else if (isNaN(portalId)) {
867
+ return reject(
868
+ new Error(
869
+ `Hub ID from the HEAD request is not a number: '${portalId}' (${url3})`
870
+ )
871
+ );
872
+ }
873
+ const hublet = "na1";
874
+ return resolve3({ portalId, contentId, hublet });
875
+ }
876
+ }
877
+ ).on("error", (err) => {
878
+ console.error(err);
879
+ reject(err);
880
+ }).end();
881
+ });
882
+ }
883
+
884
+ // src/proxyPage/proxyPage.ts
885
+ import path6 from "path";
886
+ import { getAccountId, getEnv } from "@hubspot/cli-lib/lib/config.js";
887
+ import { get as hsGet2 } from "@hubspot/cli-lib/http.js";
888
+
889
+ // src/lib/proxyHelpers.ts
890
+ import fs from "fs";
891
+ import { resolve as resolve2 } from "path";
892
+ var localJsRenderStartString = '<!-- proxy local render of "';
893
+ var localJsRenderEndString = "end proxy local render -->";
894
+ var findLocalRenderPlaceholders = (body) => {
895
+ let offsetSoFar = 0;
896
+ const result = [];
897
+ while (offsetSoFar < body.length && offsetSoFar !== -1) {
898
+ const startOffset = body.indexOf(localJsRenderStartString, offsetSoFar);
899
+ offsetSoFar = startOffset;
900
+ if (startOffset >= 0) {
901
+ const nextNewlineOffset = body.indexOf(
902
+ "\n",
903
+ startOffset + localJsRenderStartString.length
904
+ );
905
+ const pathEndOffset = body.indexOf(
906
+ '"',
907
+ startOffset + localJsRenderStartString.length
908
+ );
909
+ const nearestNewlineOrQuoteAfterBlockOpen = Math.min(
910
+ nextNewlineOffset,
911
+ pathEndOffset
912
+ );
913
+ offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
914
+ if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
915
+ const path8 = body.substring(
916
+ startOffset + localJsRenderStartString.length,
917
+ pathEndOffset
918
+ );
919
+ offsetSoFar = pathEndOffset + 1;
920
+ if (startOffset >= 0 && path8) {
921
+ const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
922
+ const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
923
+ offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
924
+ if (endOffset >= startOffset && endOffset < nextCommentEndOffset) {
925
+ const jsonString = body.substring(pathEndOffset + 1, endOffset).trim();
926
+ try {
927
+ const json = JSON.parse(jsonString);
928
+ result.push({
929
+ startOffset,
930
+ endOffset: endOffset + localJsRenderEndString.length,
931
+ path: path8,
932
+ json
933
+ });
934
+ offsetSoFar = endOffset + localJsRenderEndString.length;
935
+ } catch (e) {
936
+ console.error(
937
+ `Invalid JSON inside <!-- proxy local render .. --> string (around offset ${pathEndOffset})`
938
+ );
939
+ offsetSoFar = endOffset;
940
+ }
941
+ }
942
+ }
943
+ }
944
+ }
945
+ }
946
+ return result;
947
+ };
948
+ var getHSProjectConfig = (hsProjectConfigPath) => {
949
+ try {
950
+ return JSON.parse(fs.readFileSync(hsProjectConfigPath, "utf8"));
951
+ } catch (e) {
952
+ console.warn(
953
+ `Missing hsproject.json file (${resolve2(hsProjectConfigPath)}): `,
954
+ e.message
955
+ );
956
+ }
957
+ };
958
+ var getProjectNameFromHSConfig = (hsProjectConfigPath) => {
959
+ return getHSProjectConfig(hsProjectConfigPath).name;
960
+ };
961
+
962
+ // src/proxyPage/utils.ts
963
+ import { createEmptyServerRenderContext } from "@hubspot/cms-components";
964
+
965
+ // src/proxyPage/constants.ts
966
+ var VALID_PROXY_DOMAIN_SUFFIXES = ["localhost", "hslocal.net"];
967
+
968
+ // src/proxyPage/utils.ts
969
+ var getSubDomainFromValidLocalDomain = (hostname) => {
970
+ for (const validProxyDomainSuffix of VALID_PROXY_DOMAIN_SUFFIXES) {
971
+ if (hostname.endsWith(`.${validProxyDomainSuffix}`)) {
972
+ return hostname.slice(0, -1 * validProxyDomainSuffix.length - 1);
973
+ }
974
+ }
975
+ return void 0;
976
+ };
977
+ var randomStringWithLotsOf = (char, maxLength) => {
978
+ return new Array(Math.floor(Math.random() * maxLength)).fill(char).join("");
979
+ };
980
+ var fakeRenderJsComponent = (indexForThisRender) => {
981
+ return new Promise((resolve3, reject) => {
982
+ const randomTimeout = Math.floor(Math.random() * 200) + indexForThisRender * 1e3;
983
+ setTimeout(() => {
984
+ try {
985
+ const fakeJsRenderedOutput = `<div data-js-rendered>JS render #${indexForThisRender + 1} (${randomTimeout}ms delay) ${randomStringWithLotsOf(
986
+ "?",
987
+ 100
988
+ )}</div>
989
+ `;
990
+ resolve3({
991
+ html: fakeJsRenderedOutput,
992
+ cssNeeded: "",
993
+ renderContext: createEmptyServerRenderContext()
994
+ });
995
+ } catch (e) {
996
+ console.log("Error with JS render...");
997
+ console.error(e);
998
+ reject();
999
+ }
1000
+ }, randomTimeout);
1001
+ });
1002
+ };
1003
+ var consoleWarn = (message) => {
1004
+ console.warn("\x1B[33m%s\x1B[0m", "WARNING:", message);
1005
+ };
1006
+
1007
+ // src/proxyPage/renderLocalError.ts
1008
+ import AnsiToHtmlConverter from "ansi-to-html";
1009
+ var customColors = [
1010
+ // Normal colors
1011
+ "#000",
1012
+ // black
1013
+ "#ec392c",
1014
+ // red
1015
+ "#b3e439",
1016
+ // green
1017
+ "#fea525",
1018
+ // yellow
1019
+ "#76dff3",
1020
+ // blue
1021
+ "#fd4285",
1022
+ // magenta
1023
+ "#cfa3ff",
1024
+ // cyan
1025
+ "#f4f4f4",
1026
+ // White
1027
+ // Bright colors (mostly identical to ^)
1028
+ "#646464",
1029
+ "#ec392c",
1030
+ "#fea525",
1031
+ "#76dff3",
1032
+ "#fd4285",
1033
+ "#cfa3ff",
1034
+ "#f4f4f4"
1035
+ ];
1036
+ var Converter = new AnsiToHtmlConverter({ colors: customColors });
1037
+ var darkErrorStyles = `background-color: #222; color: #ccc; padding: 0.5em; font-family: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace;`;
1038
+ var renderLocalError_default = (path8, error) => {
1039
+ const stackWithColorClasses = Converter.toHtml(error.stack);
1040
+ return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path8}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
1041
+ };
1042
+
1043
+ // src/proxyPage/fetchPreviewInfo.ts
1044
+ import { get as hsGet } from "@hubspot/cli-lib/http.js";
1045
+ var fetchPreviewInfo_default = async (accountId, portalId, contentId) => {
1046
+ if (!contentId) {
1047
+ throw new Error(
1048
+ `Invalid contentId when attempting to fetch preview info: ${contentId}`
1049
+ );
1050
+ }
1051
+ try {
1052
+ const content = await hsGet(accountId, {
1053
+ uri: `/content/api/v4/contents/${contentId}`,
1054
+ query: { portalId },
1055
+ json: true
1056
+ });
1057
+ return {
1058
+ previewDomain: content.previewDomain ?? content.resolvedDomain,
1059
+ previewKey: content.previewKey
1060
+ };
1061
+ } catch (error) {
1062
+ if (error.statusCode === 403 && error.error.message.match(
1063
+ /^This oauth-token \([\w]+\) does not have proper permissions!/
1064
+ )) {
1065
+ const errorMessagePrefix = `Your personal access key is missing required scopes to preview a CMS page.
1066
+ You may need to re-generate a new personal access key with the required scopes and re-run \`hs-auth\`, or you may not have this functionality enabled in your account
1067
+ `;
1068
+ console.error("Error: ", errorMessagePrefix);
1069
+ console.error(error.error.message);
1070
+ throw new Error(`${errorMessagePrefix}
1071
+ ${error.error.message}`);
1072
+ } else {
1073
+ console.log(`fetchPreviewInfo Error`, error);
1074
+ if (error.options) {
1075
+ console.log(`error.options`, error.options);
1076
+ }
1077
+ if (error.response && error.response.headers) {
1078
+ console.log(`error.response.headers`, error.response.headers);
1079
+ }
1080
+ throw error;
1081
+ }
1082
+ }
1083
+ };
1084
+
1085
+ // src/proxyPage/proxyPage.ts
1086
+ import {
1087
+ buildStaticEnvConfig as buildStaticEnvConfig3
1088
+ } from "@hubspot/cms-components/config";
1089
+ var makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId) => {
1090
+ const url3 = new URL(urlToProxy);
1091
+ console.log(`Proxying request to ${url3.href}`, {
1092
+ previewKey,
1093
+ contentId
1094
+ });
1095
+ let proxiedQueryParams = {};
1096
+ for (const queryKey of url3.searchParams.keys()) {
1097
+ const values = url3.searchParams.getAll(queryKey);
1098
+ if (values.length > 1) {
1099
+ proxiedQueryParams[queryKey] = values;
1100
+ } else {
1101
+ proxiedQueryParams[queryKey] = values[0];
1102
+ }
1103
+ }
1104
+ proxiedQueryParams = {
1105
+ ...proxiedQueryParams,
1106
+ hs_preview: `${previewKey}-${contentId}`,
1107
+ hsLocalProxy: true
1108
+ };
1109
+ const result = hsGet2(accountId, {
1110
+ baseUrl: url3.origin,
1111
+ uri: url3.pathname,
1112
+ query: proxiedQueryParams,
1113
+ json: false,
1114
+ useQuerystring: true
1115
+ });
1116
+ return result.catch((error) => {
1117
+ if (error.statusCode >= 400 && error.statusCode < 500 && !!error.response.body) {
1118
+ return error.response.body;
1119
+ } else {
1120
+ throw error;
1121
+ }
1122
+ });
1123
+ };
1124
+ var renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholder, webRoot2, viteServer, pageUrl, environmentConfig, hsProjectJsonProjectName, webRootProjectComponent) => {
1125
+ const { path: placeholderPath } = localRenderPlaceholder;
1126
+ const [
1127
+ __projectIdentifier,
1128
+ projectFolder,
1129
+ projectComponentFolder,
1130
+ componentFolder,
1131
+ componentTypeFolder,
1132
+ componentFileName
1133
+ ] = placeholderPath.split("/");
1134
+ const partialPath = `${componentFolder}/${componentTypeFolder}/`;
1135
+ if (projectFolder !== hsProjectJsonProjectName) {
1136
+ throw new Error(
1137
+ `Unable to render component located outside of the project folder "${hsProjectJsonProjectName}". Components should be nested within the project folder. Check that the specified path is correct: ${placeholderPath}.`
1138
+ );
1139
+ } else if (projectComponentFolder !== webRootProjectComponent) {
1140
+ throw new Error(
1141
+ `The specified component folder "${projectComponentFolder}" does not match the webroot project component folder "${webRootProjectComponent}/${projectComponentFolder}" specified to the cms-dev-server. Components must be located within the webroot project folder. Check that the specified path is correct: ${placeholderPath}.`
1142
+ );
1143
+ }
1144
+ const resolvedPath = path6.resolve(webRoot2, partialPath, componentFileName);
1145
+ if (placeholderPath.startsWith("/fake/path/to/")) {
1146
+ return fakeRenderJsComponent(indexForThisRender);
1147
+ } else if (partialPath === ENTRY_POINTS_PATH) {
1148
+ return renderPartial_default(
1149
+ viteServer,
1150
+ resolvedPath,
1151
+ localRenderPlaceholder.json,
1152
+ pageUrl,
1153
+ environmentConfig
1154
+ );
1155
+ } else if (partialPath === MODULE_FOLDER_PATH) {
1156
+ return renderModule_default(
1157
+ viteServer,
1158
+ resolvedPath,
1159
+ localRenderPlaceholder.json,
1160
+ pageUrl,
1161
+ environmentConfig
1162
+ );
1163
+ } else {
1164
+ throw new Error(`Unimplemented render of ${placeholderPath}.`);
1165
+ }
1166
+ };
1167
+ async function proxySpecificPage(response, portalId, hublet, contentId, webRoot2, viteServer, projectName, projectComponentPath, urlToProxy, fullOriginalUrl) {
1168
+ let accountId;
1169
+ let proxyEnv;
1170
+ try {
1171
+ accountId = getAccountId(portalId);
1172
+ if (accountId === null) {
1173
+ throw new Error();
1174
+ }
1175
+ proxyEnv = getEnv(accountId);
1176
+ } catch (e) {
1177
+ response.status(500).end(
1178
+ `Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`
1179
+ );
1180
+ return;
1181
+ }
1182
+ if (!accountId) {
1183
+ response.status(500).end(
1184
+ `Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`
1185
+ );
1186
+ return;
1187
+ }
1188
+ try {
1189
+ const previewInfo = await fetchPreviewInfo_default(accountId, portalId, contentId);
1190
+ const { previewKey } = previewInfo;
1191
+ const pageHtml = await makeProxyPreviewRequest(
1192
+ accountId,
1193
+ urlToProxy,
1194
+ previewKey,
1195
+ contentId
1196
+ );
1197
+ const environmentConfig = buildStaticEnvConfig3(
1198
+ portalId,
1199
+ hublet,
1200
+ proxyEnv,
1201
+ false
1202
+ );
1203
+ const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule(
1204
+ "@hubspot/cms-components"
1205
+ );
1206
+ const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
1207
+ const numPlaceholders = localRenderPlaceholders.length;
1208
+ let numJsRenderFailures = 0;
1209
+ let islands = [];
1210
+ const renderPromisesByChunkIndex = new Array(
1211
+ numPlaceholders
1212
+ );
1213
+ if (localRenderPlaceholders.length > 0) {
1214
+ let offsetSoFar = 0;
1215
+ const pageChunks = new Array(numPlaceholders + 1);
1216
+ for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
1217
+ const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
1218
+ pageChunks[indexForThisRender] = pageHtml.slice(
1219
+ offsetSoFar,
1220
+ localRenderPlaceholder.startOffset
1221
+ );
1222
+ const renderPromise = renderComponentForPlaceholder(
1223
+ indexForThisRender,
1224
+ localRenderPlaceholder,
1225
+ webRoot2,
1226
+ viteServer,
1227
+ fullOriginalUrl,
1228
+ environmentConfig,
1229
+ projectName,
1230
+ projectComponentPath
1231
+ );
1232
+ renderPromisesByChunkIndex[indexForThisRender] = renderPromise.then((promiseResult) => {
1233
+ let { html, cssNeeded, renderContext } = promiseResult;
1234
+ console.log(
1235
+ `Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`
1236
+ );
1237
+ if (renderContext.islands.length > 0) {
1238
+ islands = islands.concat(renderContext.islands);
1239
+ }
1240
+ if (cssNeeded) {
1241
+ return `${cssNeeded}
1242
+ ${html}`;
1243
+ }
1244
+ return html;
1245
+ }).catch((e) => {
1246
+ numJsRenderFailures += 1;
1247
+ console.error(e);
1248
+ return renderLocalError_default(localRenderPlaceholder.path, e);
1249
+ });
1250
+ offsetSoFar = localRenderPlaceholder.endOffset;
1251
+ }
1252
+ pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
1253
+ response.writeHead(200);
1254
+ for (let i = 0; i < localRenderPlaceholders.length; i++) {
1255
+ const chunk = pageChunks[i];
1256
+ response.write(chunk);
1257
+ const foobar = await renderPromisesByChunkIndex[i];
1258
+ response.write(foobar);
1259
+ }
1260
+ response.write(
1261
+ getServerGlobalsToInject(environmentConfig, fullOriginalUrl)
1262
+ );
1263
+ if (islands.length > 0) {
1264
+ const sortedIslandRoots = sortIslandRootsByPriority(islands);
1265
+ const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(
1266
+ sortedIslandRoots,
1267
+ viteServer
1268
+ );
1269
+ response.write(islandRuntimeAndGlobalScriptHtml);
1270
+ }
1271
+ response.write(pageChunks[pageChunks.length - 1]);
1272
+ response.end();
1273
+ } else {
1274
+ response.writeHead(200);
1275
+ response.write(pageHtml);
1276
+ response.end();
1277
+ }
1278
+ } catch (error) {
1279
+ response.status(500).end(
1280
+ `Failed proxy render of page id = ${contentId} hub id = ${portalId}
1281
+
1282
+ ${error.stack}`
1283
+ );
1284
+ return;
1285
+ }
1286
+ }
1287
+
1288
+ // src/routes/proxyPageRouteHandler.ts
1289
+ async function proxyPageRouteHandler(request2, response, next) {
1290
+ const { viteServer, webRoot: webRoot2, projectName, projectComponentPath } = request2.app.locals;
1291
+ if (!request2.accepts().includes("text/html")) {
1292
+ return response.sendStatus(404);
1293
+ }
1294
+ const fullOriginalUrl = fullOriginalUrlFromRequest(request2);
1295
+ const domainToProxy = getSubDomainFromValidLocalDomain(request2.hostname);
1296
+ const urlToProxy = `http://${domainToProxy}${request2.originalUrl}`;
1297
+ if (!domainToProxy) {
1298
+ if (VALID_PROXY_DOMAIN_SUFFIXES.includes(request2.hostname)) {
1299
+ const message = `Can't make a proxy request, you need to prepend the real page's domain to '${request2.hostname}' (i.e. your.page.com.${request2.hostname})`;
1300
+ consoleWarn(message);
1301
+ return response.status(400).send(message);
1302
+ } else {
1303
+ const message = `Can't make a proxy request, the domain '${request2.hostname}' is not a valid proxy-able domain`;
1304
+ consoleWarn(message);
1305
+ return response.status(400).send(message);
1306
+ }
1307
+ }
1308
+ if (request2.query.hs_preview) {
1309
+ const message = `Can't make a proxy request, you cannot proxy URLs that include internal query params like hs_preview`;
1310
+ consoleWarn(message);
1311
+ return response.status(400).send(message);
1312
+ }
1313
+ try {
1314
+ const { portalId, contentId, hublet } = await fetchContentMetadata(
1315
+ urlToProxy
1316
+ );
1317
+ await proxySpecificPage(
1318
+ response,
1319
+ portalId,
1320
+ hublet,
1321
+ contentId,
1322
+ webRoot2,
1323
+ viteServer,
1324
+ projectName,
1325
+ projectComponentPath,
1326
+ urlToProxy,
1327
+ fullOriginalUrl
1328
+ );
1329
+ } catch (e) {
1330
+ next(e);
1331
+ }
1332
+ }
1333
+
1334
+ // src/routes/proxyPageResourceRedirect.ts
1335
+ import request from "request";
1336
+ var HCMS_PATH = "/_hcms/";
1337
+ var HS_FS_PATH = "/hs-fs/";
1338
+ var HUB_FS_PATH = "/hubfs/";
1339
+ var isInternalCMSRoute = (req) => req.path.startsWith(HCMS_PATH) || req.path.startsWith(HS_FS_PATH) || req.path.startsWith(HUB_FS_PATH);
1340
+ function proxyPageResourceRedirect(req, res, next) {
1341
+ const isAHtmlRequest = req.accepts().includes("text/html");
1342
+ if (isAHtmlRequest && !isInternalCMSRoute(req) || VALID_PROXY_DOMAIN_SUFFIXES.includes(req.hostname)) {
1343
+ next();
1344
+ return;
1345
+ }
1346
+ const domainToProxy = getSubDomainFromValidLocalDomain(req.hostname);
1347
+ const pathToProxy = req.originalUrl;
1348
+ const urlToProxy = `https://${domainToProxy}${pathToProxy}`;
1349
+ request(urlToProxy).pipe(res);
1350
+ }
1351
+
1352
+ // src/routes/homeRouteHandler.tsx
1353
+ import { Fragment, jsx as jsx6, jsxs as jsxs3 } from "react/jsx-runtime";
1354
+ var homeRouteHandler = async (request2, response) => {
1355
+ const { webRoot: webRoot2, storybookEnabled, devServerPort } = request2.app.locals;
1356
+ const { partialNames } = findAllPartialsInRoot(webRoot2);
1357
+ const { moduleNames } = findAllModulesInRoot(webRoot2);
1358
+ const { html: responseHtml } = await renderOnServer(
1359
+ /* @__PURE__ */ jsxs3(Fragment, { children: [
1360
+ storybookEnabled ? /* @__PURE__ */ jsx6("h2", { children: /* @__PURE__ */ jsx6("a", { href: `//storybook.${request2.hostname}:${devServerPort}`, children: "Storybook" }) }) : null,
1361
+ /* @__PURE__ */ jsx6("h2", { children: "Partials" }),
1362
+ /* @__PURE__ */ jsx6(PartialsList, { webRoot: webRoot2, partialNames }),
1363
+ /* @__PURE__ */ jsx6("h2", { children: "Modules" }),
1364
+ /* @__PURE__ */ jsx6(ModulesList_default, { webRoot: webRoot2, moduleNames })
1365
+ ] }),
1366
+ null,
1367
+ null
1368
+ );
1369
+ response.status(200).set({ "Content-Type": "text/html" }).end(responseHtml);
1370
+ };
1371
+ var homeRouteHandler_default = homeRouteHandler;
1372
+
1373
+ // src/lib/debug.ts
1374
+ import { default as debugFactory } from "debug";
1375
+ var debug = debugFactory("cms-dev-server");
1376
+
1377
+ // src/routes/proxyPathPageRouteHandler.tsx
1378
+ import { jsx as jsx7, jsxs as jsxs4 } from "react/jsx-runtime";
1379
+ async function proxyPathPageRouteHandler(request2, response, next) {
1380
+ const {
1381
+ viteServer,
1382
+ webRoot: webRoot2,
1383
+ devServerHost,
1384
+ devServerPort,
1385
+ projectName,
1386
+ projectComponentPath
1387
+ } = request2.app.locals;
1388
+ if (!request2.accepts().includes("text/html")) {
1389
+ return response.sendStatus(404);
1390
+ }
1391
+ if (!request2.query.page) {
1392
+ const { html: responseHtml } = await renderOnServer(
1393
+ /* @__PURE__ */ jsxs4("div", { children: [
1394
+ /* @__PURE__ */ jsx7("h2", { children: "Local Proxy" }),
1395
+ /* @__PURE__ */ jsxs4("form", { action: "/proxy", children: [
1396
+ /* @__PURE__ */ jsx7("label", { htmlFor: "page", style: { display: "block" }, children: "Page URL" }),
1397
+ /* @__PURE__ */ jsx7(
1398
+ "input",
1399
+ {
1400
+ style: { width: "300px" },
1401
+ name: "page",
1402
+ type: "text",
1403
+ placeholder: "https://somecmspage.com/path"
1404
+ }
1405
+ ),
1406
+ /* @__PURE__ */ jsx7("button", { style: { display: "block" }, children: "Proxy" })
1407
+ ] })
1408
+ ] }),
1409
+ null,
1410
+ null
1411
+ );
1412
+ response.status(200).set({ "Content-Type": "text/html" }).end(responseHtml);
1413
+ return;
1414
+ }
1415
+ let proxyPageUrl;
1416
+ try {
1417
+ proxyPageUrl = new URL(request2.query.page);
1418
+ } catch (e) {
1419
+ const message = "Please provide a valid page query parameter, e.g., http://localhost:3000/proxy?page=https://yourdomain.com/path";
1420
+ consoleWarn(message);
1421
+ response.status(400).send(message);
1422
+ return;
1423
+ }
1424
+ if (proxyPageUrl.searchParams.has("hs_preview")) {
1425
+ const message = `Can't make a proxy request, you cannot proxy URLs that include internal query params like hs_preview`;
1426
+ consoleWarn(message);
1427
+ return response.status(400).send(message);
1428
+ }
1429
+ try {
1430
+ const { portalId, contentId, hublet } = await fetchContentMetadata(
1431
+ proxyPageUrl.href
1432
+ );
1433
+ await proxySpecificPage(
1434
+ response,
1435
+ portalId,
1436
+ hublet,
1437
+ contentId,
1438
+ webRoot2,
1439
+ viteServer,
1440
+ projectName,
1441
+ projectComponentPath,
1442
+ proxyPageUrl.href,
1443
+ proxyPageUrl.href
1444
+ );
1445
+ } catch (e) {
1446
+ next(e);
1447
+ }
1448
+ }
1449
+
1450
+ // src/routes/proxyPathPageResourceRedirect.ts
1451
+ import fetch from "node-fetch";
1452
+ var HCMS_PATH2 = "/_hcms/";
1453
+ var HS_FS_PATH2 = "/hs-fs/";
1454
+ var HUB_FS_PATH2 = "/hubfs/";
1455
+ var isInternalCMSRoute2 = (req) => req.path.startsWith(HCMS_PATH2) || req.path.startsWith(HS_FS_PATH2) || req.path.startsWith(HUB_FS_PATH2);
1456
+ function proxyPathPageResourceRedirect(req, res, next) {
1457
+ const isAHtmlRequest = req.accepts().includes("text/html");
1458
+ let proxyPageUrl;
1459
+ let refererUrl;
1460
+ try {
1461
+ refererUrl = new URL(req.headers.referer);
1462
+ proxyPageUrl = new URL(
1463
+ new URL(req.headers.referer).searchParams.get("page")
1464
+ );
1465
+ } catch (e) {
1466
+ next();
1467
+ return;
1468
+ }
1469
+ if (!refererUrl.pathname.startsWith("/proxy")) {
1470
+ next();
1471
+ return;
1472
+ }
1473
+ if (isAHtmlRequest && !isInternalCMSRoute2(req)) {
1474
+ const encodedPageUrl = encodeURIComponent(
1475
+ `${proxyPageUrl.origin}${req.url}`
1476
+ );
1477
+ res.redirect(`/proxy?page=${encodedPageUrl}`);
1478
+ return;
1479
+ }
1480
+ const urlToProxy = `https://${proxyPageUrl.host}${req.url}`;
1481
+ fetch(urlToProxy).then((response) => response.body.pipe(res)).catch((err) => console.log(err));
1482
+ }
1483
+
1484
+ // src/routes/createDevServerRoutes.ts
1485
+ var STORYBOOK_DOMAINS = VALID_PROXY_DOMAIN_SUFFIXES.map(
1486
+ (domain) => `storybook.${domain}`
1487
+ );
1488
+ var createDevServerRoutes = async (viteServer, storybookPort) => {
1489
+ const devServerApp = Router();
1490
+ devServerApp.use((request2, response, next) => {
1491
+ const { method, url: url3, hostname } = request2;
1492
+ debug(`${method}:${hostname}${url3}`);
1493
+ next();
1494
+ });
1495
+ if (storybookPort) {
1496
+ devServerApp.use(
1497
+ createProxyMiddleware(
1498
+ (__pathname, req) => STORYBOOK_DOMAINS.includes(req.hostname),
1499
+ {
1500
+ logLevel: "warn",
1501
+ target: `http://localhost:${storybookPort}`
1502
+ }
1503
+ )
1504
+ );
1505
+ }
1506
+ devServerApp.use(viteServer.middlewares);
1507
+ devServerApp.get("/proxy", proxyPathPageRouteHandler);
1508
+ devServerApp.get("/partials/", linksToAllPartialsRouteHandler_default);
1509
+ devServerApp.get("/partial/:partial", partial_default);
1510
+ devServerApp.get("/modules/", linksToAllModulesRouteHandler_default);
1511
+ devServerApp.get("/module/:moduleName", module_default);
1512
+ devServerApp.get("/", homeRouteHandler_default);
1513
+ devServerApp.get("/*", proxyPathPageResourceRedirect);
1514
+ devServerApp.get("/*", proxyPageResourceRedirect);
1515
+ devServerApp.get("/*", proxyPageRouteHandler);
1516
+ return devServerApp;
1517
+ };
1518
+ var createDevServerRoutes_default = createDevServerRoutes;
1519
+
1520
+ // src/shadowDevServer/startShadowDevServer.ts
1521
+ import net from "net";
1522
+ import express from "express";
1523
+
1524
+ // src/shadowDevServer/createShadowDevServerRoutes.ts
1525
+ import { Router as Router2 } from "express";
1526
+ import { getAccountId as getAccountId2 } from "@hubspot/cli-lib/lib/config.js";
1527
+ import cors from "cors";
1528
+ function getShadowDevServerCheckHandler(devServerPort) {
1529
+ return async function shadowDevServerCheckHandler(request2, response) {
1530
+ const { query } = request2;
1531
+ if (query) {
1532
+ const {
1533
+ hostName,
1534
+ pathName,
1535
+ protocol,
1536
+ contentId,
1537
+ portalId: portalIdString
1538
+ } = query;
1539
+ const pageUrl = `${protocol}//${hostName}${pathName}`;
1540
+ const portalId = parseInt(portalIdString, 10);
1541
+ let accountId;
1542
+ let hasJSBuildingBlocks = false;
1543
+ let localProxyUrl;
1544
+ try {
1545
+ accountId = getAccountId2(portalId);
1546
+ if (accountId === null) {
1547
+ throw new Error();
1548
+ }
1549
+ } catch (e) {
1550
+ response.status(500).end(
1551
+ `Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`
1552
+ );
1553
+ return;
1554
+ }
1555
+ try {
1556
+ const previewInfo = await fetchPreviewInfo_default(
1557
+ accountId,
1558
+ portalId,
1559
+ contentId
1560
+ );
1561
+ const { previewKey } = previewInfo;
1562
+ const pageHtml = await makeProxyPreviewRequest(
1563
+ accountId,
1564
+ pageUrl,
1565
+ previewKey,
1566
+ contentId
1567
+ );
1568
+ const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
1569
+ if (localRenderPlaceholders.length) {
1570
+ hasJSBuildingBlocks = true;
1571
+ localProxyUrl = `http://${hostName}.hslocal.net:${devServerPort}${pathName}`;
1572
+ }
1573
+ response.status(200).set({ "Content-Type": "application/json" }).json({ hasJSBuildingBlocks, localProxyUrl });
1574
+ } catch (error) {
1575
+ response.status(500).end(
1576
+ `Failed proxy render of page id = ${contentId} hub id = ${portalId}
1577
+
1578
+ ${error.stack}`
1579
+ );
1580
+ return;
1581
+ }
1582
+ } else {
1583
+ response.status(500).end(
1584
+ `Missing pageUrl param, cannot check for proxied page without a pageUrl`
1585
+ );
1586
+ }
1587
+ };
1588
+ }
1589
+ async function createShadowDevServerRoutes(devServerPort) {
1590
+ const shadowDevServerRoutes = Router2();
1591
+ shadowDevServerRoutes.get(
1592
+ "/check-if-local-dev-server",
1593
+ cors(),
1594
+ getShadowDevServerCheckHandler(devServerPort)
1595
+ );
1596
+ return shadowDevServerRoutes;
1597
+ }
1598
+
1599
+ // src/shadowDevServer/startShadowDevServer.ts
1600
+ var testNetServer = net.createServer();
1601
+ async function startShadowDevServer(devServerPort, shadowPort) {
1602
+ const portIsTaken = await new Promise((res, rej) => {
1603
+ console.log(`Starting proxy link server on port ${shadowPort}`);
1604
+ testNetServer.once("error", (err) => {
1605
+ if (err["code"] === "EADDRINUSE") {
1606
+ console.error(
1607
+ `Port ${shadowPort} is in use. HubSpot is unable to automatically create proxy links in the Sprocket Menu`
1608
+ );
1609
+ res(true);
1610
+ } else {
1611
+ rej(err);
1612
+ }
1613
+ });
1614
+ testNetServer.once("listening", () => {
1615
+ testNetServer.close();
1616
+ });
1617
+ testNetServer.once("close", () => {
1618
+ res(false);
1619
+ });
1620
+ testNetServer.listen(shadowPort);
1621
+ });
1622
+ if (portIsTaken) {
1623
+ return;
1624
+ }
1625
+ const shadowDevServer = express();
1626
+ shadowDevServer.listen(shadowPort);
1627
+ shadowDevServer.use("/", await createShadowDevServerRoutes(devServerPort));
1628
+ }
1629
+
1630
+ // src/createViteDevServer.ts
1631
+ import { createServer as createViteServer } from "vite";
1632
+ import { default as react } from "@vitejs/plugin-react";
1633
+ import mkcert from "vite-plugin-mkcert";
1634
+ async function createViteDevServer(webRoot2, port, sslEnabled, domainsToProxy = []) {
1635
+ const additionalMkcertHosts = domainsToProxy.map((proxyDomain) => [
1636
+ `${proxyDomain}.localhost`,
1637
+ `${proxyDomain}.hslocal.net`
1638
+ ]).flat();
1639
+ additionalMkcertHosts.push("*.hslocal.net", "hslocal.net");
1640
+ const origin = sslEnabled ? `https://hslocal.net:${port}` : `http://hslocal.net:${port}`;
1641
+ const viteConfig = {
1642
+ appType: "custom",
1643
+ server: {
1644
+ middlewareMode: true,
1645
+ host: "hslocal.net",
1646
+ origin,
1647
+ https: sslEnabled,
1648
+ hmr: {
1649
+ protocol: sslEnabled ? "wss" : void 0
1650
+ }
1651
+ },
1652
+ ssr: {
1653
+ // TODO: might need more entries here to get things to resolve through
1654
+ // resolveWebRootDepsPlugin
1655
+ noExternal: "@hubspot/cms-components"
1656
+ },
1657
+ resolve: {
1658
+ dedupe: ["react", "react-dom", "@hubspot/cms-components"]
1659
+ },
1660
+ optimizeDeps: {
1661
+ include: ["react", "react-dom", "react-dom/client"]
1662
+ },
1663
+ plugins: [
1664
+ sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
1665
+ react(),
1666
+ resolveIslandPlugin()
1667
+ ],
1668
+ css: {
1669
+ postcss: webRoot2
1670
+ }
1671
+ };
1672
+ return createViteServer(viteConfig);
1673
+ }
1674
+ var createViteDevServer_default = createViteDevServer;
1675
+
1676
+ // src/lib/httpsRedirectingServer.ts
1677
+ import net2 from "net";
1678
+ import http2 from "http";
1679
+ import https2 from "https";
1680
+ function requireHTTPS(message, response) {
1681
+ const newLocation = `https://${message.headers.host}${message.url}`;
1682
+ response.writeHead(302, {
1683
+ Location: newLocation
1684
+ }).end();
1685
+ }
1686
+ function createHttpsRedirectingServer(opts, handler) {
1687
+ const innerHTTPServer = http2.createServer(requireHTTPS);
1688
+ const innerHTTPSServer = https2.createServer(opts, handler);
1689
+ const server = net2.createServer((socket) => {
1690
+ socket.once("data", (buffer) => {
1691
+ socket.pause();
1692
+ const byte = buffer[0];
1693
+ let protocol;
1694
+ if (byte === 22) {
1695
+ protocol = "https";
1696
+ } else if (32 < byte && byte < 127) {
1697
+ protocol = "http";
1698
+ } else {
1699
+ throw new Error(
1700
+ "Unknown issue with incoming data, unknown if http or https"
1701
+ );
1702
+ }
1703
+ const proxy = protocol === "http" ? innerHTTPServer : innerHTTPSServer;
1704
+ if (proxy) {
1705
+ socket.unshift(buffer);
1706
+ proxy.emit("connection", socket);
1707
+ }
1708
+ process.nextTick(() => socket.resume());
1709
+ });
1710
+ });
1711
+ return { server, innerHTTPServer, innerHTTPSServer };
1712
+ }
1713
+
1714
+ // src/createDevServer.ts
1715
+ import {
1716
+ getEnv as getEnv2,
1717
+ getAccountId as getAccountId3,
1718
+ loadConfig,
1719
+ validateConfig
1720
+ } from "@hubspot/cli-lib/lib/config.js";
1721
+
1722
+ // src/proxyPage/fetchDomains.ts
1723
+ import { get as hsGet3 } from "@hubspot/cli-lib/http.js";
1724
+
1725
+ // src/lib/errors.ts
1726
+ var MISSING_SCOPE_ERROR_PREFIX = `Your personal access key is missing required scopes fetch domains.
1727
+ You may need to re-generate a new personal access key with the required scopes and re-run \`hs-auth\`, or you may not have this functionality enabled in your account
1728
+ `;
1729
+ var OAUTH_ERROR_REGEX = /^This oauth-token \([\w]+\) does not have proper permissions!/;
1730
+ var NOT_PUBLIC_USE_ERROR = `The scope needed for this API call isn't available for public use`;
1731
+ var MissingScopeError = class extends Error {
1732
+ constructor(error) {
1733
+ let messageEnd = "";
1734
+ if (error.error.message.match(OAUTH_ERROR_REGEX)) {
1735
+ messageEnd = error.error.message;
1736
+ }
1737
+ super(`${MISSING_SCOPE_ERROR_PREFIX}
1738
+ ${messageEnd}`);
1739
+ Object.setPrototypeOf(this, MissingScopeError.prototype);
1740
+ }
1741
+ };
1742
+ function logMissingScopeWarning(error) {
1743
+ console.warn(error.message);
1744
+ }
1745
+ function isMissingScopeError(error) {
1746
+ return error.statusCode === 403 && (error.error.message.match(OAUTH_ERROR_REGEX) || error.error.message.startsWith(NOT_PUBLIC_USE_ERROR));
1747
+ }
1748
+
1749
+ // src/proxyPage/fetchDomains.ts
1750
+ async function fetchDomains(portalId) {
1751
+ try {
1752
+ const result = await hsGet3(portalId, {
1753
+ uri: `/cms/v3/domains`,
1754
+ query: { portalId },
1755
+ json: true
1756
+ });
1757
+ return result.results;
1758
+ } catch (error) {
1759
+ if (isMissingScopeError(error)) {
1760
+ throw new MissingScopeError(error);
1761
+ }
1762
+ throw error;
1763
+ }
1764
+ }
1765
+ async function fetchWebsiteDomainNames(portalId) {
1766
+ const domains = await fetchDomains(portalId);
1767
+ const filteredDomains = domains.filter((domain) => {
1768
+ return domain.isUsedForBlogPost || domain.isUsedForSitePage || domain.isUsedForLandingPage;
1769
+ });
1770
+ const domainNames = filteredDomains.map((r) => r.domain);
1771
+ return domainNames;
1772
+ }
1773
+
1774
+ // src/createDevServer.ts
1775
+ var BASE_PATH = "/";
1776
+ var PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3e3;
1777
+ var SHADOW_PORT = 1442;
1778
+ var STORYBOOK_PORT = process.env.STORYBOOK_PORT ? parseInt(process.env.STORYBOOK_PORT, 10) : 3123;
1779
+ async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2, hubspotCliAccountNameOption2, sslEnabledOption2) {
1780
+ console.log(
1781
+ "Warning: this is a prerelease and requires specific HubSpot account configuration to work"
1782
+ );
1783
+ let authedPortalId = null;
1784
+ let authedEnv = null;
1785
+ if (hubspotCliConfigPathOption2 && hubspotCliAccountNameOption2) {
1786
+ console.log(
1787
+ `Loading HS auth (account = ${hubspotCliAccountNameOption2}) configuration at: ${hubspotCliConfigPathOption2}`
1788
+ );
1789
+ } else if (hubspotCliConfigPathOption2) {
1790
+ console.log(
1791
+ `Loading HS auth configuration at: ${hubspotCliConfigPathOption2}`
1792
+ );
1793
+ } else if (hubspotCliAccountNameOption2) {
1794
+ console.log(
1795
+ `Loading HS auth (account = ${hubspotCliAccountNameOption2}) configuration.`
1796
+ );
1797
+ }
1798
+ loadConfig(hubspotCliConfigPathOption2 || null, { useEnv: false });
1799
+ if (validateConfig()) {
1800
+ authedPortalId = getAccountId3(hubspotCliAccountNameOption2);
1801
+ authedEnv = getEnv2(hubspotCliAccountNameOption2);
1802
+ if (!authedPortalId && hubspotCliAccountNameOption2) {
1803
+ console.error(
1804
+ `Couldn't find ${hubspotCliAccountNameOption2} in your hubspot.config.yaml`
1805
+ );
1806
+ process.exit(1);
1807
+ }
1808
+ } else {
1809
+ console.warn(
1810
+ `Couldn't find an account to use, make sure there is hubspot.config.yaml in this folder (or a parent).
1811
+ If needed you can refer to another config file with --config.
1812
+
1813
+ Local proxy functionality will not work without setting up authentication.`
1814
+ );
1815
+ }
1816
+ let domainsToProxy = [];
1817
+ if (sslEnabledOption2 && authedPortalId) {
1818
+ try {
1819
+ const portalDomains = await fetchWebsiteDomainNames(authedPortalId);
1820
+ domainsToProxy = (process.env.DOMAINS_TO_PROXY || "").split(",").filter((d) => !!d);
1821
+ domainsToProxy = [...domainsToProxy, ...portalDomains];
1822
+ } catch (e) {
1823
+ if (e instanceof MissingScopeError) {
1824
+ logMissingScopeWarning(e);
1825
+ } else {
1826
+ console.warn(
1827
+ `Failed to fetch domains for ${authedPortalId}, HTTPS proxying won't work with them.`
1828
+ );
1829
+ }
1830
+ }
1831
+ }
1832
+ const authedHublet = "na1";
1833
+ const absoluteWebRoot = normalizePath4(path7.resolve(process.cwd(), webRoot2));
1834
+ const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, "").split("/").slice(-2);
1835
+ const viteServer = await createViteDevServer_default(
1836
+ absoluteWebRoot,
1837
+ PORT,
1838
+ sslEnabledOption2,
1839
+ domainsToProxy
1840
+ );
1841
+ const viteHTTPSConfig = viteServer.config.server.https;
1842
+ const httpsKey = viteHTTPSConfig ? viteHTTPSConfig.key : null;
1843
+ const httpsCert = viteHTTPSConfig ? viteHTTPSConfig.cert : null;
1844
+ const httpServers = [];
1845
+ const expressServer = express2();
1846
+ expressServer.locals.devServerHost = "hslocal.net";
1847
+ expressServer.locals.devServerPort = PORT;
1848
+ expressServer.locals.webRoot = webRoot2;
1849
+ expressServer.locals.viteServer = viteServer;
1850
+ expressServer.locals.authedPortalId = authedPortalId;
1851
+ expressServer.locals.authedEnv = authedEnv;
1852
+ expressServer.locals.authedHublet = authedHublet;
1853
+ expressServer.locals.storybookEnabled = storybook2;
1854
+ expressServer.locals.storybookPort = STORYBOOK_PORT;
1855
+ expressServer.locals.projectName = getProjectNameFromHSConfig(
1856
+ path7.join(webRoot2, "../hsproject.json")
1857
+ );
1858
+ expressServer.locals.projectComponentPath = webRootProjectComponentFolder;
1859
+ expressServer.use(bodyParser.json());
1860
+ expressServer.use(
1861
+ BASE_PATH,
1862
+ await createDevServerRoutes_default(viteServer, storybook2 ? STORYBOOK_PORT : null)
1863
+ );
1864
+ if (sslEnabledOption2) {
1865
+ if (httpsKey && httpsCert) {
1866
+ const { server, innerHTTPServer, innerHTTPSServer } = createHttpsRedirectingServer(
1867
+ { key: httpsKey, cert: httpsCert },
1868
+ expressServer
1869
+ );
1870
+ server.listen(PORT);
1871
+ httpServers.push(server);
1872
+ httpServers.push(innerHTTPServer);
1873
+ httpServers.push(innerHTTPSServer);
1874
+ } else {
1875
+ console.error("Failed to start a HTTPS server, try --no-ssl");
1876
+ process.exit(1);
1877
+ }
1878
+ } else {
1879
+ const httpServer = http3.createServer(expressServer);
1880
+ httpServer.listen(PORT);
1881
+ httpServers.push(httpServer);
1882
+ }
1883
+ startShadowDevServer(PORT, SHADOW_PORT);
1884
+ let extraServerInfo = "";
1885
+ const protocol = sslEnabledOption2 ? "https" : "http";
1886
+ if (authedPortalId) {
1887
+ extraServerInfo += `, hubid=${authedPortalId}`;
1888
+ }
1889
+ if (authedEnv && authedEnv !== "prod") {
1890
+ extraServerInfo += `, env=${authedEnv}`;
1891
+ }
1892
+ console.log(
1893
+ `
1894
+ HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressServer.locals.projectComponentPath} (at ${protocol}://hslocal.net:${PORT}${extraServerInfo})
1895
+ `
1896
+ );
1897
+ if (storybook2) {
1898
+ const packageRoot = path7.dirname(url2.fileURLToPath(import.meta.url));
1899
+ const configPath = path7.resolve(packageRoot, "./storybook");
1900
+ const storybookProcess = spawn(
1901
+ "npx",
1902
+ [
1903
+ "sb",
1904
+ "dev",
1905
+ "-p",
1906
+ STORYBOOK_PORT.toString(),
1907
+ "-c",
1908
+ configPath,
1909
+ "--quiet",
1910
+ "--no-open"
1911
+ ],
1912
+ {
1913
+ cwd: process.cwd(),
1914
+ env: {
1915
+ ...process.env,
1916
+ WEB_ROOT: path7.join(webRoot2, "components")
1917
+ }
1918
+ }
1919
+ );
1920
+ console.log(`Starting storybook server on port ${STORYBOOK_PORT}`);
1921
+ if (debug.enabled) {
1922
+ storybookProcess.stdout.pipe(process.stdout);
1923
+ }
1924
+ storybookProcess.stderr.pipe(process.stderr);
1925
+ }
1926
+ return {
1927
+ close: () => {
1928
+ const serverClosePromises = httpServers.map(
1929
+ (server) => new Promise((resolve3) => {
1930
+ server.close(() => {
1931
+ resolve3(null);
1932
+ });
1933
+ })
1934
+ );
1935
+ return Promise.allSettled([...serverClosePromises, viteServer.close()]);
1936
+ }
1937
+ };
1938
+ }
1939
+ var createDevServer_default = createDevServer;
1940
+
1941
+ // src/run.ts
1942
+ var {
1943
+ webRoot,
1944
+ hubspotCliConfigPathOption,
1945
+ hubspotCliAccountNameOption,
1946
+ sslEnabledOption,
1947
+ storybook
1948
+ } = getDevServerCommandLineOptions(process.argv);
5
1949
  if (!webRoot) {
6
- throw new Error(`No web root path argument specified`);
1950
+ throw new Error(`No web root path argument specified`);
7
1951
  }
8
- createDevServer(webRoot, storybook, hubspotCliConfigPathOption, hubspotCliAccountNameOption, sslEnabledOption);
1952
+ createDevServer_default(
1953
+ webRoot,
1954
+ storybook,
1955
+ hubspotCliConfigPathOption,
1956
+ hubspotCliAccountNameOption,
1957
+ sslEnabledOption
1958
+ );