Skip to content

refactor: convention alignment — helpers, constants, imports, tests - #1950

Merged
jerome-benoit merged 9 commits into
mainfrom
refactor/factorization-audit-quick-wins
Jul 5, 2026
Merged

jerome-benoit merged 9 commits into
mainfrom
refactor/factorization-audit-quick-wins

Conversation

@jerome-benoit

@jerome-benoit jerome-benoit commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Convention alignment across src/, ui/common/tests/, ui/web/, and root tests. 9 atomic commits, 28 files, +140/-113 lines. Zero behavior changes.

Commits (rebase-merge preserves atomicity)

Commit Content
refactor: adopt isEmpty() helper for emptiness checks 9 sites (strings, arrays, Maps)
refactor: adopt Constants.UNIT_DIVIDER_KILO for kW→W conversion 4 sites
refactor(ui-server): use JSONStringify for unknown MCP tool payload 1 site (Map/Set-bearing unknown)
refactor: promote inline literals to named constants 5 constants (as const narrowing)
refactor(ui-web): add .js extension to relative import in vitest.config 1 line (last missing .js in the codebase)
docs: document Number.parseInt/parseFloat convention exceptions 3 anti-regression anchors (4 call sites)
refactor(ui-common/tests): use DEFAULT_HOST/DEFAULT_PORT constants 72 test literals
refactor(tests): use component barrels instead of deep imports 10 test imports
refactor: apply post-review polish 4 findings: coverage gap + naming coherence + spec-anchor + qualifier restore

Findings resolved (by axis)

  • Helper adoption — 9 isEmpty() + 1 isNotEmptyArray() + 1 JSONStringify. Uniform application of the utility usage rules in AGENTS.md.
  • Constants factorization — 4 sites migrated to Constants.UNIT_DIVIDER_KILO; 5 module-scope constants promoted with SCREAMING_SNAKE_CASE + unit suffixes + as const literal-type narrowing (DEFAULT_PERSIST_STATE, DEFAULT_EXPONENTIAL_BACKOFF_BASE_DELAY_MS, DEFAULT_AUTH_CACHE_TTL_SECONDS reuse, MAX_ITEMS_PER_REPORT_MESSAGE, AVG_ENTRY_SIZE_BYTES).
  • Convention exception documentation — 3 inline anti-regression anchors at Number.parseInt/parseFloat sites where convertToInt/convertToFloat cannot substitute (radix-16 hex parsing × 2, NaN sentinel for POSITIVE_INFINITY fallback × 1). Mirrors the existing Number() preservation anchor at OCPP16IncomingRequestService.ts:273.
  • Test-side convention — 72 hardcoded 'localhost'/8080 literals in ui/common/tests/ replaced with DEFAULT_HOST/DEFAULT_PORT from ui/common/src/constants.ts. 10 test deep-imports routed through component barrels. 1 missing .js extension corrected.

Details per commit in the respective commit bodies.

Scope fence

Deferred to separate PRs:

  • Helpers reorganization: relocate getMessageTypeString/getWebSocketCloseEventStatusString out of Utils.ts; rename Helpers*.ts → *Helpers.ts (domain-first); move getConfiguredMaxNumberOfConnectors/hasFeatureProfile/getPhaseRotationValue to their domain-specific modules.
  • moduleName mass rename: 55 files, camelCase → SCREAMING_SNAKE_CASE.
  • Barrel gap fills: ocpp/index.js and performance/index.js to eliminate ~150 unavoidable test deep-imports; lift updateAuthorizationCache common core to OCPPServiceUtils.ts; extract applyBootNotificationResponse prelude.
  • Branded numeric types: Milliseconds/Seconds/Bytes template-literal brands (mirrors the existing UUIDv4 pattern) to make unit-mismatch bugs compile-time errors.

None of these are touched here.

Quality gates

Package typecheck lint tests
root (simulator) pass pass 2954/2960 (6 skipped, unrelated to this PR)
ui-common pass pass 120/120
ui-cli pass pass 152/152
ui-web pass pass 532/532

Regressions

None. Each commit is a semantic-preserving substitution or comment-only addition. git diff main..HEAD adds:

  • 0 new .length === 0 / .size !== 0 violations
  • 0 new raw JSON.stringify(unknown) calls
  • 0 new unguarded Number.parseInt/parseFloat calls
  • 0 new type assertions (as any, @ts-ignore, etc.)

The 6 skipped tests in the root package are pre-existing (unrelated to any file changed by this PR).

Merge recommendation

Rebase-merge to preserve atomic history — each commit is a self-contained review unit at a distinct convention axis.

@hyperspace-pr-bot hyperspace-pr-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code is fully readable now. I can see that:

  1. isEmpty(this.connectors) works correctly for Map (checks size === 0) — the semantics are preserved.
  2. !isEmpty(this.connectors) at line 1957 correctly replaces this.connectors.size !== 0.
  3. All the Constants.* replacements are valid (existing constants with correct values).
  4. The Constants.DEFAULT_PERSIST_STATE refactor in Configuration.ts is clean.
  5. The MAX_ITEMS_PER_REPORT_MESSAGE promotion to module scope is correct.
  6. The AVG_ENTRY_SIZE_BYTES module constant is fine.
  7. The barrel import consolidations in tests are valid.

No substantive issues found. The diff is a clean, behavior-preserving refactor with correct semantic substitutions throughout.

This PR is a well-executed refactoring exercise — all substitutions are semantically equivalent, the new named constants accurately reflect their values and scope, and the barrel import consolidations follow the project's stated conventions. No correctness or maintainability issues were identified.

PR Bot Information

Version: 1.26.14

@hyperspace-pr-bot

Copy link
Copy Markdown
Contributor

Summary

The following content is AI-generated and provides a summary of the pull request:


refactor: factorization audit quick wins — helper adoption, constants, imports

This PR applies a set of convention/consistency improvements across 28 files with zero behavior changes. Changes were identified through a multi-agent parallel audit against project memory conventions.

🔧 Changes Overview

Helper adoption (isEmpty / isNotEmptyArray)

  • Replaced 9 raw .length === 0 / .size !== 0 checks with the isEmpty() helper across: ChargingStation.ts, CoherentMeterValuesManager.ts, OCPP20CertificateManager.ts, OCPPServiceUtils.ts, CoherentMeterValueBuilder.ts, CoherentSession.ts, EvProfiles.ts, OCPP20IncomingRequestService.ts, ConfigurationValidation.ts

JSONStringify adoption

  • UIMCPServer.ts: replaced JSON.stringify(payload) with JSONStringify(payload) for unknown-typed MCP tool payloads that may contain Map values silently dropped by raw JSON serialization

Constants factorization

  • 4 kW→W conversion sites: * 1000 → * Constants.UNIT_DIVIDER_KILO in ChargingStation.ts and HelpersConfig.ts
  • 5 new/promoted named constants:
    • Constants.DEFAULT_EXPONENTIAL_BACKOFF_BASE_DELAY_MS = 100 — used in WS reconnect and message resend backoff
    • DEFAULT_PERSIST_STATE — collapsed redundant defaultPersistState alias in Configuration.ts
    • MAX_ITEMS_PER_REPORT_MESSAGE = 100 — promoted from function-scope in OCPP20IncomingRequestService.ts with OCPP 2.0.1 spec anchor comment
    • AVG_ENTRY_SIZE_BYTES = 500 — promoted from function-scope in InMemoryAuthCache.ts with unit suffix
    • Constants.DEFAULT_AUTH_CACHE_TTL_SECONDS — replaced inline 3600 in OCPPAuthServiceImpl.ts

Convention exception documentation

  • Added 3 inline comments at Number.parseInt/Number.parseFloat sites in UIServerNet.ts and OCPPServiceUtils.ts explaining why convertToInt/convertToFloat cannot substitute (radix-16 hex parsing; NaN sentinel)

Test-side conventions

  • 72 literal replacements in ui/common/tests/: 'localhost'/8080 → DEFAULT_HOST/DEFAULT_PORT constants across config.test.ts and WebSocketClient.test.ts
  • 10 barrel corrections: deep imports of Logger.js, Configuration.js, ConfigurationKeyUtils.js, TemplateMigrations.js, ConnectorStatus.js → their component barrels
  • 1 .js extension added to relative import in ui/web/vitest.config.ts

✅ Quality

  • 3758/3764 tests pass, 0 fail, 6 skipped across all packages
  • TypeCheck and lint pass on all packages

Does this PR introduce a breaking change?

  • Yes
  • No

  • 🔄 Regenerate and Update Summary
  • ✏️ Insert as PR Description (deletes this comment)
  • 🗑️ Delete comment
PR Bot Information

Version: 1.26.14

  • Summary Prompt: Default Prompt
  • Correlation ID: 40467570-788c-11f1-8a9b-a2b408756f40
  • LLM: anthropic--claude-4.6-sonnet
  • Event Trigger: pull_request.opened
  • Output Template: Repository PR Template
  • File Content Strategy: Full file content

@jerome-benoit
jerome-benoit force-pushed the refactor/factorization-audit-quick-wins branch from 2392b9f to 5135d69 Compare July 5, 2026 16:38
@jerome-benoit jerome-benoit changed the title refactor: factorization audit quick wins — helper adoption, constants, imports refactor: convention alignment — helpers, constants, imports, tests Jul 5, 2026
@jerome-benoit
jerome-benoit force-pushed the refactor/factorization-audit-quick-wins branch from 5135d69 to 35dd2f8 Compare July 5, 2026 16:54
Replace raw .length === 0 / .size !== 0 patterns with isEmpty() helper
per code style convention (utility usage rules).

Adoption sites (9):
- ChargingStation.ts:1957,2121 — Map.size !== 0
- OCPP20IncomingRequestService.ts:1343 — array.length === 0
- OCPP20CertificateManager.ts:477 — array.length === 0
- CoherentMeterValuesManager.ts:157 — array.length === 0
- meter-values/CoherentMeterValueBuilder.ts:174,
  CoherentSession.ts:86, EvProfiles.ts:109 — array.length === 0

Preserved as-is with anchor comment (1):
- OCPPServiceUtils.ts:1113 — string.length === 0 on a value that was
  just .trim()'ed one line above. isEmpty()'s string branch is
  value.trim().length === 0, so adopting it here would be
  semantically identical but redundantly re-trim. Documented in-place
  so a future adoption pass does not silently regress this site.

5 files gained an isEmpty import; 4 files already had it.

No behavior change; convention alignment only.
Replace inline * 1000 literal with the canonical constant already
defined in src/utils/Constants.ts:139. Same 4 sites, same semantics.

Sites:
- ChargingStation.ts:1686,1691
- HelpersConfig.ts:173,178

HelpersConfig.ts gained a Constants import; ChargingStation.ts already
had it.
UIMCPServer.createToolResponse accepts payload: unknown, which may
contain Map or Set values from downstream procedures. Raw JSON.stringify
silently drops those entries; JSONStringify handles them via a custom
replacer per code style convention.

The peer method createToolErrorResponse stringifies { error, status }
(both primitives) — safe with raw JSON.stringify, no change needed.
Convention alignment (SCREAMING_SNAKE_CASE + unit suffixes + literal
types via `as const`):

- Configuration.ts: collapse camelCase 'defaultPersistState' alias into
  the exported DEFAULT_PERSIST_STATE = true as const (was 2
  declarations, now 1; literal type preserved).
- Constants.ts: add DEFAULT_RECONNECT_BASE_DELAY_MS = 100 (renamed to
  DEFAULT_EXPONENTIAL_BACKOFF_BASE_DELAY_MS in a subsequent commit
  for broader scope). Used at ChargingStation.ts:1609,2789 (2 sites)
  — previously inline literal.
- OCPPAuthServiceImpl.ts:602: replace inline 3600 with
  Constants.DEFAULT_AUTH_CACHE_TTL_SECONDS (already existed, unused
  at this site).
- OCPP20IncomingRequestService.ts: promote function-scope
  'maxItemsPerMessage = 100' to module-scope
  MAX_ITEMS_PER_REPORT_MESSAGE = 100 as const (literal type preserved).
- InMemoryAuthCache.ts: promote function-scope 'avgEntrySize = 500'
  to module-scope AVG_ENTRY_SIZE_BYTES = 500 as const; drop the
  '// Rough estimate: 500 bytes per entry' inline comment — the
  _BYTES suffix + AVG prefix are self-documenting per the naming
  convention.

No behavior change; naming and structural alignment only.
ESM + moduleResolution: NodeNext requires .js extension on all relative
imports. This was the only missing .js extension in the entire codebase.
Add inline comments anchoring 3 comments covering 4 call sites where
the raw pattern is intentional (convertToInt/convertToFloat cannot
substitute):

- UIServerNet.ts:155 — covers 2 sites at 156-157: radix-16 for
  IPv4-mapped IPv6 hex octet parsing; convertToInt does not accept
  a radix parameter.
- UIServerNet.ts:176 — 1 site at 178: radix-16 for IPv6 hex group
  normalization; same reason.
- OCPPServiceUtils.ts:1490 — 1 site at 1492: Number.parseFloat NaN
  sentinel drives the POSITIVE_INFINITY fallback branch downstream;
  convertToFloat throws on NaN and would break the fallback.

Anti-regression anchors: without these, a future helper-adoption pass
would 'fix' these sites and silently break behavior. Same pattern as
the existing Number() preservation anchor at
OCPP16IncomingRequestService.ts:273.
Tests were hardcoding 'localhost' and 8080 literals across 72 sites in
config.test.ts and WebSocketClient.test.ts. Replace with the DEFAULT_HOST
and DEFAULT_PORT constants already exported from src/constants.ts —
tests now use the same defaults as production code.

Sites (72 total):
- config.test.ts: 14 host + 18 port = 32
- WebSocketClient.test.ts: 20 host + 20 port = 40

All 120 ui-common tests still pass.
Tests outside a component must use the component's barrel per the
import discipline convention. 10 sites corrected:

- helpers/TemplateFixtures.ts: CURRENT_SCHEMA_VERSION via
  charging-station/index.js (was TemplateMigrations.js)
- 3 ui-server tests: logger via utils/index.js (was Logger.js)
- ui-server/UIMCPServer.integration.test.ts: Configuration via
  utils/index.js (was Configuration.js)
- 3 ocpp/2.0 tests: buildConfigKey/addConfigurationKey/setConfiguration\
  KeyValue/deleteConfigurationKey/getConfigurationKey via
  charging-station/index.js (was ConfigurationKeyUtils.js)
- OCPP20ServiceUtils-TransactionEvent.test.ts: merge ConnectorStatus
  and EmptyObject into a single type-import from types/index.js
  (was ConnectorStatus.js direct); addConfigurationKey via
  charging-station/index.js.

All 2954/2960 tests still pass. Deep imports remain only where the
target symbol is a genuine barrel gap (ui-server/, ocpp sub-components,
performance/storage/) — those are follow-up work.
3 findings addressed after the initial pass:

1. Coverage gap — ConfigurationValidation.ts:124: replace
   remapErrors.length > 0 with isNotEmptyArray(remapErrors) and add
   isNotEmptyArray to the intra-utils direct import. Plain array
   guard was missed by the isEmpty adoption pass.

2. Naming coherence — DEFAULT_RECONNECT_BASE_DELAY_MS was used at 2
   semantically different sites in ChargingStation.ts:
   - line 1608: WS reconnect exponential backoff (wsConnectionRetry
     Count driven)
   - line 2788: message resend exponential backoff (messageIdx
     driven)
   Both use the same computeExponentialBackOffDelay helper with same
   jitter/base — system-wide backoff policy. Rename to
   DEFAULT_EXPONENTIAL_BACKOFF_BASE_DELAY_MS to reflect the generic
   role and prevent 'reconnect' semantics from leaking into unrelated
   retry contexts.

3. Info-loss — the previous commit removed the '// Rough estimate:
   500 bytes per entry' comment from AVG_ENTRY_SIZE_BYTES. AVG_
   prefix + _BYTES suffix are dimensionally self-documenting but do
   NOT convey that the value is unmeasured. Restore a qualifier
   comment.

(A fourth finding — priority-3 spec-anchor comment for
MAX_ITEMS_PER_REPORT_MESSAGE naming OCPP 2.0.1 §2.1.16/§2.1.18
DeviceDataCtrlr.ItemsPerMessage/BytesPerMessage as the runtime
ceiling — was folded into its origin commit d5d33b4 via fixup
during rebase, so it does not appear in this commit's diff.)

Quality gates: typecheck clean, tests pass, lint clean.
@jerome-benoit
jerome-benoit force-pushed the refactor/factorization-audit-quick-wins branch from 35dd2f8 to 5e332b9 Compare July 5, 2026 17:17
@jerome-benoit
jerome-benoit merged commit 0b0352f into main Jul 5, 2026
44 checks passed
jerome-benoit added a commit that referenced this pull request Jul 5, 2026
…_PERSIST_STATE

Two sub-components had no parent index.ts barrel and one canonical
default was stranded in Configuration.ts. Cross-component consumers
were forced into deep imports that bypass the codebase's flat parent
barrel convention (matching src/charging-station/ocpp/index.ts,
src/charging-station/meter-values/index.ts, etc.).

New barrels:
- src/charging-station/ui-server/index.ts — exposes UIMCPServer,
  UIServerFactory, UIWebSocketServer, HttpMethod (UIServerUtils),
  DEFAULT_COMPRESSION_THRESHOLD_BYTES (UIServerSecurity), plus
  AbstractUIService and BroadcastChannelResponseLogContext from
  ui-services/. UIHttpServer is deliberately not re-exported: it is
  @deprecated pending removal in a future major, and re-exporting via
  a fresh barrel would surface the deprecation on every barrel
  consumer.
- src/charging-station/broadcast-channel/index.ts — exposes
  ChargingStationWorkerBroadcastChannel and
  UIServiceWorkerBroadcastChannel. WorkerBroadcastChannel is an
  abstract base kept internal to the sub-component (imported by its
  two concrete subclasses only).

Both new barrels carry an `@file` JSDoc header matching the peer
convention (meter-values/index.ts, ocpp/auth/index.ts) that documents
what is exposed AND — critically — what is deliberately NOT re-exported
and why. This anchors the exposure discipline in the barrel itself so
a future maintainer opening the file can see the rationale without
consulting commit history. Symmetric rationale is now stated for every
abstract-class omission (AbstractUIServer, WorkerBroadcastChannel) and
for the deprecated omission (UIHttpServer).

Extended existing barrel:
- src/utils/index.ts: add DEFAULT_PERSIST_STATE to the Configuration
  re-export. Explore F-3 finding from PR #1950 review v3 - the
  constant was exported from Configuration.ts but not surfaced by
  src/utils/index.ts, forcing any future caller to bypass the barrel.
  Zero current callers affected; closes the gap prospectively.

No consumer migrations in this PR — existing tests inside
tests/charging-station/ui-server/ and tests/charging-station/broadcast-channel/
are internal-component tests (X.test.ts imports X.ts directly per the
PR #1950 precedent) and remain valid as-is. Source-to-source deep
imports (Bootstrap.ts, ChargingStation.ts, ConfigurationSchema.ts,
UIServiceWorkerBroadcastChannel.ts, AbstractUIService.ts) are deferred
to a follow-up (PR-D') to keep this PR focused on barrel infrastructure.

Quality gates: typecheck clean, lint clean, 577/577 targeted tests
pass (ui-server + broadcast-channel + Configuration suites).
jerome-benoit added a commit that referenced this pull request Jul 5, 2026
…_PERSIST_STATE (#1952)

Close 3 barrel gaps identified during the PR #1950 audit chain.

New barrels (respect the flat parent barrel convention already used by
`src/charging-station/ocpp/index.ts`, `.../meter-values/index.ts`,
`src/performance/index.ts`):

- `src/charging-station/ui-server/index.ts` — exposes UIMCPServer,
  UIServerFactory, UIWebSocketServer, HttpMethod (UIServerUtils),
  DEFAULT_COMPRESSION_THRESHOLD_BYTES (UIServerSecurity),
  AbstractUIService, BroadcastChannelResponseLogContext. Deliberately
  omits UIHttpServer (@deprecated pending removal), AbstractUIServer
  (internal extension point), UIServerAccessPolicy/UIServerNet
  helpers, and ui-services concrete implementations — all documented
  in the `@file` JSDoc header.

- `src/charging-station/broadcast-channel/index.ts` — exposes
  ChargingStationWorkerBroadcastChannel and
  UIServiceWorkerBroadcastChannel. Deliberately omits
  WorkerBroadcastChannel (abstract base with only internal subclasses)
  — documented in the `@file` JSDoc header.

Both barrels carry an `@file` header matching the peer convention
(`meter-values/index.ts`, `ocpp/auth/index.ts`) that documents what is
exposed AND what is deliberately NOT re-exported and why — anchoring
the exposure discipline in the file itself.

Extended barrel:
- `src/utils/index.ts`: add `DEFAULT_PERSIST_STATE` to the
  `Configuration` re-export block. Closes an Explore-flagged barrel
  gap prospectively; zero current callers affected.

No consumer migrations in this PR — tests inside the sub-components
follow the "test-of-that-file uses direct import" precedent from
PR #1950. Source-to-source deep imports (5 sites: Bootstrap.ts,
ChargingStation.ts, ConfigurationSchema.ts,
UIServiceWorkerBroadcastChannel.ts, AbstractUIService.ts) are deferred
to a follow-up PR-D' to keep this PR focused on barrel infrastructure.

Quality gates: typecheck clean, lint clean, 577/577 targeted tests
pass (ui-server + broadcast-channel + Configuration suites).

Diff: +41/-1 across 3 files.

Reviews applied (3 rounds, 4 agents each): 1 substantive convergent
finding v2 addressed (JSDoc headers on both new barrels); v3 saturation
HIGH declared by 4/4 agents (0 substantive findings, 6 false positives
rejected via caller-trace).
jerome-benoit added a commit that referenced this pull request Jul 5, 2026
…annel barrels (#1953)

Migrate the 2 external cross-sub-component deep imports enabled by the barrels introduced in #1952 to route through the barrel index files per the flat parent barrel convention.

Sites migrated (2):
- Bootstrap.ts:61 UIServerFactory — deep → ui-server/index.js
- ChargingStation.ts:114 ChargingStationWorkerBroadcastChannel —
  deep → broadcast-channel/index.js

Sites deliberately NOT migrated (documented in PR body):
- Bootstrap.ts:13 AbstractUIServer (type) — not re-exported; internal
  extension point per the ui-server barrel's `@file` omission list.
- ConfigurationSchema.ts:7 UIServerNet.isHostLiteralWithoutPort —
  UIServerNet not re-exported; internal helper per the omission list.
- AbstractUIService.ts:33 UIServiceWorkerBroadcastChannel (value) —
  adjacent sub-component crossing. Migrating triggers a circular-load
  ReferenceError at test time because the broadcast-channel barrel
  re-exports both concrete channels, transitively pulling
  ChargingStationWorkerBroadcastChannel's charging-station chain back
  through ui-server before class declarations complete.
- UIServiceWorkerBroadcastChannel.ts:1 AbstractUIService (type-only) —
  adjacent sub-component crossing; kept direct for symmetry.

Convention codified: barrels are for CROSS-COMPONENT external
consumers, not for adjacent-sub-component crossings within the same
parent module. Matches the meter-values/index.ts convention.

Quality gates: typecheck clean, lint clean, 2955/2961 tests pass, 0 fail.

Diff: +2/-2 across 2 files.

Follow-up to #1952 (barrel gaps closure). PR-D' from the sequence
tracked in #1950's scope fence.
@jerome-benoit
jerome-benoit deleted the refactor/factorization-audit-quick-wins branch July 5, 2026 20:24
jerome-benoit added a commit that referenced this pull request Jul 6, 2026
… dead exports, tests (#1956)

* refactor: convention alignment round 2 — canonical defaults, helpers, dead exports, tests

Follow-up to #1950/#1952/#1953/#1954. Post-audit factorization; behavior-preserving.

Canonical defaults promoted to Constants.ts:
- UNIT_DIVIDER_CENTI/DECI (100/10); adopt UNIT_DIVIDER_KILO at 3 kW/kWh sites
- DEFAULT_RECONNECT_JITTER_PERCENT, SOC_MAXIMUM_PERCENT
- DEFAULT_AUTH_CACHE_MAX_ABSOLUTE_LIFETIME_MS
- DEFAULT_REMOTE_AUTH_CACHE_TTL_SECONDS
- MS_PER_DAY, SECONDS_PER_DAY (align with existing MS_PER_HOUR)

Canonical defaults promoted to OCPP20Constants.ts (OCPP-variable-read fallbacks):
- DEFAULT_RETRY_BACKOFF_{WAIT_MINIMUM,RANDOM_RANGE}_SECONDS
- DEFAULT_RETRY_BACKOFF_REPEAT_TIMES
- DEFAULT_CERT_SIGNING_WAIT_MINIMUM_SECONDS

Module-scope constants:
- WS_DEFLATE_{CONCURRENCY_LIMIT,SERVER_MAX_WINDOW_BITS,ZLIB_*} in UIWebSocketServer
- STATISTICS_PERCENTILE in PerformanceStatistics
- AUTH_CACHE_LIFETIME_{MIN,MAX}_SECONDS, AUTH_CACHE_MIN_ENTRIES,
  AUTH_TIMEOUT_{MIN,MAX}_SECONDS in ConfigValidator
- JITTER_PERCENT local to src/worker/ (module standalone; no cross-dep)
- SIGINT/SIGTERM_EXIT_CODE, MISSING_VALUE_PLACEHOLDER,
  TEMPLATE_NAME_SUFFIX, TRUNCATED_HASH_ID_LENGTH in ui/cli output
- SKIN_ERROR_RELOAD_COUNT_KEY in ui/web core

Helper adoption:
- millisecondsToSeconds (date-fns) at AbstractUIServer / InMemoryAuthCache / test
- isNotEmptyString in TemplateValidation
- WebSocketReadyState enum (ui-common) at CLI wsIcon/renderers and web stationStatus
- OCPP16ChargePointStatus / OCPP20ConnectorStatusEnumType enum keys instead
  of string literals in CLI STATUS_ABBREVIATIONS and web CONNECTOR_STATUS_VARIANT
- nonEmptyStringOrUndefined shared helper (ui/web/src/shared/utils) adopted
  by 3 composables + skin error extractor
- Extracted OCPPRequestService.logRequestHandlerError() consumed by OCPP16/20
  RequestService (byte-identical catch shell)

Barrel/module hygiene:
- Close barrel gap: meter-values/index.ts exposes disposeCoherentSessionRuntime
  (JSDoc already advertised it)
- UIServerAccessPolicy imports UI_SERVER_ACCESS_POLICY_DEFAULTS via utils/index
  barrel (drop deep import)
- ui/web skins route 8 imports through @/shared/utils/index barrel
- UIServiceWorkerBroadcastChannel type-only imports AbstractUIService via
  ui-server/index barrel (safe by type erasure; comment documents the constraint)

Dead barrel exports pruned (0 external consumers):
- src/utils: FieldError, applyConfigurationMigration, coerceConfigurationVersion,
  queueMicrotaskErrorThrowing (tests updated to import from source)
- charging-station/meter-values: ChargingCurvePoint
- ui-server/mcp: MCPToolSchema
- ocpp/auth: AuthStats, CacheStats, CertificateAuthProvider, CertificateInfo
- ocpp/2.0/__testable__: SendMessageFn, TestableRequestServiceOptions/Result
  re-exports; TestableOCPP20IncomingRequestService downgraded to module-private;
  TestableOCPP20VariableManager type re-export dropped

Anchor-comment reasons added on 3 eslint-disable directives (Utils /
StatisticUtils / UIServerFactory).

Test constants:
- Heartbeat interval sites use Constants.DEFAULT_HEARTBEAT_INTERVAL_MS /
  secondsToMilliseconds
- New tests/utils/TestNetworkConstants.ts: TEST_SUPERVISION_URL derived from
  Constants.DEFAULT_UI_SERVER_{HOST,PORT}; adopted at MessageChannelUtils.test
  + StorageTestHelpers + ConfigurationFixtures
- Rate-limit / mock-timers-tick 60000 literals replaced by minutesToMilliseconds(1)
  in UIServerSecurity / OCPP20CertSigningRetryManager / SignedMeterValues tests

Deliberately not applied (documented rationale):
- src/worker/WorkerAbstract isNotEmptyString adoption: src/worker/ is a
  standalone module with zero cross-module dependencies; retracted rather
  than adding an import to ../utils
- AbstractUIService → broadcast-channel/index value-import via barrel:
  empirically amplifies circular dependencies 62 → 71 because the barrel also
  re-exports ChargingStationWorkerBroadcastChannel whose transitive graph
  closes a runtime cycle back through ui-server/index; deep import kept

Quality gates:
- pnpm typecheck: clean (root + ui-common + cli + web)
- pnpm lint: 0 errors (1 pre-existing cspell warning unchanged)
- pnpm circular-deps: 62 (baseline unchanged)
- pnpm test: 2955/2961 pass (6 skipped pre-existing; 0 fail)

* [autofix.ci] apply automated fixes

* refactor: address self-review findings — DRY constant refs, helper adoption, naming

Fixes 9 findings surfaced by fan-out self-review of commit a25f4ba.
Behavior-preserving; no public API change.

Findings addressed:

- H1 (DRY, Constants.ts) — `DEFAULT_AUTH_CACHE_MAX_ABSOLUTE_LIFETIME_MS` and
  `MS_PER_DAY` both held the literal `86_400_000` (same value, same commit).
  Class-static forward-reference is illegal in TypeScript (TS2729:
  "Property 'B' is used before its initialization"), so the shared literal is
  hoisted to module-scope `DAY_IN_MS` / `DAY_IN_SECONDS` helpers before the
  class and referenced from both derived defaults and canonical time-unit
  constants. Single source of truth restored.

- H2 (DRY, ConfigValidator.ts) — `AUTH_CACHE_LIFETIME_MAX_SECONDS = 86_400`
  duplicated `Constants.SECONDS_PER_DAY = 86_400`. Fixed cross-file by
  importing `Constants` (already reachable via `../../../../utils/index.js`)
  and referencing `Constants.SECONDS_PER_DAY`.

- M1 (helper adoption, ui/cli format.ts:102) — `fuzzyTime` still used
  `diff / 1000` while the same PR adopted `millisecondsToSeconds` from
  `date-fns` at 4 other sites. Replaced by `millisecondsToSeconds(diff)`
  for consistency.

- L1 (naming coherence, ConfigValidator.ts) — Renamed
  `AUTH_CACHE_LIFETIME_{MIN,MAX}_SECONDS` to
  `AUTH_CACHE_TTL_{MIN,MAX}_SECONDS` to align with the pre-existing
  `DEFAULT_AUTH_CACHE_TTL_SECONDS` naming family. Two words for one concept
  eliminated within the auth module.

- L2 (naming coherence, ui/cli output) — Renamed cli
  `MISSING_VALUE_PLACEHOLDER` to `EMPTY_VALUE_PLACEHOLDER` to align with
  ui/web's pre-existing `EMPTY_VALUE_PLACEHOLDER`. Values remain
  medium-specific (`'–'` cli / `'Ø'` web), only the semantic role name is
  shared. 6 sites updated.

- L3 (stranded export, format.ts) — `TRUNCATED_HASH_ID_LENGTH` had zero
  external consumers (only the in-file default arg on `truncateId`).
  Dropped `export` keyword.

- L4 (stranded export, format.ts) — `TEMPLATE_NAME_SUFFIX` had zero external
  consumers (only the in-file `stripTemplateSuffix` helper). Dropped
  `export` keyword; the helper itself keeps `export` (2 external consumers).

- L5 (documented duplication, WorkerUtils.ts) — JSDoc on `JITTER_PERCENT`
  now explicitly cross-references `Constants.DEFAULT_RECONNECT_JITTER_PERCENT`
  and documents the maintenance invariant. The two constants must stay
  synchronized manually because `src/worker/` is a standalone module (no
  cross-module value imports).

- I1 (anchor accuracy, StatisticUtils.ts:52) — The
  `no-unnecessary-condition` disable reason is reworded from a plausible-
  but-imprecise "JSON.parse violation" framing to the actual root cause:
  `baseIndex+1` can equal `sortedDataSet.length`, and TypeScript indexes
  as `number` (no `noUncheckedIndexedAccess`), so the runtime `!= null`
  guard is genuinely needed for out-of-bounds protection.

Empirical retraction verifications:

- B1-5 (cycle amplification 62 → 71) — Re-verified by applying only the
  retracted change on top of `daad8a9d` and running `pnpm circular-deps`:
  62 baseline, 71 after B1-5, 62 after revert. Retraction rationale holds.

- A1-17 (`src/worker/` standalone) — Re-verified by `grep -rE
  "^import.*\.\./" src/worker/`: zero cross-module value imports; the new
  L5 JSDoc documents the exception rationale in-source.

Quality gates:
- pnpm typecheck: clean (root + ui-common + cli + web)
- pnpm lint: 0 errors (1 pre-existing cspell warning unchanged)
- pnpm circular-deps: 62 (baseline unchanged)
- pnpm test: 2955/2961 pass (6 skipped pre-existing; 0 fail)

* docs: fix JSDoc accuracy from review v3 findings (G1, A1, A2)

Doc-only follow-up to commit 6ba8503. Behavior unchanged.

- G1 (JITTER doc accuracy) — Reworded both `Constants.DEFAULT_RECONNECT_JITTER_PERCENT`
  and worker-local `JITTER_PERCENT` JSDoc from the empirically false claim
  "symmetric ±20 %" to "bounds the jitter within ±20 %". The `randomizeDelay`
  algorithm couples sign and magnitude through a single uniform draw, so with
  `random ∈ [0, 1)` and `sign = random < 0.5 ? -1 : +1` the output range is
  `(0.9·delay, delay] ∪ [1.1·delay, 1.2·delay)` — asymmetric, with a gap at
  `[delay, 1.1·delay)`. The new wording accurately caps the magnitude without
  overclaiming symmetry; the WorkerUtils docstring adds an explicit distribution
  note pointing to `randomizeDelay`. Algorithm itself pre-dates the PR and is
  behavior-preserved.

- A1 (InMemoryAuthCache @PARAM defaults) — Three JSDoc `@param default:` fields
  were pointing at raw literals (3600, 86400000, 60000) instead of the promoted
  Constants members. Aligned with the pattern already used for `maxEntries`
  (which cites `Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES`): now all six
  `@param default:` values reference the canonical `Constants.*` symbol.

- A2 (DEFAULT_REMOTE_AUTH_CACHE_TTL_SECONDS wording) — JSDoc used the phrase
  "distinct from local `_TTL_SECONDS = 3600`" where `_TTL_SECONDS` is not an
  actual symbol. Replaced by explicit sibling reference
  `DEFAULT_AUTH_CACHE_TTL_SECONDS (3600, local cache default)`.

Quality gates:
- pnpm typecheck: clean (root + ui-common + cli + web)
- pnpm lint: 0 errors (1 pre-existing cspell warning unchanged)
- pnpm circular-deps: 62 (baseline unchanged)

* fix: web-test regression from A2-5 + review v4 findings + documented quality gates

Restores web test suite to full green after documented quality gates surfaced
regressions the prior review rounds missed. Behavior-preserving vs the intent
of round-1 refactor.

Regressions fixed (QG-1/QG-2/QG-3 — blockers surfaced by `pnpm --filter web
test:coverage`):

- `stationStatus.ts` — round-1 finding A2-5 replaced `switch (status?.toLowerCase())`
  by a Record keyed by `OCPP16ChargePointStatus.*` / `OCPP20ConnectorStatusEnumType.*`
  enum values. That change (a) dropped the case-insensitive contract asserted by
  `stationStatus.test.ts:74`, and (b) introduced a module-scope runtime access
  to `ui-common` enum values, which fails at module init when the containing
  test suite mocks `ui-common` (2 file-level FAILs in `useAddStationsForm.test.ts`
  and `useStartTxForm.test.ts`).

  Design chosen (Option F in review v4 report): keep the Record structure but
  key it by lowercase string literals and normalize input via `.toLowerCase()`
  on lookup. Retains the refactor benefit (Record > switch for O(1) lookup,
  clearer add/remove semantics), restores case-insensitive input, removes the
  module-scope enum dependency, and preserves behaviour for the 9 status values
  the switch covered. Enum imports dropped since no other value site remains.

  Web test suite: 31 files / 532 tests pass (previously 3 files failed / 1
  test failed).

Review v4 low-severity findings:

- v4-A1 `Constants.ts:77` — JSDoc "bounds within ±20 %" for
  `DEFAULT_RECONNECT_JITTER_PERCENT` implied a bidirectional range, but algebra
  of the sole consumer `computeExponentialBackOffDelay` (`jitter = delay ×
  jitterPercent × secureRandom()` with `secureRandom() ∈ [0, 1)`) yields
  `jitter ∈ [0, +20 %)` strictly non-negative. Reworded to describe the
  additive-uniform-draw semantic and cross-reference the two distinct consumer
  distributions.
- v4-A2 `WorkerUtils.ts:12` — "shared jitter policy" overclaimed behavioural
  parity between the two consumers (positive-only vs asymmetric with a
  probability-zero gap). Softened to "shared jitter magnitude cap".
- v4-B1 `ConfigurationFixtures.ts:67` — `uiServer.options` still hardcoded
  `host: 'localhost', port: 8080` after the sibling `supervisionUrls` field on
  the same object literal was migrated to `TEST_SUPERVISION_URL`. Extended
  `tests/utils/TestNetworkConstants.ts` to also export `TEST_UI_SERVER_HOST`
  and `TEST_UI_SERVER_PORT` (re-exports of `Constants.DEFAULT_UI_SERVER_HOST` /
  `Constants.DEFAULT_UI_SERVER_PORT`).
- v4-B4 `ConfigurationMigrations.test.ts:130,141` — string literals
  `'ws://localhost:8080'` in a file the PR already touched (barrel-to-source
  import migration) but where the URL literals were skipped in round 2.
  Migrated to `TEST_SUPERVISION_URL`.

Lint policy alignment (user directive "aucun warning"):

- `cspell.config.yaml` — added `subclassing` (used in
  `src/charging-station/ui-server/index.ts:10`, pre-existing since #1954). Root
  lint now reports 0 errors AND 0 warnings.

Deferred (documented in review v4 report, out of this PR's scope):

- v4-B2 `ConfigValidator.ts` MIN/MAX bounds harmonization (already tracked as M2)
- v4-B3 asymmetry between `1.6/__testable__/index.ts` (exports
  `TestableOCPP16IncomingRequestService`) and `2.0/__testable__/index.ts`
  (interface demoted to non-exported in round 2). Requires either restoring
  the 2.0 export or migrating 1.6 consumers to `ReturnType<typeof …>` —
  larger touch, kept for a dedicated follow-up.
- Pre-existing gap/asymmetry in `randomizeDelay`'s distribution
  (`(−10 %, 0] ∪ [+10 %, +20 %)` — magnitude and sign both derive from a single
  uniform draw). Documented in-source, not fixed by this refactor.

Quality gates (documented per `.serena/memories/task_completion_checklist`):

- Root: `pnpm format` / `typecheck` / `lint` (0 err, 0 warn) / `build` / `test`
  (2955 pass / 6 skipped / 0 fail)
- CLI: `pnpm format` / `typecheck` / `lint` / `build` / `test` (152/152 pass)
- Web: `pnpm format` / `typecheck` / `lint` / `build` / `test:coverage`
  (532/532 pass, 31 test files)
- Circular deps: 62 (baseline unchanged)

* docs: tighten prose in 5 comments — state-describing, not narrative

Removes historical/imperative framing ("kept as", "hoisted to", "if a future
edit converts...", "must not access... because") in favour of concise
statements of what is.

- `Constants.ts:9` module-scope helper: 3→2 lines
- `Constants.ts:80` DEFAULT_RECONNECT_JITTER_PERCENT JSDoc: 6→4 lines
- `WorkerUtils.ts:1` JITTER_PERCENT JSDoc: 9→5 lines
- `UIServiceWorkerBroadcastChannel.ts:1` type-only barrier: 5→3 lines
- `stationStatus.ts:64` CONNECTOR_STATUS_VARIANT: reworded, same length

Net: -9 lines. All invariants preserved (TS2729, cross-module boundary,
runtime-cycle prevention, no-module-scope-enum). Behavior unchanged.

Quality gates:
- Root: format / typecheck / lint (0 err, 0 warn) / build / test (2955 pass)
- CLI: 5/5 clean (152/152 pass)
- Web: 5/5 clean (532/532 pass, test:coverage)

* fix: address review v5 findings — imperative comment, dead exports, module-scope enum

Applies the 3 actionable findings from review round 5. Behavior-preserving.

- v5-A1 `SkinLoadError.vue:28-32` — Reworded `resetToDefault` JSDoc from 4-line
  imperative `NOTE: ...should clear the reload-count sessionStorage key...`
  to 1-line state-describing `Counter is reset by useSkin.switchSkin on
  successful load.` Missed by the round-4 comment tightening sweep.

- v5-B1 `TestNetworkConstants.ts` / `ConfigurationFixtures.ts` — Retired
  `TEST_UI_SERVER_HOST` / `TEST_UI_SERVER_PORT` exports (1 external consumer
  each, both at the same `ConfigurationFixtures.ts:71` expression — criterion 10
  requires ≥2 consumers). Inlined `Constants.DEFAULT_UI_SERVER_HOST` /
  `Constants.DEFAULT_UI_SERVER_PORT` at the single call site.
  `TEST_SUPERVISION_URL` remains exported (5 consumers).

- v5-B2 `ui/web/src/shared/utils/stationStatus.ts` — Removed the module-scope
  value import `import { WebSocketReadyState } from 'ui-common'` and switched
  `getWebSocketStateVariant` to 4 module-local numeric constants
  `WS_STATE_{CONNECTING,OPEN,CLOSING,CLOSED} = 0/1/2/3`. Eliminates the same
  ui-common runtime module-scope dependency that the round-4 fix removed for
  `CONNECTOR_STATUS_VARIANT`. No behavior change (values match WHATWG WebSocket
  readyState spec).

Quality gates:
- Root: 5/5 clean, 2942/2948 pass
- CLI: 5/5 clean, 152/152 pass
- Web: 5/5 clean, 532/532 pass (test:coverage)
- Circular deps: 62 (baseline)

* docs: drop narrative comments in stationStatus.ts

Removes two comment blocks that narrated rationale ("mirror of...",
"module-local to keep...", "test suites mock...") instead of describing
what is. The `WS_STATE_*` constants and lowercase Record keys are
self-documenting.

- `stationStatus.ts:62-66` — 4-line rationale block removed; `cspell:ignore`
  directive retained
- `stationStatus.ts:83-85` — 3-line rationale block removed

Quality gates: root/web 5/5 clean, 532/532 pass.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant