Skip to content

Phase 8 / Task D1: Findings 018 + 024 (coordinated) — endpoint.csapi() + re-privatization #179

Closed

Description

@Sam-Bolling

Phase 8 Task

Task ID: D1
Title: Findings 018 + 024 (Coordinated) — endpoint.csapi() + Re-Privatization
Source: Senior dev code review #2 — coordinated execution of two findings as a single unit
Severity: P2-Major (locked decision: Option A3 — coordinated unit, executed last and alone)
Category: API Design / Encapsulation / Refactor
Ownership: Ours (CSAPI module + src/ogc-api/endpoint.ts)
Phase 8 phase: D — Coordinated Structural Refactor


Goal

Restore the OgcApiEndpoint invariant (root and getCollectionDocument private), add the discoverable endpoint.csapi(id) entry point, refactor createCSAPIBuilder into a value-shaped pure factory, and close the network-error EndpointError wrapping that Task B2 deferred. After D1:

  • The public CSAPI surface = one constructor entry point (endpoint.csapi(id)) + URL-builder methods + parser functions
  • Zero unsound runtime casts in CSAPI factory code
  • Standalone createCSAPIBuilder is value-shaped, pure, trivially testable without OgcApiEndpoint doubles
  • Every endpoint.csapi() initialization path is instanceof EndpointError-narrowable

Acceptance criteria (from P8-contribution-goal-and-definition.md): A2 (no endpoint.root/getCollectionDocument public exposure), A7 (endpoint.csapi() discoverable entry point), A8 (no isCollectionInfo runtime cast), and the factory-level half of A4 deferred from B2.

Locked Decision

⚠️ This decision is locked. Do not re-litigate in this issue. Surface deviations to the user; do not silently re-decide.

Decision: Option A3 (coordinated execution). Findings 018 (add endpoint.csapi() convenience method) and 024 (re-privatize OgcApiEndpoint.root / getCollectionDocument) are executed as a single coordinated unit. They cannot be split:

  • Re-privatizing root / getCollectionDocument (024) without first introducing endpoint.csapi() (018) breaks the documented standalone createCSAPIBuilder(endpoint, id) workflow.
  • Adding endpoint.csapi() (018) without re-privatizing (024) leaves the root escape hatch open and silently invites consumer code to keep calling it.

The standalone createCSAPIBuilder is kept, not removed — but its signature changes to value-shaped inputs (CSAPICollectionRef + ReadonlyMap<string, string>), removing the awaited network calls and the isCollectionInfo runtime cast. The network awaits move into endpoint.csapi() where they belong.

The endpoint.csapi() body MUST use dynamic imports (await import('./csapi/factory.js'), await import('./csapi/helpers.js')). Static imports would re-introduce the CSAPI dependency edge that issue #122 / commit 20a35d2 deliberately removed.

The try/catch re-throw guard (if (e instanceof EndpointError) throw e;) is mandatory — never double-wrap; only wrap unexpected upstream errors.

This is the highest-risk and highest-payoff change in Phase 8. Execute last, alone, after every other Phase 8 task is green.

Locked in:


Problem Statement

Three coupled defects on the public surface:

  1. OgcApiEndpoint.root and getCollectionDocument are public in the current code — they were temporarily made public earlier in the CSAPI work to let createCSAPIBuilder call them. They were always intended to be private (upstream's design); leaving them public leaks internal document-fetch primitives onto the upstream OgcApiEndpoint API.
  2. No discoverable entry point — to construct a CSAPI builder, a consumer must (a) instantiate OgcApiEndpoint, (b) import createCSAPIBuilder from a sub-path, (c) pass the endpoint plus a collection ID. The natural mirror of endpoint.edr(id) does not exist.
  3. createCSAPIBuilder contains an unsound runtime cast — it calls endpoint.getCollectionDocument(id) and runs the result through a hand-rolled isCollectionInfo type guard. If the typed endpoint.getCollectionInfo(id) were used instead, the guard becomes unreachable and the runtime cast disappears.

Affected code:

  • src/ogc-api/endpoint.ts — root and getCollectionDocument are public (must revert to private); no csapi() method exists
  • src/ogc-api/csapi/factory.ts — current createCSAPIBuilder(endpoint, collectionId) performs awaits, isCollectionInfo cast, scanCsapiLinks, and error-throwing inside the factory
  • src/ogc-api/csapi/factory.spec.ts — relies on fake-OgcApiEndpoint test doubles
  • src/ogc-api/endpoint.spec.ts — line ~2868 (re-verify; Phase 7 may have shifted) asserts on getCollectionDocument shape

Impact: Public-API leak (024 is P2), missing-discoverability friction (018 is P3), unsound cast (eliminated as a side effect of D1).

Files to Modify

File Action Est. Lines Purpose
src/ogc-api/csapi/factory.ts Modify ~30 New value-shaped signature createCSAPIBuilder(collection: CSAPICollectionRef, resourceUrls: ReadonlyMap<string, string>): CSAPIQueryBuilder; awaits removed; isCollectionInfo cast removed; defensive new Map(resourceUrls) copy on input
src/ogc-api/csapi/factory.spec.ts Modify ~−60 net Fake-OgcApiEndpoint doubles deleted; tests construct CSAPICollectionRef literals + Map<CSAPIResourceType, string> literals directly
src/ogc-api/endpoint.ts Modify ~50 New public async csapi(collectionId): Promise<CSAPIQueryBuilder> with try/catch + re-throw guard + dynamic imports; root and getCollectionDocument flipped back to private
src/ogc-api/endpoint.spec.ts Modify ~80 added Migrate the one getCollectionDocument-shape test (~line 2868, re-verify) to assert through getCollectionInfo; add new csapi() describe block (happy path, hasConnectedSystems-false, getCollectionInfo-rejects-TypeError → wrapped EndpointError, getCollectionInfo-rejects-EndpointError → re-thrown as-is, not double-wrapped)
src/ogc-api/csapi/index.ts Verify ~0 Standalone createCSAPIBuilder export name unchanged; only the signature changed. No barrel change required unless CSAPICollectionRef is being newly exported (it already is, per Task A2)

Cross-reference P8-implementation-guide §4.6 for the canonical files-modified list and full 8-step sequence. If you find yourself adding a file that isn't in the implementation guide, stop — surface the question.

Implementation Approach

Execute the canonical 8-step sequence verbatim from P8-implementation-guide §4.6.

Step 1 — Refactor factory.ts to value-shaped inputs:

import type { CSAPICollectionRef } from './model.js';

/**
 * Constructs a {@link CSAPIQueryBuilder} from pre-resolved collection metadata.
 *
 * Pure factory: no I/O, no `await`, no error wrapping. Network-aware
 * composition lives in {@link OgcApiEndpoint.csapi} (the discoverable
 * entry point); this standalone factory is the value-shaped form for
 * tests and advanced consumers who already hold the inputs.
 *
 * @public
 */
export function createCSAPIBuilder(
  collection: CSAPICollectionRef,
  resourceUrls: ReadonlyMap<string, string>
): CSAPIQueryBuilder {
  return new CSAPIQueryBuilder(collection, new Map(resourceUrls));
}

The new Map(resourceUrls) defensive copy lets the factory accept ReadonlyMap while preserving the builder's internal mutable-map invariant.

Step 2 — Update factory.spec.ts: delete fake-OgcApiEndpoint test doubles. Replace with literal CSAPICollectionRef and literal Map<CSAPIResourceType, string> construction. Net simplification estimated at −60 LOC.

Step 3 — Add public async csapi() to endpoint.ts:

public async csapi(collectionId: string): Promise<CSAPIQueryBuilder> {
  if (!(await this.hasConnectedSystems)) {
    throw new EndpointError('Endpoint does not support Connected Systems');
  }
  let collection: OgcApiCollectionInfo;
  let rootDoc: OgcApiDocument;
  try {
    collection = await this.getCollectionInfo(collectionId);
    rootDoc = await this.root;
  } catch (e) {
    if (e instanceof EndpointError) throw e; // re-throw guard — never double-wrap
    throw new EndpointError(
      `Failed to initialize CSAPI builder for collection '${collectionId}': ${
        e instanceof Error ? e.message : String(e)
      }`
    );
  }
  const links = Array.isArray(rootDoc?.links) ? rootDoc.links : [];
  const { createCSAPIBuilder } = await import('./csapi/factory.js');
  const { scanCsapiLinks } = await import('./csapi/helpers.js');
  return createCSAPIBuilder(collection, scanCsapiLinks(links));
}

Critical: dynamic imports only. Static imports re-introduce the dependency edge issue #122 (20a35d2) deliberately removed.

Step 4 — Re-privatize:

-public get root(): Promise<OgcApiDocument> {
+private get root(): Promise<OgcApiDocument> {

-public getCollectionDocument(id: string): Promise<OgcApiDocument> {
+private getCollectionDocument(id: string): Promise<OgcApiDocument> {

Step 5 — Migrate the one external test caller at src/ogc-api/endpoint.spec.ts:~2868. Re-verify the line first:

git grep -n "getCollectionDocument" -- src/ogc-api/endpoint.spec.ts

Migrate the assertion from endpoint.getCollectionDocument('iot-sensors') to endpoint.getCollectionInfo('iot-sensors') — the OgcApiCollectionInfo.links shape carries the same {rel: 'ogc-cs:systems'} evidence the old test asserted on.

Step 6 — Verify the isCollectionInfo cast is gone:

git grep -n "isCollectionInfo" -- src/ogc-api/csapi/

Expected zero matches (definition site in factory.ts removed; no other call sites).

Step 7 — Update barrel exports if needed: src/ogc-api/csapi/index.ts — only the standalone createCSAPIBuilder's signature changed; the export name stays. No barrel change required.

Step 8 — Add the csapi() test suite in src/ogc-api/endpoint.spec.ts. Cover four cases minimally:

  1. Happy path: mock getCollectionInfo + root to resolve with valid CSAPI-advertising fixtures; assert returned CSAPIQueryBuilder has the expected availableResources.
  2. No CSAPI: mock hasConnectedSystems false; assert thrown EndpointError with the "does not support" message.
  3. Network failure: mock getCollectionInfo to reject with new TypeError('Network error'); assert the thrown error instanceof EndpointError, message includes the original.
  4. Pre-typed error pass-through: mock getCollectionInfo to reject with new EndpointError('upstream-thrown'); assert the same EndpointError instance is re-thrown (not double-wrapped). Use toBe (identity) where possible.

Scope — What NOT to Touch

Acceptance Criteria

  • src/ogc-api/csapi/factory.ts createCSAPIBuilder signature swapped to (collection: CSAPICollectionRef, resourceUrls: ReadonlyMap<string, string>): CSAPIQueryBuilder (synchronous, no await)
  • isCollectionInfo runtime cast deleted; git grep -n "isCollectionInfo" -- src/ogc-api/csapi/ returns 0
  • src/ogc-api/csapi/factory.spec.ts simplified — fake-OgcApiEndpoint doubles deleted; tests use literal CSAPICollectionRef + Map
  • src/ogc-api/endpoint.ts root and getCollectionDocument flipped back to private; git grep -n "public root\|public getCollectionDocument" src/ogc-api/endpoint.ts returns 0
  • src/ogc-api/endpoint.ts has new public async csapi(collectionId): Promise<CSAPIQueryBuilder> with the canonical body (try/catch + re-throw guard + dynamic imports of factory/helpers)
  • src/ogc-api/endpoint.spec.ts:~2868 shape assertion migrated from getCollectionDocument to getCollectionInfo (no test case loss)
  • New csapi() describe block in endpoint.spec.ts covers: happy path, hasConnectedSystems-false, getCollectionInfo-rejects-TypeError → wrapped EndpointError, getCollectionInfo-rejects-EndpointError → re-thrown identity (not double-wrapped)
  • Combined post-D1 invariant: git grep -n "throw new Error\|throw new TypeError" -- src/ogc-api/csapi/ src/ogc-api/endpoint.ts returns 0 (locks B2 + D1 together)
  • Static imports of csapi/factory.js or csapi/helpers.js from endpoint.ts are absent (dependency-edge regression check)
  • All modified files pass npx prettier --check
  • npm run typecheck exits 0
  • npm run lint exits 0
  • npm run test:browser exits 0
  • npm run test:node exits 0

Acceptance Gate (verification command)

The Phase 8 roadmap defines a specific verification command for this task (P8-ROADMAP §Phase D Task D1). Paste the output of these commands on the issue before closing:

# 1. Re-privatization landed
git grep -n "public root\|public getCollectionDocument" src/ogc-api/endpoint.ts
# Expected: zero matches

# 2. Unsound cast eliminated
git grep -n "isCollectionInfo" -- src/ogc-api/csapi/
# Expected: zero matches

# 3. Combined post-D1 throw-type invariant (locks B2 + D1 together)
git grep -n "throw new Error\|throw new TypeError" -- src/ogc-api/csapi/ src/ogc-api/endpoint.ts
# Expected: zero matches

# 4. Confirm dynamic imports — static imports of factory/helpers from endpoint.ts must be absent
git grep -n "from './csapi/factory" -- src/ogc-api/endpoint.ts
git grep -n "from './csapi/helpers" -- src/ogc-api/endpoint.ts
# Expected: only the dynamic `await import(...)` calls; no top-of-file static `import { ... } from './csapi/...'` lines

# 5. Targeted spec — new csapi() describe block green
npm run test:browser -- src/ogc-api/endpoint.spec.ts

# 6. Full upstream QA suite (must mirror .github/workflows/qa.yml)
npm run format:check
npm run typecheck
npm run lint
npm run test:browser
npm run test:node

Expected output:

  • All four git grep invariants return their expected zero / dynamic-only matches
  • Targeted endpoint.spec.ts run: every new csapi() test case green; every pre-existing test case still green
  • All five upstream QA commands exit 0

Smoke test handoff: Phase 8's smoke test (smoke-test-prompt-template-phase-8.md) Step 17 (endpoint.csapi() end-to-end against all four servers) is the live-server validation for this task. The acceptance gate above is the unit-level invariant; Step 17 is the interop validation.

Dependencies

Mandatory. Walk the P8-ROADMAP dependency graph and fill in every applicable row.

Blocked by:

  • Task A2 (CSAPICollectionRef) — D1's new factory signature requires this type
  • Task B2 (EndpointError standardization) — D1 closes the factory-level wrapping that B2 deferred; both tasks together establish the post-D1 throw-type invariant
  • Tasks A1, A3, A4, B1, C1 must be green and CI-passing before D1 starts. D1 must not be split into smaller commits, and any breakage discovered must be unambiguously attributable to D1's refactor (not to upstream Phase 8 churn).

Blocks: Phase E (smoke test + upstream patch). Phase E cannot start until D1 is green.

Related: Smoke-test Step 17 (live endpoint.csapi() validation across OSH, 52N, OS4CSAPI-OSH, cs-go); upstream issue #122 / commit 20a35d2 (the dependency edge that the dynamic imports preserve)

Roadmap dependency row: P8-ROADMAP §Phase D Task D1: "Effort: Medium-High (~6 hours: 8-step sequence + tests + verification). Risk: Medium — touches upstream-authored file and changes a published factory shape. Mitigation: execute last and alone, with all other Phase 8 changes already green; full CI gate before generating the patch. Dependencies: Task A2 (CSAPICollectionRef) — required for the new factory signature; Task B2 (EndpointError standardization) — Task D1 closes the factory-level wrapping that B2 deferred; Tasks A1–A4, B1, C1 — should be green; D1 is the single coordinated unit and must not be split."

References

# Document What It Provides
1 P8-contribution-goal-and-definition.md Phase 8 goal, scope, acceptance criteria, locked decisions
2 P8-implementation-guide.md §4.6 Authoritative execution-level guide — full 8-step sequence
3 P8-ROADMAP.md §Phase D Task D1 Task ordering, dependencies, acceptance gate
4 docs/code-review/018-pending-p3-endpoint-csapi-convenience-method.md Authoritative "why" — discoverable entry point
5 docs/code-review/024-pending-p2-endpoint-root-publicly-exposed.md Authoritative "why" — re-privatization (Option A3 locked)
6 src/ogc-api/csapi/factory.ts Receives the value-shape signature swap
7 src/ogc-api/csapi/factory.spec.ts Simplified to value-literal construction (~−60 LOC)
8 src/ogc-api/endpoint.ts Receives csapi() + re-privatization
9 src/ogc-api/endpoint.spec.ts Migrated shape test + new csapi() describe block
10 Upstream issue #122 / commit 20a35d2 Reason endpoint.csapi() MUST use dynamic imports
11 smoke-test-prompt-template-phase-8.md Step 17 Live-server endpoint.csapi() validation across 4 servers

Activity

  1. Sam-Bolling commented on Apr 29, 2026

    @Sam-Bolling
    Author

    Workflow & Closing Step (applies to this issue)

    When working this issue, follow this workflow exactly:

    1. Check off the Acceptance Criteria checkboxes in this issue body as each item is satisfied — edit the issue body in place, do not just track the state externally.
    2. Commit and sync all changes from VS Code to the GitHub repository (git commit + git push origin <branch>). Verify with git status that the working tree is clean and git log origin/<branch>..HEAD is empty.
    3. Final step (mandatory): close this issue with a summary comment. The closing comment must contain at minimum:
      • The commit SHA(s) that satisfy this issue.
      • Confirmation that every Acceptance Criteria checkbox is now ticked in the body.
      • The acceptance-gate command output (or a one-line "all gates exit 0" with a link to the run, if applicable).
      • Any deviation from the locked decision (none expected).

    The issue is not complete until it has been closed with a summary comment per step 3. Closing-with-comment is part of the issue's own definition of done. Do not declare this task finished and do not move to the next task while this issue is still open.

    Acceptance-gate scrub: NO manual review

    Any prior wording in this issue body that asks for a "manual review confirmation paragraph", "manual review paragraph", "human review", or any other free-form prose-confirmation gate is rescinded. The acceptance gate is the set of automated commands listed under Acceptance Gate (verification command) — exit codes only, no manual-review prose. If any such manual-review wording appears in the original body of this issue, treat it as a no-op and ignore it.

    If the original verification block called for a "manual review confirmation" step, the corrected gate is:

    • All npx prettier --check invocations exit 0.
    • All npm run QA invocations (format:check, typecheck, lint, test:browser, test:node) exit 0.
    • Any browser-suite failures must be confirmed pre-existing on the parent baseline (phase-8 HEAD prior to this task's commit) — paste a one-line git stash; npx jest <suite>; git stash pop reproduction in the closing comment.

    For PR-page verification gates that previously called for "manual / browser" inspection of pull/136, replace with API-based verification using the GitHub MCP tools (mcp_io_github_git_pull_request_read, mcp_io_github_git_list_commits) — no browser, no manual screenshotting.

  2. Sam-Bolling commented on Apr 30, 2026

    @Sam-Bolling
    Author

    D1 split into 4 sub-tasks (2026-04-29)

    This task is the highest-risk refactor in Phase 8. To reduce blast radius and create checkpoint commits, D1 is split into four sub-issues. Each sub-issue is independently committable and reversible.

    Sequencing: D1a → D1b → D1c → D1d. D1a blocks D1b/c/d; D1b blocks D1c; D1c blocks D1d. D1d is the final sub-issue that closes this parent.

    This split does not change the locked decisions in this issue (Findings 018 + 024, Option A3, value-shaped factory, dynamic import for #122). Acceptance criteria here remain the source of truth — the sub-issues partition the work, they do not redefine it.

  3. Sam-Bolling commented on Apr 30, 2026

    @Sam-Bolling
    Author

    D1 (coordinated refactor) complete. All four sub-tasks shipped, full QA gate green for phase-8 changes, phase-8 pushed (02cf405).

    Sub-task closures

    Sub-task Issue Commit Outcome
    D1a — recon #182 n/a (read-only) Verified Findings 019 / 021 / 024 surface; produced fact sheet + locked sequencing
    D1b — code #183 a41ce07 Added OgcApiEndpoint.csapi(id) (dynamic imports preserve #122 dep-edge); reshaped createCSAPIBuilder to pure value-shaped (CSAPICollectionRef, ReadonlyMap) → CSAPIQueryBuilder; rewrote factory.spec.ts (5 tests); added csapi() block in endpoint.spec.ts (5 tests)
    D1c — privatization #184 02cf405 public get root → private, public getCollectionDocument(id) → private; deleted redundant describe(''getCollectionDocument'') block (subsumed by D1b''s csapi() happy-path assertion); two spyOn calls cast as any (test-only, intentional)
    D1d — closeout #185 n/a Full QA gate, push, close

    Locked decisions honored

    Net surface change vs main

    • +1 public method: OgcApiEndpoint.csapi(collectionId): Promise<CSAPIQueryBuilder>
    • −2 public members (re-privatized): OgcApiEndpoint.root getter, OgcApiEndpoint.getCollectionDocument(id)
    • 0 deprecation tags / shims — pre-release package, hard reshape per Phase 8 / D1b: Add endpoint.csapi(id) (additive — no removals) #183 acceptance
    • createCSAPIBuilder signature change: async (endpoint, id) → sync (CSAPICollectionRef, ReadonlyMap). Subpath consumers (@camptocamp/ogc-client/csapi) get a typed value-shaped factory.

    QA gate (D1d)

    Step Result
    npm run format:check exit 0
    npm run typecheck exit 0
    npm run lint exit 0
    npm run test:browser 58/62 suites pass, 1748 tests pass. 4 failing suites (http-utils, wms/endpoint, wmts/endpoint, wfs/endpoint) are pre-existing Windows-only esbuild worker-resolution failures; git log main..HEAD confirms no phase-8 commit touches those paths
    npm run test:node exit 0, 62/62 suites, 1831 tests pass, 4 skipped, 0 failed — confirms zero functional regressions
    git push origin phase-8 ca1157c..02cf405 phase-8 -> phase-8

    Sub-finding from D1b: the isCollectionInfo runtime cast disappeared with the factory reshape (a41ce07); git grep -n isCollectionInfo -- src/ returns 0 matches. The Finding 024 acceptance gate on that line is satisfied.

    Next phase

    D1 closes the way for E1 (#180) and E2 (#181) — the squash-onto-clean-pr / PR #136 refresh.

    Closing as completed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions