@lp-labs/time-series-index 0.0.0-stage → 0.1.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 Libin Prasanth
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,59 @@
1
- # Temporary Holding Version
1
+ # @lp-labs/time-series-index
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
+ A bounded in-memory index for numeric time series with sorted range retrieval and fixed-width
4
+ aggregates. Timestamps are safe integer epoch units chosen consistently by the caller.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ npm install @lp-labs/time-series-index
10
+ ```
11
+
12
+ Includes ES2022 ESM and CommonJS builds with TypeScript declarations. CommonJS:
13
+ `const { createTimeSeriesIndex } = require('@lp-labs/time-series-index')`.
14
+
15
+ ## Quickstart
16
+
17
+ ```js
18
+ import { createTimeSeriesIndex } from '@lp-labs/time-series-index';
19
+
20
+ const index = createTimeSeriesIndex();
21
+ index.upsert('temperature', { timestamp: 1000, value: 18.5 });
22
+ index.upsert('temperature', { timestamp: 2000, value: 19 });
23
+ console.log(index.query('temperature', { from: 1000, to: 1500 }));
24
+ console.log(index.aggregate('temperature', 1000));
25
+ ```
26
+
27
+ ## API
28
+
29
+ - `createTimeSeriesIndex({ maxSeries?, maxPoints? })` defaults to 1,000 series and 1,000,000
30
+ total points. `maxSeries` is capped at 100,000; `maxPoints` at 10,000,000.
31
+ - `upsert(series, { timestamp, value })` inserts in timestamp order. Re-inserting a timestamp
32
+ replaces its value without consuming capacity. Timestamps are safe integers; values must be
33
+ finite numbers.
34
+ - `query(series, { from?, to?, limit? })` returns detached, ascending points in the inclusive
35
+ range. The default limit is the total point capacity.
36
+ - `aggregate(series, width, { from?, to? })` returns occupied, epoch-aligned buckets containing
37
+ `[start, end)` boundaries, count, sum, min, max and average. `width` is a positive safe integer.
38
+ - `removeSeries`, `clear`, `seriesCount`, and `pointCount` manage and report state.
39
+
40
+ Unknown series throw `TimeSeriesIndexError` with code `unknown-series`; capacity failures use
41
+ code `capacity`. Validate timestamps and units at your application boundary (milliseconds,
42
+ seconds and other epochs are not inferred).
43
+
44
+ ## Customization and limitations
45
+
46
+ The index is process-local, single-threaded, and stores raw points in JavaScript arrays. Insert
47
+ and query are O(log n) lookup plus O(n) array movement/copying for a series; queries and bucket
48
+ aggregation are linear in returned/scanned points. There is no retention policy, persistence,
49
+ interpolation, gap filling, timezone/calendar bucketing, counter-rate logic, distributed
50
+ replication, or arbitrary dimensional metrics. Aggregation uses ordinary floating-point sums and
51
+ includes only observed buckets.
52
+
53
+ ## Support
54
+
55
+ If this library is useful to you, consider supporting its maintenance with a [donation via PayPal](https://www.paypal.me/LibinPrasanth).
56
+
57
+ ## Author
58
+
59
+ Created by [Libin Prasanth](https://www.linkedin.com/in/libinprasanth/). Connect on LinkedIn for updates and discussion.
@@ -0,0 +1,36 @@
1
+ export interface DataPoint {
2
+ timestamp: number;
3
+ value: number;
4
+ }
5
+ export interface TimeSeriesOptions {
6
+ maxSeries?: number;
7
+ maxPoints?: number;
8
+ }
9
+ export interface QueryRange {
10
+ from?: number;
11
+ to?: number;
12
+ limit?: number;
13
+ }
14
+ export interface Bucket {
15
+ start: number;
16
+ end: number;
17
+ count: number;
18
+ sum: number;
19
+ min: number;
20
+ max: number;
21
+ average: number;
22
+ }
23
+ export interface TimeSeriesIndex {
24
+ readonly seriesCount: number;
25
+ readonly pointCount: number;
26
+ upsert(series: string, point: DataPoint): void;
27
+ removeSeries(series: string): boolean;
28
+ query(series: string, range?: QueryRange): DataPoint[];
29
+ aggregate(series: string, width: number, range?: QueryRange): Bucket[];
30
+ clear(): void;
31
+ }
32
+ export declare class TimeSeriesIndexError extends Error {
33
+ readonly code: 'capacity' | 'unknown-series';
34
+ constructor(code: 'capacity' | 'unknown-series', message: string);
35
+ }
36
+ export declare function createTimeSeriesIndex(options?: TimeSeriesOptions): TimeSeriesIndex;
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TimeSeriesIndexError = void 0;
4
+ exports.createTimeSeriesIndex = createTimeSeriesIndex;
5
+ class TimeSeriesIndexError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.code = code;
10
+ this.name = 'TimeSeriesIndexError';
11
+ }
12
+ }
13
+ exports.TimeSeriesIndexError = TimeSeriesIndexError;
14
+ const isRecord = (value) => {
15
+ if (!value || typeof value !== 'object' || Array.isArray(value))
16
+ return false;
17
+ const prototype = Object.getPrototypeOf(value);
18
+ return prototype === Object.prototype || prototype === null;
19
+ };
20
+ function assertPlainObject(value, name) {
21
+ if (!isRecord(value))
22
+ throw new TypeError(`${name} must be a plain object.`);
23
+ }
24
+ function bounded(value, name, minimum, maximum) {
25
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
26
+ throw new RangeError(`${name} must be an integer from ${minimum} through ${maximum}.`);
27
+ }
28
+ return value;
29
+ }
30
+ function validateSeries(value) {
31
+ if (typeof value !== 'string' || value.length === 0 || value.length > 256) {
32
+ throw new TypeError('Series name must be a non-empty string of at most 256 characters.');
33
+ }
34
+ }
35
+ function validateTime(value, name) {
36
+ if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
37
+ throw new TypeError(`${name} must be a safe integer timestamp.`);
38
+ }
39
+ }
40
+ function createTimeSeriesIndex(options = {}) {
41
+ assertPlainObject(options, 'Options');
42
+ const maxSeries = bounded(options.maxSeries ?? 1000, 'maxSeries', 1, 100_000);
43
+ const maxPoints = bounded(options.maxPoints ?? 1_000_000, 'maxPoints', 1, 10_000_000);
44
+ const seriesMap = new Map();
45
+ let pointCount = 0;
46
+ const requireSeries = (name) => {
47
+ validateSeries(name);
48
+ const points = seriesMap.get(name);
49
+ if (!points)
50
+ throw new TimeSeriesIndexError('unknown-series', `Unknown series: ${name}`);
51
+ return points;
52
+ };
53
+ const rangeValues = (range = {}) => {
54
+ assertPlainObject(range, 'Range');
55
+ const from = range.from;
56
+ const to = range.to;
57
+ if (from !== undefined)
58
+ validateTime(from, 'from');
59
+ if (to !== undefined)
60
+ validateTime(to, 'to');
61
+ if (from !== undefined && to !== undefined && from > to)
62
+ throw new RangeError('from must not exceed to.');
63
+ const limit = bounded(range.limit ?? maxPoints, 'limit', 0, maxPoints);
64
+ return { from: from ?? Number.MIN_SAFE_INTEGER, to: to ?? Number.MAX_SAFE_INTEGER, limit };
65
+ };
66
+ return {
67
+ get seriesCount() {
68
+ return seriesMap.size;
69
+ },
70
+ get pointCount() {
71
+ return pointCount;
72
+ },
73
+ upsert(name, input) {
74
+ validateSeries(name);
75
+ if (!isRecord(input))
76
+ throw new TypeError('Point must be a plain object.');
77
+ validateTime(input.timestamp, 'timestamp');
78
+ if (typeof input.value !== 'number' || !Number.isFinite(input.value)) {
79
+ throw new TypeError('Point value must be finite.');
80
+ }
81
+ let points = seriesMap.get(name);
82
+ if (!points) {
83
+ if (seriesMap.size >= maxSeries)
84
+ throw new TimeSeriesIndexError('capacity', 'Series capacity reached.');
85
+ points = [];
86
+ seriesMap.set(name, points);
87
+ }
88
+ let low = 0;
89
+ let high = points.length;
90
+ while (low < high) {
91
+ const middle = (low + high) >>> 1;
92
+ if (points[middle].timestamp < input.timestamp)
93
+ low = middle + 1;
94
+ else
95
+ high = middle;
96
+ }
97
+ const replacing = points[low]?.timestamp === input.timestamp;
98
+ if (!replacing && pointCount >= maxPoints)
99
+ throw new TimeSeriesIndexError('capacity', 'Point capacity reached.');
100
+ const point = Object.freeze({ timestamp: input.timestamp, value: input.value });
101
+ if (replacing)
102
+ points[low] = point;
103
+ else {
104
+ points.splice(low, 0, point);
105
+ pointCount++;
106
+ }
107
+ },
108
+ removeSeries(name) {
109
+ validateSeries(name);
110
+ const points = seriesMap.get(name);
111
+ if (!points)
112
+ return false;
113
+ pointCount -= points.length;
114
+ return seriesMap.delete(name);
115
+ },
116
+ query(name, range = {}) {
117
+ const points = requireSeries(name);
118
+ const { from, to, limit } = rangeValues(range);
119
+ let low = 0;
120
+ let high = points.length;
121
+ while (low < high) {
122
+ const middle = (low + high) >>> 1;
123
+ if (points[middle].timestamp < from)
124
+ low = middle + 1;
125
+ else
126
+ high = middle;
127
+ }
128
+ const output = [];
129
+ for (let index = low; index < points.length && output.length < limit; index++) {
130
+ if (points[index].timestamp > to)
131
+ break;
132
+ output.push({ ...points[index] });
133
+ }
134
+ return output;
135
+ },
136
+ aggregate(name, width, range = {}) {
137
+ const points = requireSeries(name);
138
+ if (!Number.isSafeInteger(width) || width <= 0)
139
+ throw new RangeError('width must be a positive safe integer.');
140
+ const { from, to, limit } = rangeValues(range);
141
+ const buckets = new Map();
142
+ let considered = 0;
143
+ for (const point of points) {
144
+ if (point.timestamp < from)
145
+ continue;
146
+ if (point.timestamp > to)
147
+ break;
148
+ if (considered >= limit)
149
+ break;
150
+ considered++;
151
+ const start = Math.floor(point.timestamp / width) * width;
152
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(start + width)) {
153
+ throw new RangeError('Bucket boundaries exceed the safe integer timestamp range.');
154
+ }
155
+ let bucket = buckets.get(start);
156
+ if (!bucket)
157
+ buckets.set(start, (bucket = { count: 0, sum: 0, min: Infinity, max: -Infinity }));
158
+ bucket.count++;
159
+ bucket.sum += point.value;
160
+ if (!Number.isFinite(bucket.sum))
161
+ throw new RangeError('Bucket sum exceeds finite number range.');
162
+ bucket.min = Math.min(bucket.min, point.value);
163
+ bucket.max = Math.max(bucket.max, point.value);
164
+ }
165
+ return [...buckets]
166
+ .sort(([a], [b]) => a - b)
167
+ .map(([start, bucket]) => ({
168
+ start,
169
+ end: start + width,
170
+ count: bucket.count,
171
+ sum: bucket.sum,
172
+ min: bucket.min,
173
+ max: bucket.max,
174
+ average: bucket.sum / bucket.count,
175
+ }));
176
+ },
177
+ clear() {
178
+ seriesMap.clear();
179
+ pointCount = 0;
180
+ },
181
+ };
182
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,36 @@
1
+ export interface DataPoint {
2
+ timestamp: number;
3
+ value: number;
4
+ }
5
+ export interface TimeSeriesOptions {
6
+ maxSeries?: number;
7
+ maxPoints?: number;
8
+ }
9
+ export interface QueryRange {
10
+ from?: number;
11
+ to?: number;
12
+ limit?: number;
13
+ }
14
+ export interface Bucket {
15
+ start: number;
16
+ end: number;
17
+ count: number;
18
+ sum: number;
19
+ min: number;
20
+ max: number;
21
+ average: number;
22
+ }
23
+ export interface TimeSeriesIndex {
24
+ readonly seriesCount: number;
25
+ readonly pointCount: number;
26
+ upsert(series: string, point: DataPoint): void;
27
+ removeSeries(series: string): boolean;
28
+ query(series: string, range?: QueryRange): DataPoint[];
29
+ aggregate(series: string, width: number, range?: QueryRange): Bucket[];
30
+ clear(): void;
31
+ }
32
+ export declare class TimeSeriesIndexError extends Error {
33
+ readonly code: 'capacity' | 'unknown-series';
34
+ constructor(code: 'capacity' | 'unknown-series', message: string);
35
+ }
36
+ export declare function createTimeSeriesIndex(options?: TimeSeriesOptions): TimeSeriesIndex;
@@ -0,0 +1,177 @@
1
+ export class TimeSeriesIndexError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.code = code;
6
+ this.name = 'TimeSeriesIndexError';
7
+ }
8
+ }
9
+ const isRecord = (value) => {
10
+ if (!value || typeof value !== 'object' || Array.isArray(value))
11
+ return false;
12
+ const prototype = Object.getPrototypeOf(value);
13
+ return prototype === Object.prototype || prototype === null;
14
+ };
15
+ function assertPlainObject(value, name) {
16
+ if (!isRecord(value))
17
+ throw new TypeError(`${name} must be a plain object.`);
18
+ }
19
+ function bounded(value, name, minimum, maximum) {
20
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
21
+ throw new RangeError(`${name} must be an integer from ${minimum} through ${maximum}.`);
22
+ }
23
+ return value;
24
+ }
25
+ function validateSeries(value) {
26
+ if (typeof value !== 'string' || value.length === 0 || value.length > 256) {
27
+ throw new TypeError('Series name must be a non-empty string of at most 256 characters.');
28
+ }
29
+ }
30
+ function validateTime(value, name) {
31
+ if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
32
+ throw new TypeError(`${name} must be a safe integer timestamp.`);
33
+ }
34
+ }
35
+ export function createTimeSeriesIndex(options = {}) {
36
+ assertPlainObject(options, 'Options');
37
+ const maxSeries = bounded(options.maxSeries ?? 1000, 'maxSeries', 1, 100_000);
38
+ const maxPoints = bounded(options.maxPoints ?? 1_000_000, 'maxPoints', 1, 10_000_000);
39
+ const seriesMap = new Map();
40
+ let pointCount = 0;
41
+ const requireSeries = (name) => {
42
+ validateSeries(name);
43
+ const points = seriesMap.get(name);
44
+ if (!points)
45
+ throw new TimeSeriesIndexError('unknown-series', `Unknown series: ${name}`);
46
+ return points;
47
+ };
48
+ const rangeValues = (range = {}) => {
49
+ assertPlainObject(range, 'Range');
50
+ const from = range.from;
51
+ const to = range.to;
52
+ if (from !== undefined)
53
+ validateTime(from, 'from');
54
+ if (to !== undefined)
55
+ validateTime(to, 'to');
56
+ if (from !== undefined && to !== undefined && from > to)
57
+ throw new RangeError('from must not exceed to.');
58
+ const limit = bounded(range.limit ?? maxPoints, 'limit', 0, maxPoints);
59
+ return { from: from ?? Number.MIN_SAFE_INTEGER, to: to ?? Number.MAX_SAFE_INTEGER, limit };
60
+ };
61
+ return {
62
+ get seriesCount() {
63
+ return seriesMap.size;
64
+ },
65
+ get pointCount() {
66
+ return pointCount;
67
+ },
68
+ upsert(name, input) {
69
+ validateSeries(name);
70
+ if (!isRecord(input))
71
+ throw new TypeError('Point must be a plain object.');
72
+ validateTime(input.timestamp, 'timestamp');
73
+ if (typeof input.value !== 'number' || !Number.isFinite(input.value)) {
74
+ throw new TypeError('Point value must be finite.');
75
+ }
76
+ let points = seriesMap.get(name);
77
+ if (!points) {
78
+ if (seriesMap.size >= maxSeries)
79
+ throw new TimeSeriesIndexError('capacity', 'Series capacity reached.');
80
+ points = [];
81
+ seriesMap.set(name, points);
82
+ }
83
+ let low = 0;
84
+ let high = points.length;
85
+ while (low < high) {
86
+ const middle = (low + high) >>> 1;
87
+ if (points[middle].timestamp < input.timestamp)
88
+ low = middle + 1;
89
+ else
90
+ high = middle;
91
+ }
92
+ const replacing = points[low]?.timestamp === input.timestamp;
93
+ if (!replacing && pointCount >= maxPoints)
94
+ throw new TimeSeriesIndexError('capacity', 'Point capacity reached.');
95
+ const point = Object.freeze({ timestamp: input.timestamp, value: input.value });
96
+ if (replacing)
97
+ points[low] = point;
98
+ else {
99
+ points.splice(low, 0, point);
100
+ pointCount++;
101
+ }
102
+ },
103
+ removeSeries(name) {
104
+ validateSeries(name);
105
+ const points = seriesMap.get(name);
106
+ if (!points)
107
+ return false;
108
+ pointCount -= points.length;
109
+ return seriesMap.delete(name);
110
+ },
111
+ query(name, range = {}) {
112
+ const points = requireSeries(name);
113
+ const { from, to, limit } = rangeValues(range);
114
+ let low = 0;
115
+ let high = points.length;
116
+ while (low < high) {
117
+ const middle = (low + high) >>> 1;
118
+ if (points[middle].timestamp < from)
119
+ low = middle + 1;
120
+ else
121
+ high = middle;
122
+ }
123
+ const output = [];
124
+ for (let index = low; index < points.length && output.length < limit; index++) {
125
+ if (points[index].timestamp > to)
126
+ break;
127
+ output.push({ ...points[index] });
128
+ }
129
+ return output;
130
+ },
131
+ aggregate(name, width, range = {}) {
132
+ const points = requireSeries(name);
133
+ if (!Number.isSafeInteger(width) || width <= 0)
134
+ throw new RangeError('width must be a positive safe integer.');
135
+ const { from, to, limit } = rangeValues(range);
136
+ const buckets = new Map();
137
+ let considered = 0;
138
+ for (const point of points) {
139
+ if (point.timestamp < from)
140
+ continue;
141
+ if (point.timestamp > to)
142
+ break;
143
+ if (considered >= limit)
144
+ break;
145
+ considered++;
146
+ const start = Math.floor(point.timestamp / width) * width;
147
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(start + width)) {
148
+ throw new RangeError('Bucket boundaries exceed the safe integer timestamp range.');
149
+ }
150
+ let bucket = buckets.get(start);
151
+ if (!bucket)
152
+ buckets.set(start, (bucket = { count: 0, sum: 0, min: Infinity, max: -Infinity }));
153
+ bucket.count++;
154
+ bucket.sum += point.value;
155
+ if (!Number.isFinite(bucket.sum))
156
+ throw new RangeError('Bucket sum exceeds finite number range.');
157
+ bucket.min = Math.min(bucket.min, point.value);
158
+ bucket.max = Math.max(bucket.max, point.value);
159
+ }
160
+ return [...buckets]
161
+ .sort(([a], [b]) => a - b)
162
+ .map(([start, bucket]) => ({
163
+ start,
164
+ end: start + width,
165
+ count: bucket.count,
166
+ sum: bucket.sum,
167
+ min: bucket.min,
168
+ max: bucket.max,
169
+ average: bucket.sum / bucket.count,
170
+ }));
171
+ },
172
+ clear() {
173
+ seriesMap.clear();
174
+ pointCount = 0;
175
+ },
176
+ };
177
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@lp-labs/time-series-index",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A bounded in-memory sorted index for timestamped numeric series.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/cjs/index.js",
8
+ "module": "./dist/esm/index.js",
9
+ "types": "./dist/esm/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/esm/index.d.ts",
14
+ "default": "./dist/esm/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/cjs/index.d.ts",
18
+ "default": "./dist/cjs/index.js"
19
+ }
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "sideEffects": false,
29
+ "engines": {
30
+ "node": ">=18"
31
+ },
32
+ "scripts": {
33
+ "build": "node scripts/build.mjs",
34
+ "typecheck": "npm run build && node scripts/check-types.mjs",
35
+ "test": "npm run build && node --test tests/*.test.mjs",
36
+ "format": "prettier --write src scripts tests *.json README.md",
37
+ "format:check": "prettier --check src scripts tests *.json README.md",
38
+ "prepack": "npm run build"
39
+ },
40
+ "devDependencies": {
41
+ "typescript": "^5.9.3",
42
+ "prettier": "^3.6.2"
43
+ },
44
+ "prettier": {
45
+ "singleQuote": true,
46
+ "semi": true,
47
+ "trailingComma": "all",
48
+ "printWidth": 100,
49
+ "endOfLine": "lf"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "registry": "https://registry.npmjs.org/"
54
+ },
55
+ "author": {
56
+ "name": "Libin Prasanth",
57
+ "url": "https://www.linkedin.com/in/libinprasanth/"
58
+ },
59
+ "funding": {
60
+ "type": "paypal",
61
+ "url": "https://www.paypal.me/LibinPrasanth"
62
+ }
63
+ }