@nexgen-os/core 0.4.2 → 0.5.1

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.
@@ -0,0 +1,99 @@
1
+ /**
2
+ * A PV*SOL study into the model: `@nexgen-os/pvsol` reads the .pvprj file,
3
+ * and this file gives what it describes to the gestures of the core — the
4
+ * project, its participant and the inverters through `importProject()`, the
5
+ * PV system and its arrays, each with its own orientation, through
6
+ * `describePvSystem()` of the `solar` module. So a study imported again finds
7
+ * what is there and adds only what is new: the PV system is found by its
8
+ * name at its participant.
9
+ *
10
+ * What a study describes is a design: nothing is dated as installed, and the
11
+ * country is the caller's, never assumed. The load profile and the results
12
+ * PV*SOL simulated stay in the study read (`study`) for the module that
13
+ * compares or keeps them; nothing of them is written here.
14
+ *
15
+ * A study whose arrays lack a power or an orientation is refused before
16
+ * anything is written, `pvsol_incomplete`: an importer never guesses a
17
+ * figure. What the reader named stays as warnings.
18
+ */
19
+ import { readPvsolStudy } from '@nexgen-os/pvsol';
20
+ import { describePvSystem, requireModule } from '../gestures.js';
21
+ import { GestureError } from '../refusal.js';
22
+ import { importProject } from './project.js';
23
+ /** The name a study gives its PV system, its project and its participant, unless the caller names them. */
24
+ function names(study, options) {
25
+ const title = study.project.title ?? 'PV*SOL study';
26
+ return { project: options.project ?? title, participant: options.participant ?? study.project.customer_company ?? title, system: title };
27
+ }
28
+ /**
29
+ * A study as the description `importProject()` takes: the project in the
30
+ * caller's country, one participant — a prosumer when the study carries a
31
+ * consumption, a producer otherwise — at the address of the system as the
32
+ * study writes it, in one line for a geocoder to place, and its inverters by
33
+ * manufacturer and model, with their count.
34
+ */
35
+ export function projectOfPvsolStudy(study, options) {
36
+ const named = names(study, options);
37
+ const consumes = study.load_profile !== null || (study.results?.consumption_kwh ?? 0) > 0;
38
+ return {
39
+ name: named.project,
40
+ country: options.country,
41
+ participants: [{
42
+ name: named.participant,
43
+ category: consumes ? 'prosumer' : 'producer',
44
+ place: { country: options.country, ...(study.project.site_address ? { address_line1: study.project.site_address } : {}) },
45
+ ...(options.time_zone ? { time_zone: options.time_zone } : {}),
46
+ devices: study.inverters.map((i) => ({
47
+ device_type: 'inverter',
48
+ name: [i.manufacturer, i.model].filter(Boolean).join(' ') || 'Inverter',
49
+ unit_count: i.count,
50
+ })),
51
+ }],
52
+ };
53
+ }
54
+ /**
55
+ * Writes a PV*SOL study — the bytes of its .pvprj file or the study already
56
+ * read — into an organisation, or finds it there: see the head of this file.
57
+ * Refuses `pvsol_unreadable` (not a PV*SOL study), `pvsol_incomplete` (an
58
+ * array without a power or an orientation, or no array at all),
59
+ * `module_not_installed` (the `solar` module holds the arrays), and what
60
+ * `importProject()` and `describePvSystem()` refuse.
61
+ */
62
+ export async function importPvsolStudy(db, organisationId, file, options) {
63
+ let study;
64
+ try {
65
+ study = file instanceof Uint8Array ? readPvsolStudy(file) : file;
66
+ }
67
+ catch (e) {
68
+ throw new GestureError(e.message);
69
+ }
70
+ if (study.arrays.length === 0)
71
+ throw new GestureError('pvsol_incomplete: the study holds no array with modules');
72
+ const arrays = study.arrays.map((a) => {
73
+ if (a.power_kwp === null || a.azimuth_deg === null || a.tilt_deg === null) {
74
+ const missing = [a.power_kwp === null && 'power', a.azimuth_deg === null && 'azimuth', a.tilt_deg === null && 'tilt'].filter(Boolean).join(', ');
75
+ throw new GestureError(`pvsol_incomplete: the array ${a.name} has no ${missing}`);
76
+ }
77
+ return { name: a.name, azimuth_deg: a.azimuth_deg, tilt_deg: a.tilt_deg, kwp: a.power_kwp };
78
+ });
79
+ await requireModule(db, 'solar');
80
+ const named = names(study, options);
81
+ const project = await importProject(db, organisationId, projectOfPvsolStudy(study, options), options);
82
+ const participantId = project.objects.find((o) => o.kind === 'participant')?.id ?? null;
83
+ const found = participantId === null ? undefined
84
+ : (await db.query(`select id from devices where participant_id = $1 and name = $2 and device_type = 'solar'`, [participantId, named.system])).rows[0];
85
+ let pvSystem;
86
+ if (found) {
87
+ const rows = (await db.query('select id from solar.pv_arrays where device_id = $1 order by name', [found.id])).rows;
88
+ pvSystem = { name: named.system, outcome: 'found', device_id: found.id, arrays: rows.map((r) => r.id) };
89
+ }
90
+ else if (options.dryRun || participantId === null) {
91
+ pvSystem = { name: named.system, outcome: 'to_create', device_id: null, arrays: [] };
92
+ }
93
+ else {
94
+ const kwp = Math.round(arrays.reduce((s, a) => s + a.kwp, 0) * 1e6) / 1e6;
95
+ const made = await describePvSystem(db, { participant_id: participantId, name: named.system, kwp, arrays });
96
+ pvSystem = { name: named.system, outcome: 'created', device_id: made.device_id, arrays: made.arrays };
97
+ }
98
+ return { dry_run: options.dryRun ?? false, project, pv_system: pvSystem, warnings: study.problems, study };
99
+ }
@@ -9,7 +9,7 @@
9
9
  * `writeEpw()` writes.
10
10
  */
11
11
  import { type WeatherFile, type WeatherFileLocation, type WeatherFileWarning, type WeatherYear } from '@nexgen-os/weather-files';
12
- import type { Db } from '../db.js';
12
+ import { type Db } from '../db.js';
13
13
  export interface WeatherTarget {
14
14
  organisationId: string;
15
15
  /** The object the weather is about, by its kind and its id: a weather point, a participant. */
@@ -22,7 +22,8 @@ export interface WeatherTarget {
22
22
  * station network, a licensed model). A typical year is `simulated` and
23
23
  * named after its years (`typical year 2005-2020`); real years are
24
24
  * `measured` and unnamed, unless told otherwise. Importing the same file
25
- * again replaces the values.
25
+ * again replaces the values. The file is stored whole or not at all: one
26
+ * series refused leaves none of the others.
26
27
  */
27
28
  export declare function importWeatherFile(db: Db, target: WeatherTarget, file: WeatherFile, options: {
28
29
  sourceCode: string;
@@ -9,6 +9,7 @@
9
9
  * `writeEpw()` writes.
10
10
  */
11
11
  import { WEATHER_QUANTITIES } from '@nexgen-os/weather-files';
12
+ import { atomically } from '../db.js';
12
13
  import { storeSeries } from '../connectors/interfaces.js';
13
14
  const HOUR_MS = 3_600_000;
14
15
  /**
@@ -17,17 +18,20 @@ const HOUR_MS = 3_600_000;
17
18
  * station network, a licensed model). A typical year is `simulated` and
18
19
  * named after its years (`typical year 2005-2020`); real years are
19
20
  * `measured` and unnamed, unless told otherwise. Importing the same file
20
- * again replaces the values.
21
+ * again replaces the values. The file is stored whole or not at all: one
22
+ * series refused leaves none of the others.
21
23
  */
22
24
  export async function importWeatherFile(db, target, file, options) {
23
25
  const kind = options.kind ?? (file.typical ? 'simulated' : 'measured');
24
26
  const name = options.name !== undefined ? options.name : file.typical ? `typical year ${file.years[0]}-${file.years[file.years.length - 1]}` : null;
25
- const series = [];
26
- for (const s of file.series) {
27
- const stored = await storeSeries(db, { organisationId: target.organisationId, objectKind: target.objectKind, objectId: target.objectId, sourceCode: options.sourceCode, kind, name }, s);
28
- series.push({ quantity_code: s.quantity_code, ...stored });
29
- }
30
- return { series, warnings: file.warnings };
27
+ return atomically(db, async () => {
28
+ const series = [];
29
+ for (const s of file.series) {
30
+ const stored = await storeSeries(db, { organisationId: target.organisationId, objectKind: target.objectKind, objectId: target.objectId, sourceCode: options.sourceCode, kind, name }, s);
31
+ series.push({ quantity_code: s.quantity_code, ...stored });
32
+ }
33
+ return { series, warnings: file.warnings };
34
+ });
31
35
  }
32
36
  /**
33
37
  * The weather series of an object for one calendar year in the location's
@@ -50,6 +50,8 @@ export declare function getObject(db: Db, kind: string, id: string): Promise<Rec
50
50
  export declare function readSeries(db: Db, seriesId: string, from: string, to: string, step: string): Promise<import("./series.js").Bucket[]>;
51
51
  /** The value of a parameter for an object, through the cascade of defaults (`parameter_of()`). */
52
52
  export declare function parameterOf(db: Db, kind: string, id: string, attributeType: string, at?: string): Promise<unknown>;
53
+ /** Refuses `module_not_installed` when the module of that code is not installed. */
54
+ export declare function requireModule(db: Db, code: string): Promise<void>;
53
55
  /** The indicators of an object over a period (`kpis.of()`). */
54
56
  export declare function kpisOf(db: Db, kind: string, id: string, from: string, to: string): Promise<unknown[]>;
55
57
  /** The estimates of a module (`solar.estimates`, `battery.estimates`) about a participant or a device. */
@@ -125,6 +127,35 @@ export interface DeviceInput {
125
127
  export declare function installDevice(db: Db, d: DeviceInput): Promise<{
126
128
  id: string;
127
129
  }>;
130
+ export interface PvArrayInput {
131
+ name: string;
132
+ /** Degrees clockwise from true north: 180 faces south. */
133
+ azimuth_deg: number;
134
+ /** Degrees from horizontal. */
135
+ tilt_deg: number;
136
+ /** The array's DC power; the system's when it has one array. */
137
+ kwp?: number;
138
+ mounting?: string;
139
+ }
140
+ export interface PvSystemInput {
141
+ participant_id: string;
142
+ name: string;
143
+ /** The DC power of the system, kWp. */
144
+ kwp: number;
145
+ arrays: PvArrayInput[];
146
+ installed_on?: string;
147
+ }
148
+ /**
149
+ * A PV system of a participant, described as the `solar` module reads it: a
150
+ * device of the core (`install_device()`, type `solar`), its row of
151
+ * `solar.devices` with its DC power, and one row of `solar.pv_arrays` per
152
+ * array with its own orientation. Its yield is then a computation of the
153
+ * module (`solar.yield`).
154
+ */
155
+ export declare function describePvSystem(db: Db, p: PvSystemInput): Promise<{
156
+ device_id: string;
157
+ arrays: string[];
158
+ }>;
128
159
  /**
129
160
  * The readings of one entity of a Home Assistant export, read by its format
130
161
  * library (`@nexgen-os/homeassistant`) and written through `store()` as a
@@ -162,6 +193,42 @@ export declare function moveAction(db: Db, actionId: string, toStatus: string, o
162
193
  id: string;
163
194
  status: string;
164
195
  }>;
196
+ /** An organisation; the person this acts as becomes its owner (`create_organisation()`). */
197
+ export declare function createOrganisation(db: Db, name: string): Promise<{
198
+ id: string;
199
+ }>;
200
+ /** Who is a member of an organisation, with their role: a person's id, never more of their account. */
201
+ export declare function listMembers(db: Db, organisationId: string): Promise<{
202
+ user_id: string;
203
+ role: string;
204
+ created_at: string;
205
+ }[]>;
206
+ /** Gives a person a role in an organisation (`add_member()`); viewer when no role is given. */
207
+ export declare function addMember(db: Db, m: {
208
+ organisation_id: string;
209
+ user_id: string;
210
+ role?: string;
211
+ }): Promise<{
212
+ organisation_id: string;
213
+ user_id: string;
214
+ role: string;
215
+ }>;
216
+ /** Changes a member's role (`set_member_role()`); an organisation keeps an owner. */
217
+ export declare function setMemberRole(db: Db, m: {
218
+ organisation_id: string;
219
+ user_id: string;
220
+ role: string;
221
+ }): Promise<{
222
+ organisation_id: string;
223
+ user_id: string;
224
+ role: string;
225
+ }>;
226
+ /** Removes a member (`remove_member()`); an organisation keeps an owner. */
227
+ export declare function removeMember(db: Db, organisationId: string, userId: string): Promise<{
228
+ organisation_id: string;
229
+ user_id: string;
230
+ removed: true;
231
+ }>;
165
232
  /** Issues a key on an organisation; the secret is in the answer once, and nowhere else. */
166
233
  export declare function createApiKey(db: Db, k: {
167
234
  organisation_id: string;
@@ -199,3 +266,52 @@ export type ComputationName = keyof Computations;
199
266
  export declare const COMPUTATIONS: ComputationName[];
200
267
  /** Runs a module's computation with the request it takes, after checking the module is installed. */
201
268
  export declare function compute(db: Db, computations: Computations, name: ComputationName, request: Record<string, unknown>): Promise<unknown>;
269
+ export interface PvYieldAtInput {
270
+ project_id: string;
271
+ /** The participant's name: the place, the roof, the client. */
272
+ name: string;
273
+ /** ISO 3166-1 alpha-2: the country is data of the place, never assumed. */
274
+ country: string;
275
+ lon: number;
276
+ lat: number;
277
+ time_zone?: string;
278
+ kwp: number;
279
+ /** Degrees clockwise from true north: 180 faces south. */
280
+ azimuth_deg: number;
281
+ tilt_deg: number;
282
+ /** A whole calendar year PVGIS covers; without it, the mean of every year it covers. */
283
+ year?: number;
284
+ /**
285
+ * The system loss the person says for this place, a fraction (0.025 for
286
+ * 2.5 %): set on the participant as `system_loss`, where any other
287
+ * surface reads it too; without it, the cascade answers (decision 0055).
288
+ */
289
+ system_loss?: number;
290
+ profileCode?: string;
291
+ }
292
+ /**
293
+ * The yield of a PV system at a point, in one gesture: the participant
294
+ * joins the project at that point, its PV system is described with one
295
+ * array (`describePvSystem()`), the `solar` module estimates its yield for
296
+ * the year asked, or as the mean of every year PVGIS covers (`solar.yield`),
297
+ * and it is read back by calendar month through `resample()`, in UTC, the
298
+ * mean of the years. The system loss is the place's: the one given is set
299
+ * on the participant, and the estimate says the level it was read at.
300
+ */
301
+ export declare function estimatePvYieldAt(db: Db, computations: Computations, p: PvYieldAtInput): Promise<{
302
+ participant_id: string;
303
+ device_id: string;
304
+ estimate_id: string;
305
+ annual_kwh: number;
306
+ kwh_per_kwp: number;
307
+ years: {
308
+ from: number;
309
+ to: number;
310
+ };
311
+ system_loss: Record<string, unknown> | null;
312
+ provenance: string;
313
+ months: {
314
+ month: number;
315
+ kwh: number;
316
+ }[];
317
+ }>;
package/dist/gestures.js CHANGED
@@ -93,7 +93,8 @@ export async function parameterOf(db, kind, id, attributeType, at) {
93
93
  const { value } = await first(db, 'select parameter_of($1, $2, $3, coalesce($4::timestamptz, now())) as value', [kindOf(kind), id, attributeType, at ?? null]);
94
94
  return value;
95
95
  }
96
- async function requireModule(db, code) {
96
+ /** Refuses `module_not_installed` when the module of that code is not installed. */
97
+ export async function requireModule(db, code) {
97
98
  const [found] = await rows(db, 'select 1 from modules where code = $1', [code]);
98
99
  if (found === undefined)
99
100
  throw new GestureError(`module_not_installed: the ${code} module is not installed on this database`);
@@ -166,6 +167,27 @@ export async function installDevice(db, d) {
166
167
  return first(db, `select install_device($1, $2, $3, $4, $5, $6, $7, coalesce($8, 1)) id`, [d.participant_id, d.device_type, d.name, d.product_id ?? null, d.rated_power_kw ?? null, d.installed_on ?? null,
167
168
  d.source_code ?? null, d.unit_count ?? null]);
168
169
  }
170
+ /**
171
+ * A PV system of a participant, described as the `solar` module reads it: a
172
+ * device of the core (`install_device()`, type `solar`), its row of
173
+ * `solar.devices` with its DC power, and one row of `solar.pv_arrays` per
174
+ * array with its own orientation. Its yield is then a computation of the
175
+ * module (`solar.yield`).
176
+ */
177
+ export async function describePvSystem(db, p) {
178
+ await requireModule(db, 'solar');
179
+ if (p.arrays.length === 0)
180
+ throw new GestureError('pv_array_required: a PV system has at least one array, with its azimuth and tilt');
181
+ const { id } = await installDevice(db, { participant_id: p.participant_id, device_type: 'solar', name: p.name, rated_power_kw: p.kwp, ...(p.installed_on ? { installed_on: p.installed_on } : {}) });
182
+ await db.query('insert into solar.devices (id, kwp_dc) values ($1, $2)', [id, p.kwp]);
183
+ const arrays = [];
184
+ for (const a of p.arrays) {
185
+ const row = await first(db, `insert into solar.pv_arrays (organisation_id, device_id, name, azimuth_deg, tilt_deg, mounting, kwp_dc)
186
+ select d.organisation_id, d.id, $2, $3, $4, $5, $6 from devices d where d.id = $1 returning id`, [id, a.name, a.azimuth_deg, a.tilt_deg, a.mounting ?? null, a.kwp ?? (p.arrays.length === 1 ? p.kwp : null)]);
187
+ arrays.push(row.id);
188
+ }
189
+ return { device_id: id, arrays };
190
+ }
169
191
  /**
170
192
  * The readings of one entity of a Home Assistant export, read by its format
171
193
  * library (`@nexgen-os/homeassistant`) and written through `store()` as a
@@ -206,6 +228,33 @@ export async function moveAction(db, actionId, toStatus, on) {
206
228
  return { id: actionId, status: toStatus };
207
229
  }
208
230
  // ---------------------------------------------------------------------------
231
+ // Organisations and their members — what follows an installation
232
+ // ---------------------------------------------------------------------------
233
+ /** An organisation; the person this acts as becomes its owner (`create_organisation()`). */
234
+ export async function createOrganisation(db, name) {
235
+ return first(db, 'select create_organisation($1) id', [name]);
236
+ }
237
+ /** Who is a member of an organisation, with their role: a person's id, never more of their account. */
238
+ export async function listMembers(db, organisationId) {
239
+ return rows(db, 'select user_id, role::text as role, created_at from organisation_members where organisation_id = $1 order by created_at, user_id', [organisationId]);
240
+ }
241
+ /** Gives a person a role in an organisation (`add_member()`); viewer when no role is given. */
242
+ export async function addMember(db, m) {
243
+ const role = m.role ?? 'viewer';
244
+ await db.query('select add_member($1, $2, $3::member_role)', [m.organisation_id, m.user_id, role]);
245
+ return { organisation_id: m.organisation_id, user_id: m.user_id, role };
246
+ }
247
+ /** Changes a member's role (`set_member_role()`); an organisation keeps an owner. */
248
+ export async function setMemberRole(db, m) {
249
+ await db.query('select set_member_role($1, $2, $3::member_role)', [m.organisation_id, m.user_id, m.role]);
250
+ return { organisation_id: m.organisation_id, user_id: m.user_id, role: m.role };
251
+ }
252
+ /** Removes a member (`remove_member()`); an organisation keeps an owner. */
253
+ export async function removeMember(db, organisationId, userId) {
254
+ await db.query('select remove_member($1, $2)', [organisationId, userId]);
255
+ return { organisation_id: organisationId, user_id: userId, removed: true };
256
+ }
257
+ // ---------------------------------------------------------------------------
209
258
  // Keys — an owner's gestures (decision 0046)
210
259
  // ---------------------------------------------------------------------------
211
260
  /** Issues a key on an organisation; the secret is in the answer once, and nowhere else. */
@@ -230,3 +279,40 @@ export async function compute(db, computations, name, request) {
230
279
  throw new GestureError(`computation_not_loaded: ${name} is the code of its module, and this surface was started without it`);
231
280
  return fn(db, request);
232
281
  }
282
+ /**
283
+ * The yield of a PV system at a point, in one gesture: the participant
284
+ * joins the project at that point, its PV system is described with one
285
+ * array (`describePvSystem()`), the `solar` module estimates its yield for
286
+ * the year asked, or as the mean of every year PVGIS covers (`solar.yield`),
287
+ * and it is read back by calendar month through `resample()`, in UTC, the
288
+ * mean of the years. The system loss is the place's: the one given is set
289
+ * on the participant, and the estimate says the level it was read at.
290
+ */
291
+ export async function estimatePvYieldAt(db, computations, p) {
292
+ const place = { country: p.country, geometry: { type: 'Point', coordinates: [p.lon, p.lat, 0] }, location_precision: 'rooftop' };
293
+ const participant = await addParticipant(db, { project_id: p.project_id, name: p.name, place, category: 'prosumer', ...(p.time_zone ? { time_zone: p.time_zone } : {}) });
294
+ if (p.system_loss !== undefined) {
295
+ await db.query(`select set_attribute('participant', $1, 'system_loss', $2::jsonb, null, null, 'said by the person', 'estimated')`, [participant.id, JSON.stringify(p.system_loss)]);
296
+ }
297
+ const system = await describePvSystem(db, {
298
+ participant_id: participant.id, name: 'PV system', kwp: p.kwp,
299
+ arrays: [{ name: 'Array 1', azimuth_deg: p.azimuth_deg, tilt_deg: p.tilt_deg }],
300
+ });
301
+ const estimate = await compute(db, computations, 'solar.yield', {
302
+ deviceId: system.device_id, ...(p.year !== undefined ? { years: { from: p.year, to: p.year } } : {}), ...(p.profileCode ? { profileCode: p.profileCode } : {}),
303
+ });
304
+ const { provenance, years, system_loss } = await first(db, `select provenance, inputs -> 'weather' -> 'years' years, inputs -> 'system_loss' system_loss from solar.estimates where id = $1`, [estimate.estimateId]);
305
+ const n = years.to - years.from + 1;
306
+ const byMonth = new Map();
307
+ for (const b of await resample(db, estimate.seriesId, `${years.from}-01-01T00:00:00Z`, `${years.to + 1}-01-01T00:00:00Z`, '1 month', { timeZone: 'UTC' })) {
308
+ if (b.value === null)
309
+ continue;
310
+ const month = Number(b.bucket.slice(5, 7));
311
+ byMonth.set(month, (byMonth.get(month) ?? 0) + Number(b.value));
312
+ }
313
+ const months = [...byMonth.entries()].sort(([a], [b]) => a - b).map(([month, kwh]) => ({ month, kwh: Math.round((kwh / n) * 10) / 10 }));
314
+ return {
315
+ participant_id: participant.id, device_id: system.device_id, estimate_id: estimate.estimateId,
316
+ annual_kwh: estimate.annualKwh, kwh_per_kwp: estimate.kwhPerKwp, years, system_loss, provenance, months,
317
+ };
318
+ }
package/dist/index.d.ts CHANGED
@@ -6,13 +6,14 @@
6
6
  * that write what a format library reads into the model, and the gestures the
7
7
  * command line and the MCP server share, each acting as a person (`session.ts`).
8
8
  */
9
- export type { Db } from './db.js';
9
+ export { atomically, type Db } from './db.js';
10
10
  export { orientation, polygonWkt, closed, type Point as Vertex } from './geometry.js';
11
11
  export * from './address.js';
12
12
  export * from './series.js';
13
13
  export * from './time.js';
14
14
  export * from './connectors/interfaces.js';
15
15
  export * from './connectors/meter-data.js';
16
+ export * from './connectors/devices.js';
16
17
  export * from './connectors/runner.js';
17
18
  export * from './connectors/pvlib.js';
18
19
  export * from './connectors/settlement.js';
package/dist/index.js CHANGED
@@ -1,9 +1,19 @@
1
+ /**
2
+ * `@nexgen-os/core` — what the code of Nexgen OS shares: the database seam,
3
+ * the standard shape of a place and the geocoder chain, the interfaces of
4
+ * the connectors, the series API (`store()` and the reads), the shared
5
+ * geometry, the runner of the program connectors in other languages, the importers
6
+ * that write what a format library reads into the model, and the gestures the
7
+ * command line and the MCP server share, each acting as a person (`session.ts`).
8
+ */
9
+ export { atomically } from './db.js';
1
10
  export { orientation, polygonWkt, closed } from './geometry.js';
2
11
  export * from './address.js';
3
12
  export * from './series.js';
4
13
  export * from './time.js';
5
14
  export * from './connectors/interfaces.js';
6
15
  export * from './connectors/meter-data.js';
16
+ export * from './connectors/devices.js';
7
17
  export * from './connectors/runner.js';
8
18
  export * from './connectors/pvlib.js';
9
19
  export * from './connectors/settlement.js';
package/dist/series.d.ts CHANGED
@@ -1,10 +1,7 @@
1
+ import type { SeriesPoint } from '@nexgen-os/solar';
1
2
  import type { Db } from './db.js';
2
- /** One value at one instant, ISO 8601 with its offset, with its quality code (0 measured when absent; 3 missing). */
3
- export interface SeriesPoint {
4
- at: string;
5
- value: number;
6
- quality?: number;
7
- }
3
+ /** One value at one instant: the type the computations of `@nexgen-os/solar` read, one definition for both. */
4
+ export type { SeriesPoint };
8
5
  /** What names a series when it may not exist yet: the keys of `series_ensure()`. */
9
6
  export interface SeriesIdentity {
10
7
  /** The kind of the object observed: `organisation`, `project`, `participant`, `meter`, `device` or `series`. */
@@ -31,6 +28,10 @@ export interface Bucket {
31
28
  expected: number | null;
32
29
  quality: number | null;
33
30
  }
31
+ /** One bucket of several series added up (`aggregate()`): `series` is how many of them held a value in it. */
32
+ export interface AggregateBucket extends Bucket {
33
+ series: number;
34
+ }
34
35
  export interface Reading {
35
36
  at: string;
36
37
  value: number;
@@ -68,6 +69,10 @@ export declare function resample(db: Db, seriesId: string, from: string, to: str
68
69
  timeZone?: string | null;
69
70
  issuedBefore?: string | null;
70
71
  }): Promise<Bucket[]>;
72
+ /** Several series of one summable quantity added up on a regular step (`aggregate()`), each read as `resample()` reads it. */
73
+ export declare function aggregate(db: Db, seriesIds: string[], from: string, to: string, step: string, options?: {
74
+ timeZone?: string | null;
75
+ }): Promise<AggregateBucket[]>;
71
76
  /** The stored values themselves, in time order (`window()`): how a register's index is read. */
72
77
  export declare function window(db: Db, seriesId: string, from: string, to: string, limit?: number): Promise<Reading[]>;
73
78
  /** The latest value that is not missing of each series (`latest()`). */
package/dist/series.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Series: the SQL functions of the core, typed for TypeScript.
2
2
  //
3
3
  // One way to write (`store()`), one family of reads (`resample()`,
4
- // `window()`, `latest()`, `fill()`, `coverage()`, `forecastAt()`,
4
+ // `aggregate()`, `window()`, `latest()`, `fill()`, `coverage()`, `forecastAt()`,
5
5
  // `exportRows()`), each a thin call of the function of the same name in
6
6
  // schema `nexgen` (decision 0031). Nothing here computes a bucket, converts
7
7
  // a unit or fills a gap: the database does, so that a page, a module, the
@@ -33,6 +33,11 @@ export async function resample(db, seriesId, from, to, step, options = {}) {
33
33
  const r = await db.query(`select bucket, value, samples, expected, quality from resample($1, $2::timestamptz, $3::timestamptz, $4::interval, $5, $6::timestamptz)`, [seriesId, from, to, step, options.timeZone ?? null, options.issuedBefore ?? null]);
34
34
  return r.rows.map((b) => ({ ...b, bucket: iso(b.bucket) }));
35
35
  }
36
+ /** Several series of one summable quantity added up on a regular step (`aggregate()`), each read as `resample()` reads it. */
37
+ export async function aggregate(db, seriesIds, from, to, step, options = {}) {
38
+ const r = await db.query(`select bucket, value, series, samples, expected, quality from aggregate($1::uuid[], $2::timestamptz, $3::timestamptz, $4::interval, $5)`, [seriesIds, from, to, step, options.timeZone ?? null]);
39
+ return r.rows.map((b) => ({ ...b, bucket: iso(b.bucket) }));
40
+ }
36
41
  /** The stored values themselves, in time order (`window()`): how a register's index is read. */
37
42
  export async function window(db, seriesId, from, to, limit = 100_000) {
38
43
  const r = await db.query(`select at, value, quality from nexgen.window($1, $2::timestamptz, $3::timestamptz, $4)`, [seriesId, from, to, limit]);
package/dist/time.d.ts CHANGED
@@ -1,6 +1 @@
1
- /**
2
- * Offset of a time zone from UTC at an instant, minutes east (Brussels in
3
- * winter: 60). Throws `time_zone_unknown` for a name that is not an IANA
4
- * time zone.
5
- */
6
- export declare function offsetAt(timeZone: string, ms: number): number;
1
+ export { offsetAt } from '@nexgen-os/solar';
package/dist/time.js CHANGED
@@ -1,25 +1,4 @@
1
- // Time zones, read through the platform's `Intl`: what a module needs to cut
2
- // days, weeks and months in a participant's own time, without a dependency.
3
- const formatters = new Map();
4
- /**
5
- * Offset of a time zone from UTC at an instant, minutes east (Brussels in
6
- * winter: 60). Throws `time_zone_unknown` for a name that is not an IANA
7
- * time zone.
8
- */
9
- export function offsetAt(timeZone, ms) {
10
- let format = formatters.get(timeZone);
11
- if (!format) {
12
- try {
13
- format = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' });
14
- }
15
- catch {
16
- throw new Error(`time_zone_unknown: ${timeZone} is not an IANA time zone`);
17
- }
18
- formatters.set(timeZone, format);
19
- }
20
- const name = format.formatToParts(new Date(ms)).find((p) => p.type === 'timeZoneName')?.value ?? 'GMT';
21
- const m = /^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(name);
22
- if (!m)
23
- throw new Error(`time_zone_unknown: ${timeZone} gives the offset ${name}`);
24
- return m[1] ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3])) : 0;
25
- }
1
+ // Time zones: `offsetAt()` lives with the computations of `@nexgen-os/solar`
2
+ // (MIT, decision 0063), which cut local days and years without the core; the
3
+ // core reads the same function, so that there is one implementation.
4
+ export { offsetAt } from '@nexgen-os/solar';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexgen-os/core",
3
- "version": "0.4.2",
3
+ "version": "0.5.1",
4
4
  "description": "What the code of Nexgen OS shares: the database seam, the standard place and the geocoder chain, the series API, the connector interfaces, the engine glue, and the importers and exporters of the file formats.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "repository": {
@@ -17,6 +17,7 @@
17
17
  },
18
18
  "files": [
19
19
  "dist",
20
+ "schema",
20
21
  "README.md",
21
22
  "LICENSE"
22
23
  ],
@@ -32,11 +33,16 @@
32
33
  "build": "tsc -p tsconfig.build.json && node ../../scripts/copy-license.mjs"
33
34
  },
34
35
  "dependencies": {
35
- "@nexgen-os/enedis-r6x": "^0.4.0",
36
- "@nexgen-os/energy-bill": "^0.4.0",
37
- "@nexgen-os/geojson": "^0.4.0",
38
- "@nexgen-os/homeassistant": "^0.4.0",
39
- "@nexgen-os/weather-files": "^0.4.0"
36
+ "@nexgen-os/dsmr": "^0.5.0",
37
+ "@nexgen-os/enedis-r6x": "^0.5.0",
38
+ "@nexgen-os/energy-bill": "^0.5.0",
39
+ "@nexgen-os/evcc": "^0.5.0",
40
+ "@nexgen-os/geojson": "^0.5.0",
41
+ "@nexgen-os/homeassistant": "^0.5.0",
42
+ "@nexgen-os/project-sheet": "^0.5.0",
43
+ "@nexgen-os/pvsol": "^0.5.0",
44
+ "@nexgen-os/solar": "^0.5.0",
45
+ "@nexgen-os/weather-files": "^0.5.0"
40
46
  },
41
47
  "peerDependencies": {
42
48
  "pg": "^8.23.1"