bun-plugin-stx 0.2.897 → 0.2.899

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,5 +1,7 @@
1
+ /** A caller can lower its own priority, never take priority above navigation. */
2
+ export declare function renderRequestPriority(request?: Request): RenderPriority;
1
3
  export declare function createRenderAdmission(options?: RenderAdmissionOptions): {
2
- run: <T>(start: () => Promise<T>, signal?: AbortSignal) => Promise<T>
4
+ run: <T>(start: () => Promise<T>, signal?: AbortSignal, priority?: RenderPriority) => Promise<T>
3
5
  };
4
6
  /** Bounds work before a render allocates its script contexts and HTML. */
5
7
  export declare interface RenderAdmissionOptions {
@@ -7,6 +9,7 @@ export declare interface RenderAdmissionOptions {
7
9
  renderQueueLimit?: number
8
10
  renderQueueTimeoutMs?: number
9
11
  }
12
+ declare type RenderPriority = 'foreground' | 'background';
10
13
  export declare class RenderAdmissionError extends Error {
11
14
  readonly status: 408 | 503;
12
15
  constructor(status: 408 | 503);
package/dist/serve.d.ts CHANGED
@@ -29,6 +29,31 @@ export declare function fillRouteParams(html: string, params: Record<string, str
29
29
  * cache, never correctness.
30
30
  */
31
31
  export declare function serverScriptsReadParams(serverScripts: string[], paramNames: string[]): boolean;
32
+ /**
33
+ * A route's params for a render that may be kept as every address's shell,
34
+ * and whether anything read them while it rendered.
35
+ *
36
+ * `serverScriptsReadParams` sees the page's own server scripts and nothing
37
+ * else. A script-less page's `{{ params.model }}`, a prop bound from it and a
38
+ * component's server script reading `params` all ran with the first address's
39
+ * values, and that render was served for every address after it
40
+ * (stacksjs/stx#2188). A render reads its params through this object, so it
41
+ * can say so wherever the read happens. Only a param's own name counts: a
42
+ * missing key reads the same for every address, and the engine probes context
43
+ * values for markers (`_isSignal`, `then`) that are not reads of a param.
44
+ */
45
+ export declare function trackParamReads(params: Record<string, string>): { params: Record<string, string>, read: () => boolean };
46
+ /**
47
+ * Whether templates use a route segment by its bare name (`[model].stx`
48
+ * binds `model`) in something the server evaluates: `{{ }}`, `{!! !!}`, a
49
+ * directive's arguments, a bound attribute, or a server script.
50
+ *
51
+ * A bare name cannot be tracked as `params` is: it is a plain string, and
52
+ * every expression is handed every context value, so a read of it looks like
53
+ * any other. Coarse like `serverScriptsReadParams`: a match that is not the
54
+ * param costs the shared shell, never correctness.
55
+ */
56
+ export declare function templatesReadParamNames(sources: string[], paramNames: string[]): boolean;
32
57
  /**
33
58
  * The answer to a request whose URL cannot be parsed, or null for any other.
34
59
  *
package/dist/serve.js CHANGED
@@ -9160,6 +9160,10 @@ class RenderAdmissionError extends Error {
9160
9160
  this.name = "RenderAdmissionError";
9161
9161
  }
9162
9162
  }
9163
+ function renderRequestPriority(request) {
9164
+ const purpose = `${request?.headers.get("purpose") || ""} ${request?.headers.get("sec-purpose") || ""}`;
9165
+ return purpose.toLowerCase().split(/[;,\s]+/).some((value) => value === "prefetch" || value === "prerender") ? "background" : "foreground";
9166
+ }
9163
9167
  function integer(value, fallback, minimum) {
9164
9168
  if (value === undefined)
9165
9169
  return fallback;
@@ -9171,20 +9175,32 @@ function createRenderAdmission(options = {}) {
9171
9175
  const concurrency = integer(options.renderConcurrency, 4, 1);
9172
9176
  const queueLimit = integer(options.renderQueueLimit, 32, 0);
9173
9177
  const timeoutMs = integer(options.renderQueueTimeoutMs, 15000, 1);
9178
+ const backgroundConcurrency = Math.max(1, Math.floor(concurrency / 2));
9179
+ const backgroundQueueLimit = Math.max(0, queueLimit - concurrency);
9174
9180
  const waiting = [];
9175
9181
  let active = 0;
9176
- function release() {
9182
+ let activeBackground = 0;
9183
+ function release(priority) {
9177
9184
  active--;
9178
- waiting.shift()?.start();
9185
+ if (priority === "background")
9186
+ activeBackground--;
9187
+ while (active < concurrency && waiting.length) {
9188
+ const foreground = waiting.findIndex((entry) => entry.priority === "foreground");
9189
+ if (foreground < 0 && activeBackground >= backgroundConcurrency)
9190
+ break;
9191
+ waiting.splice(foreground < 0 ? 0 : foreground, 1)[0]?.start();
9192
+ }
9179
9193
  }
9180
- async function acquire(signal) {
9194
+ async function acquire(signal, priority) {
9181
9195
  if (signal?.aborted)
9182
9196
  throw new RenderAdmissionError(408);
9183
- if (active < concurrency) {
9197
+ if (active < concurrency && (priority === "foreground" || activeBackground < backgroundConcurrency)) {
9184
9198
  active++;
9199
+ if (priority === "background")
9200
+ activeBackground++;
9185
9201
  return;
9186
9202
  }
9187
- if (waiting.length >= queueLimit)
9203
+ if (waiting.length >= queueLimit || priority === "background" && waiting.filter((entry) => entry.priority === "background").length >= backgroundQueueLimit)
9188
9204
  throw new RenderAdmissionError(503);
9189
9205
  await new Promise((resolve, reject) => {
9190
9206
  let settled = false;
@@ -9204,12 +9220,15 @@ function createRenderAdmission(options = {}) {
9204
9220
  };
9205
9221
  const abort = () => fail(408);
9206
9222
  const entry = {
9223
+ priority,
9207
9224
  start() {
9208
9225
  if (settled)
9209
9226
  return;
9210
9227
  settled = true;
9211
9228
  cleanup();
9212
9229
  active++;
9230
+ if (priority === "background")
9231
+ activeBackground++;
9213
9232
  resolve();
9214
9233
  }
9215
9234
  };
@@ -9222,14 +9241,14 @@ function createRenderAdmission(options = {}) {
9222
9241
  });
9223
9242
  }
9224
9243
  return {
9225
- async run(start, signal) {
9226
- await acquire(signal);
9244
+ async run(start, signal, priority = "foreground") {
9245
+ await acquire(signal, priority);
9227
9246
  try {
9228
9247
  if (signal?.aborted)
9229
9248
  throw new RenderAdmissionError(408);
9230
9249
  return await start();
9231
9250
  } finally {
9232
- release();
9251
+ release(priority);
9233
9252
  }
9234
9253
  }
9235
9254
  };
@@ -9390,6 +9409,45 @@ function serverScriptsReadParams(serverScripts, paramNames) {
9390
9409
  const pattern = new RegExp(`(?:^|[^\\w$.])(?:${names.join("|")})(?![\\w$])`);
9391
9410
  return serverScripts.some((script) => pattern.test(script));
9392
9411
  }
9412
+ function trackParamReads(params) {
9413
+ let read = false;
9414
+ const isParam = (key) => typeof key === "string" && Object.hasOwn(params, key);
9415
+ const tracked = new Proxy(params, {
9416
+ get(target, key, receiver) {
9417
+ if (isParam(key))
9418
+ read = true;
9419
+ return Reflect.get(target, key, receiver);
9420
+ },
9421
+ has(target, key) {
9422
+ if (isParam(key))
9423
+ read = true;
9424
+ return Reflect.has(target, key);
9425
+ },
9426
+ ownKeys(target) {
9427
+ read = true;
9428
+ return Reflect.ownKeys(target);
9429
+ }
9430
+ });
9431
+ return { params: tracked, read: () => read };
9432
+ }
9433
+ function templatesReadParamNames(sources, paramNames) {
9434
+ if (paramNames.length === 0)
9435
+ return false;
9436
+ const names = paramNames.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
9437
+ const reads = new RegExp(`(?:^|[^\\w$.])(?:${names.join("|")})(?![\\w$])`);
9438
+ const evaluated = /\{\{([\s\S]*?)\}\}|\{!!([\s\S]*?)!!\}|@[a-z]\w*\s*\(([^\n]*)\)|\s:[\w.-]+\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
9439
+ for (const source of sources) {
9440
+ const { serverScripts, templateContent } = extractServerScriptsFromTemplate(source);
9441
+ if (serverScriptsReadParams(serverScripts, paramNames))
9442
+ return true;
9443
+ for (const match of templateContent.matchAll(evaluated)) {
9444
+ const expression = match.slice(1).find((part) => part !== undefined) ?? "";
9445
+ if (reads.test(expression))
9446
+ return true;
9447
+ }
9448
+ }
9449
+ return false;
9450
+ }
9393
9451
  var CSRF_COOKIE = "X-CSRF-Token";
9394
9452
  function malformedRequestResponse(req) {
9395
9453
  if (URL.canParse(req.url))
@@ -9913,6 +9971,7 @@ After installing: bun add bun-plugin-stx`);
9913
9971
  let assetsInitialized = false;
9914
9972
  const htmlCache = boundedCache(options.renderCacheLimit ?? 512);
9915
9973
  const pendingShellRenders = new Map;
9974
+ const paramReaders = new Map;
9916
9975
  const renderAdmission = createRenderAdmission(options);
9917
9976
  const ENABLE_HTML_CACHE = options.renderCache === true;
9918
9977
  const RENDER_CACHE_VARY = options.renderCacheVary ?? "request";
@@ -10055,6 +10114,7 @@ function __stxOverlay(errs){
10055
10114
  const watchersStarted = new Map;
10056
10115
  const clearRenderCaches = () => {
10057
10116
  htmlCache.clear();
10117
+ paramReaders.clear();
10058
10118
  renderCacheStore?.invalidate();
10059
10119
  cssCssCache.clear();
10060
10120
  resolvedStxModule?.clearDevCaches?.();
@@ -10719,7 +10779,7 @@ function __stxOverlay(errs){
10719
10779
  reqCtx.responseHeaders = { ...reqCtx.responseHeaders, ...headers };
10720
10780
  }
10721
10781
  async function processTemplate(filePath, reqCtx) {
10722
- return renderAdmission.run(() => renderTemplate(filePath, reqCtx), reqCtx?.request?.signal);
10782
+ return renderAdmission.run(() => renderTemplate(filePath, reqCtx), reqCtx?.request?.signal, renderRequestPriority(reqCtx?.request));
10723
10783
  }
10724
10784
  async function renderTemplate(filePath, reqCtx) {
10725
10785
  const ticket = await renderTicket(reqCtx);
@@ -10916,7 +10976,7 @@ function __stxOverlay(errs){
10916
10976
  return null;
10917
10977
  }
10918
10978
  async function processTemplateDynamic(filePath, paramNames, paramValues, routePath, reqCtx) {
10919
- return renderAdmission.run(() => renderTemplateDynamic(filePath, paramNames, paramValues, routePath, reqCtx), reqCtx?.request?.signal);
10979
+ return renderAdmission.run(() => renderTemplateDynamic(filePath, paramNames, paramValues, routePath, reqCtx), reqCtx?.request?.signal, renderRequestPriority(reqCtx?.request));
10920
10980
  }
10921
10981
  async function renderTemplateDynamic(filePath, paramNames, paramValues, routePath, reqCtx) {
10922
10982
  const ticket = await renderTicket(reqCtx);
@@ -10934,7 +10994,12 @@ function __stxOverlay(errs){
10934
10994
  }
10935
10995
  const isMutating = !!reqCtx && reqCtx.method !== "GET" && reqCtx.method !== "HEAD";
10936
10996
  const skipCacheHint = /(?:^|[^\w$])__stx_skip_cache\s*=\s*true/.test(content);
10937
- const cacheShell = ENABLE_HTML_CACHE && RENDER_CACHE_VARY === "source" && paramNames.length > 0 && !isMutating && !skipCacheHint && allowsRenderCache(reqCtx) && !serverScriptsReadParams(dynServerScripts, paramNames);
10997
+ let cacheShell = ENABLE_HTML_CACHE && RENDER_CACHE_VARY === "source" && paramNames.length > 0 && !isMutating && !skipCacheHint && allowsRenderCache(reqCtx) && !serverScriptsReadParams(dynServerScripts, paramNames);
10998
+ if (cacheShell) {
10999
+ const reader = paramReaders.get(filePath);
11000
+ if (reader && await templateSignatureFresh(reader))
11001
+ cacheShell = false;
11002
+ }
10938
11003
  if (reqCtx)
10939
11004
  reqCtx.params = paramsObj;
10940
11005
  if (cacheShell) {
@@ -10968,7 +11033,8 @@ function __stxOverlay(errs){
10968
11033
  for (const name of paramNames) {
10969
11034
  context[name] = paramsObj[name];
10970
11035
  }
10971
- context.params = paramsObj;
11036
+ const paramReads = cacheShell ? trackParamReads(paramsObj) : undefined;
11037
+ context.params = paramReads ? paramReads.params : paramsObj;
10972
11038
  const { processDirectives, extractVariables, defaultConfig, injectRouterScript: injectRouter } = await stxModule;
10973
11039
  injectServeLocaleContext(context);
10974
11040
  injectServeRequestContext(context, reqCtx);
@@ -11032,6 +11098,10 @@ ${output}`;
11032
11098
  });
11033
11099
  if (!cacheShell)
11034
11100
  return output;
11101
+ if (paramReads?.read() || templatesReadParamNames([templateContent, ...await Promise.all([...dependencies].filter((dep) => dep !== filePath).map((dep) => Bun.file(dep).text().catch(() => "")))], paramNames)) {
11102
+ paramReaders.set(filePath, await buildTemplateSignature(filePath, dependencies));
11103
+ return fillRouteParams(output, paramsObj);
11104
+ }
11035
11105
  const recordedResponse = readResponseStatus(context) !== undefined || !!readResponseHeaders(context);
11036
11106
  if (!context.__stx_skip_cache && !recordedResponse && allowsRenderCache(reqCtx) && isRenderableCacheCandidate(output) && placeholdersAreReady) {
11037
11107
  const signature = await buildTemplateSignature(filePath, dependencies);
@@ -11565,7 +11635,7 @@ ${output}`;
11565
11635
  ...partialsDir && { partialsDir },
11566
11636
  autoShell: false
11567
11637
  };
11568
- const html = await renderAdmission.run(() => processDirectives(componentTemplate, {}, `${componentsDir}/${componentName}.stx`, componentOpts, new Set), req.signal);
11638
+ const html = await renderAdmission.run(() => processDirectives(componentTemplate, {}, `${componentsDir}/${componentName}.stx`, componentOpts, new Set), req.signal, renderRequestPriority(req));
11569
11639
  return new Response(html, {
11570
11640
  headers: { "Content-Type": "text/html; charset=utf-8", ...corsHeaders }
11571
11641
  });
@@ -12287,5 +12357,7 @@ export {
12287
12357
  sharedScriptCacheControl,
12288
12358
  staticCacheControl,
12289
12359
  staticContentType,
12360
+ templatesReadParamNames,
12361
+ trackParamReads,
12290
12362
  usableErrorPage
12291
12363
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bun-plugin-stx",
3
3
  "type": "module",
4
- "version": "0.2.897",
4
+ "version": "0.2.899",
5
5
  "description": "A Bun plugin that allows for using Laravel Blade-like syntax.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -74,7 +74,7 @@
74
74
  "typecheck": "bun tsc --noEmit"
75
75
  },
76
76
  "dependencies": {
77
- "@stacksjs/stx": "0.2.897",
78
- "stx-router": "0.2.897"
77
+ "@stacksjs/stx": "0.2.899",
78
+ "stx-router": "0.2.899"
79
79
  }
80
80
  }