@tempo-kit/plugin-batch 0.0.0-stage → 2.0.0-rc.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/CHANGELOG.md ADDED
@@ -0,0 +1,50 @@
1
+ # Changelog
2
+
3
+ All notable changes to the `@tempo-kit/plugin-batch` project will be documented in this file.
4
+
5
+ ## [2.0.0] - 2026-11-27
6
+
7
+ ### Breaking Changes
8
+ - Migrated package namespace from `@magmacomputing/tempo-plugin-batch` to `@tempo-kit/plugin-batch`.
9
+ - Updated `peerDependencies` to `tempo-kit@^5.0.0`.
10
+
11
+ ## [2.0.0] - 2026-11-27
12
+
13
+ ### Breaking Changes
14
+ - Migrated package namespace from `@magmacomputing/tempo-plugin-batch` to `@tempo-kit/plugin-batch`.
15
+ - Updated `peerDependencies` to `tempo-kit@^5.0.0`.
16
+
17
+ ## [1.2.1] - 2026-10-02
18
+
19
+ ### Enhanced
20
+ - **Runtime Introspection & Branding**:
21
+ - Added `[Symbol.toStringTag]` getter returning `'Tempo.BatchOrchestrator'` on `BatchOrchestrator` for structured runtime type identification and DevTools inspection.
22
+
23
+ ## [1.2.0] - 2026-09-18
24
+
25
+ ### Added
26
+ - **Subpath Side-Effect Installation (`/install`)**:
27
+ - Added dedicated `@tempo-kit/plugin-batch/install` entrypoint for zero-boilerplate side-effect registration on the global `Tempo` instance via `autoInstall`.
28
+ - Configured `package.json` with `"sideEffects": ["./dist/install.js"]` to ensure the root package entrypoint remains 100% pure and tree-shakeable.
29
+
30
+ ## [1.1.0] - 2026-09-08
31
+
32
+ ### Added & Enhanced
33
+ - **Worker Thread Runtime Flag Inheritance (`execArgv`)**:
34
+ - Configured `BatchOrchestrator` to forward `process.execArgv` to spawned worker threads.
35
+ - Workers automatically inherit native runtime flags (such as `--harmony-temporal`) or custom loader configurations (`--import`) without bundling or depending on a polyfill, strictly preserving Tempo's zero-dependency, native-first Temporal philosophy.
36
+ - **Shorthand Mutation Parsing**:
37
+ - Added support for relative duration shorthand strings (e.g. `+1d`, `+1w`, `+1h`, `+1m`) alongside `{ Term: Value }` mutation objects.
38
+
39
+ ## [1.0.2] - 2026-08-20
40
+
41
+ ### Fixed
42
+ - **Peer Dependencies**: Expanded peerDependency range to support Tempo v4.0.0.
43
+
44
+ ## [1.0.0] - 2026-06-29
45
+
46
+ ### Added
47
+ - Initial release of the `tempo-plugin-batch` community plugin.
48
+ - Implements `BatchOrchestrator` for extreme-throughput parallel processing of Tempo mutation tasks.
49
+ - Utilizes a graceful degradation architecture: attempts lock-free `SharedArrayBuffer` mapping, gracefully falling back to `postMessage` arrays on unsupported environments.
50
+ - Adds the `Tempo.batch(epochs, mutationArgs)` namespace for executing mutations across millions of timestamps simultaneously without blocking the main event loop.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Magma Computing
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,58 @@
1
- # Temporary Holding Version
1
+ ![Tempo Plugin](https://raw.githubusercontent.com/magmacomputing/magma/main/packages/tempo/public/plugin-logo.svg)
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
+ # @tempo-kit/plugin-batch
4
+
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/@tempo-kit/plugin-batch"><img src="https://img.shields.io/npm/v/@tempo-kit/plugin-batch?style=flat-square" alt="npm version" style="display: inline-block; margin: 0 4px;"></a> <a href="https://www.npmjs.com/package/tempo-kit"><img src="https://img.shields.io/npm/dependency-version/@tempo-kit/plugin-batch/peer/tempo-kit?style=flat-square" alt="npm peer dependency version" style="display: inline-block; margin: 0 4px;"></a> <a href="https://www.npmjs.com/package/@tempo-kit/plugin-batch"><img src="https://img.shields.io/npm/l/@tempo-kit/plugin-batch?style=flat-square" alt="License" style="display: inline-block; margin: 0 4px;"></a> <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-Ready-blue?logo=typescript&style=flat-square" alt="TypeScript Ready" style="display: inline-block; margin: 0 4px;"></a> <a href="https://magmacomputing.github.io/magma/doc/9-plugins/batch.index.html"><img src="https://img.shields.io/badge/Docs-VitePress-brightgreen?logo=vitepress&style=flat-square" alt="Documentation" style="display: inline-block; margin: 0 4px;"></a>
7
+ </p>
8
+
9
+ This is a Community plugin for the [Tempo](https://github.com/magmacomputing/magma) library that parallelizes massive epoch mutation tasks across worker threads utilizing lock-free `SharedArrayBuffer` architecture for extreme throughput.
10
+
11
+ 👉 **[View the full documentation on our GitHub Pages](https://magmacomputing.github.io/magma/doc/9-plugins/batch.index.html)**
12
+
13
+ > **Perfect for:** Heavy data ETL pipelines, massive IoT telemetry ingestion, financial ledger chronometrics, and any parallel bulk date-processing workloads.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @tempo-kit/plugin-batch
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ```typescript
24
+ import { Tempo } from 'tempo-kit';
25
+ import { BatchPlugin } from '@tempo-kit/plugin-batch';
26
+
27
+ Tempo.init({
28
+ extends: [BatchPlugin]
29
+ });
30
+
31
+ // Assume `epochs` is a massive array of integers representing timestamps
32
+ const epochs = [1700000000000, 1700000001000, /* ... millions more ... */];
33
+
34
+ // Mutate millions of dates concurrently using the worker pool
35
+ // The engine automatically splits the payload and offloads to workers!
36
+ const batchResult = await Tempo.batch(epochs, { weeks: 1 });
37
+
38
+ console.log(batchResult); // Returns an array of mutated timestamp integers
39
+ ```
40
+
41
+ > ⚡ **[Try this live in the interactive Tempo Sandbox ↗](https://magmacomputing.github.io/magma/repl/index.html?plugin=batch)**
42
+
43
+ ### Rehydration
44
+
45
+ By default, `Tempo.batch` returns an array of primitive `number` timestamps to maximize throughput over the thread boundary. If you need fully-fledged `Tempo` objects back, pass `{ rehydrate: true }`:
46
+
47
+ ```typescript
48
+ // Returns an array of Tempo instances instead of integers
49
+ const tempoInstances = await Tempo.batch(epochs, { weeks: 1 }, { rehydrate: true });
50
+ ```
51
+
52
+ ### Graceful Degradation
53
+
54
+ If the host environment does not support `SharedArrayBuffer` (or if it is blocked by CORS/COOP headers in the browser), the orchestrator intelligently and transparently falls back to using traditional `postMessage` structural cloning chunks to ensure execution never halts.
55
+
56
+ ## Licensing
57
+
58
+ This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
@@ -0,0 +1,60 @@
1
+ export interface BatchOptions {
2
+ /**
3
+ * Number of threads to use. Defaults to the number of logical CPUs.
4
+ */
5
+ threads?: number;
6
+ /**
7
+ * If true, the output array will contain hydrated Tempo instances instead of raw epoch numbers.
8
+ * Default is false (returns raw epochs for maximum performance).
9
+ */
10
+ rehydrate?: boolean;
11
+ }
12
+ /**
13
+ * Orchestrates the parallel execution of a mutation or formatting operation across an array of epochs.
14
+ */
15
+ export declare class BatchOrchestrator {
16
+ /**
17
+ * Sanitizes process.execArgv using a positive AllowList of worker-safe options (loaders, polyfills, inspection).
18
+ * Any V8 memory/optimization flags or process-level flags are safely dropped.
19
+ *
20
+ * @param argv - Array of Node CLI options (defaults to process.execArgv)
21
+ * @returns Sanitized array of CLI options safe for worker_threads
22
+ * @internal
23
+ */
24
+ static sanitizeExecArgv(argv?: string[]): string[];
25
+ get [Symbol.toStringTag](): string;
26
+ /**
27
+ * Transforms an array of epochs using a worker pool.
28
+ * @param epochs Array of raw millisecond epoch numbers.
29
+ * @param operation The tempo mutation string (e.g. '+1w').
30
+ * @param options Execution options.
31
+ * @returns Array of transformed epochs.
32
+ */
33
+ static transform(epochs: number[], operation: string, options?: BatchOptions): Promise<any[]>;
34
+ /**
35
+ * Transforms epochs using SharedArrayBuffer for maximum performance.
36
+ * Workers read from and write to shared memory concurrently.
37
+ *
38
+ * @param epochs - Array of millisecond epoch numbers
39
+ * @param operation - The tempo mutation string
40
+ * @param threadCount - Number of worker threads to spawn
41
+ * @param chunkSize - Number of epochs per chunk
42
+ * @param options - Execution options
43
+ * @returns Array of transformed epochs
44
+ * @internal
45
+ */
46
+ private static _transformWithSAB;
47
+ /**
48
+ * Transforms epochs using postMessage for worker communication.
49
+ * Falls back to this method when SharedArrayBuffer is unavailable.
50
+ *
51
+ * @param epochs - Array of millisecond epoch numbers
52
+ * @param operation - The tempo mutation string
53
+ * @param threadCount - Number of worker threads to spawn
54
+ * @param chunkSize - Number of epochs per chunk
55
+ * @param options - Execution options
56
+ * @returns Array of transformed epochs
57
+ * @internal
58
+ */
59
+ private static _transformWithPostMessage;
60
+ }
@@ -0,0 +1,23 @@
1
+ import { BatchOrchestrator, type BatchOptions } from './BatchOrchestrator.js';
2
+ import { type TempoPlugin } from 'tempo-kit/plugin/sdk';
3
+ export { BatchOrchestrator };
4
+ export type { BatchOptions };
5
+ declare module 'tempo-kit' {
6
+ namespace Tempo {
7
+ /**
8
+ * Orchestrates the parallel execution of a mutation or formatting operation across an array of epochs.
9
+ * Automatically distributes the workload across a pool of Web Workers using SharedArrayBuffers (when available).
10
+ *
11
+ * @param epochs - Array of raw millisecond epoch numbers to process
12
+ * @param operation - The tempo mutation string (e.g., '+1w')
13
+ * @param options - Execution options including thread count and return format
14
+ * @returns A promise resolving to an array of transformed epochs (or Tempo instances)
15
+ */
16
+ function batch(epochs: number[], operation: string, options?: BatchOptions): Promise<any[]>;
17
+ }
18
+ }
19
+ /**
20
+ * The Batch Plugin.
21
+ * Exposes `Tempo.batch()` for high-performance, multi-threaded array processing.
22
+ */
23
+ export declare const BatchPlugin: TempoPlugin;
package/dist/index.js ADDED
@@ -0,0 +1,243 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
+
19
+ // src/BatchOrchestrator.ts
20
+ import os from "os";
21
+ import fs from "fs";
22
+ import { Worker } from "worker_threads";
23
+ import { fileURLToPath } from "url";
24
+ import path from "path";
25
+ var __filename = fileURLToPath(import.meta.url);
26
+ var __dirname = path.dirname(__filename);
27
+ var isTS = __filename.endsWith(".ts");
28
+ var distWorkerPath = path.join(__dirname, "../dist/worker.js");
29
+ var srcWorkerPath = path.join(__dirname, "worker.ts");
30
+ var hasDist = fs.existsSync(distWorkerPath);
31
+ var hasSrc = fs.existsSync(srcWorkerPath);
32
+ var nodeMajor = parseInt(process.versions.node?.split(".")[0] || "0", 10);
33
+ var hasTsSupport = nodeMajor >= 26 || (process.execArgv || []).some(
34
+ (arg) => arg.includes("tsx") || arg.includes("ts-node") || arg.includes("strip-types") || arg.includes("--loader")
35
+ );
36
+ var WORKER_PATH = isTS ? hasDist && !hasTsSupport ? distWorkerPath : hasSrc ? srcWorkerPath : distWorkerPath : path.join(__dirname, "worker.js");
37
+ var ALLOWED_FLAGS_WITH_VALUE = /* @__PURE__ */ new Set([
38
+ "--import",
39
+ "--loader",
40
+ "--experimental-loader",
41
+ "-r",
42
+ "--require"
43
+ ]);
44
+ var ALLOWED_STANDALONE_FLAGS = /* @__PURE__ */ new Set([
45
+ "--experimental-vm-modules",
46
+ "--experimental-temporal",
47
+ "--experimental-specifier-resolution",
48
+ "--inspect",
49
+ "--inspect-brk",
50
+ "--trace-warnings",
51
+ "--no-warnings",
52
+ "--trace-deprecation",
53
+ "--no-deprecation"
54
+ ]);
55
+ var BatchOrchestrator = class {
56
+ /**
57
+ * Sanitizes process.execArgv using a positive AllowList of worker-safe options (loaders, polyfills, inspection).
58
+ * Any V8 memory/optimization flags or process-level flags are safely dropped.
59
+ *
60
+ * @param argv - Array of Node CLI options (defaults to process.execArgv)
61
+ * @returns Sanitized array of CLI options safe for worker_threads
62
+ * @internal
63
+ */
64
+ static sanitizeExecArgv(argv = process.execArgv || []) {
65
+ const result = [];
66
+ for (let i = 0; i < argv.length; i++) {
67
+ const arg = argv[i];
68
+ const eqIdx = arg.indexOf("=");
69
+ const hasEq = eqIdx !== -1;
70
+ const rawFlag = hasEq ? arg.slice(0, eqIdx) : arg;
71
+ const flag = rawFlag.replace(/_/g, "-");
72
+ if (ALLOWED_FLAGS_WITH_VALUE.has(flag)) {
73
+ if (hasEq) {
74
+ result.push(arg);
75
+ } else if (i + 1 < argv.length) {
76
+ result.push(arg, argv[++i]);
77
+ }
78
+ continue;
79
+ }
80
+ if (ALLOWED_STANDALONE_FLAGS.has(flag)) {
81
+ result.push(arg);
82
+ continue;
83
+ }
84
+ }
85
+ return result;
86
+ }
87
+ get [Symbol.toStringTag]() {
88
+ return "Tempo.BatchOrchestrator";
89
+ }
90
+ /**
91
+ * Transforms an array of epochs using a worker pool.
92
+ * @param epochs Array of raw millisecond epoch numbers.
93
+ * @param operation The tempo mutation string (e.g. '+1w').
94
+ * @param options Execution options.
95
+ * @returns Array of transformed epochs.
96
+ */
97
+ static async transform(epochs, operation, options = {}) {
98
+ if (epochs.length === 0) return [];
99
+ if (options.threads !== void 0) {
100
+ if (!Number.isInteger(options.threads) || options.threads <= 0)
101
+ throw new Error("options.threads must be a positive integer");
102
+ }
103
+ const threadCount = options.threads ?? os.cpus().length;
104
+ const chunkSize = Math.ceil(epochs.length / threadCount);
105
+ if (typeof SharedArrayBuffer !== "undefined") {
106
+ return this._transformWithSAB(epochs, operation, threadCount, chunkSize, options);
107
+ } else {
108
+ return this._transformWithPostMessage(epochs, operation, threadCount, chunkSize, options);
109
+ }
110
+ }
111
+ /**
112
+ * Transforms epochs using SharedArrayBuffer for maximum performance.
113
+ * Workers read from and write to shared memory concurrently.
114
+ *
115
+ * @param epochs - Array of millisecond epoch numbers
116
+ * @param operation - The tempo mutation string
117
+ * @param threadCount - Number of worker threads to spawn
118
+ * @param chunkSize - Number of epochs per chunk
119
+ * @param options - Execution options
120
+ * @returns Array of transformed epochs
121
+ * @internal
122
+ */
123
+ static async _transformWithSAB(epochs, operation, threadCount, chunkSize, options) {
124
+ const inputBuffer = new SharedArrayBuffer(epochs.length * 8);
125
+ const outputBuffer = new SharedArrayBuffer(epochs.length * 8);
126
+ const inputView = new Float64Array(inputBuffer);
127
+ for (let i = 0; i < epochs.length; i++) {
128
+ inputView[i] = epochs[i];
129
+ }
130
+ const workers = [];
131
+ const actualThreads = Math.min(threadCount, Math.ceil(epochs.length / chunkSize));
132
+ const execArgv = this.sanitizeExecArgv();
133
+ for (let i = 0; i < actualThreads; i++) {
134
+ const startIdx = i * chunkSize;
135
+ const endIdx = Math.min((i + 1) * chunkSize, epochs.length);
136
+ const workerPromise = new Promise((resolve, reject) => {
137
+ const worker = new Worker(WORKER_PATH, {
138
+ workerData: {
139
+ mode: "sab",
140
+ inputBuffer,
141
+ outputBuffer,
142
+ startIdx,
143
+ endIdx,
144
+ operation
145
+ },
146
+ execArgv
147
+ });
148
+ worker.on("message", (msg) => {
149
+ if (msg.status === "done") resolve();
150
+ else reject(new Error(msg.error));
151
+ });
152
+ worker.on("error", reject);
153
+ worker.on("exit", (code) => {
154
+ if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
155
+ });
156
+ });
157
+ workers.push(workerPromise);
158
+ }
159
+ await Promise.all(workers);
160
+ const outputView = new Float64Array(outputBuffer);
161
+ const result = new Array(epochs.length);
162
+ for (let i = 0; i < epochs.length; i++) {
163
+ result[i] = outputView[i];
164
+ }
165
+ return result;
166
+ }
167
+ /**
168
+ * Transforms epochs using postMessage for worker communication.
169
+ * Falls back to this method when SharedArrayBuffer is unavailable.
170
+ *
171
+ * @param epochs - Array of millisecond epoch numbers
172
+ * @param operation - The tempo mutation string
173
+ * @param threadCount - Number of worker threads to spawn
174
+ * @param chunkSize - Number of epochs per chunk
175
+ * @param options - Execution options
176
+ * @returns Array of transformed epochs
177
+ * @internal
178
+ */
179
+ static async _transformWithPostMessage(epochs, operation, threadCount, chunkSize, options) {
180
+ const workers = [];
181
+ const actualThreads = Math.min(threadCount, Math.ceil(epochs.length / chunkSize));
182
+ const execArgv = this.sanitizeExecArgv();
183
+ for (let i = 0; i < actualThreads; i++) {
184
+ const startIdx = i * chunkSize;
185
+ const endIdx = Math.min((i + 1) * chunkSize, epochs.length);
186
+ const chunk = epochs.slice(startIdx, endIdx);
187
+ const workerPromise = new Promise((resolve, reject) => {
188
+ const worker = new Worker(WORKER_PATH, {
189
+ workerData: {
190
+ mode: "postMessage",
191
+ chunk,
192
+ operation
193
+ },
194
+ execArgv
195
+ });
196
+ worker.on("message", (msg) => {
197
+ if (msg.status === "done") resolve(msg.result);
198
+ else reject(new Error(msg.error));
199
+ });
200
+ worker.on("error", reject);
201
+ worker.on("exit", (code) => {
202
+ if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
203
+ });
204
+ });
205
+ workers.push(workerPromise);
206
+ }
207
+ const resultsArray = await Promise.all(workers);
208
+ return resultsArray.flat();
209
+ }
210
+ };
211
+
212
+ // auto-inject-version:tempo-kit/plugin/sdk
213
+ var sdk_exports = {};
214
+ __export(sdk_exports, {
215
+ definePlugin: () => definePlugin,
216
+ defineTerm: () => defineTerm
217
+ });
218
+ __reExport(sdk_exports, sdk_star);
219
+ import * as sdk_star from "tempo-kit/plugin/sdk";
220
+ import { definePlugin as originalPlugin, defineTerm as originalTerm } from "tempo-kit/plugin/sdk";
221
+ var definePlugin = (config) => originalPlugin({ ...config, version: "2.0.0-rc.0" });
222
+ var defineTerm = (config) => originalTerm({ ...config, version: "2.0.0-rc.0" });
223
+
224
+ // src/index.ts
225
+ var BatchPlugin = definePlugin({
226
+ name: "batch",
227
+ install(TempoRef) {
228
+ if (TempoRef.batch) {
229
+ return;
230
+ }
231
+ TempoRef.batch = async function(epochs, operation, options) {
232
+ const results = await BatchOrchestrator.transform(epochs, operation, options);
233
+ if (options?.rehydrate) {
234
+ return results.map((epoch) => new TempoRef(epoch));
235
+ }
236
+ return results;
237
+ };
238
+ }
239
+ });
240
+ export {
241
+ BatchOrchestrator,
242
+ BatchPlugin
243
+ };
@@ -0,0 +1 @@
1
+ export * from './index.js';
@@ -0,0 +1,246 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
+
19
+ // auto-inject-version:tempo-kit/plugin/sdk
20
+ var sdk_exports = {};
21
+ __export(sdk_exports, {
22
+ definePlugin: () => definePlugin,
23
+ defineTerm: () => defineTerm
24
+ });
25
+ __reExport(sdk_exports, sdk_star);
26
+ import * as sdk_star from "tempo-kit/plugin/sdk";
27
+ import { definePlugin as originalPlugin, defineTerm as originalTerm } from "tempo-kit/plugin/sdk";
28
+ var definePlugin = (config) => originalPlugin({ ...config, version: "2.0.0-rc.0" });
29
+ var defineTerm = (config) => originalTerm({ ...config, version: "2.0.0-rc.0" });
30
+
31
+ // src/BatchOrchestrator.ts
32
+ import os from "os";
33
+ import fs from "fs";
34
+ import { Worker } from "worker_threads";
35
+ import { fileURLToPath } from "url";
36
+ import path from "path";
37
+ var __filename = fileURLToPath(import.meta.url);
38
+ var __dirname = path.dirname(__filename);
39
+ var isTS = __filename.endsWith(".ts");
40
+ var distWorkerPath = path.join(__dirname, "../dist/worker.js");
41
+ var srcWorkerPath = path.join(__dirname, "worker.ts");
42
+ var hasDist = fs.existsSync(distWorkerPath);
43
+ var hasSrc = fs.existsSync(srcWorkerPath);
44
+ var nodeMajor = parseInt(process.versions.node?.split(".")[0] || "0", 10);
45
+ var hasTsSupport = nodeMajor >= 26 || (process.execArgv || []).some(
46
+ (arg) => arg.includes("tsx") || arg.includes("ts-node") || arg.includes("strip-types") || arg.includes("--loader")
47
+ );
48
+ var WORKER_PATH = isTS ? hasDist && !hasTsSupport ? distWorkerPath : hasSrc ? srcWorkerPath : distWorkerPath : path.join(__dirname, "worker.js");
49
+ var ALLOWED_FLAGS_WITH_VALUE = /* @__PURE__ */ new Set([
50
+ "--import",
51
+ "--loader",
52
+ "--experimental-loader",
53
+ "-r",
54
+ "--require"
55
+ ]);
56
+ var ALLOWED_STANDALONE_FLAGS = /* @__PURE__ */ new Set([
57
+ "--experimental-vm-modules",
58
+ "--experimental-temporal",
59
+ "--experimental-specifier-resolution",
60
+ "--inspect",
61
+ "--inspect-brk",
62
+ "--trace-warnings",
63
+ "--no-warnings",
64
+ "--trace-deprecation",
65
+ "--no-deprecation"
66
+ ]);
67
+ var BatchOrchestrator = class {
68
+ /**
69
+ * Sanitizes process.execArgv using a positive AllowList of worker-safe options (loaders, polyfills, inspection).
70
+ * Any V8 memory/optimization flags or process-level flags are safely dropped.
71
+ *
72
+ * @param argv - Array of Node CLI options (defaults to process.execArgv)
73
+ * @returns Sanitized array of CLI options safe for worker_threads
74
+ * @internal
75
+ */
76
+ static sanitizeExecArgv(argv = process.execArgv || []) {
77
+ const result = [];
78
+ for (let i = 0; i < argv.length; i++) {
79
+ const arg = argv[i];
80
+ const eqIdx = arg.indexOf("=");
81
+ const hasEq = eqIdx !== -1;
82
+ const rawFlag = hasEq ? arg.slice(0, eqIdx) : arg;
83
+ const flag = rawFlag.replace(/_/g, "-");
84
+ if (ALLOWED_FLAGS_WITH_VALUE.has(flag)) {
85
+ if (hasEq) {
86
+ result.push(arg);
87
+ } else if (i + 1 < argv.length) {
88
+ result.push(arg, argv[++i]);
89
+ }
90
+ continue;
91
+ }
92
+ if (ALLOWED_STANDALONE_FLAGS.has(flag)) {
93
+ result.push(arg);
94
+ continue;
95
+ }
96
+ }
97
+ return result;
98
+ }
99
+ get [Symbol.toStringTag]() {
100
+ return "Tempo.BatchOrchestrator";
101
+ }
102
+ /**
103
+ * Transforms an array of epochs using a worker pool.
104
+ * @param epochs Array of raw millisecond epoch numbers.
105
+ * @param operation The tempo mutation string (e.g. '+1w').
106
+ * @param options Execution options.
107
+ * @returns Array of transformed epochs.
108
+ */
109
+ static async transform(epochs, operation, options = {}) {
110
+ if (epochs.length === 0) return [];
111
+ if (options.threads !== void 0) {
112
+ if (!Number.isInteger(options.threads) || options.threads <= 0)
113
+ throw new Error("options.threads must be a positive integer");
114
+ }
115
+ const threadCount = options.threads ?? os.cpus().length;
116
+ const chunkSize = Math.ceil(epochs.length / threadCount);
117
+ if (typeof SharedArrayBuffer !== "undefined") {
118
+ return this._transformWithSAB(epochs, operation, threadCount, chunkSize, options);
119
+ } else {
120
+ return this._transformWithPostMessage(epochs, operation, threadCount, chunkSize, options);
121
+ }
122
+ }
123
+ /**
124
+ * Transforms epochs using SharedArrayBuffer for maximum performance.
125
+ * Workers read from and write to shared memory concurrently.
126
+ *
127
+ * @param epochs - Array of millisecond epoch numbers
128
+ * @param operation - The tempo mutation string
129
+ * @param threadCount - Number of worker threads to spawn
130
+ * @param chunkSize - Number of epochs per chunk
131
+ * @param options - Execution options
132
+ * @returns Array of transformed epochs
133
+ * @internal
134
+ */
135
+ static async _transformWithSAB(epochs, operation, threadCount, chunkSize, options) {
136
+ const inputBuffer = new SharedArrayBuffer(epochs.length * 8);
137
+ const outputBuffer = new SharedArrayBuffer(epochs.length * 8);
138
+ const inputView = new Float64Array(inputBuffer);
139
+ for (let i = 0; i < epochs.length; i++) {
140
+ inputView[i] = epochs[i];
141
+ }
142
+ const workers = [];
143
+ const actualThreads = Math.min(threadCount, Math.ceil(epochs.length / chunkSize));
144
+ const execArgv = this.sanitizeExecArgv();
145
+ for (let i = 0; i < actualThreads; i++) {
146
+ const startIdx = i * chunkSize;
147
+ const endIdx = Math.min((i + 1) * chunkSize, epochs.length);
148
+ const workerPromise = new Promise((resolve, reject) => {
149
+ const worker = new Worker(WORKER_PATH, {
150
+ workerData: {
151
+ mode: "sab",
152
+ inputBuffer,
153
+ outputBuffer,
154
+ startIdx,
155
+ endIdx,
156
+ operation
157
+ },
158
+ execArgv
159
+ });
160
+ worker.on("message", (msg) => {
161
+ if (msg.status === "done") resolve();
162
+ else reject(new Error(msg.error));
163
+ });
164
+ worker.on("error", reject);
165
+ worker.on("exit", (code) => {
166
+ if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
167
+ });
168
+ });
169
+ workers.push(workerPromise);
170
+ }
171
+ await Promise.all(workers);
172
+ const outputView = new Float64Array(outputBuffer);
173
+ const result = new Array(epochs.length);
174
+ for (let i = 0; i < epochs.length; i++) {
175
+ result[i] = outputView[i];
176
+ }
177
+ return result;
178
+ }
179
+ /**
180
+ * Transforms epochs using postMessage for worker communication.
181
+ * Falls back to this method when SharedArrayBuffer is unavailable.
182
+ *
183
+ * @param epochs - Array of millisecond epoch numbers
184
+ * @param operation - The tempo mutation string
185
+ * @param threadCount - Number of worker threads to spawn
186
+ * @param chunkSize - Number of epochs per chunk
187
+ * @param options - Execution options
188
+ * @returns Array of transformed epochs
189
+ * @internal
190
+ */
191
+ static async _transformWithPostMessage(epochs, operation, threadCount, chunkSize, options) {
192
+ const workers = [];
193
+ const actualThreads = Math.min(threadCount, Math.ceil(epochs.length / chunkSize));
194
+ const execArgv = this.sanitizeExecArgv();
195
+ for (let i = 0; i < actualThreads; i++) {
196
+ const startIdx = i * chunkSize;
197
+ const endIdx = Math.min((i + 1) * chunkSize, epochs.length);
198
+ const chunk = epochs.slice(startIdx, endIdx);
199
+ const workerPromise = new Promise((resolve, reject) => {
200
+ const worker = new Worker(WORKER_PATH, {
201
+ workerData: {
202
+ mode: "postMessage",
203
+ chunk,
204
+ operation
205
+ },
206
+ execArgv
207
+ });
208
+ worker.on("message", (msg) => {
209
+ if (msg.status === "done") resolve(msg.result);
210
+ else reject(new Error(msg.error));
211
+ });
212
+ worker.on("error", reject);
213
+ worker.on("exit", (code) => {
214
+ if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
215
+ });
216
+ });
217
+ workers.push(workerPromise);
218
+ }
219
+ const resultsArray = await Promise.all(workers);
220
+ return resultsArray.flat();
221
+ }
222
+ };
223
+
224
+ // src/index.ts
225
+ var BatchPlugin = definePlugin({
226
+ name: "batch",
227
+ install(TempoRef) {
228
+ if (TempoRef.batch) {
229
+ return;
230
+ }
231
+ TempoRef.batch = async function(epochs, operation, options) {
232
+ const results = await BatchOrchestrator.transform(epochs, operation, options);
233
+ if (options?.rehydrate) {
234
+ return results.map((epoch) => new TempoRef(epoch));
235
+ }
236
+ return results;
237
+ };
238
+ }
239
+ });
240
+
241
+ // src/install.ts
242
+ (0, sdk_exports.autoInstall)(BatchPlugin);
243
+ export {
244
+ BatchOrchestrator,
245
+ BatchPlugin
246
+ };
@@ -0,0 +1 @@
1
+ export {};
package/dist/worker.js ADDED
@@ -0,0 +1,116 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
+
19
+ // src/worker.ts
20
+ import { workerData, parentPort } from "worker_threads";
21
+ import { Tempo } from "tempo-kit";
22
+
23
+ // auto-inject-version:tempo-kit/plugin/sdk
24
+ var sdk_exports = {};
25
+ __export(sdk_exports, {
26
+ definePlugin: () => definePlugin,
27
+ defineTerm: () => defineTerm
28
+ });
29
+ __reExport(sdk_exports, sdk_star);
30
+ import * as sdk_star from "tempo-kit/plugin/sdk";
31
+ import { definePlugin as originalPlugin, defineTerm as originalTerm } from "tempo-kit/plugin/sdk";
32
+ var definePlugin = (config) => originalPlugin({ ...config, version: "2.0.0-rc.0" });
33
+ var defineTerm = (config) => originalTerm({ ...config, version: "2.0.0-rc.0" });
34
+
35
+ // src/worker.ts
36
+ var RE_SHORTHAND_OP = /^([+-]?\d+)\s*([a-zA-Z]+)$/;
37
+ var UNIT_MAP = {
38
+ d: "days",
39
+ day: "days",
40
+ days: "days",
41
+ w: "weeks",
42
+ week: "weeks",
43
+ weeks: "weeks",
44
+ m: "minutes",
45
+ min: "minutes",
46
+ mins: "minutes",
47
+ minute: "minutes",
48
+ minutes: "minutes",
49
+ h: "hours",
50
+ hr: "hours",
51
+ hrs: "hours",
52
+ hour: "hours",
53
+ hours: "hours",
54
+ s: "seconds",
55
+ sec: "seconds",
56
+ secs: "seconds",
57
+ second: "seconds",
58
+ seconds: "seconds",
59
+ mo: "months",
60
+ month: "months",
61
+ months: "months",
62
+ y: "years",
63
+ yr: "years",
64
+ yrs: "years",
65
+ year: "years",
66
+ years: "years"
67
+ };
68
+ function resolveMutationPayload(op) {
69
+ if ((0, sdk_exports.isString)(op)) {
70
+ const match = op.trim().match(RE_SHORTHAND_OP);
71
+ if (match) {
72
+ const count = parseInt(match[1], 10);
73
+ const unit = match[2].toLowerCase();
74
+ const mappedUnit = UNIT_MAP[unit];
75
+ if (mappedUnit) {
76
+ return { [mappedUnit]: count };
77
+ }
78
+ }
79
+ }
80
+ return op;
81
+ }
82
+ function applyMutation(t, op) {
83
+ return t.add(op);
84
+ }
85
+ async function run() {
86
+ if (!parentPort) return;
87
+ const { mode, operation } = workerData;
88
+ const resolvedOp = resolveMutationPayload(operation);
89
+ try {
90
+ if (mode === "sab") {
91
+ const { inputBuffer, outputBuffer, startIdx, endIdx } = workerData;
92
+ const inputView = new Float64Array(inputBuffer);
93
+ const outputView = new Float64Array(outputBuffer);
94
+ for (let i = startIdx; i < endIdx; i++) {
95
+ const epoch = inputView[i];
96
+ const t = new Tempo(epoch);
97
+ const resultT = applyMutation(t, resolvedOp);
98
+ outputView[i] = resultT.epoch.ms;
99
+ }
100
+ parentPort.postMessage({ status: "done" });
101
+ } else if (mode === "postMessage") {
102
+ const { chunk } = workerData;
103
+ const result = new Array(chunk.length);
104
+ for (let i = 0; i < chunk.length; i++) {
105
+ const epoch = chunk[i];
106
+ const t = new Tempo(epoch);
107
+ const resultT = applyMutation(t, resolvedOp);
108
+ result[i] = resultT.epoch.ms;
109
+ }
110
+ parentPort.postMessage({ status: "done", result });
111
+ }
112
+ } catch (error) {
113
+ parentPort.postMessage({ status: "error", error: error.message || String(error) });
114
+ }
115
+ }
116
+ run();
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@tempo-kit/plugin-batch",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.0-rc.0",
4
+ "description": "Tempo community plugin bringing C-level parallelization to massive date arrays via SharedArrayBuffer and Worker Threads.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "sideEffects": [
8
+ "./dist/install.js"
9
+ ],
10
+ "license": "MIT",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/magmacomputing/magma.git",
14
+ "directory": "packages/plugins/batch"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "CHANGELOG.md",
20
+ "LICENSE"
21
+ ],
22
+ "publishConfig": {
23
+ "registry": "https://registry.npmjs.org/",
24
+ "access": "public"
25
+ },
26
+ "scripts": {
27
+ "build": "tsup && tsc",
28
+ "test": "vitest run -c ../vitest.shared.ts",
29
+ "prepublishOnly": "tempo-cli prepublish"
30
+ },
31
+ "peerDependencies": {
32
+ "tempo-kit": "^5.0.0"
33
+ },
34
+ "devDependencies": {
35
+ "@js-temporal/polyfill": "^0.5.1",
36
+ "tempo-kit": "^5.0.0"
37
+ },
38
+ "keywords": [
39
+ "tempo-kit",
40
+ "tempo-kit-plugin",
41
+ "tempo",
42
+ "temporal",
43
+ "tempo-plugin",
44
+ "batch",
45
+ "parallel",
46
+ "threads",
47
+ "worker",
48
+ "performance"
49
+ ],
50
+ "type": "module",
51
+ "exports": {
52
+ ".": {
53
+ "types": "./dist/index.d.ts",
54
+ "import": "./dist/index.js",
55
+ "default": "./dist/index.js"
56
+ },
57
+ "./install": {
58
+ "types": "./dist/index.d.ts",
59
+ "import": "./dist/install.js",
60
+ "default": "./dist/install.js"
61
+ }
62
+ }
63
+ }