ARG NODE_BASE=node:22-bookworm-slim
# Three stages, two published images: the one modules are COMPILED in, and the one they RUN in.
#
# **They were the same image, and that was a mistake.** A module's recipe starts from this and
# invokes the compiler out of it, so the compiler had to be here — and because the same image was
# also what every module ran in, every running container on every machine carried a TypeScript
# compiler it would never invoke. The answer is separate stages rather than one image bad at both
# jobs. `build.artifacts` in module.json names the published stage each — `toolchain` and `runtime`.
#
# The `deps` stage is neither published nor named there: it is where the mesh's package registry is
# reached, so it is where — and only where — the credential to reach it exists. The toolchain copies
# resolved node_modules out of it, so the credential is in no image any machine ever holds
# (novox/hq ADR 0076). This is the buildkit-secret's job done without buildkit, because a machine's
# docker may carry no buildx.

# ---- deps: node_modules resolved from the mesh's registry, credential and all ----------------
FROM ${NODE_BASE} AS deps
RUN apt-get update \
      && apt-get install -y --no-install-recommends git ca-certificates \
      && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY package.json ./
# The builder writes .npmrc into the build context; it authenticates to the mesh's package registry
# for the @novox scope, which is where @novox/mesh-sdk resolves. This stage is not published, so the
# credential travels no further than here. Development dependencies included: the compiler is one.
COPY .npmrc ./.npmrc
RUN npm install --no-audit --no-fund

# ---- toolchain: what a module is compiled in, WITHOUT the credential --------------------------
FROM ${NODE_BASE} AS toolchain
WORKDIR /app
COPY package.json ./
# The resolved libraries, but not the .npmrc that resolved them.
COPY --from=deps /app/node_modules ./node_modules
# The toolkit arrives compiled. It used to arrive as sources, and this compiled it by hand — the
# hook that builds it on install was running all along, and the result was then packed out of the
# package, because with no explicit file list npm falls back to .gitignore and that ignores the
# build output. Fixed where it belonged, in the toolkit.
COPY tsconfig.json ./
COPY src ./src
RUN npm run build

# ---- what the running image needs, and nothing else -------------------------------------------
# Its own stage so the toolchain image keeps its build tools while the runtime image does not.
FROM toolchain AS lean
RUN npm prune --omit=dev

# ---- runtime: what a module runs in -----------------------------------------------------------
FROM ${NODE_BASE} AS runtime
WORKDIR /app
COPY package.json ./
COPY --from=lean /app/node_modules ./node_modules
COPY --from=toolchain /app/dist ./dist
ENTRYPOINT ["node", "dist/main.js"]
