@homepages/concrete 1.0.2 → 2.0.0

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/codemods/manifest.json +12 -0
  3. package/codemods/unlayer-author-css.mjs +194 -0
  4. package/dist/artifact/playground/client/assets/index-CW7co-u9.js +1101 -0
  5. package/dist/artifact/playground/client/assets/index-CckS2ONm.css +1 -0
  6. package/dist/artifact/playground/client/index.html +2 -2
  7. package/dist/artifact/playground/client/island-canvas-host.mjs +1 -1
  8. package/dist/artifact/playground/host.mjs +24 -24
  9. package/dist/base.css +15 -2
  10. package/dist/cli/build/artifact.js +5 -2
  11. package/dist/cli/build/captures.js +15 -18
  12. package/dist/cli/build/fixtures.js +11 -3
  13. package/dist/cli/build/sections.js +13 -4
  14. package/dist/cli/build/static.js +1 -1
  15. package/dist/cli/check/load-workspace.js +6 -1
  16. package/dist/cli/check/stages/bundles.js +3 -1
  17. package/dist/cli/commands.js +1 -1
  18. package/dist/cli/dev/load-template.js +32 -25
  19. package/dist/cli/dev/server.js +11 -3
  20. package/dist/cli/dev/vite.js +78 -22
  21. package/dist/cli/dev/workspace-reader.js +2 -6
  22. package/dist/cli/media/derive.js +30 -3
  23. package/dist/cli/media/deriver-plugin.js +6 -2
  24. package/dist/cli/media/frame-rung-floor.js +18 -0
  25. package/dist/css/compile.js +26 -4
  26. package/dist/css/graph.js +2 -1
  27. package/dist/css/rules.js +72 -1
  28. package/dist/eslint/authoring.js +2 -0
  29. package/dist/eslint/rules/island-ids.js +39 -0
  30. package/dist/fixtures/load.js +6 -1
  31. package/dist/fixtures/media-plugin.js +32 -17
  32. package/dist/fixtures/media.js +41 -8
  33. package/dist/fixtures/package-stylesheets.js +59 -0
  34. package/dist/fixtures/property.js +40 -9
  35. package/dist/fixtures/resolve.js +58 -5
  36. package/dist/fixtures/rows.js +6 -1
  37. package/dist/fixtures.d.ts +80 -12
  38. package/dist/fixtures.js +7 -3
  39. package/dist/index.d.ts +2 -1
  40. package/dist/index.js +2 -1
  41. package/dist/islands/island-id.js +8 -0
  42. package/dist/islands/marker.d.ts +14 -4
  43. package/dist/islands/marker.js +18 -6
  44. package/dist/packages/external/concrete/package.js +1 -1
  45. package/dist/packages/internal/island-runtime/dist/index.js +4 -2
  46. package/dist/packages/internal/island-runtime/dist/island-id-context.js +15 -0
  47. package/dist/packages/internal/island-runtime/dist/use-island-id.d.ts +24 -0
  48. package/dist/packages/internal/island-runtime/dist/use-island-id.js +44 -0
  49. package/dist/packages/internal/template-contracts/dist/slot-catalog.d.ts +1 -1
  50. package/dist/packages/internal/template-contracts/dist/slot-catalog.js +44 -2
  51. package/dist/primitives/slot-bindings.d.ts +19 -13
  52. package/dist/primitives/slot-bindings.js +7 -3
  53. package/dist/rules/registry.js +19 -0
  54. package/dist/section/section.d.ts +6 -1
  55. package/dist/template/logic-shim.d.ts +2 -1
  56. package/dist/template/logic-shim.js +2 -1
  57. package/guide/reference/cli/INDEX.md +2 -2
  58. package/guide/reference/cli/build.md +2 -2
  59. package/guide/reference/cli/check.md +1 -1
  60. package/guide/reference/cli/dev.md +1 -1
  61. package/guide/reference/cli/property-add.md +1 -1
  62. package/guide/reference/cli/property-list.md +1 -1
  63. package/guide/reference/cli/publish.md +1 -1
  64. package/guide/reference/cli/upgrade.md +1 -1
  65. package/guide/reference/rules/INDEX.md +4 -1
  66. package/package.json +1 -1
  67. package/dist/artifact/playground/client/assets/index-BSA1yutg.css +0 -1
  68. package/dist/artifact/playground/client/assets/index-JloQyj8h.js +0 -1101
@@ -140,7 +140,7 @@ function sourcesOf(metafile) {
140
140
  }
141
141
  /** Build a placed section's renderer bundle and its island chunks. */
142
142
  async function buildSection(input) {
143
- const { root, key } = input;
143
+ const { root, key, minRungWidth } = input;
144
144
  const cacheDir = mediaCacheDir(root);
145
145
  const found = /* @__PURE__ */ new Map();
146
146
  const assets = /* @__PURE__ */ new Map();
@@ -169,12 +169,18 @@ async function buildSection(input) {
169
169
  for (const [masterKey, filename] of deriver.masters) masters.set(masterKey, filename);
170
170
  for (const path of deriver.passthrough) passthrough.add(path);
171
171
  };
172
- const rendererDeriver = createMediaDeriver({ cacheDir });
172
+ const rendererDeriver = createMediaDeriver({
173
+ cacheDir,
174
+ minRungWidth
175
+ });
173
176
  const rendered = await rendererPass(input, rendererDeriver, found, true);
174
177
  collect(rendererDeriver, rendered.outputFiles, rendered.metafile);
175
178
  const islands = [];
176
179
  for (const [islandKey, file] of [...found].sort(([a], [b]) => a < b ? -1 : 1)) {
177
- const deriver = createMediaDeriver({ cacheDir });
180
+ const deriver = createMediaDeriver({
181
+ cacheDir,
182
+ minRungWidth
183
+ });
178
184
  const bytes = await runPass(`The island chunk ${islandKey}`, async () => {
179
185
  const result = await build({
180
186
  entryPoints: [file],
@@ -225,7 +231,10 @@ async function buildSection(input) {
225
231
  * not delete it. Never written to an artifact.
226
232
  */
227
233
  async function buildFramedRenderer(input) {
228
- return (await rendererPass(input, createMediaDeriver({ cacheDir: mediaCacheDir(input.root) }), /* @__PURE__ */ new Map(), false)).bytes;
234
+ return (await rendererPass(input, createMediaDeriver({
235
+ cacheDir: mediaCacheDir(input.root),
236
+ minRungWidth: input.minRungWidth
237
+ }), /* @__PURE__ */ new Map(), false)).bytes;
229
238
  }
230
239
  /** Where `check` writes a framed renderer to import it: inside the workspace, so its React resolves from there. */
231
240
  function framedRendererPath(root, key, bytes) {
@@ -7,8 +7,8 @@ import { dirname, extname, join } from "node:path";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
8
  import { readFile } from "node:fs/promises";
9
9
  import { createHash } from "node:crypto";
10
- import { build } from "esbuild";
11
10
  import { createRequire } from "node:module";
11
+ import { build } from "esbuild";
12
12
 
13
13
  //#region src/cli/build/static.ts
14
14
  function sha256(bytes) {
@@ -2,6 +2,7 @@ import { isTemplate } from "../../template/define-template.js";
2
2
  import { listModules } from "../../section/discovery.js";
3
3
  import { MEDIA_LOADERS, createFixtureMediaPlugin, externalOutsideWorkspace } from "../../fixtures/media-plugin.js";
4
4
  import { runningCopyPlugin } from "../../template/running-copy.js";
5
+ import { createPackageStylesheetsPlugin } from "../../fixtures/package-stylesheets.js";
5
6
  import { existsSync } from "node:fs";
6
7
  import { join, relative, sep } from "node:path";
7
8
  import { pathToFileURL } from "node:url";
@@ -35,6 +36,7 @@ async function loadWorkspace(root) {
35
36
  };
36
37
  const files = listModules(root);
37
38
  const media = createFixtureMediaPlugin(root);
39
+ const stylesheets = await createPackageStylesheetsPlugin(root);
38
40
  let result;
39
41
  try {
40
42
  result = await build({
@@ -56,7 +58,8 @@ async function loadWorkspace(root) {
56
58
  plugins: [
57
59
  runningCopyPlugin(),
58
60
  externalOutsideWorkspace(root),
59
- media.plugin
61
+ media.plugin,
62
+ stylesheets.plugin
60
63
  ],
61
64
  sourcemap: "inline",
62
65
  metafile: true,
@@ -78,6 +81,8 @@ async function loadWorkspace(root) {
78
81
  message: m.text
79
82
  }))
80
83
  };
84
+ } finally {
85
+ await stylesheets.dispose();
81
86
  }
82
87
  process.setSourceMapsEnabled(true);
83
88
  const outputByInput = /* @__PURE__ */ new Map();
@@ -1,5 +1,6 @@
1
1
  import { publishedSectionKey } from "../../../packages/internal/template-artifact/dist/layout.js";
2
2
  import "../../../packages/internal/template-artifact/dist/index.js";
3
+ import { frameRungFloor } from "../../media/frame-rung-floor.js";
3
4
  import { exportSite } from "../../../section/discovery.js";
4
5
  import { buildFramedRenderer, buildSection, framedRendererPath } from "../../build/sections.js";
5
6
  import { workspacePath } from "../load-workspace.js";
@@ -39,7 +40,8 @@ async function bundlesStage(ctx) {
39
40
  root: ctx.root,
40
41
  key: publishedSectionKey(template.key, entry.key),
41
42
  module: join(ctx.root, site.module),
42
- exportName: site.exportName
43
+ exportName: site.exportName,
44
+ minRungWidth: frameRungFloor(template)
43
45
  };
44
46
  let section;
45
47
  try {
@@ -78,7 +78,7 @@ const DECLARED_COMMANDS = [
78
78
  constraints: [
79
79
  "The only producer of an artifact. Nothing else — no bare bundler — writes one.",
80
80
  "Deterministic: the same tree builds to the same artifact hash.",
81
- "An image or document template also carries `captures/`: every authored fixture at every declared format, taken exactly as `dev`'s *Download fixture render* takes it — the enabled pages and their zip, or the PDF. Captures sit outside the artifact hash, and need Playwright: without it, build refuses with the install line.",
81
+ "An image or document template also carries `captures/`: every authored fixture at every declared format, taken exactly as `dev`'s *Download* takes it — the enabled pages and their zip, or the PDF. Captures sit outside the artifact hash, and need Playwright: without it, build refuses with the install line.",
82
82
  `The default output directory, \`${DEFAULT_BUILD_DIR}/\`, is gitignored by the scaffold.`
83
83
  ]
84
84
  },
@@ -1,5 +1,6 @@
1
1
  import { islandEsbuildPlugin } from "./islands.js";
2
2
  import { MEDIA_LOADERS, createFixtureMediaPlugin, externalOutsideWorkspace } from "../../fixtures/media-plugin.js";
3
+ import { createPackageStylesheetsPlugin } from "../../fixtures/package-stylesheets.js";
3
4
  import { join } from "node:path";
4
5
  import { pathToFileURL } from "node:url";
5
6
  import { build } from "esbuild";
@@ -10,32 +11,38 @@ let serial = 0;
10
11
  async function loadTemplateModule(options) {
11
12
  const { root } = options;
12
13
  const media = createFixtureMediaPlugin(root);
14
+ const stylesheets = await createPackageStylesheetsPlugin(root);
13
15
  const outfile = join(root, ".concrete", "cache", "dev", "template.mjs");
14
- await build({
15
- entryPoints: [options.templateFile],
16
- bundle: true,
17
- format: "esm",
18
- platform: "node",
19
- target: "node22",
20
- outfile,
21
- absWorkingDir: root,
22
- packages: "external",
23
- jsx: "automatic",
24
- loader: {
25
- ".css": "empty",
26
- ...MEDIA_LOADERS
27
- },
28
- plugins: [
29
- externalOutsideWorkspace(root),
30
- islandEsbuildPlugin({
31
- root,
32
- markerSpecifier: options.markerSpecifier
33
- }),
34
- media.plugin
35
- ],
36
- write: true,
37
- logLevel: "silent"
38
- });
16
+ try {
17
+ await build({
18
+ entryPoints: [options.templateFile],
19
+ bundle: true,
20
+ format: "esm",
21
+ platform: "node",
22
+ target: "node22",
23
+ outfile,
24
+ absWorkingDir: root,
25
+ packages: "external",
26
+ jsx: "automatic",
27
+ loader: {
28
+ ".css": "empty",
29
+ ...MEDIA_LOADERS
30
+ },
31
+ plugins: [
32
+ externalOutsideWorkspace(root),
33
+ islandEsbuildPlugin({
34
+ root,
35
+ markerSpecifier: options.markerSpecifier
36
+ }),
37
+ media.plugin,
38
+ stylesheets.plugin
39
+ ],
40
+ write: true,
41
+ logLevel: "silent"
42
+ });
43
+ } finally {
44
+ await stylesheets.dispose();
45
+ }
39
46
  return {
40
47
  template: (await import(`${pathToFileURL(outfile).href}?load=${Date.now()}-${serial++}`)).default,
41
48
  assets: media.assets
@@ -10,7 +10,7 @@ import { croppedMediaUrl, cutRegion } from "./crop.js";
10
10
  import { createHmrBus } from "./hmr.js";
11
11
  import { RequestError, contentTypeFor, readBody, sendBytes, sendFile, sendHtml, sendText } from "./http.js";
12
12
  import { respondToHandlerError } from "./request-error.js";
13
- import { createDevVite } from "./vite.js";
13
+ import { createDevVite, settleBrowserDependencies } from "./vite.js";
14
14
  import { DevWorkspace } from "./workspace-reader.js";
15
15
  import { existsSync, statSync } from "node:fs";
16
16
  import { dirname, extname, join, relative, resolve, sep } from "node:path";
@@ -67,12 +67,14 @@ async function startDevServer(options) {
67
67
  const browserMarker = FROM_SOURCE ? `/@fs/${sourceMarker.replace(/^\/+/, "")}` : "@homepages/concrete";
68
68
  const serverMarker = FROM_SOURCE ? sourceMarker : "@homepages/concrete";
69
69
  const islandEntries = findWorkspaceIslands(root).map((file) => relative(root, file));
70
+ const browserAssets = /* @__PURE__ */ new Map();
70
71
  const vite = await createDevVite({
71
72
  root,
72
73
  packageRoot,
73
74
  markerSpecifier: browserMarker,
74
75
  hmrPort: port + 100,
75
- islandEntries
76
+ islandEntries,
77
+ assets: browserAssets
76
78
  });
77
79
  let islands = {
78
80
  map: {},
@@ -103,7 +105,10 @@ async function startDevServer(options) {
103
105
  packageRoot
104
106
  });
105
107
  const origin = `http://localhost:${port}/`;
108
+ let browserGraphSettled = null;
106
109
  const capture = async (request) => {
110
+ browserGraphSettled ??= settleBrowserDependencies(vite, [...islands.previewHost === null ? [] : [islands.previewHost], ...Object.values(islands.map)]);
111
+ await browserGraphSettled;
107
112
  try {
108
113
  return await captureFixture(capturer, origin, request);
109
114
  } catch (err) {
@@ -134,11 +139,13 @@ async function startDevServer(options) {
134
139
  clientDir,
135
140
  baseCss: join(packageRoot, FROM_SOURCE ? join("src", "css", "base.css") : join("dist", "base.css")),
136
141
  log,
142
+ browserAssets,
137
143
  crops: /* @__PURE__ */ new Map()
138
144
  };
139
145
  const fixturesDir = join(root, "fixtures") + sep;
140
146
  const onChange = (path) => {
141
147
  vite.moduleGraph.invalidateAll();
148
+ browserGraphSettled = null;
142
149
  if (path.startsWith(fixturesDir)) {
143
150
  workspace.invalidateFixtures();
144
151
  hmr.broadcast(HMR_EVENTS.fixtures);
@@ -266,7 +273,8 @@ async function sendFixtureMedia(ctx, req, url, res) {
266
273
  sendText(res, 405, "fixture media only reads; the playground accepts no uploads.");
267
274
  return;
268
275
  }
269
- const asset = await ctx.workspace.fixtureAsset(decodeURIComponent(url.pathname));
276
+ const path = decodeURIComponent(url.pathname);
277
+ const asset = await ctx.workspace.fixtureAsset(path) ?? ctx.browserAssets.get(path);
270
278
  if (asset === void 0) {
271
279
  sendText(res, 404, "not found");
272
280
  return;
@@ -1,6 +1,7 @@
1
1
  import { createTsconfigPathsPlugin } from "./tsconfig-paths.js";
2
2
  import { islandTransformPlugin, toPosixPath } from "./islands.js";
3
3
  import { imageDimensions } from "../../fixtures/image-dimensions.js";
4
+ import { MEDIA_EXTENSIONS, fixtureMediaModule } from "../../fixtures/media-plugin.js";
4
5
  import { extname, isAbsolute, relative } from "node:path";
5
6
  import { readFile } from "node:fs/promises";
6
7
  import react from "@vitejs/plugin-react";
@@ -19,33 +20,52 @@ const RASTER_EXTENSIONS = /* @__PURE__ */ new Set([
19
20
  ".avif"
20
21
  ]);
21
22
  /**
22
- * A raster imported from a module is an OBJECT in the authoring contract (`AuthorImage`:
23
- * url, width, height, responsive) where Vite would hand back a URL string. `dev` serves
24
- * the master and derives no ladder — the ladder is the build's (`responsive: null`, the
25
- * same answer fixture media gets in `dev`). A query suffix (`?url`, `?raw`) is the
26
- * author asking Vite for the string form on purpose, and is left to Vite.
23
+ * Every asset import in the BROWSER graph, resolved exactly as the server graph resolves
24
+ * it (../../fixtures/media-plugin.ts): a raster yields the `AuthorImage` object the
25
+ * authoring contract promises, everything else its served `/fixture-media/` URL string.
26
+ *
27
+ * Left to itself Vite answers differently on both counts — it inlines a file under
28
+ * `assetsInlineLimit` as a `data:` URI and names the rest by their workspace path — and an
29
+ * island is in BOTH graphs, so a divergence is an attribute mismatch React reports on the
30
+ * island's own element at hydration. `build` has no such split (both its graphs are
31
+ * esbuild's), so this is the dev server's alone to close.
32
+ *
33
+ * What it mints is recorded in `assets`, which the server's `/fixture-media/` route reads
34
+ * alongside the server graph's index: an island declaring `serverFrame = false` is stubbed
35
+ * out of that graph, so its assets are minted only here.
36
+ *
37
+ * A query suffix (`?url`, `?raw`) is the author asking Vite for a form of their own on
38
+ * purpose, and is left to Vite.
27
39
  */
28
- function authorImagePlugin(root) {
40
+ function fixtureMediaVitePlugin(root, assets) {
29
41
  return {
30
- name: "concrete-dev:author-image",
42
+ name: "concrete-dev:fixture-media",
31
43
  enforce: "pre",
32
44
  async load(id) {
33
- if (id.includes("?") || !RASTER_EXTENSIONS.has(extname(id).toLowerCase())) return null;
34
- const bytes = await readFile(id);
35
- const url = isInside(root, id) ? `/${toPosixPath(relative(root, id))}` : `/@fs/${toPosixPath(id).replace(/^\/+/, "")}`;
36
- const size = imageDimensions(bytes) ?? {
37
- width: 0,
38
- height: 0
39
- };
40
- return `export default ${JSON.stringify({
41
- url,
42
- responsive: null,
43
- width: size.width,
44
- height: size.height
45
- })};`;
45
+ if (id.includes("?")) return null;
46
+ const ext = extname(id).toLowerCase();
47
+ if (!isInside(root, id)) return rasterFromPackage(id, ext);
48
+ if (!MEDIA_EXTENSIONS.has(ext)) return null;
49
+ const { asset, value } = fixtureMediaModule(id, await readFile(id));
50
+ assets.set(asset.url, asset);
51
+ return `export default ${JSON.stringify(value)};`;
46
52
  }
47
53
  };
48
54
  }
55
+ async function rasterFromPackage(id, ext) {
56
+ if (!RASTER_EXTENSIONS.has(ext)) return null;
57
+ const size = imageDimensions(await readFile(id)) ?? {
58
+ width: 0,
59
+ height: 0
60
+ };
61
+ const url = `/@fs/${toPosixPath(id).replace(/^\/+/, "")}`;
62
+ return `export default ${JSON.stringify({
63
+ url,
64
+ responsive: null,
65
+ width: size.width,
66
+ height: size.height
67
+ })};`;
68
+ }
49
69
  async function createDevVite(options) {
50
70
  const { root, packageRoot } = options;
51
71
  const pathsPlugin = await createTsconfigPathsPlugin(root);
@@ -60,7 +80,7 @@ async function createDevVite(options) {
60
80
  markerSpecifier: options.markerSpecifier
61
81
  }),
62
82
  react(),
63
- authorImagePlugin(root),
83
+ fixtureMediaVitePlugin(root, options.assets),
64
84
  ...pathsPlugin === null ? [] : [pathsPlugin]
65
85
  ],
66
86
  server: {
@@ -80,6 +100,42 @@ async function createDevVite(options) {
80
100
  }
81
101
  });
82
102
  }
103
+ /**
104
+ * Resolves once the browser graph reachable from `entryUrls` has been transformed and the
105
+ * dependency optimizer has committed every package that graph imports. Never rejects: a
106
+ * module that fails to transform is left for the page to report.
107
+ *
108
+ * A capture awaits this before Chromium opens a page. A package import Vite first meets
109
+ * mid-page — one the dependency scan missed, or one added after the cache under
110
+ * `node_modules/.vite` was written — re-optimizes, and when that moves an optimized file
111
+ * Vite FULL-RELOADS every open page, destroying the one a capture is settling. Met here,
112
+ * with no page open, the reload lands on nobody.
113
+ */
114
+ async function settleBrowserDependencies(vite, entryUrls) {
115
+ const client = vite.environments.client;
116
+ const optimizer = client.depsOptimizer;
117
+ const seen = /* @__PURE__ */ new Set();
118
+ const crawl = async (url) => {
119
+ if (seen.has(url) || optimizer?.isOptimizedDepUrl(url) === true) return;
120
+ seen.add(url);
121
+ try {
122
+ await client.transformRequest(url);
123
+ } catch {
124
+ return;
125
+ }
126
+ const node = await client.moduleGraph.getModuleByUrl(url);
127
+ await Promise.all([...node?.importedModules ?? []].map((imported) => crawl(imported.url)));
128
+ };
129
+ await Promise.all(entryUrls.map(crawl));
130
+ if (optimizer === void 0) return;
131
+ for (;;) {
132
+ await optimizer.scanProcessing;
133
+ const pending = Object.values(optimizer.metadata.discovered).flatMap((dep) => dep.processing === void 0 ? [] : [dep.processing]);
134
+ if (pending.length === 0) break;
135
+ await Promise.all(pending);
136
+ }
137
+ await new Promise((resolveTurn) => setImmediate(resolveTurn));
138
+ }
83
139
 
84
140
  //#endregion
85
- export { authorImagePlugin, createDevVite };
141
+ export { createDevVite, fixtureMediaVitePlugin, settleBrowserDependencies };
@@ -5,7 +5,6 @@ import { renderInstanceSlots } from "../../fixtures/media.js";
5
5
  import { materializeTemplate, resolveEdit } from "../../template/materialize.js";
6
6
  import { loadFixtures } from "../../fixtures/load.js";
7
7
  import { resolveFixture } from "../../fixtures/resolve.js";
8
- import { synthesizeEmptyFixtures } from "../../fixtures/synthesize-empties.js";
9
8
  import { materializeSection } from "../../section/materialize.js";
10
9
  import { loadTemplateModule } from "./load-template.js";
11
10
  import { createElement } from "react";
@@ -74,8 +73,7 @@ function hostFixture(fixture, sizeOf) {
74
73
  facts: fixture.facts,
75
74
  media,
76
75
  instances: fixture.contentDoc.instances,
77
- provenance: fixture.provenance,
78
- ...fixture.synthesized ? { synthesized: true } : {}
76
+ provenance: fixture.provenance
79
77
  };
80
78
  }
81
79
  var DevWorkspace = class {
@@ -144,13 +142,11 @@ var DevWorkspace = class {
144
142
  if (result.resolved !== null) resolved.set(fixture.id, result.resolved);
145
143
  }
146
144
  const authored = loaded.fixtures.flatMap((f) => resolved.get(f.id) ?? []);
147
- const first = authored[0];
148
- const empties = first === void 0 ? [] : synthesizeEmptyFixtures(first, materialized.placements);
149
145
  const sizeOf = (url) => loaded.assets.get(url)?.bytes;
150
146
  return {
151
147
  loaded,
152
148
  resolved,
153
- hosted: [...authored, ...empties].map((fixture) => hostFixture(fixture, sizeOf)),
149
+ hosted: authored.map((fixture) => hostFixture(fixture, sizeOf)),
154
150
  violations
155
151
  };
156
152
  })();
@@ -15,6 +15,31 @@ const DERIVABLE_EXTENSIONS = /* @__PURE__ */ new Set([
15
15
  ".webp",
16
16
  ".avif"
17
17
  ]);
18
+ /**
19
+ * The rungs of `rungs` a rendered frame can ever select, for a master `width` wide whose
20
+ * long edge is `longEdge`: every rung at least `floor` px wide, plus the top rung.
21
+ *
22
+ * A rendered template's page is a frame document whose window is exactly the format's
23
+ * box — the canvas scales the iframe, it never narrows it — so an unsized `<Image>`
24
+ * (`sizes` defaults to `100vw`) asks for the frame width times the device pixel ratio,
25
+ * and a candidate narrower than the frame is never the one a DPR >= 1 screen picks. The
26
+ * top rung stays whatever its width: it is what a frame wider than the master picks.
27
+ *
28
+ * Dropping a candidate can never degrade a render, whatever `sizes` an author wrote or
29
+ * whatever DPR a browser has: every rung kept is wider than every rung dropped, so a
30
+ * browser choosing from the kept set lands on the rung it chose before or a wider one.
31
+ * Measured on a `deck16x9` canvas at DPR 1, 2 and 3: every image fetched exactly one
32
+ * candidate, and never one narrower than the frame unless it was the master's top rung.
33
+ *
34
+ * `width` is estimated per rung the way `encodeRung` resizes (`fit: inside` on the long
35
+ * edge), before encoding, so a dropped rung costs no encode. An off-by-one at the floor
36
+ * only decides whether one more candidate ships, never what a frame shows.
37
+ */
38
+ function frameReachableRungs(rungs, width, longEdge, floor) {
39
+ if (floor === void 0 || floor <= 0 || longEdge <= 0 || rungs.length === 0) return [...rungs];
40
+ const top = rungs[rungs.length - 1];
41
+ return rungs.filter((edge) => edge === top || Math.round(width * Math.min(edge, longEdge) / longEdge) >= floor);
42
+ }
18
43
  /** 8 hex chars of sha256 over the master's bytes — the shared stem of every derivative. */
19
44
  function masterHash(bytes) {
20
45
  return createHash("sha256").update(bytes).digest("hex").slice(0, 8);
@@ -152,7 +177,8 @@ async function deriveAuthorImage(absPath, bytes, opts = {}) {
152
177
  const hash = masterHash(bytes);
153
178
  const stem = basename(absPath, extname(absPath));
154
179
  if (!SAFE_STEM.test(stem)) throw new UnsafeStemError(absPath, stem);
155
- const masterKey = `${stem}|${hash}`;
180
+ const floor = opts.minRungWidth !== void 0 && opts.minRungWidth > 0 ? opts.minRungWidth : void 0;
181
+ const masterKey = floor === void 0 ? `${stem}|${hash}` : `${stem}|${hash}|frame${String(floor)}`;
156
182
  const memoKey = `${opts.cacheDir ?? ""}|${masterKey}`;
157
183
  const master = masterAsset(absPath, hash, bytes);
158
184
  const memoHit = derivationCache.get(memoKey);
@@ -190,7 +216,8 @@ async function deriveAuthorImage(absPath, bytes, opts = {}) {
190
216
  const { encodeRung, formatPolicyFor, rungsFor } = await loadImageLadder();
191
217
  const buffer = Buffer.from(bytes);
192
218
  const meta = await sharp(buffer).metadata();
193
- const rungs = rungsFor(Math.max(meta.width ?? 0, meta.height ?? 0));
219
+ const longEdge = Math.max(meta.width ?? 0, meta.height ?? 0);
220
+ const rungs = frameReachableRungs(rungsFor(longEdge), meta.width ?? 0, longEdge, floor);
194
221
  const specs = formatPolicyFor({
195
222
  format: meta.format,
196
223
  hasAlpha: meta.hasAlpha
@@ -249,4 +276,4 @@ async function deriveAuthorImage(absPath, bytes, opts = {}) {
249
276
  }
250
277
 
251
278
  //#endregion
252
- export { DERIVABLE_EXTENSIONS, UnsafeStemError, deriveAuthorImage, mapConcurrent, masterHash };
279
+ export { DERIVABLE_EXTENSIONS, UnsafeStemError, deriveAuthorImage, frameReachableRungs, mapConcurrent, masterHash };
@@ -6,7 +6,8 @@ import { readFile } from "node:fs/promises";
6
6
  const NAMESPACE = "media-deriver";
7
7
  const RESOLVING = Symbol("media-deriver:resolving");
8
8
  const RASTER_FILTER = /\.(?:[jJ][pP][eE]?[gG]|[pP][nN][gG]|[wW][eE][bB][pP]|[aA][vV][iI][fF])$/;
9
- /** A fresh deriver per esbuild pass; `cacheDir` opts it into the on-disk ladder cache. */
9
+ /** A fresh deriver per esbuild pass; `cacheDir` opts it into the on-disk ladder cache, and
10
+ * `minRungWidth` (a rendered template's frame width) drops the rungs no frame selects. */
10
11
  function createMediaDeriver(opts = {}) {
11
12
  const derived = /* @__PURE__ */ new Map();
12
13
  const masters = /* @__PURE__ */ new Map();
@@ -38,7 +39,10 @@ function createMediaDeriver(opts = {}) {
38
39
  namespace: NAMESPACE
39
40
  }, async (args) => {
40
41
  const bytes = await readFile(args.path);
41
- const derivation = await deriveAuthorImage(args.path, bytes, { cacheDir: opts.cacheDir });
42
+ const derivation = await deriveAuthorImage(args.path, bytes, {
43
+ cacheDir: opts.cacheDir,
44
+ minRungWidth: opts.minRungWidth
45
+ });
42
46
  for (const asset of derivation.derivatives) derived.set(asset.filename, asset);
43
47
  const { key, filename, bytes: masterBytes, contentType } = derivation.master;
44
48
  derived.set(filename, {
@@ -0,0 +1,18 @@
1
+ import { captureViewport } from "../../packages/internal/format-geometry/dist/capture.js";
2
+ import "../../packages/internal/format-geometry/dist/index.js";
3
+
4
+ //#region src/cli/media/frame-rung-floor.ts
5
+ /**
6
+ * The frame width, in CSS px at DPR 1, of the template's narrowest declared format —
7
+ * undefined for a website, whose pages are served at any viewport and keep the full
8
+ * ladder. The narrowest, so a multi-format template keeps every rung any of its frames
9
+ * can select.
10
+ */
11
+ function frameRungFloor(template) {
12
+ if (template.output === "website") return void 0;
13
+ const widths = template.formats.filter((format) => format.width !== void 0).map((format) => captureViewport(format).width);
14
+ return widths.length === 0 ? void 0 : Math.min(...widths);
15
+ }
16
+
17
+ //#endregion
18
+ export { frameRungFloor };
@@ -1,8 +1,11 @@
1
1
  import { compileFormatVariantsToCss } from "../design-system/format-variants.js";
2
2
  import { collectCssGraph } from "./graph.js";
3
3
  import { inlineCssGraph } from "./inline.js";
4
- import { externalUrlViolations, tailwindImportViolations } from "./rules.js";
4
+ import { externalUrlViolations, retiredLayerViolations, tailwindImportViolations } from "./rules.js";
5
+ import { readFileSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
5
7
  import { createHash } from "node:crypto";
8
+ import { createRequire } from "node:module";
6
9
  import { compile, optimize } from "@tailwindcss/node";
7
10
  import { Scanner } from "@tailwindcss/oxide";
8
11
 
@@ -17,10 +20,26 @@ function buildTailwindEntry(inlinedCss, template) {
17
20
  if (template.output === "website") return inlinedCss;
18
21
  return `${inlinedCss.trimEnd()}\n\n${compileFormatVariantsToCss(template.formats)}`;
19
22
  }
23
+ const TAILWIND_PACKAGE = "tailwindcss";
24
+ /**
25
+ * The framework's own file for a `tailwindcss` stylesheet import — `tailwindcss` or a
26
+ * subpath such as `tailwindcss/theme.css` — read from the package's `style` export.
27
+ * Undefined for any other specifier, and for a subpath the package does not export as
28
+ * a stylesheet, which Tailwind's own resolver then reports.
29
+ */
30
+ function resolveFrameworkTailwindCss(id) {
31
+ if (id !== TAILWIND_PACKAGE && !id.startsWith(`${TAILWIND_PACKAGE}/`)) return void 0;
32
+ const manifest = createRequire(import.meta.url).resolve(`${TAILWIND_PACKAGE}/package.json`);
33
+ const { exports } = JSON.parse(readFileSync(manifest, "utf8"));
34
+ const entry = exports[id === TAILWIND_PACKAGE ? "." : `.${id.slice(11)}`];
35
+ const file = typeof entry === "string" ? entry : entry?.style;
36
+ return file === void 0 ? void 0 : join(dirname(manifest), file);
37
+ }
20
38
  async function compileTailwind(root, entry) {
21
39
  const compiler = await compile(entry, {
22
40
  base: root,
23
- onDependency: () => {}
41
+ onDependency: () => {},
42
+ customCssResolver: (id) => Promise.resolve(resolveFrameworkTailwindCss(id))
24
43
  });
25
44
  const scanner = new Scanner({ sources: [...compiler.root === "none" ? [] : compiler.root === null ? [{
26
45
  base: root,
@@ -53,12 +72,15 @@ async function compileTemplateCss(input) {
53
72
  violations: importViolations
54
73
  };
55
74
  const css = await compileTailwind(input.root, buildTailwindEntry(inlined.css, input.template));
56
- const violations = input.template.output === "website" ? [] : await externalUrlViolations({
75
+ const violations = [...await retiredLayerViolations({
76
+ root: input.root,
77
+ sources: graph
78
+ }), ...input.template.output === "website" ? [] : await externalUrlViolations({
57
79
  root: input.root,
58
80
  templateFile: input.templateFile,
59
81
  css,
60
82
  sources: graph
61
- });
83
+ })];
62
84
  const bytes = new TextEncoder().encode(css);
63
85
  const contentHash = createHash("sha256").update(bytes).digest("hex");
64
86
  return {
package/dist/css/graph.js CHANGED
@@ -26,6 +26,7 @@ const EMPTY_LOADERS = Object.fromEntries([
26
26
  ".pdf",
27
27
  ".zip"
28
28
  ].map((ext) => [ext, "empty"]));
29
+ const INTERCEPTED_FILTER = /^[^./]|\.css$/;
29
30
  function isOwnResolve(pluginData) {
30
31
  return typeof pluginData === "object" && pluginData !== null && pluginData.concreteCssGraph === true;
31
32
  }
@@ -33,7 +34,7 @@ function graphPlugin() {
33
34
  return {
34
35
  name: "concrete-css-graph",
35
36
  setup(api) {
36
- api.onResolve({ filter: /.*/ }, async (args) => {
37
+ api.onResolve({ filter: INTERCEPTED_FILTER }, async (args) => {
37
38
  if (args.kind === "entry-point" || isOwnResolve(args.pluginData)) return void 0;
38
39
  if (UNFOLLOWED_RE.test(args.path)) return {
39
40
  path: args.path,