@ecopages/lit 0.2.0-beta.31 → 0.2.0-beta.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,167 +1,168 @@
1
- import { AssetFactory } from "@ecopages/core/services/asset-processing-service";
2
- import path from "node:path";
3
- import { pathToFileURL } from "node:url";
4
- class LitSsrLazyPreloader {
5
- resolveDependencyPath;
6
- processDependencies;
7
- preferSourceImports;
8
- ssrPreloadedScripts = /* @__PURE__ */ new Set();
9
- ssrPreloadFailedScripts = /* @__PURE__ */ new Set();
10
- ssrPreloadEntrypointCache = /* @__PURE__ */ new Map();
11
- constructor({ resolveDependencyPath, processDependencies, preferSourceImports }) {
12
- this.resolveDependencyPath = resolveDependencyPath;
13
- this.processDependencies = processDependencies;
14
- this.preferSourceImports = preferSourceImports ?? typeof Bun !== "undefined";
15
- }
16
- getErrorCode(error) {
17
- if (typeof error !== "object" || error === null) {
18
- return "";
1
+ import { AssetFactory } from '@ecopages/core/services/asset-processing-service';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ /**
5
+ * Encapsulates SSR lazy script preload behavior for Lit components.
6
+ *
7
+ * Collects `dependencies.scripts` lazy entries with `ssr: true`, resolves the
8
+ * processed entrypoint through the asset pipeline, and imports the module so
9
+ * custom elements are registered before SSR rendering.
10
+ */
11
+ export class LitSsrLazyPreloader {
12
+ resolveDependencyPath;
13
+ processDependencies;
14
+ preferSourceImports;
15
+ ssrPreloadedScripts = new Set();
16
+ ssrPreloadFailedScripts = new Set();
17
+ ssrPreloadEntrypointCache = new Map();
18
+ constructor({ resolveDependencyPath, processDependencies, preferSourceImports }) {
19
+ this.resolveDependencyPath = resolveDependencyPath;
20
+ this.processDependencies = processDependencies;
21
+ this.preferSourceImports = preferSourceImports ?? typeof Bun !== 'undefined';
19
22
  }
20
- const code = Reflect.get(error, "code");
21
- return code === void 0 ? "" : String(code);
22
- }
23
- /**
24
- * Detects preload failures that are expected for browser-only modules.
25
- */
26
- isExpectedSsrPreloadError(error) {
27
- const errorMessage = error instanceof Error ? error.message : String(error);
28
- const errorCode = this.getErrorCode(error);
29
- if (errorCode === "ERR_UNKNOWN_FILE_EXTENSION") {
30
- return true;
23
+ getErrorCode(error) {
24
+ if (typeof error !== 'object' || error === null) {
25
+ return '';
26
+ }
27
+ const code = Reflect.get(error, 'code');
28
+ return code === undefined ? '' : String(code);
31
29
  }
32
- return errorMessage.includes(`reading 'Element'`) || errorMessage.includes("window is not defined") || errorMessage.includes("document is not defined") || errorMessage.includes("navigator is not defined");
33
- }
34
- /**
35
- * Collects lazy script file paths eligible for SSR preloading.
36
- */
37
- collectSsrPreloadScripts(components) {
38
- const scriptPaths = /* @__PURE__ */ new Set();
39
- const visitedConfigs = /* @__PURE__ */ new Set();
40
- const collect = (component) => {
41
- const config = component?.config;
42
- if (!config || visitedConfigs.has(config)) {
43
- return;
44
- }
45
- visitedConfigs.add(config);
46
- const scriptEntries = config.dependencies?.scripts ?? [];
47
- const componentFile = config.__eco?.file;
48
- if (componentFile) {
49
- const componentDir = path.dirname(componentFile);
50
- for (const script of scriptEntries) {
51
- if (typeof script === "string") {
52
- continue;
53
- }
54
- if (!script.lazy || script.ssr !== true) {
55
- continue;
56
- }
57
- if (!script.src) {
58
- continue;
59
- }
60
- scriptPaths.add(this.resolveDependencyPath(componentDir, script.src));
30
+ /**
31
+ * Detects preload failures that are expected for browser-only modules.
32
+ */
33
+ isExpectedSsrPreloadError(error) {
34
+ const errorMessage = error instanceof Error ? error.message : String(error);
35
+ const errorCode = this.getErrorCode(error);
36
+ if (errorCode === 'ERR_UNKNOWN_FILE_EXTENSION') {
37
+ return true;
61
38
  }
62
- }
63
- for (const layout of config.layouts ?? []) {
64
- collect(layout);
65
- }
66
- for (const nestedComponent of config.dependencies?.components || []) {
67
- collect(nestedComponent);
68
- }
69
- };
70
- for (const component of components) {
71
- collect(component);
39
+ return (errorMessage.includes(`reading 'Element'`) ||
40
+ errorMessage.includes('window is not defined') ||
41
+ errorMessage.includes('document is not defined') ||
42
+ errorMessage.includes('navigator is not defined'));
72
43
  }
73
- return Array.from(scriptPaths);
74
- }
75
- /**
76
- * Preloads SSR-eligible lazy scripts to register custom elements before render.
77
- */
78
- async preloadSsrLazyScripts(components) {
79
- const scripts = this.collectSsrPreloadScripts(components);
80
- if (scripts.length === 0) {
81
- return;
44
+ /**
45
+ * Collects lazy script file paths eligible for SSR preloading.
46
+ */
47
+ collectSsrPreloadScripts(components) {
48
+ const scriptPaths = new Set();
49
+ const visitedConfigs = new Set();
50
+ const collect = (component) => {
51
+ const config = component?.config;
52
+ if (!config || visitedConfigs.has(config)) {
53
+ return;
54
+ }
55
+ visitedConfigs.add(config);
56
+ const scriptEntries = config.dependencies?.scripts ?? [];
57
+ const componentFile = config.__eco?.file;
58
+ if (componentFile) {
59
+ const componentDir = path.dirname(componentFile);
60
+ for (const script of scriptEntries) {
61
+ if (typeof script === 'string') {
62
+ continue;
63
+ }
64
+ if (!script.lazy || script.ssr !== true) {
65
+ continue;
66
+ }
67
+ if (!script.src) {
68
+ continue;
69
+ }
70
+ scriptPaths.add(this.resolveDependencyPath(componentDir, script.src));
71
+ }
72
+ }
73
+ for (const layout of config.layouts ?? []) {
74
+ collect(layout);
75
+ }
76
+ for (const nestedComponent of config.dependencies?.components || []) {
77
+ collect(nestedComponent);
78
+ }
79
+ };
80
+ for (const component of components) {
81
+ collect(component);
82
+ }
83
+ return Array.from(scriptPaths);
82
84
  }
83
- await Promise.all(
84
- scripts.filter((scriptPath) => {
85
- if (this.ssrPreloadedScripts.has(scriptPath)) {
86
- return false;
85
+ /**
86
+ * Preloads SSR-eligible lazy scripts to register custom elements before render.
87
+ */
88
+ async preloadSsrLazyScripts(components) {
89
+ const scripts = this.collectSsrPreloadScripts(components);
90
+ if (scripts.length === 0) {
91
+ return;
87
92
  }
88
- if (this.ssrPreloadFailedScripts.has(scriptPath)) {
89
- return false;
93
+ await Promise.all(scripts
94
+ .filter((scriptPath) => {
95
+ if (this.ssrPreloadedScripts.has(scriptPath)) {
96
+ return false;
97
+ }
98
+ if (this.ssrPreloadFailedScripts.has(scriptPath)) {
99
+ return false;
100
+ }
101
+ return true;
102
+ })
103
+ .map(async (scriptPath) => {
104
+ const preloadEntrypoint = await this.resolveSsrPreloadEntrypoint(scriptPath);
105
+ if (!preloadEntrypoint) {
106
+ this.ssrPreloadFailedScripts.add(scriptPath);
107
+ return;
108
+ }
109
+ try {
110
+ await import(/* @vite-ignore */ pathToFileURL(preloadEntrypoint).href);
111
+ this.ssrPreloadedScripts.add(scriptPath);
112
+ }
113
+ catch (error) {
114
+ this.ssrPreloadFailedScripts.add(scriptPath);
115
+ if (this.isExpectedSsrPreloadError(error)) {
116
+ if (process.env.ECOPAGES_DEBUG === 'true') {
117
+ console.warn(`[ecopages][lit] Skipping SSR preload for browser-only lazy script: ${scriptPath}`);
118
+ }
119
+ return;
120
+ }
121
+ console.warn(`[ecopages][lit] Failed to preload lazy SSR script: ${scriptPath}`, error);
122
+ }
123
+ }));
124
+ }
125
+ /**
126
+ * Resolves the concrete JS entrypoint used for SSR preloading.
127
+ */
128
+ async resolveSsrPreloadEntrypoint(scriptPath) {
129
+ const cachedEntrypoint = this.ssrPreloadEntrypointCache.get(scriptPath);
130
+ if (cachedEntrypoint) {
131
+ return cachedEntrypoint;
90
132
  }
91
- return true;
92
- }).map(async (scriptPath) => {
93
- const preloadEntrypoint = await this.resolveSsrPreloadEntrypoint(scriptPath);
94
- if (!preloadEntrypoint) {
95
- this.ssrPreloadFailedScripts.add(scriptPath);
96
- return;
133
+ if (this.preferSourceImports) {
134
+ this.ssrPreloadEntrypointCache.set(scriptPath, scriptPath);
135
+ return scriptPath;
136
+ }
137
+ if (!this.processDependencies) {
138
+ this.ssrPreloadEntrypointCache.set(scriptPath, scriptPath);
139
+ return scriptPath;
97
140
  }
98
141
  try {
99
- await import(
100
- /* @vite-ignore */
101
- pathToFileURL(preloadEntrypoint).href
102
- );
103
- this.ssrPreloadedScripts.add(scriptPath);
104
- } catch (error) {
105
- this.ssrPreloadFailedScripts.add(scriptPath);
106
- if (this.isExpectedSsrPreloadError(error)) {
107
- if (process.env.ECOPAGES_DEBUG === "true") {
108
- console.warn(
109
- `[ecopages][lit] Skipping SSR preload for browser-only lazy script: ${scriptPath}`
110
- );
142
+ const processed = await this.processDependencies([
143
+ AssetFactory.createInlineFileScript({
144
+ filepath: scriptPath,
145
+ position: 'head',
146
+ bundle: true,
147
+ attributes: {
148
+ type: 'module',
149
+ defer: '',
150
+ },
151
+ }),
152
+ ], `lit-ssr-preload:${scriptPath}`);
153
+ const entrypoint = processed[0]?.filepath;
154
+ if (!entrypoint) {
155
+ return scriptPath;
111
156
  }
112
- return;
113
- }
114
- console.warn(`[ecopages][lit] Failed to preload lazy SSR script: ${scriptPath}`, error);
157
+ this.ssrPreloadEntrypointCache.set(scriptPath, entrypoint);
158
+ return entrypoint;
115
159
  }
116
- })
117
- );
118
- }
119
- /**
120
- * Resolves the concrete JS entrypoint used for SSR preloading.
121
- */
122
- async resolveSsrPreloadEntrypoint(scriptPath) {
123
- const cachedEntrypoint = this.ssrPreloadEntrypointCache.get(scriptPath);
124
- if (cachedEntrypoint) {
125
- return cachedEntrypoint;
126
- }
127
- if (this.preferSourceImports) {
128
- this.ssrPreloadEntrypointCache.set(scriptPath, scriptPath);
129
- return scriptPath;
130
- }
131
- if (!this.processDependencies) {
132
- this.ssrPreloadEntrypointCache.set(scriptPath, scriptPath);
133
- return scriptPath;
134
- }
135
- try {
136
- const processed = await this.processDependencies(
137
- [
138
- AssetFactory.createInlineFileScript({
139
- filepath: scriptPath,
140
- position: "head",
141
- bundle: true,
142
- attributes: {
143
- type: "module",
144
- defer: ""
160
+ catch (error) {
161
+ if (process.env.ECOPAGES_DEBUG === 'true') {
162
+ console.warn(`[ecopages][lit] Failed to resolve SSR preload entrypoint for: ${scriptPath}`, error);
145
163
  }
146
- })
147
- ],
148
- `lit-ssr-preload:${scriptPath}`
149
- );
150
- const entrypoint = processed[0]?.filepath;
151
- if (!entrypoint) {
152
- return scriptPath;
153
- }
154
- this.ssrPreloadEntrypointCache.set(scriptPath, entrypoint);
155
- return entrypoint;
156
- } catch (error) {
157
- if (process.env.ECOPAGES_DEBUG === "true") {
158
- console.warn(`[ecopages][lit] Failed to resolve SSR preload entrypoint for: ${scriptPath}`, error);
159
- }
160
- this.ssrPreloadEntrypointCache.set(scriptPath, scriptPath);
161
- return scriptPath;
164
+ this.ssrPreloadEntrypointCache.set(scriptPath, scriptPath);
165
+ return scriptPath;
166
+ }
162
167
  }
163
- }
164
168
  }
165
- export {
166
- LitSsrLazyPreloader
167
- };
@@ -0,0 +1 @@
1
+ export {};
@@ -1,105 +1,119 @@
1
- import path from "node:path";
2
- import { LitSsrLazyPreloader } from "./lit-ssr-lazy-preloader.js";
3
- import { LIT_PLUGIN_NAME } from "./lit.constants.js";
4
- import { LitStaticRenderWorkerClient } from "./lit-static-render-worker-client.js";
5
- class LitStaticRenderSession {
6
- preloader;
7
- createWorkerClient;
8
- workerClient = null;
9
- workerIdentity = null;
10
- constructor(options) {
11
- this.preloader = new LitSsrLazyPreloader({
12
- resolveDependencyPath: options.resolveDependencyPath,
13
- processDependencies: options.processDependencies,
14
- preferSourceImports: options.preferSourceImports
15
- });
16
- this.createWorkerClient = options.createWorkerClient ?? ((input) => new LitStaticRenderWorkerClient({
17
- configModulePath: input.configModulePath,
18
- runtimeOrigin: input.runtimeOrigin
19
- }));
20
- }
21
- /**
22
- * Ensures the static render worker is running for the given identity.
23
- *
24
- * @remarks
25
- * First successful start sticks that identity. Matching re-entry is a no-op.
26
- * A different `configModulePath` or `runtimeOrigin` disposes and recreates.
27
- */
28
- async ensureWorker(input) {
29
- if (this.workerClient && this.workerIdentity && this.workerIdentity.configModulePath === input.configModulePath && this.workerIdentity.runtimeOrigin === input.runtimeOrigin) {
30
- return;
1
+ import path from 'node:path';
2
+ import { LitSsrLazyPreloader } from './lit-ssr-lazy-preloader.js';
3
+ import { LIT_PLUGIN_NAME } from './lit.constants.js';
4
+ import { LitStaticRenderWorkerClient } from './lit-static-render-worker-client.js';
5
+ /**
6
+ * Plugin-runtime-scoped Lit server render session.
7
+ *
8
+ * @remarks
9
+ * Owns worker lifecycle and SSR preload for Lit page routes during static export
10
+ * and runtime/dev requests. Injected into `LitRenderer` via a lazy accessor from
11
+ * `LitPlugin`; there is no process-global coordinator.
12
+ *
13
+ * Worker init identity is sticky for the first `{ configModulePath, runtimeOrigin }`.
14
+ * Later `ensureWorker` calls with the same identity are no-ops; a different identity
15
+ * recreates the worker so stale config/origin is never silently reused.
16
+ */
17
+ export class LitStaticRenderSession {
18
+ preloader;
19
+ createWorkerClient;
20
+ workerClient = null;
21
+ workerIdentity = null;
22
+ constructor(options) {
23
+ this.preloader = new LitSsrLazyPreloader({
24
+ resolveDependencyPath: options.resolveDependencyPath,
25
+ processDependencies: options.processDependencies,
26
+ preferSourceImports: options.preferSourceImports,
27
+ });
28
+ this.createWorkerClient =
29
+ options.createWorkerClient ??
30
+ ((input) => new LitStaticRenderWorkerClient({
31
+ configModulePath: input.configModulePath,
32
+ runtimeOrigin: input.runtimeOrigin,
33
+ }));
31
34
  }
32
- if (this.workerClient) {
33
- await this.dispose();
35
+ /**
36
+ * Ensures the static render worker is running for the given identity.
37
+ *
38
+ * @remarks
39
+ * First successful start sticks that identity. Matching re-entry is a no-op.
40
+ * A different `configModulePath` or `runtimeOrigin` disposes and recreates.
41
+ */
42
+ async ensureWorker(input) {
43
+ if (this.workerClient &&
44
+ this.workerIdentity &&
45
+ this.workerIdentity.configModulePath === input.configModulePath &&
46
+ this.workerIdentity.runtimeOrigin === input.runtimeOrigin) {
47
+ return;
48
+ }
49
+ if (this.workerClient) {
50
+ await this.dispose();
51
+ }
52
+ this.workerIdentity = {
53
+ configModulePath: input.configModulePath,
54
+ runtimeOrigin: input.runtimeOrigin,
55
+ };
56
+ this.workerClient = this.createWorkerClient({
57
+ configModulePath: input.configModulePath,
58
+ runtimeOrigin: input.runtimeOrigin,
59
+ });
60
+ await this.workerClient.start();
61
+ }
62
+ async preloadStaticRoutes(context) {
63
+ await this.preloadLitRoutes(context);
64
+ }
65
+ async preloadSsrLazyScripts(components) {
66
+ await this.preloader.preloadSsrLazyScripts(components);
34
67
  }
35
- this.workerIdentity = {
36
- configModulePath: input.configModulePath,
37
- runtimeOrigin: input.runtimeOrigin
38
- };
39
- this.workerClient = this.createWorkerClient({
40
- configModulePath: input.configModulePath,
41
- runtimeOrigin: input.runtimeOrigin
42
- });
43
- await this.workerClient.start();
44
- }
45
- async preloadStaticRoutes(context) {
46
- await this.preloadLitRoutes(context);
47
- }
48
- async preloadSsrLazyScripts(components) {
49
- await this.preloader.preloadSsrLazyScripts(components);
50
- }
51
- collectSsrPreloadScripts(components) {
52
- return this.preloader.collectSsrPreloadScripts(components);
53
- }
54
- async renderPageInWorker(input) {
55
- if (!this.workerClient) {
56
- throw new Error("Lit static render worker is not active");
68
+ collectSsrPreloadScripts(components) {
69
+ return this.preloader.collectSsrPreloadScripts(components);
57
70
  }
58
- return this.workerClient.renderPage(input);
59
- }
60
- isExpectedSsrPreloadError(error) {
61
- return this.preloader.isExpectedSsrPreloadError(error);
62
- }
63
- async dispose() {
64
- await this.workerClient?.dispose();
65
- this.workerClient = null;
66
- this.workerIdentity = null;
67
- }
68
- async preloadLitRoutes(context) {
69
- if (!context.routeRendererFactory) {
70
- return;
71
+ async renderPageInWorker(input) {
72
+ if (!this.workerClient) {
73
+ throw new Error('Lit static render worker is not active');
74
+ }
75
+ return this.workerClient.renderPage(input);
76
+ }
77
+ isExpectedSsrPreloadError(error) {
78
+ return this.preloader.isExpectedSsrPreloadError(error);
71
79
  }
72
- const routes = await context.router.listStaticGenerationRoutes({ runtimeOrigin: context.baseUrl });
73
- const components = [];
74
- for (const route of routes) {
75
- const filePath = route.templateRoute.filePath;
76
- if (!this.isLitRoute(filePath, context.appConfig)) {
77
- continue;
78
- }
79
- const pageRenderer = context.routeRendererFactory.getPageRenderer(filePath);
80
- const pageModule = await pageRenderer.loadPageModule(filePath);
81
- const page = pageModule.default;
82
- if (page) {
83
- components.push(page);
84
- for (const layout of page.config?.layouts ?? []) {
85
- components.push(layout);
80
+ async dispose() {
81
+ await this.workerClient?.dispose();
82
+ this.workerClient = null;
83
+ this.workerIdentity = null;
84
+ }
85
+ async preloadLitRoutes(context) {
86
+ if (!context.routeRendererFactory) {
87
+ return;
86
88
  }
87
- for (const nestedComponent of page.config?.dependencies?.components ?? []) {
88
- components.push(nestedComponent);
89
+ const routes = await context.router.listStaticGenerationRoutes({ runtimeOrigin: context.baseUrl });
90
+ const components = [];
91
+ for (const route of routes) {
92
+ const filePath = route.templateRoute.filePath;
93
+ if (!this.isLitRoute(filePath, context.appConfig)) {
94
+ continue;
95
+ }
96
+ const pageRenderer = context.routeRendererFactory.getPageRenderer(filePath);
97
+ const pageModule = await pageRenderer.loadPageModule(filePath);
98
+ const page = pageModule.default;
99
+ if (page) {
100
+ components.push(page);
101
+ for (const layout of page.config?.layouts ?? []) {
102
+ components.push(layout);
103
+ }
104
+ for (const nestedComponent of page.config?.dependencies?.components ?? []) {
105
+ components.push(nestedComponent);
106
+ }
107
+ }
89
108
  }
90
- }
109
+ await this.preloadSsrLazyScripts(components);
91
110
  }
92
- await this.preloadSsrLazyScripts(components);
93
- }
94
- isLitRoute(filePath, appConfig) {
95
- const litIntegration = appConfig.integrations.find((plugin) => plugin.name === LIT_PLUGIN_NAME);
96
- if (!litIntegration) {
97
- return false;
111
+ isLitRoute(filePath, appConfig) {
112
+ const litIntegration = appConfig.integrations.find((plugin) => plugin.name === LIT_PLUGIN_NAME);
113
+ if (!litIntegration) {
114
+ return false;
115
+ }
116
+ const normalizedPath = path.normalize(filePath);
117
+ return litIntegration.extensions.some((extension) => normalizedPath.endsWith(extension));
98
118
  }
99
- const normalizedPath = path.normalize(filePath);
100
- return litIntegration.extensions.some((extension) => normalizedPath.endsWith(extension));
101
- }
102
119
  }
103
- export {
104
- LitStaticRenderSession
105
- };