Repository navigation
Description
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
createCSAPIBuilderis value-shaped, pure, trivially testable withoutOgcApiEndpointdoubles - Every
endpoint.csapi()initialization path isinstanceof 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 introducingendpoint.csapi()(018) breaks the documented standalonecreateCSAPIBuilder(endpoint, id)workflow. - Adding
endpoint.csapi()(018) without re-privatizing (024) leaves therootescape 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:
- P8-contribution-goal-and-definition.md §3 — Phase 8 design rails (acceptance criteria A2, A7, A8)
- P8-implementation-guide.md §3 — execution-level rails
- P8-implementation-guide §4.6 — full 8-step execution sequence (canonical)
docs/code-review/018-pending-p3-endpoint-csapi-convenience-method.mddocs/code-review/024-pending-p2-endpoint-root-publicly-exposed.md— Option A3 locked
Problem Statement
Three coupled defects on the public surface:
OgcApiEndpoint.rootandgetCollectionDocumentare public in the current code — they were temporarily made public earlier in the CSAPI work to letcreateCSAPIBuildercall them. They were always intended to be private (upstream's design); leaving them public leaks internal document-fetch primitives onto the upstreamOgcApiEndpointAPI.- No discoverable entry point — to construct a CSAPI builder, a consumer must (a) instantiate
OgcApiEndpoint, (b) importcreateCSAPIBuilderfrom a sub-path, (c) pass the endpoint plus a collection ID. The natural mirror ofendpoint.edr(id)does not exist. createCSAPIBuildercontains an unsound runtime cast — it callsendpoint.getCollectionDocument(id)and runs the result through a hand-rolledisCollectionInfotype guard. If the typedendpoint.getCollectionInfo(id)were used instead, the guard becomes unreachable and the runtime cast disappears.
Affected code:
src/ogc-api/endpoint.ts—rootandgetCollectionDocumentarepublic(must revert toprivate); nocsapi()method existssrc/ogc-api/csapi/factory.ts— currentcreateCSAPIBuilder(endpoint, collectionId)performs awaits,isCollectionInfocast,scanCsapiLinks, and error-throwing inside the factorysrc/ogc-api/csapi/factory.spec.ts— relies on fake-OgcApiEndpointtest doublessrc/ogc-api/endpoint.spec.ts— line ~2868 (re-verify; Phase 7 may have shifted) asserts ongetCollectionDocumentshape
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.tsMigrate 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:
- Happy path: mock
getCollectionInfo+rootto resolve with valid CSAPI-advertising fixtures; assert returnedCSAPIQueryBuilderhas the expectedavailableResources. - No CSAPI: mock
hasConnectedSystemsfalse; assert thrownEndpointErrorwith the "does not support" message. - Network failure: mock
getCollectionInfoto reject withnew TypeError('Network error'); assert the thrown errorinstanceof EndpointError, message includes the original. - Pre-typed error pass-through: mock
getCollectionInfoto reject withnew EndpointError('upstream-thrown'); assert the sameEndpointErrorinstance is re-thrown (not double-wrapped). UsetoBe(identity) where possible.
Scope — What NOT to Touch
- ❌ Do NOT split this task into two PRs / two commits. 018 + 024 must land together as one coordinated unit (locked decision).
- ❌ Do NOT remove the standalone
createCSAPIBuilder— only refactor its signature to value-shaped inputs. Advanced consumers and tests still need the value-shape form. - ❌ Do NOT use static
importforfactory.jsorhelpers.jsfromendpoint.ts— must be dynamic. Static imports re-introduce the dependency edge from issue P6 Task 6: Modify endpoint.ts — Remove CSAPI Coupling #122 (20a35d2). - ❌ Do NOT omit the
if (e instanceof EndpointError) throw e;re-throw guard. Double-wrappingEndpointErrorinsideEndpointErrorcorrupts the consumer narrowing contract. - ❌ Do NOT modify any unrelated
OgcApiEndpointmethod signatures or visibilities. OnlyrootandgetCollectionDocumentflip back toprivate. - ❌ Do NOT modify upstream-authored files outside
src/ogc-api/endpoint.tsandsrc/ogc-api/endpoint.spec.ts. - ❌ Do NOT touch B2's helper/parser throw conversions; B2 has already standardized those. D1's wrapping is only for the factory-level network-await path.
- ❌ Do NOT introduce a
CSAPIErrorsubclass (B2's locked decision applies —EndpointErroronly). - ❌ Do NOT pre-emptively rename
getDataStreams→getDatastreamsoutside this task — that's Task B1's job. - ❌ Do NOT add
@deprecatedtags anywhere in Phase 8 (locked decision; PR unmerged ⇒ no consumers). - ❌ Do NOT absorb consumer-side ergonomic helpers (Phase 8 hard scope fence; Closed (wontfix): library is spec-correct; server-side root cause tracked at connected-systems-go#11; institutional knowledge preserved in references.md #168 / Closed (wontfix): heuristic coordinate extraction not adopted; architecturally correct path tracked at #171 #169 stay closed wontfix).
- ❌ Do NOT re-open a Phase 8 deferred finding (020, 025, 026) or a deferred CS-Go issue (Future-enhancement (deferred): async-iterator helpers for paginated CSAPI list methods — out-of-scope until upstream broadens scope #170, Deferred enhancement: SWE Common–aware result-vector extraction (out-of-scope until upstream broadens scope) #171) inside this task.
- ❌ Do NOT change any URL-builder method outputs, parser outputs, or the
availableResourcestyping — those are A1–A4 / B1 / C1.
Acceptance Criteria
-
src/ogc-api/csapi/factory.tscreateCSAPIBuildersignature swapped to(collection: CSAPICollectionRef, resourceUrls: ReadonlyMap<string, string>): CSAPIQueryBuilder(synchronous, noawait) -
isCollectionInforuntime cast deleted;git grep -n "isCollectionInfo" -- src/ogc-api/csapi/returns 0 -
src/ogc-api/csapi/factory.spec.tssimplified — fake-OgcApiEndpointdoubles deleted; tests use literalCSAPICollectionRef+Map -
src/ogc-api/endpoint.tsrootandgetCollectionDocumentflipped back toprivate;git grep -n "public root\|public getCollectionDocument" src/ogc-api/endpoint.tsreturns 0 -
src/ogc-api/endpoint.tshas newpublic 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:~2868shape assertion migrated fromgetCollectionDocumenttogetCollectionInfo(no test case loss) - New
csapi()describe block inendpoint.spec.tscovers: happy path, hasConnectedSystems-false, getCollectionInfo-rejects-TypeError → wrappedEndpointError, 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.tsreturns 0 (locks B2 + D1 together) - Static imports of
csapi/factory.jsorcsapi/helpers.jsfromendpoint.tsare absent (dependency-edge regression check) - All modified files pass
npx prettier --check -
npm run typecheckexits 0 -
npm run lintexits 0 -
npm run test:browserexits 0 -
npm run test:nodeexits 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:nodeExpected output:
- All four
git grepinvariants return their expected zero / dynamic-only matches - Targeted
endpoint.spec.tsrun: every newcsapi()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 (
EndpointErrorstandardization) — 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
Sam-Bolling commentedon Apr 29, 2026
Workflow & Closing Step (applies to this issue)
When working this issue, follow this workflow exactly:
git commit+git push origin <branch>). Verify withgit statusthat the working tree is clean andgit log origin/<branch>..HEADis empty.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:
npx prettier --checkinvocations exit 0.npm runQA invocations (format:check,typecheck,lint,test:browser,test:node) exit 0.phase-8HEAD prior to this task's commit) — paste a one-linegit stash; npx jest <suite>; git stash popreproduction 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.refactor(csapi): validators throw EndpointError (B2 / #177)
Sam-Bolling commentedon Apr 30, 2026
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.
endpoint.edr(id)template,isCollectionInfoinventory,#122import-graph contractendpoint.csapi(id): Promise<CSAPIQueryBuilder>mirroringendpoint.edr(id)— dynamic import +EndpointErrorwrapping. No removals; old surface stays intact.root+getCollectionDocument, deleteisCollectionInforuntime cast, migrate every internal call siteSequencing: 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.feat(endpoint): add OgcApiEndpoint.csapi(); reshape createCSAPIBuilde…
refactor(endpoint): re-privatize root and getCollectionDocument (D1c/#…
Sam-Bolling commentedon Apr 30, 2026
D1 (coordinated refactor) complete. All four sub-tasks shipped, full QA gate green for phase-8 changes,
phase-8pushed (02cf405).Sub-task closures
a41ce07OgcApiEndpoint.csapi(id)(dynamic imports preserve #122 dep-edge); reshapedcreateCSAPIBuilderto pure value-shaped(CSAPICollectionRef, ReadonlyMap) → CSAPIQueryBuilder; rewrotefactory.spec.ts(5 tests); addedcsapi()block inendpoint.spec.ts(5 tests)02cf405public get root→private,public getCollectionDocument(id)→private; deleted redundantdescribe(''getCollectionDocument'')block (subsumed by D1b''scsapi()happy-path assertion); twospyOncalls castas any(test-only, intentional)Locked decisions honored
@deprecatedtag on the prior factory shape; reshape was acceptable per Phase 8 / D1b: Add endpoint.csapi(id) (additive — no removals) #183 since the package was pre-1.0 / un-released)EndpointErroras the only error class surfaced fromcsapi(); no newCSAPIErrorsubclassendpoint.csapi()facade + value-shaped factory; no consumer ergonomic helpers (Closed (wontfix): library is spec-correct; server-side root cause tracked at connected-systems-go#11; institutional knowledge preserved in references.md #168 / Closed (wontfix): heuristic coordinate extraction not adopted; architecturally correct path tracked at #171 #169 stay closed wontfix)Net surface change vs
mainOgcApiEndpoint.csapi(collectionId): Promise<CSAPIQueryBuilder>OgcApiEndpoint.rootgetter,OgcApiEndpoint.getCollectionDocument(id)createCSAPIBuildersignature change: async(endpoint, id)→ sync(CSAPICollectionRef, ReadonlyMap). Subpath consumers (@camptocamp/ogc-client/csapi) get a typed value-shaped factory.QA gate (D1d)
npm run format:checknpm run typechecknpm run lintnpm run test:browserhttp-utils,wms/endpoint,wmts/endpoint,wfs/endpoint) are pre-existing Windows-only esbuild worker-resolution failures;git log main..HEADconfirms no phase-8 commit touches those pathsnpm run test:nodegit push origin phase-8ca1157c..02cf405 phase-8 -> phase-8Sub-finding from D1b: the
isCollectionInforuntime 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.