@xemahq/repo-build-tooling 0.25.1 → 0.26.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.
@@ -1,28 +1,29 @@
1
1
  // `xema-composed-image dockerfile --prebuilt --write|--check`: renders
2
- // `<image-dir>/Dockerfile` AND `<image-dir>/Dockerfile.dockerignore` for the image that
3
- // is ASSEMBLED from build outputs made on the CI runner (`xema-composed-image stage`).
4
- // Docker compiles nothing. The full-build template (`composed-image-dockerfile.mjs`)
2
+ // `<image-dir>/Dockerfile` AND `<image-dir>/Dockerfile.dockerignore` for the image that is
3
+ // COPIED from a tree the CI runner staged (`xema-composed-image stage`). Docker installs nothing,
4
+ // compiles nothing and reaches no network. The full-build template (`composed-image-dockerfile.mjs`)
5
5
  // stays available for repositories that still build inside Docker.
6
- import { execFileSync } from 'node:child_process';
7
- import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
8
7
  import { dirname, join, posix } from 'node:path';
9
8
 
10
- import { COMPOSED_IMAGE_DIR, IN_IMAGE_ENTRY, NODE_MAJOR_LABEL } from './composed-image-paths.mjs';
9
+ import { COMPOSED_IMAGE_DIR, COMPOSED_MANIFEST_FILE, IN_IMAGE_ENTRY, NODE_MAJOR_LABEL, PROOF_DIRECTORY, STAGE_APP_LAYER, STAGE_PROOF_DIRECTORY, STAGE_STORE_LAYER, VERIFIED_IMAGE_FILE } from './composed-image-paths.mjs';
11
10
  import { toolVersion } from './composed-image-stage.mjs';
12
- import { npmrcUsesToken } from './composed-image-dockerfile.mjs';
13
- import { IGNORED_DIRECTORIES, IGNORED_FILE_PATTERNS, packageSources } from './composed-image-package-files.mjs';
14
- import { memberClosure, memberFilters, memberManifests } from './composed-image-members.mjs';
15
- import { needsPrismaSchemaEngine } from './composed-image-prisma-engine.mjs';
11
+ import { IGNORED_DIRECTORIES, IGNORED_FILE_PATTERNS } from './composed-image-package-files.mjs';
12
+ import { memberFilters } from './composed-image-members.mjs';
13
+ import { CONTEXT_DIRECTORY, rootBuildInputNames } from './staged-image-proof.mjs';
16
14
 
17
15
  export const DEFAULT_STAGE_DIR = '.xema-stage';
18
16
  const DIRECTORY = /^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*\/?$/;
19
- const CACHE_ID = /^[a-z0-9][a-z0-9-]*$/;
20
17
  const REPOSITORY = /^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/;
21
18
  const DIGEST_REFERENCE = /^[a-z0-9][a-z0-9._/-]*(:[A-Za-z0-9._-]+)?@sha256:[0-9a-f]{64}$/;
19
+ /** The image label that carries the repository its member index names; the stage reads it back from the committed Dockerfile. */
20
+ export const BUILD_SOURCE_LABEL = 'dev.xema.composed-image.build-source';
21
+ /** Where the proof stage puts the `--copy` directories, so the build context's bytes are what the stage hashed. */
22
+ const COPIED_DIRECTORY = `${PROOF_DIRECTORY}/copied`;
22
23
 
23
24
  const NODE_MAJOR = /^[1-9][0-9]*$/;
24
25
 
25
- function validate({ copy, cacheId, buildSource, stageDir, base, nodeMajor }) {
26
+ function validate({ copy, buildSource, stageDir, base, nodeMajor }) {
26
27
  if (!NODE_MAJOR.test(nodeMajor ?? '')) throw new Error(`--node-major must be the Node major of the --base image (e.g. 22), got "${nodeMajor}"`);
27
28
  if (!DIGEST_REFERENCE.test(base ?? '')) throw new Error(`--base must be an image reference pinned by digest (<ref>@sha256:<64 hex>), got "${base}"`);
28
29
  for (const directory of [...(copy ?? []), stageDir]) {
@@ -30,309 +31,106 @@ function validate({ copy, cacheId, buildSource, stageDir, base, nodeMajor }) {
30
31
  throw new Error(`"${directory}" is not a repository-relative directory`);
31
32
  }
32
33
  }
33
- if (!CACHE_ID.test(cacheId ?? '')) throw new Error(`--cache-id must be lowercase [a-z0-9-], got "${cacheId}"`);
34
34
  if (!REPOSITORY.test(buildSource ?? '')) throw new Error(`--build-source must name a repository, got "${buildSource}"`);
35
35
  }
36
36
 
37
- /** The ignore file: the build context carries sources, never local build output, except the staged outputs. */
37
+ /** The ignore file: the build context carries sources, never local build output, except the staged tree. */
38
38
  export function renderPrebuiltDockerignore({ stageDir = DEFAULT_STAGE_DIR } = {}) {
39
39
  return `# @generated by \`xema-composed-image dockerfile --prebuilt --write\` — DO NOT EDIT.
40
- # Local build output stays out of the context; the staged outputs carry dist and node_modules/.prisma paths, so they are re-included LAST.
40
+ # Local build output stays out of the context; the staged tree carries dist and node_modules paths, so it is re-included LAST.
41
41
  .git
42
42
  ${[...IGNORED_DIRECTORIES.map((d) => `**/${d}`), ...IGNORED_FILE_PATTERNS.map((p) => `**/${p}`)].join('\n')}
43
43
  !${stageDir}/**
44
44
  `;
45
45
  }
46
46
 
47
- /** The `onlyBuiltDependencies:` items of a `pnpm-workspace.yaml` text (block list; comments skipped; ends at the next top-level key). */
48
- export function onlyBuiltDependencies(workspaceYaml) {
49
- const names = [];
50
- let inList = false;
51
- for (const line of workspaceYaml.split('\n')) {
52
- if (!inList) {
53
- inList = /^onlyBuiltDependencies:\s*(#.*)?$/.test(line);
54
- continue;
55
- }
56
- if (/^\s*(#.*)?$/.test(line)) continue;
57
- if (/^\S/.test(line)) break;
58
- const item = /^\s+-\s+(?:'([^']*)'|"([^"]*)"|([^\s#]+))\s*(?:#.*)?$/.exec(line);
59
- if (item === null) throw new Error(`pnpm-workspace.yaml: cannot read onlyBuiltDependencies item "${line.trim()}"`);
60
- names.push(item[1] ?? item[2] ?? item[3]);
61
- }
62
- for (const name of names) {
63
- if (!/^[@A-Za-z0-9._/-]+$/.test(name)) throw new Error(`pnpm-workspace.yaml: onlyBuiltDependencies "${name}" is not a package name`);
64
- }
65
- return names;
66
- }
47
+ const normalizedCopy = (copy) => [...new Set(copy.map((d) => posix.normalize(`${d}/`)))];
48
+ const copyLine = (directory) => `COPY ${directory} /${COPIED_DIRECTORY}/${directory}`;
67
49
 
68
- /** The install-flag word the rendered RUN keeps as a shell variable; `injectFlags()` is what it expands to. */
69
- export const INJECT_TOKEN = '${INJECT}';
70
- export const injectFlags = () => ['--config.inject-workspace-packages=true', '--config.dedupe-injected-deps=false'];
71
-
72
- /**
73
- * The deps stage's `--lockfile-only` resolve, as words (`INJECT_TOKEN` stands for `injectFlags()`).
74
- * The image runs it `--offline` against the metadata cache `pnpm-context --image-dir` warmed; the warm-up
75
- * runs the SAME words with `--prefer-offline` (`offline: false`). Both read THIS function, so the metadata
76
- * the context holds is exactly what the image resolves.
77
- */
78
- export const lockfileOnlyWords = (filters, { offline = true } = {}) =>
79
- ['pnpm', 'install', '--lockfile-only', offline ? '--offline' : '--prefer-offline', INJECT_TOKEN, ...filters];
80
- /** The same command with the inject words expanded: `[file, ...args]`. `offline: false` is the cache warm-up form. */
81
- export const lockfileOnlyCommand = (filters, options) => lockfileOnlyWords(filters, options).flatMap((w) => (w === INJECT_TOKEN ? injectFlags() : [w]));
82
-
83
- /** The line that brings one `--copy` directory into the deps stage; `depsCopyDirs` is its inverse (pnpm-context reads the directories back from the committed Dockerfile). */
84
- const copyLine = (directory) => `COPY ${directory} ./${directory}`;
85
- export function depsCopyDirs(dockerfileText) {
86
- const deps = /^FROM base AS deps\n([\s\S]*?)^COPY --parents/m.exec(dockerfileText);
87
- if (deps === null) throw new Error('the Dockerfile has no deps stage with COPY --parents — render it: xema-composed-image dockerfile --prebuilt --write');
88
- return [...deps[1].matchAll(/^COPY (\S+\/) \.\/\1$/gm)].map((m) => m[1]);
50
+ /** What the stage reads back from the committed Dockerfile, so the stage and the render have one definition: the `--copy` directories and the build source. */
51
+ export function parseRenderedDockerfile(dockerfileText) {
52
+ const copy = [...dockerfileText.matchAll(new RegExp(`^COPY (\\S+/) /${COPIED_DIRECTORY}/\\1$`, 'gm'))].map((m) => m[1]);
53
+ const buildSource = new RegExp(`^LABEL ${BUILD_SOURCE_LABEL.replaceAll('.', '\\.')}="([^"]+)"$`, 'm').exec(dockerfileText)?.[1];
54
+ if (buildSource === undefined) throw new Error('the Dockerfile carries no build-source label — render it: xema-composed-image dockerfile --prebuilt --write');
55
+ return { copy, buildSource };
89
56
  }
90
57
 
91
- /** Build-script dependencies the image never runs: Prisma 7 with the pg adapter ships no engine (migrations run in-app), the rest are JS or fetch nothing the image needs. */
92
- export const REBUILD_EXCLUDED = Object.freeze(['prisma', '@prisma/client', '@prisma/engines', '@nestjs/core', 'esbuild', '@swc/core']);
93
-
94
- /**
95
- * The `onlyBuiltDependencies` the image must still `pnpm rebuild`: those in the members' PROD closure
96
- * (`prodPackages`: `[{ name, dir }]`) less `REBUILD_EXCLUDED`. A module that needs `node-gyp` (a `binding.gyp`
97
- * and no optional prebuilt packages) cannot be built here (the install is offline, `--ignore-scripts`, and the base
98
- * has no toolchain), so it is refused: build it on a runner of the target arch and stage the `.node` files.
99
- */
100
- export function rebuildList({ built, prodPackages }) {
101
- const present = new Map(prodPackages.map((p) => [p.name, p.dir]));
102
- const names = built.filter((name) => !REBUILD_EXCLUDED.includes(name) && present.has(name));
103
- for (const name of names) {
104
- const dir = present.get(name);
105
- let optional = 0;
106
- try {
107
- optional = Object.keys(JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).optionalDependencies ?? {}).length;
108
- } catch {
109
- /* unreadable manifest: judged by binding.gyp alone */
110
- }
111
- if (existsSync(join(dir, 'binding.gyp')) && optional === 0) {
112
- throw new Error(
113
- `${name} needs node-gyp (binding.gyp, no optional prebuilt packages) and no native artifact is staged for it: ` +
114
- 'the prebuilt composed image installs offline with --ignore-scripts and has no toolchain. ' +
115
- 'Build it on a runner of each target arch (the arm runner for arm64) and stage the .node files; see the arm64 native-artifact note in composed-image-prebuilt-dockerfile.mjs. Refusing to render.',
116
- );
117
- }
118
- }
119
- return names;
120
- }
121
-
122
- const defaultExec = (file, args, { cwd }) => execFileSync(file, args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
123
-
124
- /** `[{ name, dir }]` for every installed package in the members' prod closure (`pnpm ls --prod --parseable`); needs `pnpm install` to have run. */
125
- export function memberProdPackages({ root = process.cwd(), imageDir = COMPOSED_IMAGE_DIR, exec = defaultExec } = {}) {
126
- const words = memberFilters({ root, imageDir }).flatMap((f) => f.split(' '));
127
- const listing = exec('pnpm', ['ls', '-r', '--prod', '--depth', 'Infinity', '--parseable', ...words], { cwd: root });
128
- const seen = new Map();
129
- for (const line of listing.split('\n').map((l) => l.trim()).filter(Boolean)) {
130
- if (!line.includes('node_modules')) continue; // workspace packages themselves
131
- let dir;
132
- try {
133
- dir = realpathSync(line);
134
- const name = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name;
135
- if (typeof name === 'string') seen.set(name, dir);
136
- } catch {
137
- /* not an installed package directory */
138
- }
139
- }
140
- if (seen.size === 0) throw new Error('pnpm ls --prod listed no installed package: run pnpm install --frozen-lockfile before rendering the prebuilt Dockerfile');
141
- return [...seen].map(([name, dir]) => ({ name, dir }));
142
- }
143
-
144
- /** Where the deps stage bind-mounts `<stage dir>/prisma-engines` (`<enginesVersion>/schema-engine-<binaryTarget>`). */
145
- const PRISMA_ENGINES_MOUNT = '/xema-prisma-engines';
146
-
147
- /**
148
- * The deps-stage step that puts the Prisma schema engine where Prisma looks, rendered only when the
149
- * prod closure carries the prisma CLI (the one thing that runs the engine). It runs in DEPS so the
150
- * engine lands in `node_modules/.pnpm/@prisma+engines@<v>/node_modules/@prisma/engines/`, which the
151
- * final stage takes from deps (layer 1); assemble's copy excludes the .pnpm store.
152
- */
153
- function prismaSchemaEngineStep({ toolMount, node, stageDir }) {
154
- return `
155
- # The Prisma SCHEMA ENGINE for this image's platform. \`prisma migrate deploy\` runs it (the
156
- # Rust-free client does not replace it), and the prisma CLI downloads it into @prisma/engines
157
- # at RUNTIME when it is missing, which the read-only, non-root container refuses. The install
158
- # above is --ignore-scripts, so @prisma/engines' postinstall never fetched it. The runner
159
- # staged it for every image platform at the lockfile's engines version (Prisma's downloader,
160
- # sha256-checked) in \`${stageDir}/prisma-engines/\`; this copies the one for the platform
161
- # Prisma computes HERE into each @prisma/engines a prisma CLI resolves, and fails the build
162
- # unless it runs and reports that version. Here in deps, so the final stage carries it.
163
- RUN --network=none ${toolMount} \\
164
- --mount=type=bind,source=${stageDir}/prisma-engines,target=${PRISMA_ENGINES_MOUNT} \\
165
- node ${node} prisma-schema-engine ${PRISMA_ENGINES_MOUNT}
166
- `;
167
- }
168
-
169
- const parts = (sources) => sources.map((source) => ` ${source} \\`).join('\n');
170
-
171
- /** The prebuilt Dockerfile text. The closure and the members' literal filters are derived from `root` (`memberClosure`); `exec` is injectable for tests. */
172
- export function renderPrebuiltDockerfile({
173
- root = process.cwd(),
174
- imageDir = COMPOSED_IMAGE_DIR,
175
- copy = [],
176
- cacheId,
177
- buildSource,
178
- usesToken,
179
- stageDir = DEFAULT_STAGE_DIR,
180
- base,
181
- nodeMajor,
182
- exec,
183
- prodPackages = [],
184
- }) {
185
- if (typeof usesToken !== 'boolean') throw new Error('usesToken must be a boolean derived from .npmrc');
186
- validate({ copy, cacheId, buildSource, stageDir, base, nodeMajor });
58
+ /** The prebuilt Dockerfile text. The members' literal filters and the root build inputs are derived from `root`. */
59
+ export function renderPrebuiltDockerfile({ root = process.cwd(), imageDir = COMPOSED_IMAGE_DIR, copy = [], buildSource, stageDir = DEFAULT_STAGE_DIR, base, nodeMajor }) {
60
+ validate({ copy, buildSource, stageDir, base, nodeMajor });
187
61
  const toolingVersion = toolVersion();
188
- const workspaceFile = join(root, 'pnpm-workspace.yaml');
189
- const built = existsSync(workspaceFile) ? onlyBuiltDependencies(readFileSync(workspaceFile, 'utf8')) : [];
190
- if (built.length === 0) {
191
- throw new Error('pnpm-workspace.yaml has no onlyBuiltDependencies: — `pnpm rebuild` would have nothing to build; refusing to render');
192
- }
193
- const closure = memberClosure({ root, imageDir, exec });
194
- const rebuild = rebuildList({ built, prodPackages });
195
62
  const filters = memberFilters({ root, imageDir }).join(' ');
196
- const manifests = memberManifests({ root, imageDir });
63
+ const rootInputs = rootBuildInputNames(root);
197
64
  const dirFlag = imageDir === COMPOSED_IMAGE_DIR ? '' : ` --image-dir ${imageDir}`;
198
65
  const toolDir = '/opt/xema-composed-image';
199
66
  const toolMount = `--mount=type=bind,source=${stageDir}/tool,target=${toolDir}`;
200
67
  const node = `${toolDir}/${IN_IMAGE_ENTRY}`;
201
- const store = '--mount=type=bind,from=xema-pnpm-store,target=/root/.pnpm-store,rw';
202
- const metadata = '--mount=type=bind,from=xema-pnpm,source=cache,target=/root/.cache/pnpm,rw';
203
- const secret = usesToken ? ' --mount=type=secret,id=npm_token,required=true \\\n' : '';
204
- const tokenExport = usesToken
205
- ? 'export NPM_TOKEN="$(cat /run/secrets/npm_token)" && export GH_PACKAGES_TOKEN="$NPM_TOKEN" && \\\n '
206
- : '';
207
- const copies = [...new Set(copy.map((d) => posix.normalize(`${d}/`)))].map(copyLine).join('\n');
208
- const manifestSources = closure.map((directory) => `${directory}/package.json`);
209
- const assembleSources = [...closure.flatMap((directory) => packageSources({ root, directory })), ...manifests];
210
- const imageCopy = posix.normalize(`${imageDir}/`);
211
- const text = `# @generated by \`xema-composed-image dockerfile --prebuilt --write\` (@xemahq/repo-build-tooling@${toolingVersion}) — DO NOT EDIT.
68
+ const copies = normalizedCopy(copy).map(copyLine).join('\n');
69
+ const layers = `COPY ${stageDir}/${STAGE_STORE_LAYER}/ /\nCOPY ${stageDir}/${STAGE_APP_LAYER}/ /`;
70
+ const dockerfile = `# @generated by \`xema-composed-image dockerfile --prebuilt --write\` (@xemahq/repo-build-tooling@${toolingVersion}) — DO NOT EDIT.
212
71
  # Re-render with the same options; \`--check\` refuses a stale file (and a stale Dockerfile.dockerignore).
213
72
  #
214
- # The COMPOSED-PROCESS image of this repository, ASSEMBLED from build outputs: ONE image
215
- # per build (repository at commit), every member of \`image-build-inputs.json\` in ONE module
216
- # graph behind the SDK's \`xema-composed-process\` host. Docker compiles nothing. The CI
217
- # runner ran \`turbo run build prisma:generate\` for the members' closures and
218
- # \`xema-composed-image stage ${stageDir}\` gathered the outputs into the build-step
219
- # directory \`${stageDir}/\` (\`out/\` = dist and generated Prisma clients, pure JS/wasm;
220
- # \`tool/\` = this tool, bind-mounted into the steps below and never copied into a layer).
73
+ # The COMPOSED-PROCESS image of this repository, COPIED from a tree the CI runner staged: ONE
74
+ # image per build (repository at commit), every member of \`image-build-inputs.json\` in ONE module
75
+ # graph behind the SDK's \`xema-composed-process\` host. Docker installs nothing, compiles nothing
76
+ # and has no network. The runner built the members (\`turbo run build prisma:generate\`) and
77
+ # \`xema-composed-image stage ${stageDir} --platform linux/<arch>\` produced, from the job's own
78
+ # pnpm store, the production tree of the members' closures for that platform (the install, the
79
+ # injected workspace packages, the member index, the Prisma clients and the platform's schema
80
+ # engine) and wrote it to \`${stageDir}/${STAGE_STORE_LAYER}/\` (the \`.pnpm\` packages, stable until the lockfile changes) and
81
+ # \`${stageDir}/${STAGE_APP_LAYER}/\` (everything else). \`${stageDir}/tool/\` is this tool, bind-mounted into the steps
82
+ # below and never copied into a layer.
221
83
  #
222
84
  # Stages:
223
- # deps arch-native. Inputs are the lockfile and the closure's manifests ONLY, so the
224
- # layer is cached until one of them changes. OFFLINE: every install RUN is
225
- # \`--network=none\` and reads only the CI runner's pnpm store (\`xema-pnpm-store\`
226
- # context), the packed pnpm and the warmed registry-metadata cache (\`xema-pnpm\`
227
- # context, built by \`xema-composed-image pnpm-context --image-dir\`). corepack
228
- # installs pnpm from that tarball, never from the network. Production install with
229
- # the workspace packages INJECTED and \`--ignore-scripts\`. \`pnpm rebuild <names>\`
230
- # runs only for \`onlyBuiltDependencies\` present in the members' PROD closure, less
231
- # prisma, @prisma/client, @prisma/engines (Prisma 7 + pg adapter ships no engine and
232
- # migrations run in-app), @nestjs/core, esbuild and @swc/core; when none is left the
233
- # step is not rendered. The list is rendered, so a change makes \`--check\` stale.
234
- # assemble source of the closure + the staged outputs, the injected copies synced to
235
- # their \`files\`, then the proofs on the target arch: Prisma clients run, the
236
- # member index is written, every member loads ALONE as \`node\`, production.
237
- # (final) \`/monorepo\` of assemble, shipped as THREE layers so a commit that changes only
238
- # members' code re-pushes only the layers that changed (see the final stage).
239
- # Nothing of the tool ships.
240
- #
241
- # NATIVE MODULES. No prod-closure module needs node-gyp today. The renderer REFUSES to render when
242
- # one appears (a \`binding.gyp\` and no optional prebuilt packages) because this image installs with
243
- # --ignore-scripts and carries no compiler. The path then: build the module on a runner of EACH target
244
- # arch natively (the \`arm\` runner for arm64; no QEMU), in the digest-pinned bookworm node image with
245
- # --network=none and the image's node headers, stage \`native/<arch>/<pkg>/*.node\`, and COPY them from
246
- # \`native/\${TARGETARCH}/\` in the deps stage.
85
+ # proof The staged tree and the repository's inputs meet. The root build inputs that decide the
86
+ # staged bytes are COPIED into \`/${PROOF_DIRECTORY}/${CONTEXT_DIRECTORY}/\` and the \`--copy\` directories into
87
+ # \`/${COPIED_DIRECTORY}/\`, which puts them in the image's content tag. \`prove\` refuses the build unless the
88
+ # stage was made at BUILD_SHA from exactly those bytes, with this tool, for this platform, and
89
+ # the literal \`--filter\` words below are the ones it staged. Then the Prisma clients run and every
90
+ # member loads ALONE as \`node\`, production, on the target arch.
91
+ # (final) the same two COPYs of the staged tree, plus the proof's verdict, so the image cannot exist without it.
247
92
  #
248
93
  # The \`--filter <package>...\` words below are LITERAL: the content hash of this image reads
249
94
  # them to narrow the lockfile to the members' closures.
250
- FROM scratch AS xema-pnpm
251
- FROM scratch AS xema-pnpm-store
252
-
253
95
  FROM ${base} AS base
254
- RUN corepack enable && \\
255
- pnpm config set store-dir /root/.pnpm-store
256
96
 
257
- FROM base AS deps
258
- WORKDIR /monorepo
259
- ENV CI=true
260
- # corepack must not download pnpm: the packed tarball comes from the runner.
261
- ENV COREPACK_ENABLE_NETWORK=0
262
- # The runner's store is bind-mounted here. Set it for pnpm explicitly: the base layer's \`pnpm config set\` was
263
- # written by whatever pnpm corepack fetched then, and an offline resolve falls back to the store index.
264
- ENV npm_config_store_dir=/root/.pnpm-store
265
- COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
266
- ${copies === '' ? '' : `${copies}\n`}COPY --parents \\
267
- ${parts(manifestSources)}
268
- ./
269
- RUN --network=none --mount=type=bind,from=xema-pnpm,target=/xema-pnpm \\
270
- test -f /xema-pnpm/staged.json || { \\
271
- echo "the prebuilt composed image needs --build-context xema-pnpm and xema-pnpm-store (CI only); render the full image (no --prebuilt) to build elsewhere" >&2; \\
272
- exit 1; \\
273
- } && corepack install -g /xema-pnpm/corepack/pnpm.tgz
274
- RUN --network=none ${store} \\
275
- ${metadata} \\
276
- ${secret} ${toolMount} \\
277
- ${tokenExport}INJECT="${injectFlags().join(' ')}" && \\
278
- cp pnpm-lock.yaml /tmp/pnpm-lock.committed.yaml && \\
279
- ${lockfileOnlyWords(filters.split(' ')).join(' ')} && \\
280
- node ${node} pins${dirFlag} /tmp/pnpm-lock.committed.yaml && \\
281
- pnpm install --prod --offline --ignore-scripts \${INJECT} ${filters} --frozen-lockfile${rebuild.length === 0 ? '' : ` && \\
282
- pnpm rebuild ${rebuild.join(' ')} ${filters}`}
283
- ${needsPrismaSchemaEngine(prodPackages) ? prismaSchemaEngineStep({ toolMount, node, stageDir }) : ''}
284
- FROM deps AS assemble
285
- COPY --parents \\
286
- ${parts(assembleSources)}
287
- ./
288
- COPY ${imageCopy} ./${imageCopy}
289
- COPY ${stageDir}/out/ ./
97
+ FROM base AS proof
98
+ WORKDIR /${PROOF_DIRECTORY}
290
99
  ARG BUILD_SHA
291
- RUN ${toolMount} \\
100
+ COPY ${stageDir}/${STAGE_PROOF_DIRECTORY}/${COMPOSED_MANIFEST_FILE} /${PROOF_DIRECTORY}/
101
+ COPY ${rootInputs.join(' ')} /${PROOF_DIRECTORY}/${CONTEXT_DIRECTORY}/
102
+ ${copies === '' ? '' : `${copies}\n`}${layers}
103
+ RUN --network=none ${toolMount} \\
104
+ : "\${BUILD_SHA:?BUILD_SHA build-arg is required}" && \\
292
105
  T="node ${node}" && \\
293
- $T sync-injected${dirFlag} && $T prisma-check${dirFlag} && \\
294
- : "\${BUILD_SHA:?BUILD_SHA build-arg is required}" && $T index "\${BUILD_SHA}" --build-source ${buildSource}${dirFlag} && \\
295
- cp ${toolDir}/src/composed-migrate.mjs /monorepo/xema-composed-migrate.mjs
106
+ $T prove /${PROOF_DIRECTORY} --root /monorepo --commit "\${BUILD_SHA}" ${filters}${dirFlag} && \\
107
+ $T prisma-check --root /monorepo${dirFlag}
296
108
 
297
109
  # Every member's module graph loads here, ALONE (one process each), through the host's own
298
110
  # entry reader, as the user and NODE_ENV the image runs with, or the image is never pushed.
299
111
  USER node
300
- RUN ${toolMount} \\
301
- NODE_ENV=production node ${node} load --each${dirFlag}
112
+ RUN --network=none ${toolMount} \\
113
+ NODE_ENV=production node ${node} load --each --root /monorepo${dirFlag}
302
114
 
303
- # The final stage is layered by how often each part changes, so a registry and a node
304
- # already holding the stable layers fetch only the rest. The three copies overlay to
305
- # exactly assemble's /monorepo (proven by a tree diff of both images).
306
- # 1 deps root manifests, the external .pnpm store, and the injected stubs that hold
307
- # only package.json. Stable while the lockfile and the closure's package.json
308
- # files are unchanged.
309
- # 2 assemble members, dist, Prisma clients, member index, migrate script: everything
310
- # but the .pnpm store, whose packages layer 1 already carries.
311
- # 3 injected the workspace copies \`node_modules/.pnpm/*@file+*\`: \`sync-injected\` fills
312
- # them from the members' files, so they change with every commit. \`--parents\`
313
- # keeps their paths under /.
314
115
  FROM base
315
116
  WORKDIR /monorepo
316
117
  LABEL ${NODE_MAJOR_LABEL}="${nodeMajor}"
317
- COPY --from=deps /monorepo /monorepo
318
- COPY --from=assemble --exclude=node_modules/.pnpm /monorepo /monorepo
319
- COPY --from=assemble --parents /monorepo/node_modules/.pnpm/*@file+* /
118
+ ${layers}
119
+ COPY --from=proof /${PROOF_DIRECTORY}/${VERIFIED_IMAGE_FILE} /monorepo/${VERIFIED_IMAGE_FILE}
120
+ LABEL ${BUILD_SOURCE_LABEL}="${buildSource}"
320
121
  ENV NODE_ENV=production
321
122
  # Set by the IMAGE, never by a deployment (kernel \`COMPOSED_PROCESS_ENV.MemberIndex\`).
322
123
  ENV XEMA_COMPOSED_MEMBER_INDEX=/monorepo/xema-composed-member-index.json
323
124
  USER node
324
125
  CMD ["node", "/monorepo/xema-composed-process"]
325
126
  `;
326
- return { dockerfile: text, dockerignore: renderPrebuiltDockerignore({ stageDir }), closure };
127
+ return { dockerfile, dockerignore: renderPrebuiltDockerignore({ stageDir }) };
327
128
  }
328
129
 
329
130
  /** `--write` writes both files; `--check` throws when either differs. */
330
- export function syncPrebuiltDockerfile({ mode, root = process.cwd(), imageDir = COMPOSED_IMAGE_DIR, exec, ...options }) {
131
+ export function syncPrebuiltDockerfile({ mode, root = process.cwd(), imageDir = COMPOSED_IMAGE_DIR, ...options }) {
331
132
  if (mode !== 'write' && mode !== 'check') throw new Error(`mode must be write or check, got "${mode}"`);
332
- const npmrc = join(root, '.npmrc');
333
- if (!existsSync(npmrc)) throw new Error(`${npmrc} is absent — the Dockerfile copies it and its token use decides the build secret`);
334
- const prodPackages = options.prodPackages ?? memberProdPackages({ root, imageDir, exec });
335
- const { dockerfile, dockerignore } = renderPrebuiltDockerfile({ ...options, root, imageDir, exec, prodPackages, usesToken: npmrcUsesToken(readFileSync(npmrc, 'utf8')) });
133
+ const { dockerfile, dockerignore } = renderPrebuiltDockerfile({ ...options, root, imageDir });
336
134
  const files = [
337
135
  [posix.join(imageDir, 'Dockerfile'), dockerfile],
338
136
  [posix.join(imageDir, 'Dockerfile.dockerignore'), dockerignore],