Files
firecrawl/apps/api/Dockerfile
Gergő Móriczandcapy-ai[bot] edd2574bee refactor(api): complete modular service architecture, env cleanup, and deployment switch removal [downstream-sync] (#6058)
* refactor(api): extract limits, jobStore, auth, and billing module slots [downstream-sync]

Routes concurrency limits, job storage, authentication, and metering through service.modules with self-contained open-source defaults (noLimits, queueJobStore, openAuth, and unmeteredBilling).

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): remove standalone optional worker roles from core [downstream-sync]

Removes zdr-worker, cclog-worker, and index-worker from built-in core roles so deployments that need them register them via Extension.workers.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): trim admin router to core routes and expose admin helpers [downstream-sync]

Keeps core operational admin endpoints in apps/api and exposes lazy admin helpers via ./unstable/admin-deps for custom extensions.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): add rootRaw router slot and remove optional root routes [downstream-sync]

Adds optional rootRaw pre-body-parser router slot, removes optional exchange, labs, and mcp action-log root routes from core, and exposes lazy helpers via ./unstable/root-routes-deps.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): trim optional v2 route families from core [downstream-sync]

Removes optional keyless, feedback, interactive browser, agent, team usage, monitor, and slack v2 routes from core and exposes shared middleware helpers via ./unstable/v2-routes-deps.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): narrow core scrape engines to built-in open-source set [downstream-sync]

Keeps wikipedia, playwright, fetch, pdf, and document as built-in core engines, adds engine trait metadata and fallback hook controls, and exposes scrape helpers for external engine extensions.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): add format extensibility seams and extract branding format [downstream-sync]

Add ScrapePlan markdown and field-preservation hooks, convert Document and DocumentMetadata to mergeable interfaces, allow extensions to widen designated core request fields, export FormatUnavailableError and TransportableError from the service entry, and remove the branding format implementation, engine feature, error class, and schema from core.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): extract changeTracking, deterministicJson, and internal formats [downstream-sync]

Remove changeTracking, deterministicJson, redactPII, product, menu, audio, video, highlights, and the YouTube postprocessor from the core transformer stack, request schemas, error classes, and engine features. Export performDirectQuoteQuery for downstream format extensions.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): isolate local PDF engine and trim PDF parser options [downstream-sync]

Keep local Rust and pdf-parse PDF extraction in the default pdf engine while removing external OCR service orchestration, caching, and extended parser options from core.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): move extended v2 request fields out of core schemas [downstream-sync]

Trim extended scrape, map, and search request fields and unused schemas from controllers/v2/types.ts, route worker and sitemap parsing through getV2RequestSchemas(), and export extension helpers.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): route Meta options through service request types [downstream-sync]

Use the extensible service ScrapeOptions type on Meta and scrapeURL so downstream type augmentations flow into engines and hooks, export v2 schema helper primitives for extension schema composition, and preserve default timeout precedence between rules and built-in transforms.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): remove legacy v0, v1, extract, and research APIs [downstream-sync]

Remove legacy v0 and v1 routes, controllers, schemas, extract worker and queue, deep-research and generate-llmstxt pipelines, and legacy search wrappers from the core API package.

Promote shared request, auth, action, and crawl-status types to v2, keep the v2 research GitHub 410 handler in deprecations, remove unused ajv-formats dependency, and expose internal extension helpers via ./unstable/legacy-api-deps.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(api): align Dockerfile, robots-txt parsing, and tests with core schema [downstream-sync]

Update Dockerfile build and runtime checks to verify dist/src/controllers/v2/crawl-status.js, route robots.txt scrape options through getV2RequestSchemas(), and align unit and self-hosted tests with narrowed core request schemas and direct-quote query helpers.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* [downstream-sync] Add policy module slot, openRequest middleware, and request hooks

Introduce the 10th PolicyModule slot with unrestrictedPolicy() default, require policy in ModulesConfig when RequestContext is widened, and add openRequest, resolveRequestContext, rejectRequest, and finalizeResponse helpers emitting request.accepted, request.rejected, and request.responding hooks.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): remove optional v2 route families from core [downstream-sync]

Removes optional mcp action logs, computer session files, alexandria
provider routing, support proxy, research proxy, and fresh feed v2
routes and their exclusive helpers from core, exposing shared route
primitives via ./unstable/v2-routes-deps.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): route v2 endpoints through openRequest and policy module [downstream-sync]

Wire core v2 routes through openRequest and resolveRequestContext, wrap 200 responses through finalizeResponse, remove inline policy pre-flight checks from v2 controllers and the core scrape/map/search pipelines, and route system discovery calls through policy.system().

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): move inline pipeline and lifecycle handlers behind hooks [downstream-sync]

Remove inline logging, analytics, indexing, monitoring, notification, and search filtering calls from core v2 controllers, workers, queue dispatch, and startup/shutdown hooks so extensions can handle them through the service hook points.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(api): preserve v2 route checks, search parse errors, robots flags, and hook tests [downstream-sync]

Restore restrictedOptionsCountryCheck on core v2 routes, add onParseError
to openRequest so /v2/search keeps its ZodError response shape, fall back
to ctx.flags.checkRobotsOnScrape in shouldCheckRobots, guard optional
meta.ctx in query transformer, and align core unit and workflow test sets
with the extracted hook and policy seams.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): remove non-core modules and stabilize package exports [downstream-sync]

Replace internal unstable subpath exports with clean public package
subpaths under firecrawl-scraper-js/*, decouple core admin, queue,
worker, and scrape helpers onto service module slots, and remove
unused non-core directories, dependencies, and workflow steps.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(api): guard worker module hooks without active service and update core error snapshot [downstream-sync]

Use installedService() when reading optional auth/limits hooks in scrape-worker so tests without an installed service continue cleanly, and update coreParts error snapshot after removing non-core error classes.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor(api): prune non-core env keys and remove deployment mode switches [downstream-sync]

Trim apps/api/src/config.ts, apps/api/.env.example, and docker-compose.yaml to
the 89 environment variables used by the open-source API and workers. Remove
unused deployment mode helpers (USE_DB_AUTHENTICATION, isSelfHosted,
lib/withAuth.ts, lib/deployment.ts, and lib/agent-interop.ts), move
bypassBilling onto Authorization, derive image OCR availability from registered
image engines, read optional caller.agentInterop and caller.hostedMcp from the
auth module result, and use IS_KUBERNETES for the queue-worker liveness check.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(api): address CI engine metadata check and code review findings [downstream-sync]

Addresses Core unit tests and review findings across service freezing, scrape/map/batch context propagation, PDF handoff and fast mode checks, Bull Board and admin metrics registries, GCS handoff bucket allowlisting, and test coverage:

- Check static engine metadata before calling engine.enabled() in isImageOcrEnabled(), getParseForceEngine(), and hasFilePrefetchEngine().
- Validate and bind optional AuthModule.lookupTeam and LimitsModule.onJobStart/onJobEnd in freezeModules().
- Preserve teamFlags on meta.ctx, flags.usOnly on robots.txt fetches, lockdown ZDR in unrestrictedPolicy() and blocklistMiddleware(), effective ZDR in mapCtx and crawl-params-preview, and blockCtx when appending to batch scrapes.
- Restore truncated PDF handoff completion and fast-mode OCR rejection when Rust extraction is disabled.
- Require explicit allowedBucket opt-in on GcsFileDownloader before invoking the downloader.
- Move admin metrics collector registry to a side-effect-free module, replay registered queues in bindBullBoard(), clear stale external slot markers on PG reservation, track maxAge acceptance per compiled scrapeOptions schema, guard crawl-status timestamp when nuqJob is null, guard proxy auto timeout transform, keep bindScrapeMeta private, re-export withTraceContextAsync, harden hasFormatOfType return type and resolveJobPriority error callback, and update/prune tests.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(api): handle aborted GCS signal, raw PDF cleanup, null teamFlags, and strict parser test [downstream-sync]

- Check signal?.aborted before returning null in feResToFilePrefetch GCS allowlist path.
- Clean up temporary PDF prefetch file in scrapePDF when shouldParse is false.
- Preserve explicit null teamFlags when populating ctx.flags in buildMetaObject.
- Align EOF_SEARCH_BYTES comment and isTruncatedPdf docstring with incremental-update truncation checks.
- Expect core strict-schema error message in parsers.test.ts when running outside production.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(api): apply auto proxy timeout before rules and export searchWithProvider [downstream-sync]

- Apply the built-in proxy=auto timeout upgrade before running extension rules so proxy=auto takes precedence over json/extension 60s bumps while keeping rule-set timeouts authoritative.
- Export searchWithProvider from firecrawl-scraper-js/search.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(api): align billing preflight, search, map filter, worker storage, and fallback hooks [downstream-sync]

- Restore billing.authorize preflight on /agent routes in checkCreditsMiddleware.
- Preserve forced scrape zero data retention on search child scrapes and blocklist checks.
- Dual-write context threatProtection onto internalOptions for rolling-deploy compatibility, refreshing on batch appendToId.
- Merge queues by name in startBullmqQueueMetrics instead of overwriting earlier registrations.
- Restore teamFlags fallbacks in crawlToCrawler when ctx.lockdown, ctx.ignoreRobotsTxt, or forced scrape ZDR are absent.
- Run search billing reservation before search.plan, forward searchState to billing.charge, support pre-routed web results and non-billable counts, preserve result categories and multi-source group metadata in search.results, and return 503 TOOL_DISCOVERY_UNAVAILABLE when tools-only discovery is unavailable.
- Add post-scope, post-limit map.filter transform hook and export applyMapFilterHook.
- Rethrow external jobStore.record failures on async worker completions and always return null to the queue when external result storage is enabled.
- Increase process.stop hook timeout from 10s to 45s.
- Resolve live team concurrency for queued crawl and batch jobs instead of freezing request-time ctx.concurrencyLimit.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(api): match schema-normalized source objects in search reserve assertion [downstream-sync]

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(api): prevent double-billing on persistence errors, prefer live crawl flags, and fix search hit routing [downstream-sync]

- Track completed success billing in scrape-worker so external jobStore.record failures do not re-bill the job in the failure handler.
- Prefer live worker teamFlags over stored context flags in crawlToCrawler and preserve Safe Mode's strict default robots enforcement unless enforceRobots is explicitly false.
- Reindex merged routed web results before operator filtering so positions reflect the merged order even when no results are filtered out.
- Only fall back to cross-group URL matching in search.results when hit.group is omitted so explicitly grouped hook hits land in their declared response array.

Downstream-Sync: required
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
2026-11-25 16:58:27 +00:00

106 lines
3.6 KiB
Docker

# syntax=docker/dockerfile:1
FROM node:22.23.5-slim@sha256:e9f565d32859f0cbfb52125eafe8be39390f24dac302dc3cdf566e8ba3ab21ee AS base
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
ENV CI=true
RUN corepack enable && corepack prepare pnpm@11.4.0 --activate
# Build Go shared library
FROM golang:1.26 AS go-build
WORKDIR /app
COPY sharedLibs/go-html-to-md ./sharedLibs/go-html-to-md
RUN cd sharedLibs/go-html-to-md && \
go mod download && \
go build -o libhtml-to-markdown.so -buildmode=c-shared html-to-markdown.go
FROM base AS build
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
curl \
build-essential \
pkg-config \
python3 \
&& rm -rf /var/lib/apt/lists/*
# FoundationDB client library (libfdb_c + headers), needed by the
# `foundationdb` npm package at install time on arches without prebuilds
ARG FDB_VERSION=7.3.63
RUN ARCH=$(dpkg --print-architecture) && \
case "$ARCH" in arm64) FDB_ARCH=aarch64 ;; *) FDB_ARCH=$ARCH ;; esac && \
curl -fsSL -o /tmp/fdb-clients.deb \
"https://github.com/apple/foundationdb/releases/download/${FDB_VERSION}/foundationdb-clients_${FDB_VERSION}-1_${FDB_ARCH}.deb" && \
dpkg -i /tmp/fdb-clients.deb && rm /tmp/fdb-clients.deb
# Install Rust
ENV RUSTUP_HOME=/usr/local/rustup \
CARGO_HOME=/usr/local/cargo \
PATH=/usr/local/cargo/bin:$PATH
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path \
&& chmod -R a+w $RUSTUP_HOME $CARGO_HOME
# Copy dependency inputs. The native workspace is included here because its
# install script builds the Rust package; API TypeScript source is copied after
# dependency install so source-only changes do not invalidate this layer.
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./
COPY native ./native
# Install dependencies
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
--mount=type=cache,target=/usr/local/cargo/registry \
--mount=type=cache,target=/app/native/target \
pnpm install --frozen-lockfile
COPY . .
# Build the application from a clean output directory.
RUN rm -rf dist && pnpm run build
ARG GIT_SHA=unknown
RUN test -s dist/src/harness.js && \
test -s dist/src/controllers/v2/crawl-status.js && \
printf '%s\n' "$GIT_SHA" > BUILD_SHA
# Remove dev dependencies
RUN pnpm prune --prod --ignore-scripts
# Runtime stage
FROM base AS runtime
# Install runtime dependencies
RUN apt-get update && apt-get install -y \
git \
procps \
curl \
&& rm -rf /var/lib/apt/lists/*
# FoundationDB client library (libfdb_c + fdbcli)
ARG FDB_VERSION=7.3.63
RUN ARCH=$(dpkg --print-architecture) && \
case "$ARCH" in arm64) FDB_ARCH=aarch64 ;; *) FDB_ARCH=$ARCH ;; esac && \
curl -fsSL -o /tmp/fdb-clients.deb \
"https://github.com/apple/foundationdb/releases/download/${FDB_VERSION}/foundationdb-clients_${FDB_VERSION}-1_${FDB_ARCH}.deb" && \
dpkg -i /tmp/fdb-clients.deb && rm /tmp/fdb-clients.deb
EXPOSE 8080
WORKDIR /app
ARG GIT_SHA=unknown
ENV FIRECRAWL_BUILD_SHA=$GIT_SHA
# Copy built application
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY --from=build /app/native ./native
COPY --from=build /app/BUILD_SHA ./BUILD_SHA
# Copy Go shared library
COPY --from=go-build /app/sharedLibs/go-html-to-md/libhtml-to-markdown.so ./sharedLibs/go-html-to-md/
RUN node -e 'const fs = require("fs"); for (const p of ["dist/src/harness.js", "dist/src/controllers/v2/crawl-status.js", "BUILD_SHA"]) { if (!fs.statSync(p).size) throw new Error(`${p} missing or empty`); }'
CMD ["node", "dist/src/harness.js", "--start-docker"]