# This is a Dockerfile with multiple 'stages', you can target a specific stage
# using Docker's 'target' option. For example if you wanted to use the container
# to run run unit tests you'd want to target the 'development' stage. Whereas
# if you wanted to build a light-weight production image you'd leave target
# undefined or set to 'production'.

# Stage 1
FROM node:24-alpine AS development

ARG GIT_COMMIT=unknown
ENV GIT_COMMIT=$GIT_COMMIT

RUN apk update \
    && apk --no-cache add curl bash ca-certificates \
    && curl https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem \
          -o /etc/ssl/certs/rds-global-bundle.pem \
    && update-ca-certificates \
    && rm -rf /var/cache/apk/*

WORKDIR /home/node/app

# copy just what we need to install dependencies
COPY package.json .
COPY pnpm-lock.yaml .
COPY pnpm-workspace.yaml .
COPY .npmrc .

# install pnpm and dependencies
RUN corepack enable

# Mount the token as a BuildKit secret and pass it only to this install step.
RUN --mount=type=secret,id=GITHUB_NPM_TOKEN,required=true,uid=1000 \
    GITHUB_NPM_TOKEN="$(cat /run/secrets/GITHUB_NPM_TOKEN)" pnpm install --frozen-lockfile

# copy in all project files
COPY . .

# build the project
RUN pnpm build
RUN pnpm build:client

# Stage 2
FROM development AS production-build

# remove dev dependencies after build
RUN rm -rf node_modules
RUN --mount=type=secret,id=GITHUB_NPM_TOKEN,required=true,uid=1000 \
    GITHUB_NPM_TOKEN="$(cat /run/secrets/GITHUB_NPM_TOKEN)" pnpm install --prod --frozen-lockfile
RUN pnpm store prune

# Stage 3
FROM node:24-alpine

EXPOSE 8080

# NOTE: in multistage docker build ARG/ENV only persist for the stage
# in which they are defined. We need `GIT_COMMIT` to be available in
# the final runtime so it must be defined in the last build stage.
ARG GIT_COMMIT=unknown
ENV GIT_COMMIT=$GIT_COMMIT
ENV NODE_ENV=production

COPY --from=production-build /etc/ssl/certs/rds-global-bundle.pem /etc/ssl/certs/rds-global-bundle.pem

RUN apk update \
    && apk --no-cache add ca-certificates \
    && apk --no-cache add curl \
    && update-ca-certificates \
    && rm -rf /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx \
    && rm -rf /usr/local/lib/node_modules/corepack /usr/local/bin/corepack \
    && rm -rf /usr/local/bin/yarn /usr/local/bin/yarnpkg /usr/local/bin/pnpm /usr/local/bin/pnpx

WORKDIR /home/node/app

# Hand pick the final compiled .js leaving the .ts source files behind in the
# previous stage. This means that the final production image is as lean as possible.
COPY --from=production-build /home/node/app/dist .
COPY --from=production-build /home/node/app/node_modules ./node_modules
COPY --from=production-build /home/node/app/package.json .

# Default command starts the server.
CMD ["node", "--import", "dd-trace/initialize.mjs", "index.js"]
