@ms-cloudpack/app-server 0.17.24 → 0.17.26
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/lib/createRoutes.d.ts.map +1 -1
- package/lib/createRoutes.js.map +1 -1
- package/lib/handleErrorPortUnavailable.d.ts.map +1 -1
- package/lib/handleErrorPortUnavailable.js.map +1 -1
- package/lib/inlineScripts/errorHandler.inline.js.map +1 -1
- package/lib/inlineScripts/getBrowserCacheRatio.inline.js.map +1 -1
- package/lib/inlineScripts/getInlineScripts.d.ts.map +1 -1
- package/lib/inlineScripts/getInlineScripts.js.map +1 -1
- package/lib/inlineScripts/getPageLoadTime.inline.js +4 -5
- package/lib/inlineScripts/getPageLoadTime.inline.js.map +1 -1
- package/lib/renderRoute/renderRoute.js.map +1 -1
- package/package.json +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createRoutes.d.ts","sourceRoot":"","sources":["../src/createRoutes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAOL,KAAK,WAAW,EAIjB,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAqB,MAAM,kCAAkC,CAAC;AAYnF,UAAU,mBAAmB;IAC3B,GAAG,EAAE,OAAO,CAAC;IACb,8CAA8C;IAC9C,GAAG,EAAE,MAAM,CAAC;IACZ,+BAA+B;IAC/B,UAAU,EAAE,WAAW,CAAC;CACzB;AAED,KAAK,mBAAmB,GAAG,IAAI,CAAC,OAAO,EAAE,UAAU,GAAG,oBAAoB,GAAG,eAAe,GAAG,SAAS,CAAC,CAAC;AAc1G;;GAEG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,mBAAmB,EAAE,OAAO,EAAE,mBAAmB,
|
|
1
|
+
{"version":3,"file":"createRoutes.d.ts","sourceRoot":"","sources":["../src/createRoutes.ts"],"names":[],"mappings":"AAAA,OA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AAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,CAAC;IAC1F,CAAC;IAED,OAAO,CAAC,KAAK,CAAC,wBAAwB,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import type { Context } from '@ms-cloudpack/api-server';\nimport {\n isBootstrapRoute,\n isProxyRoute,\n isRedirectRoute,\n isRenderedRoute,\n isStaticRoute,\n type BootstrapRoute,\n type PackageJson,\n type RenderedRoute,\n type ExpandedRenderFunctionResult,\n type RequestHandler,\n} from '@ms-cloudpack/common-types';\nimport type { Express, Request, Response } from '@ms-cloudpack/create-express-app';\nimport { express } from '@ms-cloudpack/create-express-app';\nimport { createImportMap } from '@ms-cloudpack/import-map';\nimport { slash } from '@ms-cloudpack/path-string-parsing';\nimport path from 'path';\nimport { getInlineScripts } from './inlineScripts/getInlineScripts.js';\nimport { renderRoute } from './renderRoute/renderRoute.js';\nimport { renderBootstrapRoute } from './renderBootstrapRoute.js';\nimport { createPageSessionContext } from './createPageSessionContext.js';\nimport { parseRouteMatch } from './parseRouteMatch.js';\nimport { createProxyMiddleware } from 'http-proxy-middleware';\n\ninterface CreateRoutesOptions {\n app: Express;\n /** Base app server URL, including the port */\n url: string;\n /** package.json for the app */\n definition: PackageJson;\n}\n\ntype CreateRoutesContext = Pick<Context, 'packages' | 'packageImportPaths' | 'packageHashes' | 'session'>;\n\n/** Express middleware that will match the domain to continue the route execution. */\nfunction matchDomain(domain?: RegExp): RequestHandler {\n return (req, _, next) => {\n if (!domain || domain.test(req.hostname)) {\n return next();\n }\n\n // Jump to next route.\n return next('route');\n };\n}\n\n/**\n * Creates the routes for the express app based on the config.\n */\nexport function createRoutes(options: CreateRoutesOptions, context: CreateRoutesContext) {\n const { app, ...otherOptions } = options;\n const { session } = context;\n const { config } = session;\n const { appPath } = config;\n const routes = [...(session.config.routes || [])];\n\n if (!options.definition.name) {\n throw new Error('Name field is required in the package.json file.');\n }\n\n if (!routes.length) {\n // If no routes have been defined, register a default (no path) route only.\n // This will render default HTML which includes the app's default path ('.') from the import map.\n routes.push({\n match: '/',\n // sourcePath and requestPath are required by types but unused in this case.\n entry: [{ importPath: '.', sourcePath: '' }],\n });\n }\n\n for (const route of routes) {\n const matches = Array.isArray(route.match) ? route.match : [route.match];\n\n for (const match of matches) {\n const { pathMatch, domainMatch } = parseRouteMatch(match);\n\n if (isStaticRoute(route)) {\n app.use(pathMatch, matchDomain(domainMatch), express.static(path.resolve(appPath, route.staticPath)));\n } else if (isRedirectRoute(route)) {\n app.get(pathMatch, matchDomain(domainMatch), (req, res) => {\n res.redirect(route.redirectTo);\n });\n } else if (isRenderedRoute(route) || isBootstrapRoute(route)) {\n app.get(pathMatch, matchDomain(domainMatch), (req, res) => {\n handleRequest({ ...otherOptions, route, req, res }, context).catch((err) => {\n console.error((err as Error)?.stack || err);\n res.status(500).send(`Error loading app: ${err}`);\n });\n });\n } else if (isProxyRoute(route)) {\n app.use(\n pathMatch,\n matchDomain(domainMatch),\n createProxyMiddleware({ target: route.proxyTo, ...route }) as RequestHandler,\n );\n } else {\n throw new Error(`Unknown route: ${JSON.stringify(route)}`);\n }\n }\n }\n}\n\nasync function handleRequest(\n options: Omit<CreateRoutesOptions, 'app'> & {\n req: Request;\n res: Response;\n route: RenderedRoute | BootstrapRoute;\n },\n context: CreateRoutesContext,\n) {\n const { req, res, definition, route, url } = options;\n const { session } = context;\n const { bundleServer, appServer } = session.urls;\n\n if (!bundleServer) {\n throw new Error('The bundle server URL is not yet set in the session (this is a Cloudpack bug).');\n }\n\n if (!appServer) {\n throw new Error('The app server URL is not yet set in the session (this is a Cloudpack bug).');\n }\n\n // Build the import map if it hasn't been built yet for this session version.\n // (TS can't infer that urls.bundleServer is set on session from a check above.)\n const importMap = (session.importMap ??= await createImportMap({\n ...context,\n ...session,\n urls: { bundleServer, appServer },\n }));\n\n // For production mode, no overlay script.\n const overlayScript = session.config.mode !== 'production' ? importMap.imports['@ms-cloudpack/overlay'] : undefined;\n\n // Get all entry scripts for the route.\n const entryScripts = route.entry?.map(\n (entry) => importMap.imports[slash(path.join(definition.name, entry.importPath))],\n );\n\n const pageSessionContextScript =\n `window.__cloudpack ??= {};\\n` +\n `window.__cloudpack.pageSessionContext = ${JSON.stringify(createPageSessionContext(session, req.path))};`;\n\n // Add the pageSessionContext to the top of the inlineScripts\n const inlineScripts = [pageSessionContextScript, ...(await getInlineScripts())];\n\n // Set the appropriate Cloudpack headers in the response.\n res.header('Cache-Control', 'no-cache');\n res.header('Access-Control-Allow-Origin', '*');\n\n let rendered: ExpandedRenderFunctionResult | null;\n\n if (isBootstrapRoute(route)) {\n // Render the bootstrap script\n rendered = await renderBootstrapRoute({\n session,\n importMap,\n overlayScript,\n inlineScripts,\n entryScripts,\n requestPath: req.path,\n });\n } else {\n // HTML or custom script rendering\n rendered = await renderRoute({\n ...options,\n session,\n baseUrl: url,\n importMap,\n overlayScript,\n inlineScripts,\n entryScripts,\n });\n }\n\n if (rendered) {\n res.type(rendered.contentType).status(rendered.statusCode).send(rendered.content).end();\n }\n\n console.debug(`App server: Request: ${req.path}`);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"createRoutes.js","sourceRoot":"","sources":["../src/createRoutes.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gBAAgB,EAChB,YAAY,EACZ,eAAe,EACf,eAAe,EACf,aAAa,GAMd,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,OAAO,EAAE,MAAM,kCAAkC,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAC1D,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE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AED,IAAI,QAAQ,EAAE,CAAC;QACb,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,CAAC;IAC1F,CAAC;IAED,OAAO,CAAC,KAAK,CAAC,wBAAwB,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import type { Context } from '@ms-cloudpack/api-server';\nimport {\n isBootstrapRoute,\n isProxyRoute,\n isRedirectRoute,\n isRenderedRoute,\n isStaticRoute,\n type BootstrapRoute,\n type PackageJson,\n type RenderedRoute,\n type ExpandedRenderFunctionResult,\n type RequestHandler,\n} from '@ms-cloudpack/common-types';\nimport type { Express, Request, Response } from '@ms-cloudpack/create-express-app';\nimport { express } from '@ms-cloudpack/create-express-app';\nimport { createImportMap } from '@ms-cloudpack/import-map';\nimport { slash } from '@ms-cloudpack/path-string-parsing';\nimport path from 'path';\nimport { getInlineScripts } from './inlineScripts/getInlineScripts.js';\nimport { renderRoute } from './renderRoute/renderRoute.js';\nimport { renderBootstrapRoute } from './renderBootstrapRoute.js';\nimport { createPageSessionContext } from './createPageSessionContext.js';\nimport { parseRouteMatch } from './parseRouteMatch.js';\nimport { createProxyMiddleware } from 'http-proxy-middleware';\n\ninterface CreateRoutesOptions {\n app: Express;\n /** Base app server URL, including the port */\n url: string;\n /** package.json for the app */\n definition: PackageJson;\n}\n\ntype CreateRoutesContext = Pick<Context, 'packages' | 'packageImportPaths' | 'packageHashes' | 'session'>;\n\n/** Express middleware that will match the domain to continue the route execution. */\nfunction matchDomain(domain?: RegExp): RequestHandler {\n return (req, _, next) => {\n if (!domain || domain.test(req.hostname)) {\n return next();\n }\n\n // Jump to next route.\n return next('route');\n };\n}\n\n/**\n * Creates the routes for the express app based on the config.\n */\nexport function createRoutes(options: CreateRoutesOptions, context: CreateRoutesContext): void {\n const { app, ...otherOptions } = options;\n const { session } = context;\n const { config } = session;\n const { appPath } = config;\n const routes = [...(session.config.routes || [])];\n\n if (!options.definition.name) {\n throw new Error('Name field is required in the package.json file.');\n }\n\n if (!routes.length) {\n // If no routes have been defined, register a default (no path) route only.\n // This will render default HTML which includes the app's default path ('.') from the import map.\n routes.push({\n match: '/',\n // sourcePath and requestPath are required by types but unused in this case.\n entry: [{ importPath: '.', sourcePath: '' }],\n });\n }\n\n for (const route of routes) {\n const matches = Array.isArray(route.match) ? route.match : [route.match];\n\n for (const match of matches) {\n const { pathMatch, domainMatch } = parseRouteMatch(match);\n\n if (isStaticRoute(route)) {\n app.use(pathMatch, matchDomain(domainMatch), express.static(path.resolve(appPath, route.staticPath)));\n } else if (isRedirectRoute(route)) {\n app.get(pathMatch, matchDomain(domainMatch), (req, res) => {\n res.redirect(route.redirectTo);\n });\n } else if (isRenderedRoute(route) || isBootstrapRoute(route)) {\n app.get(pathMatch, matchDomain(domainMatch), (req, res) => {\n handleRequest({ ...otherOptions, route, req, res }, context).catch((err) => {\n console.error((err as Error)?.stack || err);\n res.status(500).send(`Error loading app: ${err}`);\n });\n });\n } else if (isProxyRoute(route)) {\n app.use(\n pathMatch,\n matchDomain(domainMatch),\n createProxyMiddleware({ target: route.proxyTo, ...route }) as RequestHandler,\n );\n } else {\n throw new Error(`Unknown route: ${JSON.stringify(route)}`);\n }\n }\n }\n}\n\nasync function handleRequest(\n options: Omit<CreateRoutesOptions, 'app'> & {\n req: Request;\n res: Response;\n route: RenderedRoute | BootstrapRoute;\n },\n context: CreateRoutesContext,\n): Promise<void> {\n const { req, res, definition, route, url } = options;\n const { session } = context;\n const { bundleServer, appServer } = session.urls;\n\n if (!bundleServer) {\n throw new Error('The bundle server URL is not yet set in the session (this is a Cloudpack bug).');\n }\n\n if (!appServer) {\n throw new Error('The app server URL is not yet set in the session (this is a Cloudpack bug).');\n }\n\n // Build the import map if it hasn't been built yet for this session version.\n // (TS can't infer that urls.bundleServer is set on session from a check above.)\n const importMap = (session.importMap ??= await createImportMap({\n ...context,\n ...session,\n urls: { bundleServer, appServer },\n }));\n\n // For production mode, no overlay script.\n const overlayScript = session.config.mode !== 'production' ? importMap.imports['@ms-cloudpack/overlay'] : undefined;\n\n // Get all entry scripts for the route.\n const entryScripts = route.entry?.map(\n (entry) => importMap.imports[slash(path.join(definition.name, entry.importPath))],\n );\n\n const pageSessionContextScript =\n `window.__cloudpack ??= {};\\n` +\n `window.__cloudpack.pageSessionContext = ${JSON.stringify(createPageSessionContext(session, req.path))};`;\n\n // Add the pageSessionContext to the top of the inlineScripts\n const inlineScripts = [pageSessionContextScript, ...(await getInlineScripts())];\n\n // Set the appropriate Cloudpack headers in the response.\n res.header('Cache-Control', 'no-cache');\n res.header('Access-Control-Allow-Origin', '*');\n\n let rendered: ExpandedRenderFunctionResult | null;\n\n if (isBootstrapRoute(route)) {\n // Render the bootstrap script\n rendered = await renderBootstrapRoute({\n session,\n importMap,\n overlayScript,\n inlineScripts,\n entryScripts,\n requestPath: req.path,\n });\n } else {\n // HTML or custom script rendering\n rendered = await renderRoute({\n ...options,\n session,\n baseUrl: url,\n importMap,\n overlayScript,\n inlineScripts,\n entryScripts,\n });\n }\n\n if (rendered) {\n res.type(rendered.contentType).status(rendered.statusCode).send(rendered.content).end();\n }\n\n console.debug(`App server: Request: ${req.path}`);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handleErrorPortUnavailable.d.ts","sourceRoot":"","sources":["../src/handleErrorPortUnavailable.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,
|
|
1
|
+
{"version":3,"file":"handleErrorPortUnavailable.d.ts","sourceRoot":"","sources":["../src/handleErrorPortUnavailable.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,IAAI,CAgB5G"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handleErrorPortUnavailable.js","sourceRoot":"","sources":["../src/handleErrorPortUnavailable.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,UAAU,0BAA0B,CAAC,GAAY,EAAE,WAAmB,EAAE,KAAwB;IACpG,MAAM,SAAS,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC9D,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,OAAO,KAAK,8BAA8B,EAAE,CAAC;QAC3E,MAAM,mBAAmB,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;YAC/D,CAAC,CAAC,iKAAiK;YACnK,CAAC,CAAC,EAAE,CAAC;QACP,MAAM,YAAY,GAChB,8BAA8B,WAAW,0DAA0D,SAAS,CAAC,IAAI,CAC/G,IAAI,CACL,uCAAuC,GAAG,mBAAmB,CAAC;QAEjE,mDAAmD;QACnD,GAAG,CAAC,OAAO,GAAG,YAAY,CAAC;QAC3B,+EAA+E;QAC/E,GAAG,CAAC,KAAK,GAAG,SAAS,CAAC;IACxB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Handle the error if the port is already in use.\n */\nexport function handleErrorPortUnavailable(err: unknown, projectName: string, ports: number | number[]) {\n const portRange = typeof ports === 'number' ? [ports] : ports;\n if (err instanceof Error && err.message === 'Specified port not available') {\n const portNeedsPrivileges = portRange.some((port) => port < 1024)\n ? '\\nNote: for Mac/Linux/WSL users, you may need to run Cloudpack with elevated privileges to use port numbers less than 1024. Try running `sudo cloudpack start`.'\n : '';\n const errorMessage =\n `Cloudpack could not start \"${projectName}\" because no port from the allowed list was available: ${portRange.join(\n ', ',\n )}. Close other programs and try again.` + portNeedsPrivileges;\n\n // Edit the error message to be more user-friendly.\n err.message = errorMessage;\n // Suppress the stack trace for this error because it's not useful to the user.\n err.stack = undefined;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"handleErrorPortUnavailable.js","sourceRoot":"","sources":["../src/handleErrorPortUnavailable.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,UAAU,0BAA0B,CAAC,GAAY,EAAE,WAAmB,EAAE,KAAwB;IACpG,MAAM,SAAS,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC9D,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,OAAO,KAAK,8BAA8B,EAAE,CAAC;QAC3E,MAAM,mBAAmB,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;YAC/D,CAAC,CAAC,iKAAiK;YACnK,CAAC,CAAC,EAAE,CAAC;QACP,MAAM,YAAY,GAChB,8BAA8B,WAAW,0DAA0D,SAAS,CAAC,IAAI,CAC/G,IAAI,CACL,uCAAuC,GAAG,mBAAmB,CAAC;QAEjE,mDAAmD;QACnD,GAAG,CAAC,OAAO,GAAG,YAAY,CAAC;QAC3B,+EAA+E;QAC/E,GAAG,CAAC,KAAK,GAAG,SAAS,CAAC;IACxB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Handle the error if the port is already in use.\n */\nexport function handleErrorPortUnavailable(err: unknown, projectName: string, ports: number | number[]): void {\n const portRange = typeof ports === 'number' ? [ports] : ports;\n if (err instanceof Error && err.message === 'Specified port not available') {\n const portNeedsPrivileges = portRange.some((port) => port < 1024)\n ? '\\nNote: for Mac/Linux/WSL users, you may need to run Cloudpack with elevated privileges to use port numbers less than 1024. Try running `sudo cloudpack start`.'\n : '';\n const errorMessage =\n `Cloudpack could not start \"${projectName}\" because no port from the allowed list was available: ${portRange.join(\n ', ',\n )}. Close other programs and try again.` + portNeedsPrivileges;\n\n // Edit the error message to be more user-friendly.\n err.message = errorMessage;\n // Suppress the stack trace for this error because it's not useful to the user.\n err.stack = undefined;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errorHandler.inline.js","sourceRoot":"","sources":["../../src/inlineScripts/errorHandler.inline.ts"],"names":[],"mappings":"AAAA,oFAAoF;AAEpF,MAAM,UAAU,GAAG,CAAC,MAAM,CAAC,YAAY,GAAG;IACxC,cAAc,EAAE,EAAkB;IAClC,kBAAkB,EAAE,EAA6B;IACjD,UAAU,EAAE,GAAG,EAAE;QACf,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QACjD,MAAM,CAAC,mBAAmB,CAAC,oBAAoB,EAAE,eAAe,CAAC,CAAC;IACpE,CAAC;CACF,CAAC,CAAC;AAEH,SAAS,WAAW,CAAC,KAAiB;IACpC,UAAU,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,eAAe,CAAC,KAA4B;IACnD,UAAU,CAAC,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;AAC9C,MAAM,CAAC,gBAAgB,CAAC,oBAAoB,EAAE,eAAe,CAAC,CAAC","sourcesContent":["// This file must NOT import other files, because they won't be resolved at runtime.\n\nconst pageErrors = (window.__pageErrors = {\n uncaughtErrors: [] as ErrorEvent[],\n uncaughtRejections: [] as PromiseRejectionEvent[],\n unregister: () => {\n window.removeEventListener('error', handleError);\n window.removeEventListener('unhandledrejection', handleRejection);\n },\n});\n\nfunction handleError(event: ErrorEvent) {\n pageErrors.uncaughtErrors.push(event);\n}\n\nfunction handleRejection(event: PromiseRejectionEvent) {\n pageErrors.uncaughtRejections.push(event);\n}\n\nwindow.addEventListener('error', handleError);\nwindow.addEventListener('unhandledrejection', handleRejection);\n"]}
|
|
1
|
+
{"version":3,"file":"errorHandler.inline.js","sourceRoot":"","sources":["../../src/inlineScripts/errorHandler.inline.ts"],"names":[],"mappings":"AAAA,oFAAoF;AAEpF,MAAM,UAAU,GAAG,CAAC,MAAM,CAAC,YAAY,GAAG;IACxC,cAAc,EAAE,EAAkB;IAClC,kBAAkB,EAAE,EAA6B;IACjD,UAAU,EAAE,GAAG,EAAE;QACf,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QACjD,MAAM,CAAC,mBAAmB,CAAC,oBAAoB,EAAE,eAAe,CAAC,CAAC;IACpE,CAAC;CACF,CAAC,CAAC;AAEH,SAAS,WAAW,CAAC,KAAiB;IACpC,UAAU,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,eAAe,CAAC,KAA4B;IACnD,UAAU,CAAC,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;AAC9C,MAAM,CAAC,gBAAgB,CAAC,oBAAoB,EAAE,eAAe,CAAC,CAAC","sourcesContent":["// This file must NOT import other files, because they won't be resolved at runtime.\n\nconst pageErrors = (window.__pageErrors = {\n uncaughtErrors: [] as ErrorEvent[],\n uncaughtRejections: [] as PromiseRejectionEvent[],\n unregister: () => {\n window.removeEventListener('error', handleError);\n window.removeEventListener('unhandledrejection', handleRejection);\n },\n});\n\nfunction handleError(event: ErrorEvent): void {\n pageErrors.uncaughtErrors.push(event);\n}\n\nfunction handleRejection(event: PromiseRejectionEvent): void {\n pageErrors.uncaughtRejections.push(event);\n}\n\nwindow.addEventListener('error', handleError);\nwindow.addEventListener('unhandledrejection', handleRejection);\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"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AAE,CAAC;QACrC,sBAAsB,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;AACH,CAAC,CAAC,CAAC;AAEH,4DAA4D;AAC5D,KAAK,MAAM,KAAK,IAAI,WAAW,CAAC,gBAAgB,CAAC,UAAU,CAAC,EAAE,CAAC;IAC7D,sBAAsB,CAAC,KAAK,CAAC,CAAC;AAChC,CAAC;AAED,0DAA0D;AAC1D,YAAY,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;AAE3D,SAAS,oBAAoB;IAC3B,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC,MAAM,CAAC;IACjG,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,MAAM,CAAC;IACzD,MAAM,KAAK,GAAG,UAAU,GAAG,UAAU,CAAC;IAEtC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAW,CAAC;AAChE,CAAC;AAED,MAAM,CAAC,WAAW,KAAK,EAAE,CAAC;AAC1B,MAAM,CAAC,WAAW,CAAC,oBAAoB,GAAG,oBAAoB,CAAC","sourcesContent":["// This file must NOT import other files (except types), because they won't be resolved at runtime.\n\nconst scriptLoadResults: Record<string, 'cache' | 'network'> = {};\n\nif (!window.__cloudpack?.pageSessionContext) {\n throw new Error('window.__cloudpack.pageSessionContext is not defined');\n}\n\nconst bundleServerUrl = window.__cloudpack.pageSessionContext.bundleServerUrl;\n\nfunction isPerformanceResourceTiming(entry: PerformanceEntry): entry is PerformanceResourceTiming {\n return entry.entryType === 'resource';\n}\n\nfunction handlePerformanceEntry(item: PerformanceEntry): void {\n if (isPerformanceResourceTiming(item) && item.name.startsWith(bundleServerUrl)) {\n scriptLoadResults[item.name] = item.transferSize === 0 ? 'cache' : 'network';\n }\n}\n\nconst perfObserver = new PerformanceObserver((list) => {\n for (const item of list.getEntries()) {\n handlePerformanceEntry(item);\n }\n});\n\n// Get all the resources that were loaded before this script\nfor (const entry of performance.getEntriesByType('resource')) {\n handlePerformanceEntry(entry);\n}\n\n// Observe all resources that are loaded after this script\nperfObserver.observe({ type: 'resource', buffered: true });\n\nfunction getBrowserCacheRatio(): { ratio: number; hit: number; total: number } {\n const cacheCount = Object.values(scriptLoadResults).filter((source) => source == 'cache').length;\n const totalCount = Object.keys(scriptLoadResults).length;\n const ratio = cacheCount / totalCount;\n\n return { ratio, hit: cacheCount, total: totalCount } as const;\n}\n\nwindow.__cloudpack ??= {};\nwindow.__cloudpack.getBrowserCacheRatio = getBrowserCacheRatio;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getInlineScripts.d.ts","sourceRoot":"","sources":["../../src/inlineScripts/getInlineScripts.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AACH,wBAAsB,gBAAgB,
|
|
1
|
+
{"version":3,"file":"getInlineScripts.d.ts","sourceRoot":"","sources":["../../src/inlineScripts/getInlineScripts.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AACH,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC,CAS1D;AAID;;GAEG;AACH,wBAAsB,uBAAuB,IAAI,OAAO,CAAC,MAAM,CAAC,CAQ/D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getInlineScripts.js","sourceRoot":"","sources":["../../src/inlineScripts/getInlineScripts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAEpC,KAAK,UAAU,gBAAgB,CAAC,QAAgB;IAC9C,IAAI,OAAO,GAAG,MAAM,UAAU,CAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAE3D,2EAA2E;IAC3E,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,qBAAqB,EAAE,GAAG,CAAC,CAAC;IAEtD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,IAAI,aAAmC,CAAC;AAExC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB;IACpC,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,iBAAiB,GAAG,CAAC,MAAM,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC,CAAC,MAAM,CACnF,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAC7C,CAAC;QACF,aAAa,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IACrG,CAAC;IAED,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,IAAI,qBAAyC,CAAC;AAE9C;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB;IAC3C,IAAI,CAAC,qBAAqB,EAAE,CAAC;QAC3B,qBAAqB,GAAG,MAAM,gBAAgB,CAC5C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,qBAAqB,CAAC,CAC/E,CAAC;IACJ,CAAC;IAED,OAAO,qBAAqB,CAAC;AAC/B,CAAC","sourcesContent":["import { globSourceFiles } from '@ms-cloudpack/path-utilities';\nimport fsPromises from 'fs/promises';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nasync function readInlineScript(fileName: string) {\n let content = await fsPromises.readFile(fileName, 'utf-8');\n\n // Remove source maps from inline scripts to avoid warnings in the browser.\n content = content.replace('# sourceMappingURL=', ' ');\n\n return content;\n}\n\nlet inlineScripts: string[] | undefined;\n\n/**\n * Reads all the inline scripts except bootstrap from the file system and returns them. It caches the result for subsequent calls.\n * @returns The inline scripts excluding bootstrap.\n */\nexport async function getInlineScripts() {\n if (!inlineScripts) {\n const inlineScriptFiles = (await globSourceFiles(import.meta.url, '*.inline')).filter(\n (file) => !file.includes('bootstrap.inline'),\n );\n inlineScripts = await Promise.all(inlineScriptFiles.map((filename) => readInlineScript(filename)));\n }\n\n return inlineScripts;\n}\n\nlet bootstrapInlineScript: string | undefined;\n\n/**\n * Reads the bootstrap inline script from the file system and returns it.\n */\nexport async function getBoostrapInlineScript() {\n if (!bootstrapInlineScript) {\n bootstrapInlineScript = await readInlineScript(\n path.join(path.dirname(fileURLToPath(import.meta.url)), 'bootstrap.inline.js'),\n );\n }\n\n return bootstrapInlineScript;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"getInlineScripts.js","sourceRoot":"","sources":["../../src/inlineScripts/getInlineScripts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAEpC,KAAK,UAAU,gBAAgB,CAAC,QAAgB;IAC9C,IAAI,OAAO,GAAG,MAAM,UAAU,CAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAE3D,2EAA2E;IAC3E,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,qBAAqB,EAAE,GAAG,CAAC,CAAC;IAEtD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,IAAI,aAAmC,CAAC;AAExC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB;IACpC,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,iBAAiB,GAAG,CAAC,MAAM,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC,CAAC,MAAM,CACnF,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAC7C,CAAC;QACF,aAAa,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IACrG,CAAC;IAED,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,IAAI,qBAAyC,CAAC;AAE9C;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB;IAC3C,IAAI,CAAC,qBAAqB,EAAE,CAAC;QAC3B,qBAAqB,GAAG,MAAM,gBAAgB,CAC5C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,qBAAqB,CAAC,CAC/E,CAAC;IACJ,CAAC;IAED,OAAO,qBAAqB,CAAC;AAC/B,CAAC","sourcesContent":["import { globSourceFiles } from '@ms-cloudpack/path-utilities';\nimport fsPromises from 'fs/promises';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nasync function readInlineScript(fileName: string): Promise<string> {\n let content = await fsPromises.readFile(fileName, 'utf-8');\n\n // Remove source maps from inline scripts to avoid warnings in the browser.\n content = content.replace('# sourceMappingURL=', ' ');\n\n return content;\n}\n\nlet inlineScripts: string[] | undefined;\n\n/**\n * Reads all the inline scripts except bootstrap from the file system and returns them. It caches the result for subsequent calls.\n * @returns The inline scripts excluding bootstrap.\n */\nexport async function getInlineScripts(): Promise<string[]> {\n if (!inlineScripts) {\n const inlineScriptFiles = (await globSourceFiles(import.meta.url, '*.inline')).filter(\n (file) => !file.includes('bootstrap.inline'),\n );\n inlineScripts = await Promise.all(inlineScriptFiles.map((filename) => readInlineScript(filename)));\n }\n\n return inlineScripts;\n}\n\nlet bootstrapInlineScript: string | undefined;\n\n/**\n * Reads the bootstrap inline script from the file system and returns it.\n */\nexport async function getBoostrapInlineScript(): Promise<string> {\n if (!bootstrapInlineScript) {\n bootstrapInlineScript = await readInlineScript(\n path.join(path.dirname(fileURLToPath(import.meta.url)), 'bootstrap.inline.js'),\n );\n }\n\n return bootstrapInlineScript;\n}\n"]}
|
|
@@ -11,14 +11,13 @@ const excludedIds = [overlayRootDivId];
|
|
|
11
11
|
function debounce(func, wait) {
|
|
12
12
|
let timeout;
|
|
13
13
|
return function (...args) {
|
|
14
|
-
const later = () => {
|
|
15
|
-
timeout = null;
|
|
16
|
-
func(...args);
|
|
17
|
-
};
|
|
18
14
|
if (timeout) {
|
|
19
15
|
clearTimeout(timeout);
|
|
20
16
|
}
|
|
21
|
-
timeout = setTimeout(
|
|
17
|
+
timeout = setTimeout(() => {
|
|
18
|
+
timeout = null;
|
|
19
|
+
func(...args);
|
|
20
|
+
}, wait);
|
|
22
21
|
};
|
|
23
22
|
}
|
|
24
23
|
function hasMutationNonExcludedNodes(mutation) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getPageLoadTime.inline.js","sourceRoot":"","sources":["../../src/inlineScripts/getPageLoadTime.inline.ts"],"names":[],"mappings":"AAAA,mGAAmG;AAInG,kGAAkG;AAClG,MAAM,gBAAgB,GAAgC,wBAAwB,CAAC;AAE/E;;;GAGG;AACH,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAElD,8DAA8D;AAC9D,MAAM,WAAW,GAAa,CAAC,gBAAgB,CAAC,CAAC;AAIjD,SAAS,QAAQ,CAAsB,IAAqB,EAAE,IAAY;IACxE,IAAI,OAA6C,CAAC;IAElD,OAAO,UAAU,GAAG,IAAO;QACzB,
|
|
1
|
+
{"version":3,"file":"getPageLoadTime.inline.js","sourceRoot":"","sources":["../../src/inlineScripts/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AC,uBAAuB,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;IAE/F,SAAS,UAAU,CAAC,SAA2B;QAC7C,MAAM,aAAa,GAAG,SAAS,CAAC,MAAM,CAAC,2BAA2B,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;QAE/E,IAAI,aAAa,EAAE,CAAC;YAClB,qBAAqB,CAAC,GAAG,EAAE;gBACzB,kFAAkF;gBAClF,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;gBAE/B,uBAAuB;gBACvB,WAAW,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;gBAEvC,0BAA0B;gBAC1B,WAAW,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;gBAEjC,4BAA4B;gBAC5B,gCAAgC,CAAC,IAAI,CAAC,CAAC;YACzC,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE;QAC9B,SAAS,EAAE,IAAI;KAChB,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,MAAM,CAAC,WAAW,KAAK,EAAE,CAAC;AAC1B,MAAM,CAAC,WAAW,CAAC,eAAe,GAAG,GAAG,EAAE,CAAC,mBAAmB,CAAC","sourcesContent":["// This file must NOT import other files (except types), because they won't be resolved at runtime.\n\nimport type { elementIds } from '@ms-cloudpack/overlay/constants';\n\n// Typing hack to ensure this ID is correct while working around the limitation on runtime imports\nconst overlayRootDivId: (typeof elementIds)['root'] = 'cloudpack-overlay-root';\n\n/**\n * Performance mark name for page load time.\n * This makes it easier to see the page load time in the performance tab in dev tools\n */\nconst pageLoadMarker = 'CLOUDPACK_PAGE_LOAD_TIME';\n\n// The below dom elements will be ignored by mutation observer\nconst excludedIds: string[] = [overlayRootDivId];\n\ntype DebounceFunc<T extends unknown[]> = (...args: T) => void;\n\nfunction debounce<T extends unknown[]>(func: DebounceFunc<T>, wait: number): DebounceFunc<T> {\n let timeout: ReturnType<typeof setTimeout> | null;\n\n return function (...args: T) {\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n timeout = null;\n func(...args);\n }, wait);\n };\n}\n\nfunction hasMutationNonExcludedNodes(mutation: MutationRecord): boolean {\n return [...mutation.addedNodes].some((node) => {\n const id = (node as { id?: string }).id;\n\n if (id) {\n return !excludedIds.includes(id);\n }\n\n return true;\n });\n}\n\nconst pageLoadTimePromise = new Promise<number>((resolve) => {\n const observer = new MutationObserver(domChanged);\n\n function reportLastAnimationTime(time: number) {\n // Stop observing the DOM\n observer.disconnect();\n\n // Resolve the promise with the page load time\n resolve(time);\n }\n\n const debouncedReportLastAnimationTime = debounce(reportLastAnimationTime, 2000 /* wait ms */);\n\n function domChanged(mutations: MutationRecord[]) {\n const shouldProcess = mutations.filter(hasMutationNonExcludedNodes).length > 0;\n\n if (shouldProcess) {\n requestAnimationFrame(() => {\n // Get the current time in ms since the time when navigation has started in window\n const time = performance.now();\n\n // Clear previous marks\n performance.clearMarks(pageLoadMarker);\n\n // Mark the page load time\n performance.mark(pageLoadMarker);\n\n // Report the page load time\n debouncedReportLastAnimationTime(time);\n });\n }\n }\n\n observer.observe(document.body, {\n childList: true,\n });\n});\n\nwindow.__cloudpack ??= {};\nwindow.__cloudpack.getPageLoadTime = () => pageLoadTimePromise;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderRoute.js","sourceRoot":"","sources":["../../src/renderRoute/renderRoute.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAC5D,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,oBAAoB,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EAAE,CAAC;QAChG,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACvB,OAAO,oBAAoB,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;AACH,CAAC","sourcesContent":["import type {\n RenderFunction,\n RenderFunctionOptions,\n RenderFunctionResult,\n ExpandedRenderFunctionResult,\n RenderedRoute,\n Request,\n RenderFunctionScript,\n} from '@ms-cloudpack/common-types';\nimport { makeUrl } from '@ms-cloudpack/path-string-parsing';\nimport fsPromises from 'fs/promises';\nimport { JSDOM } from 'jsdom';\nimport path from 'path';\nimport { pathToFileURL } from 'url';\nimport { getDefaultHtmlResponse } from './getDefaultHtmlResponse.js';\nimport { getHtmlErrorResponse } from './getHtmlErrorResponse.js';\n\n/**\n * Get the response for the given route. If the route has a custom render script, use that.\n * Returns an error response if the file referenced by the script doesn't exist or throws an error.\n */\nexport async function renderRoute(options: RenderFunctionOptions): Promise<ExpandedRenderFunctionResult | null> {\n const { route, session } = options;\n const { config } = session;\n const { appPath } = config;\n\n // Get an initial result from either the render script or default handler.\n let rawResult: RenderFunctionResult;\n const renderScriptPath = route.renderScript && path.resolve(appPath, route.renderScript);\n if (renderScriptPath) {\n const scriptExt = path.extname(renderScriptPath).toLowerCase();\n if (scriptExt === '.html' || scriptExt === '.htm') {\n rawResult = await readStaticHtml(renderScriptPath);\n } else {\n rawResult = await renderCustomScript({ ...options, renderScriptPath });\n }\n } else {\n rawResult = await getDefaultHtmlResponse(options);\n }\n\n if (rawResult === null) {\n // This means the custom renderScript fully handled the request.\n return null;\n }\n\n if (rawResult === undefined) {\n return makeErrorResponse({\n message:\n `returned undefined. If the renderScript fully handled the request (sent a response), ` +\n `return null instead. Otherwise ensure that the function returns the content to be rendered.`,\n route,\n req: options.req,\n renderScriptPath,\n });\n }\n\n const result: ExpandedRenderFunctionResult = {\n contentType: 'text/html',\n statusCode: 200,\n ...(typeof rawResult === 'string' ? { content: rawResult } : rawResult),\n };\n\n // If it's HTML and a success statusCode, inject the import map and appropriate scripts.\n if (result.statusCode === 200 && isHtmlType(result.contentType)) {\n if (isHtmlAcceptable(options)) {\n // Inject the import map and scripts.\n injectScripts(options, result);\n } else {\n // It appears we're accidentally returning HTML when a different file type was requested.\n // This could happen for overly broad route matches such as '*', or if no routes are configured.\n return makeErrorResponse({\n message:\n 'returned HTML, but this appears to be a non-HTML request. This is likely due to an ' +\n 'overly broad match or other misconfiguration of server.routes in the cloudpack config.',\n route,\n renderScriptPath,\n req: options.req,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Fill in details of the message, log to console.error, and return an error response.\n * `Route ${route.match} with renderScript \"${renderScriptPath}\" ${message}`\n */\nfunction makeErrorResponse(params: {\n message: string;\n route: RenderedRoute;\n renderScriptPath: string | undefined;\n req: Request;\n}): ExpandedRenderFunctionResult {\n const { message, route, renderScriptPath, req } = params;\n const renderer = renderScriptPath ? `renderScript \"${renderScriptPath}\"` : 'the default renderer';\n const content = `Route ${JSON.stringify(route.match)} with ${renderer} ${message}`;\n console.error(`App server: request ${req.url} - ${content}`);\n\n return { statusCode: 500, contentType: 'text/plain', content };\n}\n\nfunction isHtmlAcceptable(options: Pick<RenderFunctionOptions, 'req' | 'baseUrl'>) {\n const { req, baseUrl } = options;\n // Get the request path and extension (the URL.pathname conversion gets rid of any query or hash)\n const requestPath = makeUrl(req.url, baseUrl).pathname;\n const requestExt = path.extname(requestPath);\n // Determine whether HTML is (probably) an acceptable response type (can be refined later if needed).\n // In theory we should be able to use req.accepts() but not all requests set the accept header.\n return (!requestExt || requestExt.startsWith('.htm')) && !req.xhr && isHtmlType(req.headers.accept || '*/*');\n}\n\nfunction isHtmlType(acceptOrContentType: string) {\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation/List_of_default_Accept_values\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types\n return acceptOrContentType\n .split(',')\n .map((s) => s.split(';')[0].trim())\n .some((mime) => mime === '*/*' || /xml|x?html/i.test(mime) || /^(text|application)\\/\\*$/.test(mime));\n}\n\n/**\n * Load the default export from a JS file passed as the `renderScript` in a route,\n * and return either the result of running the function, or an error page if something fails.\n */\nasync function renderCustomScript(\n params: RenderFunctionOptions & { renderScriptPath: string },\n): Promise<RenderFunctionResult> {\n const { renderScriptPath, ...options } = params;\n // Get the html factory function from a script default export.\n const renderScriptUrl = pathToFileURL(renderScriptPath).toString();\n\n // Note: because there isn't a way to purge the require cache, we need to add a cache breaker query param to the\n // script path to ensure we get the latest version of the script. This could be improved by using the git hash of\n // the file if it exists, or a hash of the content, or even the timestamp of the file.\n let cacheBreakerQueryParam = `?t=${Date.now()}`;\n try {\n const { mtime } = await fsPromises.stat(renderScriptPath);\n cacheBreakerQueryParam = `?t=${mtime.getTime()}`;\n } catch {\n /* no-op */\n }\n\n // Try importing the script\n let createHtml: RenderFunction | undefined;\n let errorMessage: string | undefined;\n try {\n const importResult = ((await import(renderScriptUrl + cacheBreakerQueryParam)) as RenderFunctionScript).default;\n if (typeof importResult === 'function') {\n createHtml = importResult;\n } else {\n errorMessage = `The render script at \"${renderScriptPath}\" does not export a default function.`;\n }\n } catch (e) {\n errorMessage = `Error importing render script at \"${renderScriptUrl}\":\\n${(e as Error).stack || e}`;\n }\n\n if (createHtml) {\n // Try running the script\n try {\n return await createHtml(options);\n } catch (e) {\n errorMessage = `Error running render script at \"${renderScriptPath}\":\\n${(e as Error).stack || e}`;\n }\n }\n\n // Return an error page. Doing this instead of returning a default or empty response ensures that\n // the user is aware of any configuration issues.\n errorMessage ??= `Unknown error loading render script at \"${renderScriptPath}\".`;\n console.error(errorMessage);\n return getHtmlErrorResponse(errorMessage);\n}\n\n/**\n * Modify the HTML response by injecting the import map, inline scripts, and entry/overlay scripts.\n *\n * Note that this just logs an error rather than returning an error response if something fails, for now.\n */\nfunction injectScripts(options: RenderFunctionOptions, result: ExpandedRenderFunctionResult): void {\n const { route, overlayScript, entryScripts, inlineScripts, importMap } = options;\n let jsdom: JSDOM;\n try {\n // TODO: JSDOM is overkill for what we're doing here--a full browser-like environment isn't\n // needed to just parse and modify the HTML. If it becomes a perf concern (less likely since\n // HTML page rendering is probably just done once per page load), we could switch to\n // a pure parser like parse5 or htmlparser2.\n jsdom = new JSDOM(result.content, { contentType: result.contentType } as ConstructorParameters<typeof JSDOM>[1]);\n } catch (e) {\n // Trying to write a test for the above, it seemed very permissive, but catch just in case\n console.error(\n `Error parsing html response for rendering route \"${JSON.stringify(route.match)}\":\\n${(e as Error).stack || e}`,\n );\n return;\n }\n\n try {\n const { document } = jsdom.window;\n\n if (entryScripts || overlayScript) {\n // Inject the import map at the top of the head, in case other scripts use it\n addScript({ document, type: 'importmap', prepend: true, content: JSON.stringify(importMap, null, 2) });\n }\n\n if (inlineScripts) {\n for (const inlineScript of inlineScripts) {\n addScript({ document, content: inlineScript });\n }\n }\n\n // inject the overlay and entry scripts\n addScript({ document, url: overlayScript });\n\n if (entryScripts) {\n for (const entryScript of entryScripts) {\n addScript({ document, url: entryScript });\n }\n }\n\n result.content = jsdom.serialize();\n } catch (e) {\n console.error(`Error injecting scripts for route \"${JSON.stringify(route.match)}\":\\n${(e as Error).stack || e}`);\n }\n}\n\n/**\n * Helper function to add a script to the document.\n * No-op if neither `url` nor `content` is provided.\n */\nfunction addScript(params: { document: Document; type?: string; prepend?: boolean; url?: string; content?: string }) {\n const { document, type = 'module', prepend, url, content } = params;\n if (!url && !content) {\n return;\n }\n\n const script = document.createElement('script');\n script.type = type;\n if (url) {\n script.src = url;\n } else if (content) {\n script.innerHTML = content;\n }\n\n if (prepend) {\n document.head.prepend(script);\n } else {\n document.head.appendChild(script);\n }\n}\n\n/**\n * Read a static HTML file, or return an error response if the file can't be read.\n */\nasync function readStaticHtml(renderScriptPath: string): Promise<RenderFunctionResult> {\n try {\n return (await fsPromises.readFile(renderScriptPath, 'utf8')) || '';\n } catch (e) {\n const message = `Error reading HTML file at \"${renderScriptPath}\":\\n${(e as Error).stack || e}`;\n console.error(message);\n return getHtmlErrorResponse(message);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"renderRoute.js","sourceRoot":"","sources":["../../src/renderRoute/renderRoute.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAC5D,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEjE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,OAA8B;IAC9D,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACnC,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC3B,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;IAE3B,0EAA0E;IAC1E,IAAI,SAA+B,CAAC;IACpC,MAAM,gBAAgB,GAAG,KAAK,CAAC,YAAY,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IACzF,IAAI,gBAAgB,EAAE,CAAC;QACrB,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,WAAW,EAAE,CAAC;QAC/D,IAAI,SAAS,KAAK,OAAO,IAAI,SAAS,KAAK,MAAM,EAAE,CAAC;YAClD,SAAS,GAAG,MAAM,cAAc,CAAC,gBAAgB,CAAC,CAAC;QACrD,CAAC;aAAM,CAAC;YACN,SAAS,GAAG,MAAM,kBAAkB,CAAC,EAAE,GAAG,OAAO,EAAE,g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C7B,CAAC;IAED,IAAI,OAAO,EAAE,CAAC;QACZ,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAChC,CAAC;SAAM,CAAC;QACN,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;IACpC,CAAC;AACH,CAAC;AAED;;GAEG;AACH,KAAK,UAAU,cAAc,CAAC,gBAAwB;IACpD,IAAI,CAAC;QACH,OAAO,CAAC,MAAM,UAAU,CAAC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;IACrE,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,OAAO,GAAG,+BAA+B,gBAAgB,OAAQ,CAAW,CAAC,KAAK,IAAI,CAAC,EAAE,CAAC;QAChG,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACvB,OAAO,oBAAoB,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;AACH,CAAC","sourcesContent":["import type {\n RenderFunction,\n RenderFunctionOptions,\n RenderFunctionResult,\n ExpandedRenderFunctionResult,\n RenderedRoute,\n Request,\n RenderFunctionScript,\n} from '@ms-cloudpack/common-types';\nimport { makeUrl } from '@ms-cloudpack/path-string-parsing';\nimport fsPromises from 'fs/promises';\nimport { JSDOM } from 'jsdom';\nimport path from 'path';\nimport { pathToFileURL } from 'url';\nimport { getDefaultHtmlResponse } from './getDefaultHtmlResponse.js';\nimport { getHtmlErrorResponse } from './getHtmlErrorResponse.js';\n\n/**\n * Get the response for the given route. If the route has a custom render script, use that.\n * Returns an error response if the file referenced by the script doesn't exist or throws an error.\n */\nexport async function renderRoute(options: RenderFunctionOptions): Promise<ExpandedRenderFunctionResult | null> {\n const { route, session } = options;\n const { config } = session;\n const { appPath } = config;\n\n // Get an initial result from either the render script or default handler.\n let rawResult: RenderFunctionResult;\n const renderScriptPath = route.renderScript && path.resolve(appPath, route.renderScript);\n if (renderScriptPath) {\n const scriptExt = path.extname(renderScriptPath).toLowerCase();\n if (scriptExt === '.html' || scriptExt === '.htm') {\n rawResult = await readStaticHtml(renderScriptPath);\n } else {\n rawResult = await renderCustomScript({ ...options, renderScriptPath });\n }\n } else {\n rawResult = await getDefaultHtmlResponse(options);\n }\n\n if (rawResult === null) {\n // This means the custom renderScript fully handled the request.\n return null;\n }\n\n if (rawResult === undefined) {\n return makeErrorResponse({\n message:\n `returned undefined. If the renderScript fully handled the request (sent a response), ` +\n `return null instead. Otherwise ensure that the function returns the content to be rendered.`,\n route,\n req: options.req,\n renderScriptPath,\n });\n }\n\n const result: ExpandedRenderFunctionResult = {\n contentType: 'text/html',\n statusCode: 200,\n ...(typeof rawResult === 'string' ? { content: rawResult } : rawResult),\n };\n\n // If it's HTML and a success statusCode, inject the import map and appropriate scripts.\n if (result.statusCode === 200 && isHtmlType(result.contentType)) {\n if (isHtmlAcceptable(options)) {\n // Inject the import map and scripts.\n injectScripts(options, result);\n } else {\n // It appears we're accidentally returning HTML when a different file type was requested.\n // This could happen for overly broad route matches such as '*', or if no routes are configured.\n return makeErrorResponse({\n message:\n 'returned HTML, but this appears to be a non-HTML request. This is likely due to an ' +\n 'overly broad match or other misconfiguration of server.routes in the cloudpack config.',\n route,\n renderScriptPath,\n req: options.req,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Fill in details of the message, log to console.error, and return an error response.\n * `Route ${route.match} with renderScript \"${renderScriptPath}\" ${message}`\n */\nfunction makeErrorResponse(params: {\n message: string;\n route: RenderedRoute;\n renderScriptPath: string | undefined;\n req: Request;\n}): ExpandedRenderFunctionResult {\n const { message, route, renderScriptPath, req } = params;\n const renderer = renderScriptPath ? `renderScript \"${renderScriptPath}\"` : 'the default renderer';\n const content = `Route ${JSON.stringify(route.match)} with ${renderer} ${message}`;\n console.error(`App server: request ${req.url} - ${content}`);\n\n return { statusCode: 500, contentType: 'text/plain', content };\n}\n\nfunction isHtmlAcceptable(options: Pick<RenderFunctionOptions, 'req' | 'baseUrl'>): boolean {\n const { req, baseUrl } = options;\n // Get the request path and extension (the URL.pathname conversion gets rid of any query or hash)\n const requestPath = makeUrl(req.url, baseUrl).pathname;\n const requestExt = path.extname(requestPath);\n // Determine whether HTML is (probably) an acceptable response type (can be refined later if needed).\n // In theory we should be able to use req.accepts() but not all requests set the accept header.\n return (!requestExt || requestExt.startsWith('.htm')) && !req.xhr && isHtmlType(req.headers.accept || '*/*');\n}\n\nfunction isHtmlType(acceptOrContentType: string): boolean {\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation/List_of_default_Accept_values\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types\n return acceptOrContentType\n .split(',')\n .map((s) => s.split(';')[0].trim())\n .some((mime) => mime === '*/*' || /xml|x?html/i.test(mime) || /^(text|application)\\/\\*$/.test(mime));\n}\n\n/**\n * Load the default export from a JS file passed as the `renderScript` in a route,\n * and return either the result of running the function, or an error page if something fails.\n */\nasync function renderCustomScript(\n params: RenderFunctionOptions & { renderScriptPath: string },\n): Promise<RenderFunctionResult> {\n const { renderScriptPath, ...options } = params;\n // Get the html factory function from a script default export.\n const renderScriptUrl = pathToFileURL(renderScriptPath).toString();\n\n // Note: because there isn't a way to purge the require cache, we need to add a cache breaker query param to the\n // script path to ensure we get the latest version of the script. This could be improved by using the git hash of\n // the file if it exists, or a hash of the content, or even the timestamp of the file.\n let cacheBreakerQueryParam = `?t=${Date.now()}`;\n try {\n const { mtime } = await fsPromises.stat(renderScriptPath);\n cacheBreakerQueryParam = `?t=${mtime.getTime()}`;\n } catch {\n /* no-op */\n }\n\n // Try importing the script\n let createHtml: RenderFunction | undefined;\n let errorMessage: string | undefined;\n try {\n const importResult = ((await import(renderScriptUrl + cacheBreakerQueryParam)) as RenderFunctionScript).default;\n if (typeof importResult === 'function') {\n createHtml = importResult;\n } else {\n errorMessage = `The render script at \"${renderScriptPath}\" does not export a default function.`;\n }\n } catch (e) {\n errorMessage = `Error importing render script at \"${renderScriptUrl}\":\\n${(e as Error).stack || e}`;\n }\n\n if (createHtml) {\n // Try running the script\n try {\n return await createHtml(options);\n } catch (e) {\n errorMessage = `Error running render script at \"${renderScriptPath}\":\\n${(e as Error).stack || e}`;\n }\n }\n\n // Return an error page. Doing this instead of returning a default or empty response ensures that\n // the user is aware of any configuration issues.\n errorMessage ??= `Unknown error loading render script at \"${renderScriptPath}\".`;\n console.error(errorMessage);\n return getHtmlErrorResponse(errorMessage);\n}\n\n/**\n * Modify the HTML response by injecting the import map, inline scripts, and entry/overlay scripts.\n *\n * Note that this just logs an error rather than returning an error response if something fails, for now.\n */\nfunction injectScripts(options: RenderFunctionOptions, result: ExpandedRenderFunctionResult): void {\n const { route, overlayScript, entryScripts, inlineScripts, importMap } = options;\n let jsdom: JSDOM;\n try {\n // TODO: JSDOM is overkill for what we're doing here--a full browser-like environment isn't\n // needed to just parse and modify the HTML. If it becomes a perf concern (less likely since\n // HTML page rendering is probably just done once per page load), we could switch to\n // a pure parser like parse5 or htmlparser2.\n jsdom = new JSDOM(result.content, { contentType: result.contentType } as ConstructorParameters<typeof JSDOM>[1]);\n } catch (e) {\n // Trying to write a test for the above, it seemed very permissive, but catch just in case\n console.error(\n `Error parsing html response for rendering route \"${JSON.stringify(route.match)}\":\\n${(e as Error).stack || e}`,\n );\n return;\n }\n\n try {\n const { document } = jsdom.window;\n\n if (entryScripts || overlayScript) {\n // Inject the import map at the top of the head, in case other scripts use it\n addScript({ document, type: 'importmap', prepend: true, content: JSON.stringify(importMap, null, 2) });\n }\n\n if (inlineScripts) {\n for (const inlineScript of inlineScripts) {\n addScript({ document, content: inlineScript });\n }\n }\n\n // inject the overlay and entry scripts\n addScript({ document, url: overlayScript });\n\n if (entryScripts) {\n for (const entryScript of entryScripts) {\n addScript({ document, url: entryScript });\n }\n }\n\n result.content = jsdom.serialize();\n } catch (e) {\n console.error(`Error injecting scripts for route \"${JSON.stringify(route.match)}\":\\n${(e as Error).stack || e}`);\n }\n}\n\n/**\n * Helper function to add a script to the document.\n * No-op if neither `url` nor `content` is provided.\n */\nfunction addScript(params: {\n document: Document;\n type?: string;\n prepend?: boolean;\n url?: string;\n content?: string;\n}): void {\n const { document, type = 'module', prepend, url, content } = params;\n if (!url && !content) {\n return;\n }\n\n const script = document.createElement('script');\n script.type = type;\n if (url) {\n script.src = url;\n } else if (content) {\n script.innerHTML = content;\n }\n\n if (prepend) {\n document.head.prepend(script);\n } else {\n document.head.appendChild(script);\n }\n}\n\n/**\n * Read a static HTML file, or return an error response if the file can't be read.\n */\nasync function readStaticHtml(renderScriptPath: string): Promise<RenderFunctionResult> {\n try {\n return (await fsPromises.readFile(renderScriptPath, 'utf8')) || '';\n } catch (e) {\n const message = `Error reading HTML file at \"${renderScriptPath}\":\\n${(e as Error).stack || e}`;\n console.error(message);\n return getHtmlErrorResponse(message);\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ms-cloudpack/app-server",
|
|
3
|
-
"version": "0.17.
|
|
3
|
+
"version": "0.17.26",
|
|
4
4
|
"description": "An implementation of the App server for Cloudpack.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -14,15 +14,15 @@
|
|
|
14
14
|
}
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@ms-cloudpack/api-server": "^0.
|
|
18
|
-
"@ms-cloudpack/bundle-server": "^0.6.
|
|
19
|
-
"@ms-cloudpack/common-types": "^0.
|
|
20
|
-
"@ms-cloudpack/create-express-app": "^1.10.
|
|
21
|
-
"@ms-cloudpack/import-map": "^0.8.
|
|
22
|
-
"@ms-cloudpack/overlay": "^0.17.
|
|
17
|
+
"@ms-cloudpack/api-server": "^0.57.0",
|
|
18
|
+
"@ms-cloudpack/bundle-server": "^0.6.35",
|
|
19
|
+
"@ms-cloudpack/common-types": "^0.24.0",
|
|
20
|
+
"@ms-cloudpack/create-express-app": "^1.10.11",
|
|
21
|
+
"@ms-cloudpack/import-map": "^0.8.21",
|
|
22
|
+
"@ms-cloudpack/overlay": "^0.17.107",
|
|
23
23
|
"@ms-cloudpack/path-string-parsing": "^1.2.6",
|
|
24
|
-
"@ms-cloudpack/path-utilities": "^2.8.
|
|
25
|
-
"@ms-cloudpack/task-reporter": "^0.14.
|
|
24
|
+
"@ms-cloudpack/path-utilities": "^2.8.1",
|
|
25
|
+
"@ms-cloudpack/task-reporter": "^0.14.8",
|
|
26
26
|
"http-proxy-middleware": "^2.0.6",
|
|
27
27
|
"jsdom": "^24.0.0"
|
|
28
28
|
},
|