@molecule/api-resource-readings 1.0.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,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-resource-readings` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-resource-readings is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
@@ -0,0 +1,90 @@
1
+ /**
2
+ * `@molecule/api-resource-readings` — generic time-series sensor data.
3
+ *
4
+ * Ingest readings via `POST /` or `POST /bulk`, then query raw or
5
+ * aggregated (5min / hour / day rollups) via `GET /?granularity=…`.
6
+ *
7
+ * Extracted from the energy-monitoring flagship — the pattern works
8
+ * for any time-series surface (IoT sensors, app metrics, financial
9
+ * tick data, etc.).
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { createReadingsRouter } from '@molecule/api-resource-readings'
14
+ *
15
+ * // Mount behind your global auth middleware — every route requires a session.
16
+ * app.use('/readings', createReadingsRouter())
17
+ * // POST /readings — ingest one reading
18
+ * // POST /readings/bulk — ingest up to 10 000 readings
19
+ * // GET /readings?granularity=raw|5min|hour|day&sensor_id=…&metric=…&from=…&to=…
20
+ * ```
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * import { ingestReading, listAggregatedReadings } from '@molecule/api-resource-readings'
25
+ *
26
+ * await ingestReading(userId, { sensor_id: 'meter-1', metric: 'kwh', value: 1.42 })
27
+ * const hourly = await listAggregatedReadings(userId, { granularity: 'hour', metric: 'kwh' })
28
+ * ```
29
+ *
30
+ * @remarks
31
+ * Unlike declarative-route resources, this package ships an Express Router
32
+ * FACTORY (`createReadingsRouter()`) — there is no `routes` /
33
+ * `requestHandlerMap` export for `mlcl inject`; mount the router yourself.
34
+ * Every route reads the caller via `requireUser(res)`
35
+ * (`res.locals.session.userId`, 401 fail-closed), so it must sit behind the
36
+ * global auth middleware, and every query/insert is scoped to that owner —
37
+ * never accept a client-supplied owner id.
38
+ *
39
+ * Aggregated queries (`granularity` ≠ `raw`) run raw SQL using `date_trunc`,
40
+ * `::int` casts, and `interval` literals — **PostgreSQL-only**. On the
41
+ * SQLite/MySQL bonds use `granularity=raw` (DataStore-based, portable) and
42
+ * bucket in application code, or supply your own dialect's aggregation.
43
+ * `ingestBulk` inserts sequentially (one INSERT per reading, max 10 000 per
44
+ * request).
45
+ *
46
+ * Tables: `src/__setup__/readings.sql` creates `readings` (owner-scoped via
47
+ * `owner_id`). An mlcl-scaffolded API replays `__setup__/*.sql` automatically
48
+ * on migrate; anywhere else run it once — nothing at runtime creates them.
49
+ *
50
+ * @e2e
51
+ * Integration checklist — drive the real UI (live preview, no mocks), adapt
52
+ * each item to this app's actual screens/flows, and check every box off one
53
+ * by one. A box you can't check is a correctness bug to fix — not a skip:
54
+ * - [ ] Recording a reading (POST /) persists its value, unit, metric, and
55
+ * recorded_at against the right sensor_id, and the chart/list reflects it:
56
+ * the newest point is the LAST entry of the chronological raw query (readings
57
+ * come back ordered by recorded_at ascending), so it shows the true latest
58
+ * value for that sensor — not a stale or averaged one.
59
+ * - [ ] A time-range query (from/to) returns ONLY readings inside the window,
60
+ * in chronological order, with no gaps or duplicates — points outside the
61
+ * range are absent and a point exactly on a boundary is present.
62
+ * - [ ] An aggregated query (granularity=5min|hour|day) computes the correct
63
+ * min/max/avg/sum/count for the readings in each bucket — spot-check one
64
+ * bucket by hand against its raw points (avg = sum / count; min and max are
65
+ * real members of the bucket; count matches the number of raw points).
66
+ * Aggregation is Postgres-only; on SQLite/MySQL use granularity=raw and
67
+ * verify the app buckets client-side instead.
68
+ * - [ ] Every value renders as a real number with its unit (e.g. "1.42 kwh"),
69
+ * never NaN, null, or undefined; a gap in the readings shows as a gap (or an
70
+ * explicit "no data"), never as a fabricated 0.
71
+ * - [ ] Malformed readings are rejected, not stored as truth: a non-numeric or
72
+ * NaN value, or a missing sensor_id/metric, is refused by validation (400) and
73
+ * never ingested; if the domain has a sane range, an out-of-range value is
74
+ * flagged/rejected by the app, not silently recorded. If the readings are
75
+ * health or otherwise personal, missing data is never shown as zero.
76
+ * - [ ] AUTHORIZATION — readings are scoped to owner_id (the authenticated
77
+ * session user via requireUser): a user sees ONLY their own readings, and no
78
+ * sensor_id/from/to filter or guessed id surfaces another user's data.
79
+ * Ingestion is authenticated (401 fail-closed) and the owner is taken from the
80
+ * session, never the request body — a caller can't spoof readings onto another
81
+ * owner or device.
82
+ *
83
+ * @module
84
+ */
85
+ export * from './browser-guard.js';
86
+ export * from './routes.js';
87
+ export * from './service.js';
88
+ export * from './types.js';
89
+ export * from './validation.js';
90
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmFG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * `@molecule/api-resource-readings` — generic time-series sensor data.
3
+ *
4
+ * Ingest readings via `POST /` or `POST /bulk`, then query raw or
5
+ * aggregated (5min / hour / day rollups) via `GET /?granularity=…`.
6
+ *
7
+ * Extracted from the energy-monitoring flagship — the pattern works
8
+ * for any time-series surface (IoT sensors, app metrics, financial
9
+ * tick data, etc.).
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { createReadingsRouter } from '@molecule/api-resource-readings'
14
+ *
15
+ * // Mount behind your global auth middleware — every route requires a session.
16
+ * app.use('/readings', createReadingsRouter())
17
+ * // POST /readings — ingest one reading
18
+ * // POST /readings/bulk — ingest up to 10 000 readings
19
+ * // GET /readings?granularity=raw|5min|hour|day&sensor_id=…&metric=…&from=…&to=…
20
+ * ```
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * import { ingestReading, listAggregatedReadings } from '@molecule/api-resource-readings'
25
+ *
26
+ * await ingestReading(userId, { sensor_id: 'meter-1', metric: 'kwh', value: 1.42 })
27
+ * const hourly = await listAggregatedReadings(userId, { granularity: 'hour', metric: 'kwh' })
28
+ * ```
29
+ *
30
+ * @remarks
31
+ * Unlike declarative-route resources, this package ships an Express Router
32
+ * FACTORY (`createReadingsRouter()`) — there is no `routes` /
33
+ * `requestHandlerMap` export for `mlcl inject`; mount the router yourself.
34
+ * Every route reads the caller via `requireUser(res)`
35
+ * (`res.locals.session.userId`, 401 fail-closed), so it must sit behind the
36
+ * global auth middleware, and every query/insert is scoped to that owner —
37
+ * never accept a client-supplied owner id.
38
+ *
39
+ * Aggregated queries (`granularity` ≠ `raw`) run raw SQL using `date_trunc`,
40
+ * `::int` casts, and `interval` literals — **PostgreSQL-only**. On the
41
+ * SQLite/MySQL bonds use `granularity=raw` (DataStore-based, portable) and
42
+ * bucket in application code, or supply your own dialect's aggregation.
43
+ * `ingestBulk` inserts sequentially (one INSERT per reading, max 10 000 per
44
+ * request).
45
+ *
46
+ * Tables: `src/__setup__/readings.sql` creates `readings` (owner-scoped via
47
+ * `owner_id`). An mlcl-scaffolded API replays `__setup__/*.sql` automatically
48
+ * on migrate; anywhere else run it once — nothing at runtime creates them.
49
+ *
50
+ * @e2e
51
+ * Integration checklist — drive the real UI (live preview, no mocks), adapt
52
+ * each item to this app's actual screens/flows, and check every box off one
53
+ * by one. A box you can't check is a correctness bug to fix — not a skip:
54
+ * - [ ] Recording a reading (POST /) persists its value, unit, metric, and
55
+ * recorded_at against the right sensor_id, and the chart/list reflects it:
56
+ * the newest point is the LAST entry of the chronological raw query (readings
57
+ * come back ordered by recorded_at ascending), so it shows the true latest
58
+ * value for that sensor — not a stale or averaged one.
59
+ * - [ ] A time-range query (from/to) returns ONLY readings inside the window,
60
+ * in chronological order, with no gaps or duplicates — points outside the
61
+ * range are absent and a point exactly on a boundary is present.
62
+ * - [ ] An aggregated query (granularity=5min|hour|day) computes the correct
63
+ * min/max/avg/sum/count for the readings in each bucket — spot-check one
64
+ * bucket by hand against its raw points (avg = sum / count; min and max are
65
+ * real members of the bucket; count matches the number of raw points).
66
+ * Aggregation is Postgres-only; on SQLite/MySQL use granularity=raw and
67
+ * verify the app buckets client-side instead.
68
+ * - [ ] Every value renders as a real number with its unit (e.g. "1.42 kwh"),
69
+ * never NaN, null, or undefined; a gap in the readings shows as a gap (or an
70
+ * explicit "no data"), never as a fabricated 0.
71
+ * - [ ] Malformed readings are rejected, not stored as truth: a non-numeric or
72
+ * NaN value, or a missing sensor_id/metric, is refused by validation (400) and
73
+ * never ingested; if the domain has a sane range, an out-of-range value is
74
+ * flagged/rejected by the app, not silently recorded. If the readings are
75
+ * health or otherwise personal, missing data is never shown as zero.
76
+ * - [ ] AUTHORIZATION — readings are scoped to owner_id (the authenticated
77
+ * session user via requireUser): a user sees ONLY their own readings, and no
78
+ * sensor_id/from/to filter or guessed id surfaces another user's data.
79
+ * Ingestion is authenticated (401 fail-closed) and the owner is taken from the
80
+ * session, never the request body — a caller can't spoof readings onto another
81
+ * owner or device.
82
+ *
83
+ * @module
84
+ */
85
+ export * from './browser-guard.js';
86
+ export * from './routes.js';
87
+ export * from './service.js';
88
+ export * from './types.js';
89
+ export * from './validation.js';
@@ -0,0 +1,4 @@
1
+ import { Router } from 'express';
2
+ /** Creates and returns the Express router for the readings resource endpoints. */
3
+ export declare function createReadingsRouter(): Router;
4
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoD,MAAM,EAAE,MAAM,SAAS,CAAA;AAclF,kFAAkF;AAClF,wBAAgB,oBAAoB,IAAI,MAAM,CAkD7C"}
package/dist/routes.js ADDED
@@ -0,0 +1,54 @@
1
+ import { Router } from 'express';
2
+ import { requireUser } from '@molecule/api-bonds-default-express';
3
+ import { validateBody as validateBodyRaw, validateQuery as validateQueryRaw, } from '@molecule/api-middleware-validation';
4
+ import { ingestBulk, ingestReading, listAggregatedReadings, listRawReadings } from './service.js';
5
+ import { readingBulkSchema, readingCreateSchema, readingQuerySchema } from './validation.js';
6
+ const validateBody = validateBodyRaw;
7
+ const validateQuery = validateQueryRaw;
8
+ /** Creates and returns the Express router for the readings resource endpoints. */
9
+ export function createReadingsRouter() {
10
+ const router = Router();
11
+ router.post('/', validateBody(readingCreateSchema), async (req, res) => {
12
+ const userId = requireUser(res);
13
+ if (!userId)
14
+ return;
15
+ res
16
+ .status(201)
17
+ .json(await ingestReading(userId, req.body));
18
+ });
19
+ router.post('/bulk', validateBody(readingBulkSchema), async (req, res) => {
20
+ const userId = requireUser(res);
21
+ if (!userId)
22
+ return;
23
+ const body = req.body;
24
+ const inserted = await ingestBulk(userId, body.readings);
25
+ res.status(201).json({ inserted });
26
+ });
27
+ router.get('/', validateQuery(readingQuerySchema), async (req, res) => {
28
+ const userId = requireUser(res);
29
+ if (!userId)
30
+ return;
31
+ const q = req.query;
32
+ const granularity = (typeof q.granularity === 'string' ? q.granularity : 'raw');
33
+ if (granularity === 'raw') {
34
+ res.json(await listRawReadings(userId, {
35
+ sensor_id: typeof q.sensor_id === 'string' ? q.sensor_id : undefined,
36
+ metric: typeof q.metric === 'string' ? q.metric : undefined,
37
+ from: typeof q.from === 'string' ? q.from : undefined,
38
+ to: typeof q.to === 'string' ? q.to : undefined,
39
+ limit: typeof q.limit === 'number' ? q.limit : undefined,
40
+ }));
41
+ }
42
+ else {
43
+ res.json(await listAggregatedReadings(userId, {
44
+ granularity,
45
+ sensor_id: typeof q.sensor_id === 'string' ? q.sensor_id : undefined,
46
+ metric: typeof q.metric === 'string' ? q.metric : undefined,
47
+ from: typeof q.from === 'string' ? q.from : undefined,
48
+ to: typeof q.to === 'string' ? q.to : undefined,
49
+ limit: typeof q.limit === 'number' ? q.limit : undefined,
50
+ }));
51
+ }
52
+ });
53
+ return router;
54
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Time-series reading service. Stores raw readings + computes
3
+ * aggregations on-the-fly via SQL-bond friendly group-by buckets.
4
+ *
5
+ * @module
6
+ */
7
+ import type { AggregatedPoint, Granularity, ReadingPoint, ReadingRow } from './types.js';
8
+ /**
9
+ * Persist a single sensor reading row for the given owner.
10
+ */
11
+ export declare function ingestReading(ownerId: string, data: {
12
+ sensor_id: string;
13
+ metric: string;
14
+ value: number;
15
+ unit?: string | null;
16
+ recorded_at?: string;
17
+ metadata?: Record<string, unknown>;
18
+ }): Promise<ReadingRow>;
19
+ /**
20
+ * Persist multiple sensor readings in sequence, returning the number successfully inserted.
21
+ */
22
+ export declare function ingestBulk(ownerId: string, readings: Array<{
23
+ sensor_id: string;
24
+ metric: string;
25
+ value: number;
26
+ unit?: string | null;
27
+ recorded_at?: string;
28
+ metadata?: Record<string, unknown>;
29
+ }>): Promise<number>;
30
+ /**
31
+ * Fetch raw, unaggregated reading points for an owner, optionally filtered by sensor, metric, and time range.
32
+ */
33
+ export declare function listRawReadings(ownerId: string, opts?: {
34
+ sensor_id?: string;
35
+ metric?: string;
36
+ from?: string;
37
+ to?: string;
38
+ limit?: number;
39
+ }): Promise<ReadingPoint[]>;
40
+ /**
41
+ * Group readings into time buckets and aggregate per bucket. Returns
42
+ * `min/max/avg/sum/count` per `(bucket, metric, sensor_id)`.
43
+ */
44
+ export declare function listAggregatedReadings(ownerId: string, opts: {
45
+ granularity: Exclude<Granularity, 'raw'>;
46
+ sensor_id?: string;
47
+ metric?: string;
48
+ from?: string;
49
+ to?: string;
50
+ limit?: number;
51
+ }): Promise<AggregatedPoint[]>;
52
+ /**
53
+ * Return the total number of readings stored for the given owner.
54
+ */
55
+ export declare function countReadings(ownerId: string): Promise<number>;
56
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAWH,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAIxF;;GAEG;AACH,wBAAsB,aAAa,CACjC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE;IACJ,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACnC,GACA,OAAO,CAAC,UAAU,CAAC,CAWrB;AAED;;GAEG;AACH,wBAAsB,UAAU,CAC9B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,KAAK,CAAC;IACd,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACnC,CAAC,GACD,OAAO,CAAC,MAAM,CAAC,CAOjB;AAED;;GAEG;AACH,wBAAsB,eAAe,CACnC,OAAO,EAAE,MAAM,EACf,IAAI,GAAE;IACJ,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,KAAK,CAAC,EAAE,MAAM,CAAA;CACV,GACL,OAAO,CAAC,YAAY,EAAE,CAAC,CAiBzB;AASD;;;GAGG;AACH,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,MAAM,EACf,IAAI,EAAE;IACJ,WAAW,EAAE,OAAO,CAAC,WAAW,EAAE,KAAK,CAAC,CAAA;IACxC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,GACA,OAAO,CAAC,eAAe,EAAE,CAAC,CAiD5B;AAED;;GAEG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEpE"}
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Time-series reading service. Stores raw readings + computes
3
+ * aggregations on-the-fly via SQL-bond friendly group-by buckets.
4
+ *
5
+ * @module
6
+ */
7
+ import { count as dbCount, create, findMany, query, } from '@molecule/api-database';
8
+ const TABLE = 'readings';
9
+ /**
10
+ * Persist a single sensor reading row for the given owner.
11
+ */
12
+ export async function ingestReading(ownerId, data) {
13
+ const result = await create(TABLE, {
14
+ owner_id: ownerId,
15
+ sensor_id: data.sensor_id,
16
+ metric: data.metric,
17
+ value: data.value,
18
+ unit: data.unit ?? null,
19
+ recorded_at: data.recorded_at ?? new Date().toISOString(),
20
+ metadata: data.metadata ?? null,
21
+ });
22
+ return result.data;
23
+ }
24
+ /**
25
+ * Persist multiple sensor readings in sequence, returning the number successfully inserted.
26
+ */
27
+ export async function ingestBulk(ownerId, readings) {
28
+ let n = 0;
29
+ for (const r of readings) {
30
+ await ingestReading(ownerId, r);
31
+ n++;
32
+ }
33
+ return n;
34
+ }
35
+ /**
36
+ * Fetch raw, unaggregated reading points for an owner, optionally filtered by sensor, metric, and time range.
37
+ */
38
+ export async function listRawReadings(ownerId, opts = {}) {
39
+ const where = [{ field: 'owner_id', operator: '=', value: ownerId }];
40
+ if (opts.sensor_id)
41
+ where.push({ field: 'sensor_id', operator: '=', value: opts.sensor_id });
42
+ if (opts.metric)
43
+ where.push({ field: 'metric', operator: '=', value: opts.metric });
44
+ if (opts.from)
45
+ where.push({ field: 'recorded_at', operator: '>=', value: opts.from });
46
+ if (opts.to)
47
+ where.push({ field: 'recorded_at', operator: '<=', value: opts.to });
48
+ const orderBy = [{ field: 'recorded_at', direction: 'asc' }];
49
+ const rows = await findMany(TABLE, { where, orderBy, limit: opts.limit ?? 1000 });
50
+ return rows.map((r) => ({
51
+ recorded_at: r.recorded_at instanceof Date ? r.recorded_at.toISOString() : String(r.recorded_at),
52
+ value: Number(r.value),
53
+ metric: r.metric,
54
+ sensor_id: r.sensor_id,
55
+ unit: r.unit,
56
+ }));
57
+ }
58
+ const GRANULARITY_TRUNC = {
59
+ '5min': "date_trunc('minute', recorded_at) - (extract(minute FROM recorded_at)::int % 5) * interval '1 minute'",
60
+ hour: "date_trunc('hour', recorded_at)",
61
+ day: "date_trunc('day', recorded_at)",
62
+ };
63
+ /**
64
+ * Group readings into time buckets and aggregate per bucket. Returns
65
+ * `min/max/avg/sum/count` per `(bucket, metric, sensor_id)`.
66
+ */
67
+ export async function listAggregatedReadings(ownerId, opts) {
68
+ const trunc = GRANULARITY_TRUNC[opts.granularity];
69
+ const sql = `
70
+ SELECT
71
+ ${trunc} AS bucket_at,
72
+ metric,
73
+ sensor_id,
74
+ MIN(value) AS min,
75
+ MAX(value) AS max,
76
+ AVG(value) AS avg,
77
+ SUM(value) AS sum,
78
+ COUNT(*) AS count
79
+ FROM ${TABLE}
80
+ WHERE owner_id = $1
81
+ ${opts.sensor_id ? 'AND sensor_id = $2' : ''}
82
+ ${opts.metric ? `AND metric = $${opts.sensor_id ? 3 : 2}` : ''}
83
+ ${opts.from ? `AND recorded_at >= $${[opts.sensor_id, opts.metric].filter(Boolean).length + 2}` : ''}
84
+ ${opts.to ? `AND recorded_at <= $${[opts.sensor_id, opts.metric, opts.from].filter(Boolean).length + 2}` : ''}
85
+ GROUP BY bucket_at, metric, sensor_id
86
+ ORDER BY bucket_at ASC
87
+ LIMIT ${opts.limit ?? 5000}
88
+ `;
89
+ const params = [ownerId];
90
+ if (opts.sensor_id)
91
+ params.push(opts.sensor_id);
92
+ if (opts.metric)
93
+ params.push(opts.metric);
94
+ if (opts.from)
95
+ params.push(opts.from);
96
+ if (opts.to)
97
+ params.push(opts.to);
98
+ const result = await query(sql, params);
99
+ return result.rows.map((r) => ({
100
+ bucket_at: r.bucket_at instanceof Date ? r.bucket_at.toISOString() : String(r.bucket_at),
101
+ metric: r.metric,
102
+ sensor_id: r.sensor_id,
103
+ min: Number(r.min),
104
+ max: Number(r.max),
105
+ avg: Number(r.avg),
106
+ sum: Number(r.sum),
107
+ count: Number(r.count),
108
+ }));
109
+ }
110
+ /**
111
+ * Return the total number of readings stored for the given owner.
112
+ */
113
+ export async function countReadings(ownerId) {
114
+ return dbCount(TABLE, [{ field: 'owner_id', operator: '=', value: ownerId }]);
115
+ }
@@ -0,0 +1,33 @@
1
+ /** Time-bucket granularity options for aggregating sensor readings. */
2
+ export type Granularity = 'raw' | '5min' | 'hour' | 'day';
3
+ /** Raw database row shape for a single sensor reading record. */
4
+ export interface ReadingRow {
5
+ id: string;
6
+ owner_id: string;
7
+ sensor_id: string;
8
+ metric: string;
9
+ value: number;
10
+ unit: string | null;
11
+ recorded_at: string | Date;
12
+ metadata: Record<string, unknown> | null;
13
+ }
14
+ /** A single sensor reading data point returned from a query. */
15
+ export interface ReadingPoint {
16
+ recorded_at: string;
17
+ value: number;
18
+ metric: string;
19
+ sensor_id: string;
20
+ unit: string | null;
21
+ }
22
+ /** A time-bucketed aggregate of sensor readings (min/max/avg/sum/count per bucket). */
23
+ export interface AggregatedPoint {
24
+ bucket_at: string;
25
+ metric: string;
26
+ sensor_id: string;
27
+ min: number;
28
+ max: number;
29
+ avg: number;
30
+ sum: number;
31
+ count: number;
32
+ }
33
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,MAAM,MAAM,WAAW,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,CAAA;AAEzD,iEAAiE;AACjE,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAA;IACV,QAAQ,EAAE,MAAM,CAAA;IAChB,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;IACnB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAA;IAC1B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAA;CACzC;AAED,gEAAgE;AAChE,MAAM,WAAW,YAAY;IAC3B,WAAW,EAAE,MAAM,CAAA;IACnB,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,EAAE,MAAM,CAAA;IACjB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;CACpB;AAED,uFAAuF;AACvF,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,EAAE,MAAM,CAAA;IACjB,GAAG,EAAE,MAAM,CAAA;IACX,GAAG,EAAE,MAAM,CAAA;IACX,GAAG,EAAE,MAAM,CAAA;IACX,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,EAAE,MAAM,CAAA;CACd"}
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,38 @@
1
+ import { z } from 'zod';
2
+ /** Supported time-bucket granularities for reading aggregation queries. */
3
+ export declare const GRANULARITIES: readonly ["raw", "5min", "hour", "day"];
4
+ /** Zod schema for validating a single reading creation payload. */
5
+ export declare const readingCreateSchema: z.ZodObject<{
6
+ sensor_id: z.ZodString;
7
+ metric: z.ZodString;
8
+ value: z.ZodNumber;
9
+ unit: z.ZodOptional<z.ZodNullable<z.ZodString>>;
10
+ recorded_at: z.ZodOptional<z.ZodString>;
11
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
12
+ }, z.core.$strip>;
13
+ /** Zod schema for validating a bulk readings creation payload (1–10 000 entries). */
14
+ export declare const readingBulkSchema: z.ZodObject<{
15
+ readings: z.ZodArray<z.ZodObject<{
16
+ sensor_id: z.ZodString;
17
+ metric: z.ZodString;
18
+ value: z.ZodNumber;
19
+ unit: z.ZodOptional<z.ZodNullable<z.ZodString>>;
20
+ recorded_at: z.ZodOptional<z.ZodString>;
21
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
22
+ }, z.core.$strip>>;
23
+ }, z.core.$strip>;
24
+ /** Zod schema for validating reading list/query filter parameters. */
25
+ export declare const readingQuerySchema: z.ZodObject<{
26
+ sensor_id: z.ZodOptional<z.ZodString>;
27
+ metric: z.ZodOptional<z.ZodString>;
28
+ from: z.ZodOptional<z.ZodString>;
29
+ to: z.ZodOptional<z.ZodString>;
30
+ granularity: z.ZodOptional<z.ZodEnum<{
31
+ raw: "raw";
32
+ "5min": "5min";
33
+ hour: "hour";
34
+ day: "day";
35
+ }>>;
36
+ limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
37
+ }, z.core.$strip>;
38
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,2EAA2E;AAC3E,eAAO,MAAM,aAAa,yCAA0C,CAAA;AAEpE,mEAAmE;AACnE,eAAO,MAAM,mBAAmB;;;;;;;iBAO9B,CAAA;AAEF,qFAAqF;AACrF,eAAO,MAAM,iBAAiB;;;;;;;;;iBAE5B,CAAA;AAEF,sEAAsE;AACtE,eAAO,MAAM,kBAAkB;;;;;;;;;;;;iBAO7B,CAAA"}
@@ -0,0 +1,25 @@
1
+ import { z } from 'zod';
2
+ /** Supported time-bucket granularities for reading aggregation queries. */
3
+ export const GRANULARITIES = ['raw', '5min', 'hour', 'day'];
4
+ /** Zod schema for validating a single reading creation payload. */
5
+ export const readingCreateSchema = z.object({
6
+ sensor_id: z.string().min(1).max(120),
7
+ metric: z.string().min(1).max(80),
8
+ value: z.number(),
9
+ unit: z.string().max(40).nullable().optional(),
10
+ recorded_at: z.string().optional(),
11
+ metadata: z.record(z.string(), z.unknown()).optional(),
12
+ });
13
+ /** Zod schema for validating a bulk readings creation payload (1–10 000 entries). */
14
+ export const readingBulkSchema = z.object({
15
+ readings: z.array(readingCreateSchema).min(1).max(10_000),
16
+ });
17
+ /** Zod schema for validating reading list/query filter parameters. */
18
+ export const readingQuerySchema = z.object({
19
+ sensor_id: z.string().optional(),
20
+ metric: z.string().optional(),
21
+ from: z.string().optional(),
22
+ to: z.string().optional(),
23
+ granularity: z.enum(GRANULARITIES).optional(),
24
+ limit: z.coerce.number().int().min(1).max(10_000).optional(),
25
+ });
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@molecule/api-resource-readings",
3
+ "version": "1.0.0",
4
+ "description": "Generic time-series sensor readings with on-the-fly aggregation (raw/5min/hour/day rollups)",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "time-series",
25
+ "sensor",
26
+ "iot",
27
+ "readings",
28
+ "resource"
29
+ ],
30
+ "license": "Apache-2.0",
31
+ "devDependencies": {
32
+ "@types/express": "5.0.6",
33
+ "@types/node": "26.1.2",
34
+ "express": "5.2.1",
35
+ "typescript": "6.0.3",
36
+ "vitest": "4.1.10",
37
+ "zod": "4.4.3"
38
+ },
39
+ "peerDependencies": {
40
+ "@molecule/api-bonds-default-express": "^1.0.0",
41
+ "@molecule/api-database": "^1.0.0",
42
+ "@molecule/api-i18n": "^1.0.0",
43
+ "@molecule/api-middleware-validation": "^1.0.0",
44
+ "express": "^5.0.0",
45
+ "zod": "^4.0.0"
46
+ }
47
+ }