@nexgen-os/fluvius 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nexgen OS contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # `@nexgen-os/fluvius`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Fluvius](https://www.fluvius.be), the distribution operator of Flanders,
4
+ as a meter data connector of Nexgen OS, on its **API for service providers**
5
+ (dienstverleners), version 3 (`https://apihub.fluvius.be/esco-live/v3/api`,
6
+ the sandbox at `esco-sbx`;
7
+ [guide](https://partner.fluvius.be/sites/fluvius/files/2024-03/ontsluiten-van-verbruiksdata-via-api-v2-met-addendum-maart2024.pdf)).
8
+ A service provider signs a data access contract with the operator; the
9
+ customer then gives it their consent on the operator's own page, and the
10
+ operator opens the quarter-hour energy of the meter. MIT.
11
+
12
+ ## The path of a load curve
13
+
14
+ 1. **Consent.** `consentLink({ referenceNumber, flow, dataPeriodFrom,
15
+ dataPeriodTo })` (`POST /shortUrlIdentifier`) gives the page where the
16
+ customer signs (`https://mijn.fluvius.be/verbruik/dienstverlener?id=…`)
17
+ and until when it can be signed. The installation records a mandate on
18
+ the meter (`grid.request_mandate()`) with the `referenceNumber` as its
19
+ `external_reference`.
20
+ 2. **Follow it.** `mandates()` (`GET /mandate`) lists the mandates of the
21
+ service provider; `mandateStatusOf()` says what the operator's status
22
+ means for the mandate of the `grid` module: `Approved` → `approved`
23
+ (`grid.decide_mandate()`), `Rejected` → `refused`, `Finished` →
24
+ `expired`, `Requested` → nothing yet.
25
+ 3. **Read.** `collectMeterReadings(db, fluvius({ … }), { connectorId,
26
+ meterId, from, to, step: 'PT15M' })` of `@nexgen-os/core` asks the one
27
+ mandate check (`grid.authorise_reading()`) first, then calls
28
+ `readings()`, which:
29
+ - refuses without the mandate the check returned (`mandate_missing`), a
30
+ step other than the quarter hour (`step_unsupported`), an EAN that is
31
+ not 18 digits (`invalid_identifier`), and a hub without its zone
32
+ (`time_zone_required`);
33
+ - asks `GET /mandate/energy` by EAN for the days `from` to `to` (`to`
34
+ excluded), each day from midnight in the hub's zone, to the second;
35
+ - returns the meter's `offtake_energy` and `injection_energy`, kWh per
36
+ quarter hour, each value dated at the start of its step in UTC (a
37
+ stamp without an offset is read in the hub's zone), with the quality
38
+ the pack maps the value's `validationState` to.
39
+
40
+ | From the answer | Series of the meter |
41
+ |---|---|
42
+ | `quarterHourlyEnergy[].measurements[0].offtake.total` | `offtake_energy`, kWh, 15 minutes |
43
+ | `quarterHourlyEnergy[].measurements[0].injection.total` | `injection_energy`, kWh, 15 minutes |
44
+
45
+ The hub's conventions are the be pack's row of the operator
46
+ (`grid.operators.meter_data` of `fluvius`): its zone, its steps and its
47
+ quality table. The table holds `READ`, the state of a value read on the
48
+ meter; a state it does not hold is refused by name (`quality_unknown`)
49
+ rather than guessed: add it to the pack when it is met.
50
+
51
+ ## Configuration
52
+
53
+ An organisation's `connectors` row names the source
54
+ `fluvius_service_provider_api` (the be pack's), its secrets by `secret_ref`
55
+ (the vault holds them; the caller resolves them and passes them as
56
+ `credentials`, the connector reads no environment), and in `config`:
57
+
58
+ | Key | What |
59
+ |---|---|
60
+ | `environment` | `live` (by default: the certificate) or `sandbox` (the client secret) |
61
+ | `tenant_id`, `scope` | the operator's tenant and the scope of its API, as its onboarding document gives them |
62
+ | `contract_number` | the service provider's data access contract number, which every consent link names |
63
+
64
+ ```ts
65
+ const client = fluvius({
66
+ credentials: { clientId, subscriptionKey, certificate, privateKey }, // from the vault
67
+ tenantId: config.tenant_id, scope: config.scope, contractNumber: config.contract_number,
68
+ });
69
+ ```
70
+
71
+ In live, the token is asked with a client assertion: a JWT signed RS256 by
72
+ the key of the certificate the operator registered, its SHA-1 thumbprint in
73
+ `x5t`, valid ten minutes (`clientAssertion()`). The key may be PKCS#1 or
74
+ PKCS#8. A token is kept until a minute before it lapses.
75
+
76
+ ## What is not done yet
77
+
78
+ - The answers in `tests/fixtures` follow the shape the live API answers,
79
+ with made-up identifiers and values: record real ones in the sandbox and
80
+ keep them beside these; the tests must pass unchanged.
81
+ - Daily and monthly energy (`VH_dag`, `VH_maand`), gas, and the reading by
82
+ insertion time (`periodType=insertTime`) are not read yet.
83
+
84
+ ## Licence
85
+
86
+ MIT ([`LICENSE`](LICENSE)).
@@ -0,0 +1,113 @@
1
+ import { type CollectedSeries, type MeterDataHub, type MeterDataProvider, type MeterOfHub } from '@nexgen-os/core';
2
+ /** The subset of `fetch` the connector uses, so a test or a proxy can stand in. */
3
+ export type HttpFetch = (url: string, init?: {
4
+ method?: string;
5
+ headers?: Record<string, string>;
6
+ body?: string;
7
+ }) => Promise<{
8
+ ok: boolean;
9
+ status: number;
10
+ json(): Promise<unknown>;
11
+ text(): Promise<string>;
12
+ }>;
13
+ /** What the operator gave the service provider at its onboarding, resolved by the caller from the connector's `secret_ref`; never stored. */
14
+ export interface FluviusCredentials {
15
+ /** The application's client id in the operator's tenant. */
16
+ clientId: string;
17
+ /** The gateway's subscription key (`Ocp-Apim-Subscription-Key`). */
18
+ subscriptionKey: string;
19
+ /** The sandbox's client secret. */
20
+ clientSecret?: string;
21
+ /** Live: the PEM of the certificate the operator registered, and of its private key (PKCS#1 or PKCS#8). */
22
+ certificate?: string;
23
+ privateKey?: string;
24
+ }
25
+ export interface FluviusOptions {
26
+ credentials: FluviusCredentials;
27
+ /** `live` (`esco-live`, certificate) or `sandbox` (`esco-sbx`, secret); from `connectors.config.environment`, `live` by default. */
28
+ environment?: 'live' | 'sandbox';
29
+ /** The tenant and the scope of the API, as the onboarding document gives them; from `connectors.config`. */
30
+ tenantId: string;
31
+ scope: string;
32
+ /** The service provider's data access contract number, for the consent link; from `connectors.config`. */
33
+ contractNumber?: string;
34
+ /** Default `https://apihub.fluvius.be`. */
35
+ baseUrl?: string;
36
+ /** Default `https://login.microsoftonline.com`. */
37
+ authorityUrl?: string;
38
+ /** Default the operator's page `https://mijn.fluvius.be/verbruik/dienstverlener`, which the link's id is appended to. */
39
+ consentPageUrl?: string;
40
+ fetch?: HttpFetch;
41
+ /** The clock, in milliseconds; a test passes a fixed one. */
42
+ now?: () => number;
43
+ }
44
+ /** The status of a mandate as the operator writes it. */
45
+ export type FluviusMandateStatus = 'Requested' | 'Approved' | 'Rejected' | 'Finished';
46
+ /** A mandate as `GET /mandate` lists it. */
47
+ export interface FluviusMandate {
48
+ referenceNumber: string;
49
+ status: string;
50
+ ean: string | null;
51
+ /** `VH_kwartier_uur` (quarter hours), `VH_dag`, `VH_maand`. */
52
+ dataServiceType: string | null;
53
+ dataPeriodFrom: string | null;
54
+ dataPeriodTo: string | null;
55
+ }
56
+ /** What the consent link is asked for: the reference the mandate will carry, the customer's flow, the data and its period. */
57
+ export interface ConsentRequest {
58
+ /** The reference the mandate carries at the operator, kept as the mandate's `external_reference`. */
59
+ referenceNumber: string;
60
+ /** `B2C` for a household, `B2B` for a company. */
61
+ flow: 'B2C' | 'B2B';
62
+ /** `VH_kwartier_uur` by default. */
63
+ dataServiceType?: string;
64
+ /** The readings the mandate covers, ISO 8601 instants. */
65
+ dataPeriodFrom: string;
66
+ dataPeriodTo: string;
67
+ }
68
+ export interface ConsentLink {
69
+ id: string;
70
+ /** The operator's page where the customer signs. */
71
+ url: string;
72
+ /** Until when the link can be signed, as the operator answers it. */
73
+ validTo: string | null;
74
+ }
75
+ /** The statuses of the operator, and what each one means for a mandate of the grid module. */
76
+ export declare const FLUVIUS_MANDATE_STATUSES: {
77
+ readonly Approved: "approved";
78
+ readonly Rejected: "refused";
79
+ readonly Finished: "expired";
80
+ };
81
+ /**
82
+ * What the operator's status means for the mandate: `approved`, `refused`
83
+ * or `expired`; null for `Requested` (the customer has not signed yet) and
84
+ * for a status it does not know.
85
+ */
86
+ export declare function mandateStatusOf(status: string | null | undefined): 'approved' | 'refused' | 'expired' | null;
87
+ export interface FluviusConnector extends MeterDataProvider {
88
+ readonly source_code: 'fluvius_service_provider_api';
89
+ /** The mandates the service provider holds, every status. */
90
+ mandates(): Promise<FluviusMandate[]>;
91
+ /** A link the customer signs on the operator's page; refuses `contract_number_required` without the contract number. */
92
+ consentLink(request: ConsentRequest): Promise<ConsentLink>;
93
+ }
94
+ /** A connector on the operator's API for service providers, version 3. `source_code` is `fluvius_service_provider_api`. */
95
+ export declare function fluvius(options: FluviusOptions): FluviusConnector;
96
+ /**
97
+ * Each quarter hour of the answer, offtake and injection, as the series of
98
+ * the meter; a state the hub's table does not hold is refused by name.
99
+ *
100
+ * The answer is the one of the API for service providers the Belgian
101
+ * distribution operators run, read the same for each of them: `headpoint`
102
+ * is one metering point or a list of them (the one of the meter is kept),
103
+ * and its quarter hours sit under its physical meters (a digital meter) or
104
+ * on the point itself (a meter read remotely, whose values the operator
105
+ * gives for the whole point). `operator` names the hub in a refusal.
106
+ */
107
+ export declare function energySeries(answer: unknown, meter: Pick<MeterOfHub, 'identifier' | 'direction'>, hub: Pick<MeterDataHub, 'time_zone' | 'quality_codes'>, operator?: string): CollectedSeries[];
108
+ /** The first instant of a day (`YYYY-MM-DD`) in a zone, to the second, as the operator wants it. */
109
+ export declare function startOfDay(day: string, timeZone: string): string;
110
+ /** An instant to the second, without milliseconds: the operator refuses them. */
111
+ export declare function seconds(iso: string): string;
112
+ /** The client assertion of the live environment: a JWT signed RS256 by the registered certificate's key, its thumbprint in `x5t`, ten minutes long. */
113
+ export declare function clientAssertion(credentials: Pick<FluviusCredentials, 'clientId' | 'certificate' | 'privateKey'>, audience: string, nowMs: number): string;
package/dist/index.js ADDED
@@ -0,0 +1,262 @@
1
+ // Fluvius — the Flemish distribution operator's API for service providers
2
+ // (dienstverleners), as a connector, on its version 3 (`apihub.fluvius.be`,
3
+ // `esco-live` or `esco-sbx`). Source `fluvius_service_provider_api`, the be
4
+ // pack's.
5
+ //
6
+ // The path of a load curve: the service provider asks a consent link
7
+ // (`POST /shortUrlIdentifier`) under its data access contract; the customer
8
+ // signs it on the operator's page; the mandate appears in `GET /mandate`
9
+ // with the status `Approved`; the quarter-hour energy of the meter is read
10
+ // by EAN (`GET /mandate/energy`), offtake and injection in one answer.
11
+ // `collectMeterReadings()` of `@nexgen-os/core` checks the mandate first
12
+ // and stores what comes back on the meter.
13
+ //
14
+ // Authentication is Microsoft Entra ID's client credentials: a client
15
+ // secret in the sandbox, a client assertion signed by the certificate the
16
+ // operator registered in live, and the gateway's subscription key on every
17
+ // call. Nothing here reads the environment or the database: the secrets are
18
+ // given by the caller, resolved from the `secret_ref` of the organisation's
19
+ // `connectors` row; the hub's conventions (its zone, its quality table, its
20
+ // steps) come from its pack row.
21
+ import { X509Certificate, createHash, createSign, randomUUID } from 'node:crypto';
22
+ import { GestureError, requireMandate, } from '@nexgen-os/core';
23
+ import { instantsOf } from '@nexgen-os/enedis-r6x';
24
+ /** The statuses of the operator, and what each one means for a mandate of the grid module. */
25
+ export const FLUVIUS_MANDATE_STATUSES = {
26
+ Approved: 'approved',
27
+ Rejected: 'refused',
28
+ Finished: 'expired',
29
+ };
30
+ /**
31
+ * What the operator's status means for the mandate: `approved`, `refused`
32
+ * or `expired`; null for `Requested` (the customer has not signed yet) and
33
+ * for a status it does not know.
34
+ */
35
+ export function mandateStatusOf(status) {
36
+ return FLUVIUS_MANDATE_STATUSES[String(status ?? '')] ?? null;
37
+ }
38
+ const QUARTER_HOUR = 'PT15M';
39
+ /** A connector on the operator's API for service providers, version 3. `source_code` is `fluvius_service_provider_api`. */
40
+ export function fluvius(options) {
41
+ const { credentials } = options;
42
+ const environment = options.environment ?? 'live';
43
+ if (!credentials?.clientId || !credentials.subscriptionKey) {
44
+ throw new GestureError('secret_not_found: fluvius needs the client id and the subscription key its connectors row names');
45
+ }
46
+ if (environment === 'live' && (!credentials.certificate || !credentials.privateKey)) {
47
+ throw new GestureError('secret_not_found: fluvius live needs the certificate and the private key its connectors row names');
48
+ }
49
+ if (environment === 'sandbox' && !credentials.clientSecret) {
50
+ throw new GestureError('secret_not_found: fluvius sandbox needs the client secret its connectors row names');
51
+ }
52
+ if (!options.tenantId || !options.scope) {
53
+ throw new GestureError('config_invalid: fluvius needs the tenant and the scope of the API in its connectors row');
54
+ }
55
+ const base = `${(options.baseUrl ?? 'https://apihub.fluvius.be').replace(/\/+$/, '')}/${environment === 'live' ? 'esco-live' : 'esco-sbx'}/v3/api`;
56
+ const authority = (options.authorityUrl ?? 'https://login.microsoftonline.com').replace(/\/+$/, '');
57
+ const tokenUrl = `${authority}/${encodeURIComponent(options.tenantId)}/oauth2/v2.0/token`;
58
+ const consentPage = options.consentPageUrl ?? 'https://mijn.fluvius.be/verbruik/dienstverlener';
59
+ const doFetch = options.fetch ?? globalThis.fetch;
60
+ const now = options.now ?? Date.now;
61
+ let token = null;
62
+ const accessToken = async () => {
63
+ if (token && now() < token.until)
64
+ return token.value;
65
+ const form = new URLSearchParams({ grant_type: 'client_credentials', client_id: credentials.clientId, scope: options.scope });
66
+ if (environment === 'live') {
67
+ form.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
68
+ form.set('client_assertion', clientAssertion(credentials, tokenUrl, now()));
69
+ }
70
+ else {
71
+ form.set('client_secret', credentials.clientSecret);
72
+ }
73
+ const response = await doFetch(tokenUrl, {
74
+ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, body: form.toString(),
75
+ });
76
+ if (!response.ok) {
77
+ const detail = (await response.text().catch(() => '')).slice(0, 300);
78
+ throw new GestureError(`source_unauthorised: fluvius token ${response.status}: ${detail}`);
79
+ }
80
+ const answer = (await response.json());
81
+ if (!answer.access_token)
82
+ throw new GestureError('source_unauthorised: fluvius token answer carries no access_token');
83
+ // A minute short of its end, so that no call leaves with a token about to lapse.
84
+ token = { value: answer.access_token, until: now() + (Number(answer.expires_in ?? 3600) - 60) * 1000 };
85
+ return token.value;
86
+ };
87
+ const call = async (path, method = 'GET', body) => {
88
+ const headers = {
89
+ Authorization: `Bearer ${await accessToken()}`, 'Ocp-Apim-Subscription-Key': credentials.subscriptionKey, Accept: 'application/json',
90
+ };
91
+ if (body !== undefined)
92
+ headers['Content-Type'] = 'application/json';
93
+ const response = await doFetch(`${base}${path}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
94
+ if (response.status === 404)
95
+ return { status: 404, data: null };
96
+ if (!response.ok) {
97
+ const detail = (await response.text().catch(() => '')).slice(0, 300);
98
+ if (response.status === 401 || response.status === 403)
99
+ throw new GestureError(`source_unauthorised: fluvius ${response.status} on ${path.replace(/\?.*$/, '')}: ${detail}`);
100
+ throw new GestureError(`source_unavailable: fluvius ${response.status} on ${method} ${path.replace(/\?.*$/, '')}: ${detail}`);
101
+ }
102
+ return { status: response.status, data: response.status === 204 ? null : await response.json() };
103
+ };
104
+ return {
105
+ source_code: 'fluvius_service_provider_api',
106
+ async mandates() {
107
+ const { data } = await call('/mandate');
108
+ const list = (data?.data?.mandates ?? []);
109
+ return list.map((m) => ({
110
+ referenceNumber: String(m.referenceNumber ?? ''),
111
+ status: String(m.status ?? ''),
112
+ ean: typeof m.ean === 'string' ? m.ean : null,
113
+ dataServiceType: typeof m.dataServiceType === 'string' ? m.dataServiceType : null,
114
+ dataPeriodFrom: typeof m.dataPeriodFrom === 'string' ? m.dataPeriodFrom : null,
115
+ dataPeriodTo: typeof m.dataPeriodTo === 'string' ? m.dataPeriodTo : null,
116
+ }));
117
+ },
118
+ async consentLink(request) {
119
+ if (!options.contractNumber) {
120
+ throw new GestureError('contract_number_required: a consent link names the data access contract; set contract_number in the connectors row');
121
+ }
122
+ const { data } = await call('/shortUrlIdentifier', 'POST', {
123
+ dataAccessContractNumber: options.contractNumber,
124
+ referenceNumber: request.referenceNumber,
125
+ flow: request.flow,
126
+ dataServices: [{
127
+ dataServiceType: request.dataServiceType ?? 'VH_kwartier_uur',
128
+ dataPeriodFrom: seconds(request.dataPeriodFrom),
129
+ dataPeriodTo: seconds(request.dataPeriodTo),
130
+ }],
131
+ });
132
+ const answer = (data?.data ?? data ?? {});
133
+ const id = typeof answer.shortUrlIdentifier === 'string' ? answer.shortUrlIdentifier : '';
134
+ if (!id)
135
+ throw new GestureError('source_unavailable: fluvius answered no shortUrlIdentifier');
136
+ return { id, url: `${consentPage}?id=${encodeURIComponent(id)}`, validTo: typeof answer.validTo === 'string' ? answer.validTo : null };
137
+ },
138
+ async readings(meter, from, to, readOptions = {}) {
139
+ requireMandate('fluvius_service_provider_api', readOptions.mandate, readOptions.scope ?? 'load_curve');
140
+ if (readOptions.step && readOptions.step !== QUARTER_HOUR) {
141
+ throw new GestureError(`step_unsupported: fluvius reads quarter hours (${QUARTER_HOUR}), not ${readOptions.step}`);
142
+ }
143
+ if (!/^\d{18}$/.test(meter.identifier)) {
144
+ throw new GestureError(`invalid_identifier: ${meter.identifier} is not an EAN of 18 digits`);
145
+ }
146
+ const hub = readOptions.hub ?? { time_zone: null, quality_codes: {} };
147
+ if (!hub.time_zone) {
148
+ throw new GestureError('time_zone_required: the days asked are the hub\'s; its pack row names no time_zone');
149
+ }
150
+ const params = new URLSearchParams({
151
+ ean: meter.identifier, periodType: 'readTime', from: startOfDay(from, hub.time_zone), to: startOfDay(to, hub.time_zone),
152
+ });
153
+ const { data } = await call(`/mandate/energy?${params.toString()}`);
154
+ return energySeries(data, meter, hub);
155
+ },
156
+ };
157
+ }
158
+ /**
159
+ * Each quarter hour of the answer, offtake and injection, as the series of
160
+ * the meter; a state the hub's table does not hold is refused by name.
161
+ *
162
+ * The answer is the one of the API for service providers the Belgian
163
+ * distribution operators run, read the same for each of them: `headpoint`
164
+ * is one metering point or a list of them (the one of the meter is kept),
165
+ * and its quarter hours sit under its physical meters (a digital meter) or
166
+ * on the point itself (a meter read remotely, whose values the operator
167
+ * gives for the whole point). `operator` names the hub in a refusal.
168
+ */
169
+ export function energySeries(answer, meter, hub, operator = 'fluvius') {
170
+ const given = answer?.data?.headpoint;
171
+ const points = given === undefined || given === null ? [] : Array.isArray(given) ? given : [given];
172
+ const headpoints = points.filter((point) => point.ean === undefined || String(point.ean) === meter.identifier);
173
+ if (points.length > 0 && headpoints.length === 0) {
174
+ throw new GestureError(`source_unavailable: ${operator} answered for ${points.map((point) => String(point.ean)).join(', ')}, not ${meter.identifier}`);
175
+ }
176
+ const quarters = headpoints.flatMap((point) => [
177
+ ...(point.quarterHourlyEnergy ?? []),
178
+ ...(point.physicalMeters ?? point.physiclaMeters ?? []).flatMap((physical) => physical.quarterHourlyEnergy ?? []),
179
+ ]);
180
+ const directions = meter.direction === 'offtake' ? ['offtake']
181
+ : meter.direction === 'injection' ? ['injection'] : ['offtake', 'injection'];
182
+ const out = [];
183
+ for (const direction of directions) {
184
+ const values = [];
185
+ for (const quarter of quarters) {
186
+ const total = quarter.measurements?.[0]?.[direction]?.total;
187
+ if (!total || typeof total.value !== 'number')
188
+ continue;
189
+ const state = typeof total.validationState === 'string' && total.validationState !== '' ? total.validationState : 'none';
190
+ const quality = hub.quality_codes[state];
191
+ if (quality === undefined) {
192
+ throw new GestureError(`quality_unknown: ${operator} state ${JSON.stringify(state)} at ${String(quarter.start)} is not in the hub's quality table; add it to the pack row`);
193
+ }
194
+ values.push({ at: instant(String(quarter.start ?? ''), hub.time_zone, operator), value: total.value, quality });
195
+ }
196
+ if (values.length === 0)
197
+ continue;
198
+ values.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
199
+ out.push({ quantity_code: `${direction}_energy`, value_kind: 'interval', step: '15 minutes', unit: 'kWh', values });
200
+ }
201
+ return out;
202
+ }
203
+ /** A stamp of the answer in UTC: its own offset, else the hub's zone; a stamp the zone skips or repeats is refused. */
204
+ function instant(text, timeZone, operator) {
205
+ if (/(Z|[+-]\d{2}:?\d{2})$/.test(text)) {
206
+ const ms = Date.parse(text);
207
+ if (Number.isNaN(ms))
208
+ throw new GestureError(`date_unreadable: ${operator} stamp ${JSON.stringify(text)}`);
209
+ return new Date(ms).toISOString();
210
+ }
211
+ const wall = Date.parse(`${text}Z`);
212
+ if (Number.isNaN(wall))
213
+ throw new GestureError(`date_unreadable: ${operator} stamp ${JSON.stringify(text)}`);
214
+ if (!timeZone)
215
+ throw new GestureError(`time_zone_required: ${operator} stamp ${text} carries no offset and the hub names no time_zone`);
216
+ const found = instantsOf(timeZone, wall);
217
+ if (found.length !== 1)
218
+ throw new GestureError(`date_unreadable: ${operator} stamp ${text} is ${found.length === 0 ? 'skipped' : 'repeated'} in ${timeZone}`);
219
+ return new Date(found[0]).toISOString();
220
+ }
221
+ /** The first instant of a day (`YYYY-MM-DD`) in a zone, to the second, as the operator wants it. */
222
+ export function startOfDay(day, timeZone) {
223
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day))
224
+ throw new GestureError(`date_unreadable: ${JSON.stringify(day)} is not YYYY-MM-DD`);
225
+ const wall = Date.parse(`${day}T00:00:00Z`);
226
+ const found = instantsOf(timeZone, wall);
227
+ if (found.length === 0)
228
+ throw new GestureError(`date_unreadable: midnight of ${day} does not exist in ${timeZone}`);
229
+ return seconds(new Date(found[0]).toISOString());
230
+ }
231
+ /** An instant to the second, without milliseconds: the operator refuses them. */
232
+ export function seconds(iso) {
233
+ const ms = Date.parse(iso);
234
+ if (Number.isNaN(ms))
235
+ throw new GestureError(`date_unreadable: ${JSON.stringify(iso)}`);
236
+ return new Date(Math.floor(ms / 1000) * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z');
237
+ }
238
+ /** The client assertion of the live environment: a JWT signed RS256 by the registered certificate's key, its thumbprint in `x5t`, ten minutes long. */
239
+ export function clientAssertion(credentials, audience, nowMs) {
240
+ let der;
241
+ try {
242
+ der = new X509Certificate(credentials.certificate).raw;
243
+ }
244
+ catch {
245
+ throw new GestureError('certificate_unreadable: fluvius live needs the PEM of the certificate the operator registered');
246
+ }
247
+ const issued = Math.floor(nowMs / 1000);
248
+ const header = { alg: 'RS256', typ: 'JWT', x5t: base64url(createHash('sha1').update(der).digest()) };
249
+ const payload = { aud: audience, iss: credentials.clientId, sub: credentials.clientId, jti: randomUUID(), nbf: issued, iat: issued, exp: issued + 600 };
250
+ const input = `${base64url(Buffer.from(JSON.stringify(header)))}.${base64url(Buffer.from(JSON.stringify(payload)))}`;
251
+ let signature;
252
+ try {
253
+ signature = createSign('RSA-SHA256').update(input).sign(credentials.privateKey);
254
+ }
255
+ catch {
256
+ throw new GestureError('certificate_unreadable: fluvius live needs the PEM of the certificate\'s private key');
257
+ }
258
+ return `${input}.${base64url(signature)}`;
259
+ }
260
+ function base64url(bytes) {
261
+ return bytes.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
262
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@nexgen-os/fluvius",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "description": "The Fluvius API for service providers as a Nexgen OS meter data connector: the customer's consent link, the mandates, and the quarter-hour energy of a meter read under mandate.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nexgen-os/nexgen-os.git",
9
+ "directory": "packages/connectors/fluvius"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "scripts": {
32
+ "build": "tsc -p tsconfig.build.json"
33
+ },
34
+ "dependencies": {
35
+ "@nexgen-os/core": "^0.5.0",
36
+ "@nexgen-os/enedis-r6x": "^0.5.0"
37
+ }
38
+ }