@lwrjs/view-registry 0.9.0-alpha.2 → 0.9.0-alpha.21

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.
@@ -278,8 +278,11 @@ var LwrViewRegistry = class {
278
278
  importer: importer || renderedView.compiledView.filePath
279
279
  };
280
280
  const stringBuilder = (0, import_shared_utils.createStringBuilder)(renderedViewContent);
281
+ let pageTtl;
281
282
  for (const viewTransformer of this.viewTransformers) {
282
- await viewTransformer.link?.(stringBuilder, mergedViewContext, linkedMetadata);
283
+ const linkResults = await viewTransformer.link?.(stringBuilder, mergedViewContext, linkedMetadata);
284
+ const ttl = linkResults && linkResults.cache?.ttl;
285
+ pageTtl = (0, import_shared_utils.shortestTtl)(ttl || void 0, pageTtl);
283
286
  }
284
287
  const linkedAssetContent = stringBuilder.toString();
285
288
  if (linkedAssetContent.includes(lwrResourcesId)) {
@@ -298,7 +301,8 @@ var LwrViewRegistry = class {
298
301
  viewRecord: {
299
302
  assetReferences: (0, import_utils.reduceSourceAssetReferences)(linkedMetadata.assetReferences),
300
303
  ...viewRecord
301
- }
304
+ },
305
+ cache: {ttl: pageTtl}
302
306
  };
303
307
  }
304
308
  return {
@@ -306,7 +310,8 @@ var LwrViewRegistry = class {
306
310
  immutable,
307
311
  viewRecord: {
308
312
  assetReferences: (0, import_utils.reduceSourceAssetReferences)(linkedMetadata.assetReferences)
309
- }
313
+ },
314
+ cache: {ttl: pageTtl}
310
315
  };
311
316
  }
312
317
  };
@@ -65,9 +65,6 @@ async function getHtmlResources(view, viewParams, resourceContext) {
65
65
  if (!def) {
66
66
  throw Error("Failed to find definition of resource: " + shimBundle);
67
67
  }
68
- if (def.stream) {
69
- def.stream.destroy();
70
- }
71
68
  requiredResources.push(def);
72
69
  const errorShimDef = await resourceRegistry.getResource({specifier: "lwr-error-shim.js", version}, runtimeEnvironment, runtimeParams);
73
70
  if (!errorShimDef) {
@@ -42,6 +42,7 @@ async function getHtmlResources(view, viewParams, resourceContext) {
42
42
  const {id: appName, bootstrap: {services} = {services: []}} = view;
43
43
  const {lwrVersion, format, hmrEnabled, bundle, debug, minify} = runtimeEnvironment;
44
44
  const {customElements} = viewMetadata;
45
+ const defRegistry = bundle ? moduleBundler : moduleRegistry;
45
46
  const version = lwrVersion;
46
47
  const isAMD = format === "amd";
47
48
  const appIdentity = {
@@ -65,9 +66,6 @@ async function getHtmlResources(view, viewParams, resourceContext) {
65
66
  if (!def) {
66
67
  throw Error("Failed to find definition of resource: " + shimBundle);
67
68
  }
68
- if (def.stream) {
69
- def.stream.destroy();
70
- }
71
69
  requiredResources.push(def);
72
70
  const errorShimDef = await resourceRegistry.getResource({specifier: "lwr-error-shim.js", version}, runtimeEnvironment, runtimeParams);
73
71
  if (!errorShimDef) {
@@ -84,7 +82,7 @@ async function getHtmlResources(view, viewParams, resourceContext) {
84
82
  }
85
83
  }
86
84
  const depth = isAMD ? {static: import_shared_utils.GraphDepth.ALL, dynamic: 1} : {static: import_shared_utils.GraphDepth.NONE, dynamic: 1};
87
- const bootstrapModuleGraph = await (0, import_shared_utils.getModuleGraphs)(bootstrapSpecifier, {includeUris: true, includeLinkedDefinitions: true, depth}, moduleRegistry, bundle ? moduleBundler : moduleRegistry, runtimeEnvironment, runtimeParams, visitedCache);
85
+ const bootstrapModuleGraph = await (0, import_shared_utils.getModuleGraphs)(bootstrapSpecifier, {includeUris: true, includeLinkedDefinitions: true, depth}, moduleRegistry, defRegistry, runtimeEnvironment, runtimeParams, visitedCache);
88
86
  const versionedSpecifier = bootstrapModuleGraph.graphs[0].specifier;
89
87
  const uri = bootstrapModuleGraph.uriMap[versionedSpecifier];
90
88
  moduleResources.push((0, import_utils.getModuleResourceByUri)(uri, runtimeEnvironment, {isPreload: false, isSSR}));
@@ -111,8 +109,8 @@ async function getHtmlResources(view, viewParams, resourceContext) {
111
109
  let importMetadata = await (0, import_shared_utils.toImportMetadata)(bootstrapModuleGraph, {imports: {}, index: {}}, moduleRegistry, runtimeEnvironment, runtimeParams);
112
110
  const customElementsRecords = [];
113
111
  const flattenedElements = (0, import_utils2.flattenCustomElements)(customElements, isSSR);
114
- await Promise.all(flattenedElements.map(async ({tagName: element, props}) => {
115
- const graph = await (0, import_shared_utils.getModuleGraphs)((0, import_shared_utils.kebabCaseToModuleSpecifer)(element), {includeUris: true, includeLinkedDefinitions: true, depth}, moduleRegistry, bundle ? moduleBundler : moduleRegistry, runtimeEnvironment, runtimeParams ? runtimeParams : {}, visitedCache);
112
+ for (const {tagName: element} of flattenedElements) {
113
+ const graph = await (0, import_shared_utils.getModuleGraphs)((0, import_shared_utils.kebabCaseToModuleSpecifer)(element), {includeUris: true, includeLinkedDefinitions: true, depth}, moduleRegistry, defRegistry, runtimeEnvironment, runtimeParams ? runtimeParams : {}, visitedCache);
116
114
  customElementsRecords.push({elementName: element, flatGraph: graph});
117
115
  const specifier = graph.graphs[0].specifier;
118
116
  const uri2 = graph.uriMap[specifier];
@@ -131,7 +129,7 @@ async function getHtmlResources(view, viewParams, resourceContext) {
131
129
  }
132
130
  }
133
131
  importMetadata = await (0, import_shared_utils.toImportMetadata)(graph, importMetadata, moduleRegistry, runtimeEnvironment, runtimeParams);
134
- }));
132
+ }
135
133
  configResources.unshift(await (0, import_utils2.getViewBootstrapConfigurationResource)({
136
134
  id: view.id,
137
135
  url: viewParams?.page?.url,
@@ -29,19 +29,15 @@ __export(exports, {
29
29
  generatePageContext: () => generatePageContext,
30
30
  getModuleResource: () => getModuleResource,
31
31
  getModuleResourceByUri: () => getModuleResourceByUri,
32
- getRouteHandler: () => getRouteHandler,
33
32
  isViewResponse: () => isViewResponse,
34
33
  normalizeRenderOptions: () => normalizeRenderOptions,
35
34
  normalizeRenderedResult: () => normalizeRenderedResult,
36
35
  reduceSourceAssetReferences: () => reduceSourceAssetReferences,
37
36
  toJsonFormat: () => toJsonFormat
38
37
  });
39
- var import_shared_utils = __toModule(require("@lwrjs/shared-utils"));
40
38
  var import_path = __toModule(require("path"));
41
- var import_path2 = __toModule(require("path"));
42
- var import_shared_utils2 = __toModule(require("@lwrjs/shared-utils"));
39
+ var import_shared_utils = __toModule(require("@lwrjs/shared-utils"));
43
40
  var import_identity = __toModule(require("@lwrjs/app-service/identity"));
44
- var import_shared_utils3 = __toModule(require("@lwrjs/shared-utils"));
45
41
  function streamToString(stream) {
46
42
  const chunks = [];
47
43
  return new Promise((resolve, reject) => {
@@ -85,7 +81,7 @@ async function generateInlineTag({specifier, type, content, stream, nonce}) {
85
81
  if (!content && !stream) {
86
82
  throw new Error(`Invalid inline Resource Definition: must have either "content" or "stream": "${specifier}"`);
87
83
  }
88
- const code = content ? content : await streamToString(stream);
84
+ const code = stream ? await streamToString(stream()) : content;
89
85
  return `<${tag}${typeStr}${nonceStr}>${code}</${tag}>`;
90
86
  }
91
87
  async function generateHtmlTag(definition) {
@@ -132,7 +128,7 @@ function normalizeRenderOptions(runtimeEnvironment, overrideRenderOptions, baseR
132
128
  };
133
129
  }
134
130
  function getTitleFromFilePath(filePath) {
135
- return filePath ? (0, import_path2.basename)(filePath, (0, import_path2.extname)(filePath)) : import_shared_utils.DEFAULT_TITLE;
131
+ return filePath ? (0, import_path.basename)(filePath, (0, import_path.extname)(filePath)) : import_shared_utils.DEFAULT_TITLE;
136
132
  }
137
133
  function generatePageContext({requestPath: url}, {id, contentTemplate, properties}) {
138
134
  const title = properties?.title || getTitleFromFilePath(contentTemplate);
@@ -141,19 +137,6 @@ function generatePageContext({requestPath: url}, {id, contentTemplate, propertie
141
137
  function isViewResponse(response) {
142
138
  return response.body !== void 0;
143
139
  }
144
- async function getRouteHandler(path, {cacheDir, rootDir}) {
145
- try {
146
- const fullPath = (0, import_shared_utils.resolveFileExtension)(path);
147
- if (fullPath.endsWith(".ts")) {
148
- path = await (0, import_shared_utils.transpileTs)(path, {rootDir, cacheDir: import_path.default.join(cacheDir, "routeHandlers")});
149
- }
150
- const moduleEntry = await Promise.resolve().then(() => __toModule(require(path)));
151
- return moduleEntry.default || moduleEntry;
152
- } catch (err) {
153
- console.log(err);
154
- throw new Error(`Unable to get routeHandler: ${path}`);
155
- }
156
- }
157
140
  async function toJsonFormat(viewRequest, viewDefinition, route, runtimeEnvironment, runtimeParams, moduleRegistry) {
158
141
  const {viewRecord} = viewDefinition;
159
142
  const {bootstrap, id: appName} = route;
@@ -186,7 +169,7 @@ async function toJsonFormat(viewRequest, viewDefinition, route, runtimeEnvironme
186
169
  });
187
170
  resources.push({
188
171
  type: "application/javascript",
189
- src: (0, import_shared_utils3.getClientBootstrapConfigurationUri)({url: viewRequest.url, id: route.id}, runtimeEnvironment, runtimeParams)
172
+ src: (0, import_shared_utils.getClientBootstrapConfigurationUri)({url: viewRequest.url, id: route.id}, runtimeEnvironment, runtimeParams)
190
173
  });
191
174
  }
192
175
  const mappingUrl = (0, import_shared_utils.getMappingUriPrefix)(runtimeEnvironment, runtimeParams);
@@ -206,7 +189,7 @@ async function toJsonFormat(viewRequest, viewDefinition, route, runtimeEnvironme
206
189
  });
207
190
  viewRecord.assetReferences?.forEach((asset) => {
208
191
  if (asset.override?.uri) {
209
- const type = (0, import_shared_utils2.mimeLookup)(asset.override?.uri);
192
+ const type = (0, import_shared_utils.mimeLookup)(asset.override?.uri);
210
193
  resources.push({type, src: asset.override?.uri});
211
194
  }
212
195
  });
@@ -229,10 +212,10 @@ async function toJsonFormat(viewRequest, viewDefinition, route, runtimeEnvironme
229
212
  }
230
213
  };
231
214
  }
232
- async function getModuleResource(moduleId, runtimeEnvironment, moduleResouceMeta, moduleRegistry, runtimeParams) {
215
+ async function getModuleResource(moduleId, runtimeEnvironment, moduleResouceMeta, defRegistry, runtimeParams) {
233
216
  const {format} = runtimeEnvironment;
234
217
  const {isSSR = false, isPreload = false} = moduleResouceMeta;
235
- const moduleUri = await moduleRegistry.resolveModuleUri(moduleId, runtimeEnvironment, runtimeParams);
218
+ const moduleUri = await defRegistry.resolveModuleUri(moduleId, runtimeEnvironment, runtimeParams);
236
219
  return {
237
220
  src: moduleUri,
238
221
  type: format === "amd" ? "application/javascript" : "module",
@@ -31,15 +31,13 @@ var import_utils = __toModule(require("./utils.cjs"));
31
31
  var import_path = __toModule(require("path"));
32
32
  var LwrViewHandler = class {
33
33
  constructor(context, globalConfig) {
34
- this.inflightRouteHandlerEvalMap = new Map();
35
- this.routeHandlerFunctionMap = new Map();
36
- this.viewRegistry = context.viewRegistry;
37
34
  this.globalConfig = globalConfig;
35
+ this.routeHandlers = context.routeHandlers;
36
+ this.viewRegistry = context.viewRegistry;
38
37
  this.moduleRegistry = context.moduleRegistry;
39
38
  }
40
39
  async getViewContent(viewRequest, route, runtimeEnvironment, runtimeParams = {}) {
41
- const {routeHandler} = route;
42
- if (routeHandler) {
40
+ if (route.routeHandler) {
43
41
  const response = await this.getRouteHandlerResponse(viewRequest, route, runtimeEnvironment, runtimeParams);
44
42
  if ((0, import_utils.isViewResponse)(response)) {
45
43
  return response;
@@ -55,7 +53,8 @@ var LwrViewHandler = class {
55
53
  body: viewDefinition2.renderedView,
56
54
  metadata: {
57
55
  viewDefinition: viewDefinition2
58
- }
56
+ },
57
+ cache: {ttl: (0, import_shared_utils.shortestTtl)(response.cache?.ttl, viewDefinition2.cache?.ttl)}
59
58
  };
60
59
  }
61
60
  const viewDefinition = await this.getDefaultRouteViewDefinition(viewRequest, route, runtimeEnvironment, runtimeParams);
@@ -63,12 +62,12 @@ var LwrViewHandler = class {
63
62
  body: viewDefinition.renderedView,
64
63
  metadata: {
65
64
  viewDefinition
66
- }
65
+ },
66
+ cache: viewDefinition.cache
67
67
  };
68
68
  }
69
69
  async getViewJson(viewRequest, route, runtimeEnvironment, runtimeParams = {}) {
70
- const {routeHandler} = route;
71
- if (routeHandler) {
70
+ if (route.routeHandler) {
72
71
  const response = await this.getRouteHandlerResponse(viewRequest, route, runtimeEnvironment, runtimeParams);
73
72
  if ((0, import_utils.isViewResponse)(response)) {
74
73
  return response;
@@ -84,9 +83,8 @@ var LwrViewHandler = class {
84
83
  return await (0, import_utils.toJsonFormat)(viewRequest, viewDefinition, route, runtimeEnvironment, runtimeParams, this.moduleRegistry);
85
84
  }
86
85
  async getViewConfiguration(viewRequest, route, runtimeEnvironment, runtimeParams = {}) {
87
- const {routeHandler} = route;
88
86
  let viewDefinition;
89
- if (routeHandler) {
87
+ if (route.routeHandler) {
90
88
  const response = await this.getRouteHandlerResponse(viewRequest, route, runtimeEnvironment, runtimeParams);
91
89
  if ((0, import_utils.isViewResponse)(response)) {
92
90
  return;
@@ -126,28 +124,18 @@ var LwrViewHandler = class {
126
124
  return viewDefinition;
127
125
  }
128
126
  async getRouteHandlerResponse(viewRequest, route, runtimeEnvironment, runtimeParams = {}) {
129
- const {rootDir, assets, contentDir, layoutsDir, cacheDir} = this.globalConfig;
130
- const paths = {rootDir, assets, contentDir, layoutsDir};
131
- const {routeHandler} = route;
132
- if (!routeHandler) {
133
- throw new Error("Route Handler is required for a CustomView");
127
+ if (!route.routeHandler) {
128
+ throw new Error("Route handler is required for a CustomView");
134
129
  }
135
- let routeHandlerFunction = this.routeHandlerFunctionMap.get(routeHandler);
136
- if (!routeHandlerFunction) {
137
- const inflightRouteHandlerPromise = this.inflightRouteHandlerEvalMap.get(routeHandler);
138
- if (inflightRouteHandlerPromise) {
139
- routeHandlerFunction = await inflightRouteHandlerPromise;
140
- } else {
141
- const handlerPromise = (0, import_utils.getRouteHandler)(routeHandler, {cacheDir, rootDir});
142
- this.inflightRouteHandlerEvalMap.set(routeHandler, handlerPromise);
143
- routeHandlerFunction = await handlerPromise;
144
- }
145
- this.routeHandlerFunctionMap.set(routeHandler, routeHandlerFunction);
146
- this.inflightRouteHandlerEvalMap.delete(routeHandler);
130
+ const routeHandler = this.routeHandlers[route.routeHandler];
131
+ if (!routeHandler) {
132
+ throw new Error(`Route handler does not exist for id: ${route.routeHandler}`);
147
133
  }
134
+ const {rootDir, assets, contentDir, layoutsDir} = this.globalConfig;
135
+ const paths = {rootDir, assets, contentDir, layoutsDir};
148
136
  const locale = runtimeParams.locale;
149
137
  const viewApi = this.getBoundApi(route, runtimeEnvironment, runtimeParams);
150
- const response = await routeHandlerFunction({...viewRequest, locale}, {route, viewApi, ...paths});
138
+ const response = await routeHandler({...viewRequest, locale}, {route, viewApi, ...paths});
151
139
  return response;
152
140
  }
153
141
  getBoundApi(route, runtimeEnvironment, runtimeParams) {
@@ -169,7 +157,8 @@ var LwrViewHandler = class {
169
157
  body: viewDefinition.renderedView,
170
158
  metadata: {
171
159
  viewDefinition
172
- }
160
+ },
161
+ cache: viewDefinition.cache
173
162
  };
174
163
  }
175
164
  };
package/build/es/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { extractMetadataFromHtml, getCacheKeyFromJson, getSpecifier, normalizeResourcePath, createStringBuilder, InflightTasks, } from '@lwrjs/shared-utils';
1
+ import { extractMetadataFromHtml, getCacheKeyFromJson, getSpecifier, normalizeResourcePath, createStringBuilder, shortestTtl, InflightTasks, } from '@lwrjs/shared-utils';
2
2
  import { normalizeRenderOptions, normalizeRenderedResult, reduceSourceAssetReferences } from './utils.js';
3
3
  import { linkLwrResources } from './linkers/link-lwr-resources.js';
4
4
  export { LwrViewHandler } from './view-handler.js';
@@ -295,9 +295,13 @@ export class LwrViewRegistry {
295
295
  importer: importer || renderedView.compiledView.filePath,
296
296
  };
297
297
  const stringBuilder = createStringBuilder(renderedViewContent);
298
+ let pageTtl;
298
299
  for (const viewTransformer of this.viewTransformers) {
299
300
  // eslint-disable-next-line no-await-in-loop
300
- await viewTransformer.link?.(stringBuilder, mergedViewContext, linkedMetadata);
301
+ const linkResults = await viewTransformer.link?.(stringBuilder, mergedViewContext, linkedMetadata);
302
+ // Keep track of the shortest TTL from each view transformer (e.g. lwcSsrViewTranformer)
303
+ const ttl = linkResults && linkResults.cache?.ttl;
304
+ pageTtl = shortestTtl(ttl || undefined, pageTtl);
301
305
  }
302
306
  const linkedAssetContent = stringBuilder.toString();
303
307
  // Link LWR related resources
@@ -321,6 +325,7 @@ export class LwrViewRegistry {
321
325
  assetReferences: reduceSourceAssetReferences(linkedMetadata.assetReferences),
322
326
  ...viewRecord,
323
327
  },
328
+ cache: { ttl: pageTtl },
324
329
  };
325
330
  }
326
331
  return {
@@ -329,6 +334,7 @@ export class LwrViewRegistry {
329
334
  viewRecord: {
330
335
  assetReferences: reduceSourceAssetReferences(linkedMetadata.assetReferences),
331
336
  },
337
+ cache: { ttl: pageTtl },
332
338
  };
333
339
  }
334
340
  }
@@ -53,10 +53,6 @@ export async function getHtmlResources(view, viewParams, resourceContext) {
53
53
  if (!def) {
54
54
  throw Error('Failed to find definition of resource: ' + shimBundle);
55
55
  }
56
- // HACK: preemptively closing the stream because it is never read
57
- if (def.stream) {
58
- def.stream.destroy();
59
- }
60
56
  requiredResources.push(def);
61
57
  // Always inline the error shim script after the shim
62
58
  const errorShimDef = (await resourceRegistry.getResource({ specifier: 'lwr-error-shim.js', version }, runtimeEnvironment, runtimeParams));
@@ -7,6 +7,7 @@ export async function getHtmlResources(view, viewParams, resourceContext) {
7
7
  const { id: appName, bootstrap: { services } = { services: [] } } = view;
8
8
  const { lwrVersion, format, hmrEnabled, bundle, debug, minify } = runtimeEnvironment;
9
9
  const { customElements } = viewMetadata;
10
+ const defRegistry = bundle ? moduleBundler : moduleRegistry;
10
11
  const version = lwrVersion;
11
12
  const isAMD = format === 'amd';
12
13
  // Application Bootstrap (ABS) module resource: "@lwrjs/app-service/{appName}/module/{format}"
@@ -53,10 +54,6 @@ export async function getHtmlResources(view, viewParams, resourceContext) {
53
54
  if (!def) {
54
55
  throw Error('Failed to find definition of resource: ' + shimBundle);
55
56
  }
56
- // HACK: preemptively closing the stream because it is never read
57
- if (def.stream) {
58
- def.stream.destroy();
59
- }
60
57
  requiredResources.push(def);
61
58
  // Always inline the error shim script after the shim
62
59
  const errorShimDef = (await resourceRegistry.getResource({ specifier: 'lwr-error-shim.js', version }, runtimeEnvironment, runtimeParams));
@@ -81,7 +78,7 @@ export async function getHtmlResources(view, viewParams, resourceContext) {
81
78
  const depth = isAMD
82
79
  ? { static: GraphDepth.ALL, dynamic: 1 }
83
80
  : { static: GraphDepth.NONE, dynamic: 1 };
84
- const bootstrapModuleGraph = await getModuleGraphs(bootstrapSpecifier, { includeUris: true, includeLinkedDefinitions: true, depth }, moduleRegistry, bundle ? moduleBundler : moduleRegistry, runtimeEnvironment, runtimeParams, visitedCache);
81
+ const bootstrapModuleGraph = await getModuleGraphs(bootstrapSpecifier, { includeUris: true, includeLinkedDefinitions: true, depth }, moduleRegistry, defRegistry, runtimeEnvironment, runtimeParams, visitedCache);
85
82
  // ADD bootstrap module uri as a script resource
86
83
  const versionedSpecifier = bootstrapModuleGraph.graphs[0].specifier;
87
84
  const uri = bootstrapModuleGraph.uriMap[versionedSpecifier];
@@ -118,8 +115,9 @@ export async function getHtmlResources(view, viewParams, resourceContext) {
118
115
  // ------- View related custom element moduleResources
119
116
  const customElementsRecords = [];
120
117
  const flattenedElements = flattenCustomElements(customElements, isSSR);
121
- await Promise.all(flattenedElements.map(async ({ tagName: element, props }) => {
122
- const graph = await getModuleGraphs(kebabCaseToModuleSpecifer(element), { includeUris: true, includeLinkedDefinitions: true, depth }, moduleRegistry, bundle ? moduleBundler : moduleRegistry, runtimeEnvironment, runtimeParams ? runtimeParams : {}, visitedCache);
118
+ for (const { tagName: element } of flattenedElements) {
119
+ // eslint-disable-next-line no-await-in-loop
120
+ const graph = await getModuleGraphs(kebabCaseToModuleSpecifer(element), { includeUris: true, includeLinkedDefinitions: true, depth }, moduleRegistry, defRegistry, runtimeEnvironment, runtimeParams ? runtimeParams : {}, visitedCache);
123
121
  // add to the viewRecord
124
122
  customElementsRecords.push({ elementName: element, flatGraph: graph });
125
123
  // PRELOAD custom element static deps as link resource
@@ -142,8 +140,9 @@ export async function getHtmlResources(view, viewParams, resourceContext) {
142
140
  imports[dynamicDep] = uri;
143
141
  }
144
142
  }
143
+ // eslint-disable-next-line no-await-in-loop
145
144
  importMetadata = await toImportMetadata(graph, importMetadata, moduleRegistry, runtimeEnvironment, runtimeParams);
146
- }));
145
+ }
147
146
  // ADD configuration of the bootstrapModule
148
147
  configResources.unshift(await getViewBootstrapConfigurationResource({
149
148
  id: view.id,
@@ -1,5 +1,4 @@
1
- import { NormalizedRenderingResult, RenderingResult, ResourceDefinition, AssetReference, RenderedAssetReference, RenderOptions, ModuleId, ViewModuleResourceContext, ViewPageContext, JsonCompatible } from '@lwrjs/types';
2
- import { PublicModuleRegistry, RuntimeEnvironment, RuntimeParams, ModuleJson, RouteHandlerViewResponse, ViewResponse, RouteHandlerFunction, LwrRoute, LwrErrorRoute, ViewRequest, LinkedViewDefinition, ModuleRegistry } from 'packages/@lwrjs/types/src';
1
+ import type { AssetReference, JsonCompatible, LinkedViewDefinition, LwrErrorRoute, LwrRoute, ModuleBundler, ModuleId, ModuleJson, ModuleRegistry, NormalizedRenderingResult, PublicModuleRegistry, RenderOptions, RenderedAssetReference, RenderingResult, ResourceDefinition, RouteHandlerViewResponse, RuntimeEnvironment, RuntimeParams, ViewModuleResourceContext, ViewPageContext, ViewRequest, ViewResponse } from '@lwrjs/types';
3
2
  export declare type HTMLResource = Partial<ResourceDefinition>;
4
3
  export declare function generateHtmlTag(definition: HTMLResource): Promise<string>;
5
4
  export declare function normalizeRenderedResult({ renderedView, metadata, options, }: RenderingResult): NormalizedRenderingResult;
@@ -7,19 +6,8 @@ export declare function reduceSourceAssetReferences(assets: AssetReference[]): R
7
6
  export declare function normalizeRenderOptions(runtimeEnvironment: RuntimeEnvironment, overrideRenderOptions?: RenderOptions, baseRenderOptions?: RenderOptions): Required<RenderOptions>;
8
7
  export declare function generatePageContext({ requestPath: url }: ViewRequest, { id, contentTemplate, properties }: LwrRoute | LwrErrorRoute): JsonCompatible<ViewPageContext>;
9
8
  export declare function isViewResponse(response: RouteHandlerViewResponse): response is ViewResponse;
10
- interface RouteHandlerContext {
11
- cacheDir: string;
12
- rootDir: string;
13
- }
14
- /**
15
- * Load and cache a route handler function (for a view) from the fs
16
- * @param path - path to the route handle code on the fs
17
- * @param param1 - directories
18
- */
19
- export declare function getRouteHandler(path: string, { cacheDir, rootDir }: RouteHandlerContext): Promise<RouteHandlerFunction>;
20
9
  export declare function toJsonFormat(viewRequest: ViewRequest, viewDefinition: LinkedViewDefinition, route: LwrRoute | LwrErrorRoute, runtimeEnvironment: RuntimeEnvironment, runtimeParams: RuntimeParams, moduleRegistry: ModuleRegistry): Promise<ViewResponse>;
21
- export declare function getModuleResource(moduleId: Pick<ModuleId, 'specifier' | 'version'>, runtimeEnvironment: RuntimeEnvironment, moduleResouceMeta: ViewModuleResourceContext, moduleRegistry: ModuleRegistry, runtimeParams?: RuntimeParams): Promise<ResourceDefinition>;
10
+ export declare function getModuleResource(moduleId: Pick<ModuleId, 'specifier' | 'version'>, runtimeEnvironment: RuntimeEnvironment, moduleResouceMeta: ViewModuleResourceContext, defRegistry: ModuleRegistry | ModuleBundler, runtimeParams?: RuntimeParams): Promise<ResourceDefinition>;
22
11
  export declare function getModuleResourceByUri(uri: string, runtimeEnvironment: RuntimeEnvironment, moduleResouceMeta: ViewModuleResourceContext): ResourceDefinition;
23
12
  export declare function createJsonModule(specifier: string, moduleRegistry: PublicModuleRegistry, environment: RuntimeEnvironment, params?: RuntimeParams): Promise<ModuleJson>;
24
- export {};
25
13
  //# sourceMappingURL=utils.d.ts.map
package/build/es/utils.js CHANGED
@@ -1,9 +1,6 @@
1
- import { explodeSpecifier, getMappingUriPrefix, getSpecifier, resolveFileExtension, transpileTs, DEFAULT_TITLE, } from '@lwrjs/shared-utils';
2
- import libPath from 'path';
3
1
  import { basename, extname } from 'path';
4
- import { mimeLookup } from '@lwrjs/shared-utils';
2
+ import { explodeSpecifier, getMappingUriPrefix, getSpecifier, getClientBootstrapConfigurationUri, mimeLookup, DEFAULT_TITLE, } from '@lwrjs/shared-utils';
5
3
  import { AppResourceEnum, getAppSpecifier, ResourceIdentityTypes, } from '@lwrjs/app-service/identity';
6
- import { getClientBootstrapConfigurationUri } from '@lwrjs/shared-utils';
7
4
  function streamToString(stream) {
8
5
  const chunks = [];
9
6
  return new Promise((resolve, reject) => {
@@ -51,7 +48,7 @@ async function generateInlineTag({ specifier, type, content, stream, nonce }) {
51
48
  if (!content && !stream) {
52
49
  throw new Error(`Invalid inline Resource Definition: must have either "content" or "stream": "${specifier}"`);
53
50
  }
54
- const code = content ? content : await streamToString(stream);
51
+ const code = stream ? await streamToString(stream()) : content;
55
52
  return `<${tag}${typeStr}${nonceStr}>${code}</${tag}>`;
56
53
  }
57
54
  export async function generateHtmlTag(definition) {
@@ -110,25 +107,6 @@ export function generatePageContext({ requestPath: url }, { id, contentTemplate,
110
107
  export function isViewResponse(response) {
111
108
  return response.body !== undefined;
112
109
  }
113
- /**
114
- * Load and cache a route handler function (for a view) from the fs
115
- * @param path - path to the route handle code on the fs
116
- * @param param1 - directories
117
- */
118
- export async function getRouteHandler(path, { cacheDir, rootDir }) {
119
- try {
120
- const fullPath = resolveFileExtension(path);
121
- if (fullPath.endsWith('.ts')) {
122
- path = await transpileTs(path, { rootDir, cacheDir: libPath.join(cacheDir, 'routeHandlers') });
123
- }
124
- const moduleEntry = await import(path);
125
- return moduleEntry.default || moduleEntry;
126
- }
127
- catch (err) {
128
- console.log(err);
129
- throw new Error(`Unable to get routeHandler: ${path}`);
130
- }
131
- }
132
110
  export async function toJsonFormat(viewRequest, viewDefinition, route, runtimeEnvironment, runtimeParams, moduleRegistry) {
133
111
  const { viewRecord } = viewDefinition;
134
112
  const { bootstrap, id: appName } = route;
@@ -213,10 +191,10 @@ export async function toJsonFormat(viewRequest, viewDefinition, route, runtimeEn
213
191
  },
214
192
  };
215
193
  }
216
- export async function getModuleResource(moduleId, runtimeEnvironment, moduleResouceMeta, moduleRegistry, runtimeParams) {
194
+ export async function getModuleResource(moduleId, runtimeEnvironment, moduleResouceMeta, defRegistry, runtimeParams) {
217
195
  const { format } = runtimeEnvironment;
218
196
  const { isSSR = false, isPreload = false } = moduleResouceMeta;
219
- const moduleUri = await moduleRegistry.resolveModuleUri(moduleId, runtimeEnvironment, runtimeParams);
197
+ const moduleUri = await defRegistry.resolveModuleUri(moduleId, runtimeEnvironment, runtimeParams);
220
198
  return {
221
199
  src: moduleUri,
222
200
  type: format === 'amd' ? 'application/javascript' : 'module',
@@ -1,14 +1,14 @@
1
- import { ViewRegistry, RuntimeEnvironment, NormalizedLwrGlobalConfig, ViewRequest, RuntimeParams, ViewResponse, LwrErrorRoute, LwrRoute, ModuleRegistry, RouteHandlerFunction } from '@lwrjs/types';
1
+ import { ViewRegistry, RuntimeEnvironment, NormalizedLwrGlobalConfig, ViewRequest, RuntimeParams, ViewResponse, LwrRoute, LwrErrorRoute, ModuleRegistry, ViewHandler, RouteHandlers } from '@lwrjs/types';
2
2
  export interface ViewHandlerContext {
3
3
  viewRegistry: ViewRegistry;
4
4
  moduleRegistry: ModuleRegistry;
5
+ routeHandlers: RouteHandlers;
5
6
  }
6
- export declare class LwrViewHandler {
7
+ export declare class LwrViewHandler implements ViewHandler {
8
+ globalConfig: NormalizedLwrGlobalConfig;
9
+ routeHandlers: RouteHandlers;
7
10
  viewRegistry: ViewRegistry;
8
11
  moduleRegistry: ModuleRegistry;
9
- globalConfig: NormalizedLwrGlobalConfig;
10
- inflightRouteHandlerEvalMap: Map<string, Promise<RouteHandlerFunction>>;
11
- routeHandlerFunctionMap: Map<string, RouteHandlerFunction>;
12
12
  constructor(context: ViewHandlerContext, globalConfig: NormalizedLwrGlobalConfig);
13
13
  getViewContent(viewRequest: ViewRequest, route: LwrRoute | LwrErrorRoute, runtimeEnvironment: RuntimeEnvironment, runtimeParams?: RuntimeParams): Promise<ViewResponse>;
14
14
  getViewJson(viewRequest: ViewRequest, route: LwrRoute | LwrErrorRoute, runtimeEnvironment: RuntimeEnvironment, runtimeParams?: RuntimeParams): Promise<ViewResponse>;
@@ -1,13 +1,11 @@
1
- import { normalizeResourcePath } from '@lwrjs/shared-utils';
2
- import { generateHtmlTag, generatePageContext, getRouteHandler, isViewResponse, toJsonFormat, } from './utils.js';
1
+ import { normalizeResourcePath, shortestTtl } from '@lwrjs/shared-utils';
2
+ import { generateHtmlTag, generatePageContext, isViewResponse, toJsonFormat } from './utils.js';
3
3
  import { resolve } from 'path';
4
4
  export class LwrViewHandler {
5
5
  constructor(context, globalConfig) {
6
- // TODO convert to using InflightTasks in the shared utils
7
- this.inflightRouteHandlerEvalMap = new Map();
8
- this.routeHandlerFunctionMap = new Map();
9
- this.viewRegistry = context.viewRegistry;
10
6
  this.globalConfig = globalConfig;
7
+ this.routeHandlers = context.routeHandlers;
8
+ this.viewRegistry = context.viewRegistry;
11
9
  this.moduleRegistry = context.moduleRegistry;
12
10
  }
13
11
  // Get the View's HTML Response
@@ -18,8 +16,7 @@ export class LwrViewHandler {
18
16
  route,
19
17
  // context
20
18
  runtimeEnvironment, runtimeParams = {}) {
21
- const { routeHandler } = route;
22
- if (routeHandler) {
19
+ if (route.routeHandler) {
23
20
  const response = await this.getRouteHandlerResponse(viewRequest, route, runtimeEnvironment, runtimeParams);
24
21
  if (isViewResponse(response)) {
25
22
  // Return custom view response payload as-is
@@ -38,6 +35,7 @@ export class LwrViewHandler {
38
35
  metadata: {
39
36
  viewDefinition,
40
37
  },
38
+ cache: { ttl: shortestTtl(response.cache?.ttl, viewDefinition.cache?.ttl) },
41
39
  };
42
40
  }
43
41
  // default static view
@@ -47,6 +45,7 @@ export class LwrViewHandler {
47
45
  metadata: {
48
46
  viewDefinition,
49
47
  },
48
+ cache: viewDefinition.cache,
50
49
  };
51
50
  }
52
51
  // Get the View's JSON Manifest Response
@@ -57,8 +56,7 @@ export class LwrViewHandler {
57
56
  route,
58
57
  // context
59
58
  runtimeEnvironment, runtimeParams = {}) {
60
- const { routeHandler } = route;
61
- if (routeHandler) {
59
+ if (route.routeHandler) {
62
60
  const response = await this.getRouteHandlerResponse(viewRequest, route, runtimeEnvironment, runtimeParams);
63
61
  if (isViewResponse(response)) {
64
62
  // Return custom view response payload as-is
@@ -86,9 +84,8 @@ export class LwrViewHandler {
86
84
  route,
87
85
  // context
88
86
  runtimeEnvironment, runtimeParams = {}) {
89
- const { routeHandler } = route;
90
87
  let viewDefinition;
91
- if (routeHandler) {
88
+ if (route.routeHandler) {
92
89
  const response = await this.getRouteHandlerResponse(viewRequest, route, runtimeEnvironment, runtimeParams);
93
90
  if (isViewResponse(response)) {
94
91
  // Return custom view response payload as-is
@@ -143,33 +140,18 @@ export class LwrViewHandler {
143
140
  viewRequest, route,
144
141
  // context
145
142
  runtimeEnvironment, runtimeParams = {}) {
146
- const { rootDir, assets, contentDir, layoutsDir, cacheDir } = this.globalConfig;
147
- const paths = { rootDir, assets, contentDir, layoutsDir };
148
- const { routeHandler } = route;
149
- if (!routeHandler) {
150
- throw new Error('Route Handler is required for a CustomView');
143
+ if (!route.routeHandler) {
144
+ throw new Error('Route handler is required for a CustomView');
151
145
  }
152
- // Import and instantiate route handler
153
- let routeHandlerFunction = this.routeHandlerFunctionMap.get(routeHandler);
154
- if (!routeHandlerFunction) {
155
- const inflightRouteHandlerPromise = this.inflightRouteHandlerEvalMap.get(routeHandler);
156
- if (inflightRouteHandlerPromise) {
157
- // wait on the current inflight route handler promise
158
- routeHandlerFunction = await inflightRouteHandlerPromise;
159
- }
160
- else {
161
- // get the route handler eval promise
162
- const handlerPromise = getRouteHandler(routeHandler, { cacheDir, rootDir });
163
- this.inflightRouteHandlerEvalMap.set(routeHandler, handlerPromise);
164
- routeHandlerFunction = await handlerPromise;
165
- }
166
- // add the resolved route handler function into the cache and delete the inflight entry
167
- this.routeHandlerFunctionMap.set(routeHandler, routeHandlerFunction);
168
- this.inflightRouteHandlerEvalMap.delete(routeHandler);
146
+ const routeHandler = this.routeHandlers[route.routeHandler];
147
+ if (!routeHandler) {
148
+ throw new Error(`Route handler does not exist for id: ${route.routeHandler}`);
169
149
  }
150
+ const { rootDir, assets, contentDir, layoutsDir } = this.globalConfig;
151
+ const paths = { rootDir, assets, contentDir, layoutsDir };
170
152
  const locale = runtimeParams.locale;
171
153
  const viewApi = this.getBoundApi(route, runtimeEnvironment, runtimeParams);
172
- const response = await routeHandlerFunction({ ...viewRequest, locale }, { route, viewApi, ...paths });
154
+ const response = await routeHandler({ ...viewRequest, locale }, { route: route, viewApi, ...paths });
173
155
  return response;
174
156
  }
175
157
  /*
@@ -202,6 +184,7 @@ export class LwrViewHandler {
202
184
  metadata: {
203
185
  viewDefinition,
204
186
  },
187
+ cache: viewDefinition.cache,
205
188
  };
206
189
  }
207
190
  }
package/package.json CHANGED
@@ -4,15 +4,15 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "0.9.0-alpha.2",
7
+ "version": "0.9.0-alpha.21",
8
8
  "homepage": "https://developer.salesforce.com/docs/platform/lwr/overview",
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "https://github.com/salesforce/lwr.git",
11
+ "url": "https://github.com/salesforce-experience-platform-emu/lwr.git",
12
12
  "directory": "packages/@lwrjs/view-registry"
13
13
  },
14
14
  "bugs": {
15
- "url": "https://github.com/salesforce/lwr/issues"
15
+ "url": "https://github.com/salesforce-experience-platform-emu/lwr/issues"
16
16
  },
17
17
  "type": "module",
18
18
  "types": "build/es/index.d.ts",
@@ -30,15 +30,15 @@
30
30
  "build/**/*.d.ts"
31
31
  ],
32
32
  "dependencies": {
33
- "@lwrjs/app-service": "0.9.0-alpha.2",
34
- "@lwrjs/diagnostics": "0.9.0-alpha.2",
35
- "@lwrjs/shared-utils": "0.9.0-alpha.2"
33
+ "@lwrjs/app-service": "0.9.0-alpha.21",
34
+ "@lwrjs/diagnostics": "0.9.0-alpha.21",
35
+ "@lwrjs/shared-utils": "0.9.0-alpha.21"
36
36
  },
37
37
  "devDependencies": {
38
- "@lwrjs/types": "0.9.0-alpha.2"
38
+ "@lwrjs/types": "0.9.0-alpha.21"
39
39
  },
40
40
  "engines": {
41
41
  "node": ">=14.15.4 <19"
42
42
  },
43
- "gitHead": "bcf63de23d1a2a53fb0e961dba4396e8753710dd"
43
+ "gitHead": "a89adcac80601f657becd6fd734c765e6b2a2745"
44
44
  }