@temps-sdk/plugin 0.1.0-beta.1 → 0.1.0-beta.2
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/dist/ai.d.ts +32 -0
- package/dist/ai.d.ts.map +1 -0
- package/dist/ai.js +38 -0
- package/dist/ai.js.map +1 -0
- package/dist/client.d.ts +41 -10
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +146 -89
- package/dist/client.js.map +1 -1
- package/dist/context.d.ts +21 -12
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +25 -36
- package/dist/context.js.map +1 -1
- package/dist/errors.d.ts +0 -23
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +0 -46
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +36 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +42 -6
- package/dist/index.js.map +1 -1
- package/dist/launch.d.ts +9 -0
- package/dist/launch.d.ts.map +1 -0
- package/dist/launch.js +96 -0
- package/dist/launch.js.map +1 -0
- package/dist/manifest-builder.d.ts +4 -9
- package/dist/manifest-builder.d.ts.map +1 -1
- package/dist/manifest-builder.js +7 -26
- package/dist/manifest-builder.js.map +1 -1
- package/dist/protocol.d.ts +28 -14
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +49 -94
- package/dist/protocol.js.map +1 -1
- package/dist/runtime.d.ts +21 -12
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +318 -426
- package/dist/runtime.js.map +1 -1
- package/dist/types.d.ts +147 -151
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -4
- package/dist/types.js.map +1 -1
- package/dist/ui.d.ts.map +1 -1
- package/dist/ui.js +7 -26
- package/dist/ui.js.map +1 -1
- package/package.json +10 -19
- package/LICENSE +0 -21
- package/README.md +0 -123
- package/dist/api.d.ts +0 -33
- package/dist/api.d.ts.map +0 -1
- package/dist/api.js +0 -96
- package/dist/api.js.map +0 -1
- package/dist/auth.d.ts +0 -41
- package/dist/auth.d.ts.map +0 -1
- package/dist/auth.js +0 -102
- package/dist/auth.js.map +0 -1
package/dist/runtime.js
CHANGED
|
@@ -1,511 +1,403 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
2
|
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Plugin runtime -- handles the full lifecycle of a Temps external plugin.
|
|
5
|
+
*
|
|
6
|
+
* Mirrors: crates/temps-plugin-sdk/src/runtime.rs
|
|
7
|
+
*
|
|
8
|
+
* Built for Bun -- compiled to a single binary via `bun build --compile`.
|
|
9
|
+
*
|
|
10
|
+
* Lifecycle:
|
|
11
|
+
* 1. Parse non-secret CLI arguments (--socket-path, --data-dir)
|
|
12
|
+
* 2. Emit protocol-2 hello and receive private launch configuration on stdin
|
|
13
|
+
* 3. Start Bun.serve on Unix domain socket
|
|
14
|
+
* 4. Emit ready to stdout (handshake phase 2)
|
|
15
|
+
* 5. Accept WebSocket connection from host on /_temps/channel
|
|
16
|
+
* 6. Create PluginContext with TempsClient
|
|
17
|
+
* 7. Call plugin.onStart()
|
|
18
|
+
* 8. Serve plugin routes, health, events, and embedded UI
|
|
19
|
+
* 9. Handle SIGTERM for graceful shutdown
|
|
20
|
+
*/
|
|
21
|
+
import { existsSync, mkdirSync, unlinkSync } from "node:fs";
|
|
4
22
|
import { dirname } from "node:path";
|
|
5
|
-
import { attachVerifiedCaller, verifyProxyHeaders, } from "./auth.js";
|
|
6
23
|
import { TempsClient } from "./client.js";
|
|
7
24
|
import { PluginContext } from "./context.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
25
|
+
import { emitManifest, emitReady, PLUGIN_CHANNEL_PATH, extractAuthContext } from "./protocol.js";
|
|
26
|
+
import { createEmbeddedUiHandler } from "./ui.js";
|
|
27
|
+
import { ArgsError, InitializationError } from "./errors.js";
|
|
28
|
+
import { readLaunchConfig, authenticatedHostRequest, requiresHostAuthentication, validateHealthPath } from "./launch.js";
|
|
29
|
+
/**
|
|
30
|
+
* Run a Temps plugin. This is the main entry point.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* import { runPlugin, createManifest } from "@temps-sdk/plugin";
|
|
35
|
+
*
|
|
36
|
+
* runPlugin({
|
|
37
|
+
* manifest: () => createManifest("my-plugin", "0.1.0")
|
|
38
|
+
* .displayName("My Plugin")
|
|
39
|
+
* .addNav("Dashboard", "layout-dashboard", "/dashboard")
|
|
40
|
+
* .build(),
|
|
41
|
+
*
|
|
42
|
+
* handler: (ctx) => async (req, res) => {
|
|
43
|
+
* res.writeHead(200, { "Content-Type": "application/json" });
|
|
44
|
+
* res.end(JSON.stringify({ hello: "world" }));
|
|
45
|
+
* },
|
|
46
|
+
* });
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
14
49
|
export async function runPlugin(plugin) {
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
// Stage 1: identify the protocol and requested privileges before receiving secrets.
|
|
19
|
-
emitHello(manifest);
|
|
20
|
-
const launch = await readLaunchConfig(manifest);
|
|
50
|
+
// 1. Parse CLI arguments
|
|
51
|
+
const args = parseArgs(process.argv.slice(2));
|
|
52
|
+
// Ensure data directory exists
|
|
21
53
|
mkdirSync(args.dataDir, { recursive: true });
|
|
22
|
-
|
|
23
|
-
|
|
54
|
+
const manifest = plugin.manifest();
|
|
55
|
+
validateHealthPath(manifest.health_path, manifest.name);
|
|
56
|
+
// 2. Emit manifest (handshake phase 1)
|
|
57
|
+
emitManifest(manifest);
|
|
58
|
+
const launch = await readLaunchConfig(Bun.stdin.stream(), manifest.name);
|
|
59
|
+
// Ensure socket directory exists and clean up stale socket
|
|
60
|
+
const socketDir = dirname(args.socketPath);
|
|
61
|
+
mkdirSync(socketDir, { recursive: true });
|
|
62
|
+
if (existsSync(args.socketPath)) {
|
|
63
|
+
unlinkSync(args.socketPath);
|
|
64
|
+
}
|
|
65
|
+
// Channel connection promise -- resolved when the host connects
|
|
24
66
|
let resolveChannel;
|
|
25
|
-
|
|
26
|
-
const channelReady = new Promise((resolve, reject) => {
|
|
67
|
+
const channelReady = new Promise((resolve) => {
|
|
27
68
|
resolveChannel = resolve;
|
|
28
|
-
rejectChannel = reject;
|
|
29
69
|
});
|
|
30
|
-
|
|
31
|
-
const closeListeners = new Map();
|
|
32
|
-
const errorListeners = new Map();
|
|
33
|
-
let channelClaimed = false;
|
|
70
|
+
// Track state
|
|
34
71
|
let currentContext;
|
|
35
|
-
let
|
|
36
|
-
let
|
|
72
|
+
let pluginReady = false;
|
|
73
|
+
let channelAccepted = false;
|
|
74
|
+
// Embedded UI
|
|
37
75
|
const embeddedAssets = plugin.embeddedUiAssets?.();
|
|
38
|
-
const
|
|
76
|
+
const hasUi = embeddedAssets !== undefined || plugin.uiDistPath?.() !== undefined;
|
|
77
|
+
// Build embedded UI handler if available
|
|
39
78
|
const embeddedUiHandler = embeddedAssets
|
|
40
79
|
? createEmbeddedUiHandler(embeddedAssets)
|
|
41
80
|
: undefined;
|
|
42
|
-
|
|
43
|
-
|
|
81
|
+
// Active plugin fetch handler -- set once plugin is initialized
|
|
82
|
+
let pluginFetch;
|
|
83
|
+
// Bun WebSocket adapter plumbing
|
|
84
|
+
const wsMessageListeners = new Map();
|
|
85
|
+
const wsCloseListeners = new Map();
|
|
86
|
+
// 3. Start Bun.serve on Unix socket
|
|
44
87
|
const server = Bun.serve({
|
|
45
88
|
unix: args.socketPath,
|
|
46
|
-
|
|
47
|
-
const url = new URL(
|
|
89
|
+
fetch(req, server) {
|
|
90
|
+
const url = new URL(req.url);
|
|
91
|
+
// Health discloses no caller data. Every other route, including public
|
|
92
|
+
// plugin routes forwarded by Temps, must carry the host assertion.
|
|
93
|
+
if (requiresHostAuthentication(url.pathname, manifest.health_path) &&
|
|
94
|
+
!authenticatedHostRequest(req.headers, launch.auth_secret)) {
|
|
95
|
+
return new Response("Unauthorized", { status: 401 });
|
|
96
|
+
}
|
|
97
|
+
// WebSocket upgrade for platform channel
|
|
48
98
|
if (url.pathname === PLUGIN_CHANNEL_PATH) {
|
|
49
|
-
|
|
50
|
-
if (!verification.verified) {
|
|
51
|
-
log("warn", "Rejected unauthenticated platform channel attempt", {
|
|
52
|
-
plugin: manifest.name,
|
|
53
|
-
});
|
|
54
|
-
return new Response("Unauthorized", { status: 401 });
|
|
55
|
-
}
|
|
56
|
-
if (channelClaimed)
|
|
99
|
+
if (channelAccepted)
|
|
57
100
|
return new Response("Channel already connected", { status: 409 });
|
|
58
|
-
|
|
59
|
-
|
|
101
|
+
if (server.upgrade(req)) {
|
|
102
|
+
channelAccepted = true;
|
|
60
103
|
return undefined;
|
|
61
|
-
|
|
104
|
+
}
|
|
62
105
|
return new Response("WebSocket upgrade failed", { status: 500 });
|
|
63
106
|
}
|
|
64
|
-
// Health
|
|
65
|
-
if (url.pathname === manifest.health_path) {
|
|
107
|
+
// Health endpoint -- always available
|
|
108
|
+
if (url.pathname === manifest.health_path || url.pathname === "/health") {
|
|
66
109
|
return Response.json({ status: "ok", plugin: manifest.name });
|
|
67
110
|
}
|
|
68
|
-
|
|
111
|
+
// Event delivery endpoint
|
|
112
|
+
if (url.pathname === "/_events" && req.method === "POST") {
|
|
113
|
+
return handleEventDelivery(req, plugin, currentContext);
|
|
114
|
+
}
|
|
115
|
+
// Not initialized yet
|
|
116
|
+
if (!pluginReady || !pluginFetch) {
|
|
69
117
|
return new Response("Plugin initializing", { status: 503 });
|
|
70
118
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
return authenticationRequired();
|
|
77
|
-
return handleEventDelivery(request, plugin, currentContext);
|
|
119
|
+
// Try embedded UI
|
|
120
|
+
if (embeddedUiHandler) {
|
|
121
|
+
const uiResponse = handleEmbeddedUi(url, embeddedAssets);
|
|
122
|
+
if (uiResponse)
|
|
123
|
+
return uiResponse;
|
|
78
124
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
return authenticationRequired();
|
|
82
|
-
return pluginFetch(request, verification.caller);
|
|
125
|
+
// Delegate to plugin
|
|
126
|
+
return pluginFetch(req);
|
|
83
127
|
},
|
|
84
128
|
websocket: {
|
|
85
|
-
open(
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
resolveChannel
|
|
91
|
-
rejectChannel = undefined;
|
|
129
|
+
open(ws) {
|
|
130
|
+
wsMessageListeners.set(ws, new Set());
|
|
131
|
+
wsCloseListeners.set(ws, new Set());
|
|
132
|
+
const adapter = createWsAdapter(ws, wsMessageListeners, wsCloseListeners);
|
|
133
|
+
const client = new TempsClient(adapter);
|
|
134
|
+
resolveChannel?.(client);
|
|
92
135
|
},
|
|
93
|
-
message(
|
|
94
|
-
|
|
95
|
-
|
|
136
|
+
message(ws, message) {
|
|
137
|
+
const msgStr = typeof message === "string" ? message : message.toString();
|
|
138
|
+
const listeners = wsMessageListeners.get(ws);
|
|
139
|
+
if (listeners) {
|
|
140
|
+
for (const fn of listeners)
|
|
141
|
+
fn(msgStr);
|
|
142
|
+
}
|
|
96
143
|
},
|
|
97
|
-
close(
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
144
|
+
close(ws) {
|
|
145
|
+
const listeners = wsCloseListeners.get(ws);
|
|
146
|
+
if (listeners) {
|
|
147
|
+
for (const fn of listeners)
|
|
148
|
+
fn();
|
|
149
|
+
}
|
|
150
|
+
wsMessageListeners.delete(ws);
|
|
151
|
+
wsCloseListeners.delete(ws);
|
|
103
152
|
},
|
|
104
153
|
},
|
|
105
154
|
});
|
|
155
|
+
// 4. Emit ready (handshake phase 2)
|
|
156
|
+
emitReady(hasUi);
|
|
157
|
+
// 5. Wait for the host to connect via WebSocket channel (with timeout)
|
|
158
|
+
const channelTimeoutMs = 30_000;
|
|
159
|
+
let client;
|
|
106
160
|
try {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
client
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
plugin: manifest.name,
|
|
128
|
-
event_type: event.event_type,
|
|
129
|
-
reason: errorMessage(error),
|
|
130
|
-
});
|
|
131
|
-
}
|
|
161
|
+
client = await Promise.race([
|
|
162
|
+
channelReady,
|
|
163
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("Channel connection timeout")), channelTimeoutMs)),
|
|
164
|
+
]);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
console.error("[temps-plugin] Warning: platform channel not connected, running without platform data access");
|
|
168
|
+
client = null;
|
|
169
|
+
}
|
|
170
|
+
// 6. Create PluginContext
|
|
171
|
+
const ctx = new PluginContext({
|
|
172
|
+
pluginName: manifest.name,
|
|
173
|
+
dataDir: args.dataDir,
|
|
174
|
+
authSecret: launch.auth_secret,
|
|
175
|
+
client,
|
|
176
|
+
});
|
|
177
|
+
currentContext = ctx;
|
|
178
|
+
if (client) {
|
|
179
|
+
client.onEvent((event) => {
|
|
180
|
+
plugin.onEvent?.(ctx, event);
|
|
132
181
|
});
|
|
182
|
+
}
|
|
183
|
+
// 7. Call plugin.onStart()
|
|
184
|
+
try {
|
|
185
|
+
await plugin.onStart?.(ctx);
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
throw new InitializationError(manifest.name, err instanceof Error ? err.message : String(err));
|
|
189
|
+
}
|
|
190
|
+
// 8. Mount the plugin handler
|
|
191
|
+
const nodeHandler = await plugin.handler(ctx);
|
|
192
|
+
// Wrap the Node-style (req, res) handler into a Bun fetch handler
|
|
193
|
+
pluginFetch = (req) => nodeRequestBridge(req, nodeHandler);
|
|
194
|
+
pluginReady = true;
|
|
195
|
+
// 9. Graceful shutdown
|
|
196
|
+
const shutdown = async () => {
|
|
197
|
+
console.error(`[temps-plugin] Shutting down ${manifest.name}...`);
|
|
133
198
|
try {
|
|
134
|
-
await plugin.
|
|
199
|
+
await plugin.onShutdown?.();
|
|
135
200
|
}
|
|
136
|
-
catch (
|
|
137
|
-
|
|
201
|
+
catch (err) {
|
|
202
|
+
console.error("[temps-plugin] Error during shutdown:", err);
|
|
138
203
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
filesystemUiHandler,
|
|
143
|
-
]);
|
|
144
|
-
const shutdown = async (signal) => {
|
|
145
|
-
if (shuttingDown)
|
|
146
|
-
return;
|
|
147
|
-
shuttingDown = true;
|
|
148
|
-
log("info", "Shutting down plugin", { plugin: manifest.name, signal });
|
|
204
|
+
client?.close();
|
|
205
|
+
server.stop();
|
|
206
|
+
if (existsSync(args.socketPath)) {
|
|
149
207
|
try {
|
|
150
|
-
|
|
151
|
-
}
|
|
152
|
-
catch (error) {
|
|
153
|
-
log("error", "Plugin shutdown hook failed", {
|
|
154
|
-
plugin: manifest.name,
|
|
155
|
-
reason: errorMessage(error),
|
|
156
|
-
});
|
|
208
|
+
unlinkSync(args.socketPath);
|
|
157
209
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
210
|
+
catch { /* ignore */ }
|
|
211
|
+
}
|
|
212
|
+
process.exit(0);
|
|
213
|
+
};
|
|
214
|
+
process.on("SIGTERM", shutdown);
|
|
215
|
+
process.on("SIGINT", shutdown);
|
|
216
|
+
console.error(`[temps-plugin] ${manifest.display_name ?? manifest.name} v${manifest.version} running on ${args.socketPath}`);
|
|
217
|
+
}
|
|
218
|
+
// ---------------------------------------------------------------------------
|
|
219
|
+
// Embedded UI serving (pure Bun Response)
|
|
220
|
+
// ---------------------------------------------------------------------------
|
|
221
|
+
function handleEmbeddedUi(url, assets) {
|
|
222
|
+
const pathname = url.pathname;
|
|
223
|
+
// Redirect /ui to /ui/
|
|
224
|
+
if (pathname === "/ui") {
|
|
225
|
+
return new Response(null, {
|
|
226
|
+
status: 302,
|
|
227
|
+
headers: { Location: "/ui/" },
|
|
168
228
|
});
|
|
169
229
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
server.stop(true);
|
|
173
|
-
removeSocket(args.socketPath);
|
|
174
|
-
throw error;
|
|
230
|
+
if (!pathname.startsWith("/ui/")) {
|
|
231
|
+
return undefined;
|
|
175
232
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
233
|
+
const relativePath = pathname.slice("/ui/".length) || "index.html";
|
|
234
|
+
if (relativePath.includes("..")) {
|
|
235
|
+
return new Response("Forbidden", { status: 403 });
|
|
236
|
+
}
|
|
237
|
+
// Exact match
|
|
238
|
+
const file = assets.get(relativePath);
|
|
239
|
+
if (file) {
|
|
240
|
+
return new Response(new Uint8Array(file.content), {
|
|
241
|
+
headers: {
|
|
242
|
+
"Content-Type": file.contentType,
|
|
243
|
+
"Content-Length": String(file.content.byteLength),
|
|
244
|
+
"Cache-Control": file.immutable
|
|
245
|
+
? "public, max-age=31536000, immutable"
|
|
246
|
+
: "no-cache, no-store, must-revalidate",
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
// SPA fallback for paths without file extensions
|
|
251
|
+
const hasExt = (relativePath.split("/").pop() ?? "").includes(".");
|
|
252
|
+
if (!hasExt) {
|
|
253
|
+
const index = assets.get("index.html");
|
|
254
|
+
if (index) {
|
|
255
|
+
return new Response(new Uint8Array(index.content), {
|
|
256
|
+
headers: {
|
|
257
|
+
"Content-Type": index.contentType,
|
|
258
|
+
"Content-Length": String(index.content.byteLength),
|
|
259
|
+
"Cache-Control": "no-cache, no-store, must-revalidate",
|
|
260
|
+
},
|
|
261
|
+
});
|
|
188
262
|
}
|
|
189
|
-
values.set(flag, value);
|
|
190
263
|
}
|
|
191
|
-
|
|
192
|
-
const dataDir = values.get("--data-dir");
|
|
193
|
-
if (!socketPath)
|
|
194
|
-
throw new ArgsError("--socket-path is required");
|
|
195
|
-
if (!dataDir)
|
|
196
|
-
throw new ArgsError("--data-dir is required");
|
|
197
|
-
return {
|
|
198
|
-
socketPath,
|
|
199
|
-
dataDir,
|
|
200
|
-
...(values.has("--host-api-url")
|
|
201
|
-
? { hostApiUrl: values.get("--host-api-url") }
|
|
202
|
-
: {}),
|
|
203
|
-
};
|
|
264
|
+
return new Response("Not Found", { status: 404 });
|
|
204
265
|
}
|
|
205
|
-
|
|
266
|
+
// ---------------------------------------------------------------------------
|
|
267
|
+
// Bun WebSocket -> WsLike adapter
|
|
268
|
+
// ---------------------------------------------------------------------------
|
|
269
|
+
function createWsAdapter(ws, messageListeners, closeListeners) {
|
|
206
270
|
return {
|
|
207
|
-
on(event,
|
|
271
|
+
on(event, fn) {
|
|
208
272
|
if (event === "message") {
|
|
209
|
-
messageListeners.get(
|
|
273
|
+
messageListeners.get(ws)?.add(fn);
|
|
210
274
|
}
|
|
211
|
-
if (event === "close") {
|
|
212
|
-
closeListeners.get(
|
|
213
|
-
}
|
|
214
|
-
if (event === "error") {
|
|
215
|
-
errorListeners.get(socket)?.add(listener);
|
|
275
|
+
else if (event === "close") {
|
|
276
|
+
closeListeners.get(ws)?.add(fn);
|
|
216
277
|
}
|
|
217
278
|
},
|
|
218
|
-
send(data,
|
|
279
|
+
send(data, cb) {
|
|
219
280
|
try {
|
|
220
|
-
|
|
221
|
-
|
|
281
|
+
ws.send(data);
|
|
282
|
+
cb?.();
|
|
222
283
|
}
|
|
223
|
-
catch (
|
|
224
|
-
|
|
284
|
+
catch (err) {
|
|
285
|
+
cb?.(err);
|
|
225
286
|
}
|
|
226
287
|
},
|
|
227
288
|
close() {
|
|
228
|
-
|
|
289
|
+
ws.close();
|
|
229
290
|
},
|
|
230
291
|
};
|
|
231
292
|
}
|
|
232
|
-
async function nodeRequestBridge(
|
|
233
|
-
const url = new URL(
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
catch (error) {
|
|
239
|
-
if (error instanceof RequestBodyTooLargeError)
|
|
240
|
-
return payloadTooLarge(error);
|
|
241
|
-
throw error;
|
|
293
|
+
async function nodeRequestBridge(req, handler) {
|
|
294
|
+
const url = new URL(req.url);
|
|
295
|
+
// Read body upfront
|
|
296
|
+
let bodyBuffer = Buffer.alloc(0);
|
|
297
|
+
if (req.body) {
|
|
298
|
+
bodyBuffer = Buffer.from(await req.arrayBuffer());
|
|
242
299
|
}
|
|
243
300
|
return new Promise((resolve) => {
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
incoming.on = ((event, listener) => {
|
|
301
|
+
// Build a minimal IncomingMessage shim
|
|
302
|
+
const fakeReq = Object.create(null);
|
|
303
|
+
fakeReq.url = url.pathname + url.search;
|
|
304
|
+
fakeReq.method = req.method;
|
|
305
|
+
const hdrs = {};
|
|
306
|
+
req.headers.forEach((v, k) => { hdrs[k] = v; });
|
|
307
|
+
fakeReq.headers = hdrs;
|
|
308
|
+
// Body event emitter shim
|
|
309
|
+
const dataFns = [];
|
|
310
|
+
const endFns = [];
|
|
311
|
+
fakeReq.on = ((event, fn) => {
|
|
256
312
|
if (event === "data")
|
|
257
|
-
|
|
313
|
+
dataFns.push(fn);
|
|
258
314
|
if (event === "end")
|
|
259
|
-
|
|
260
|
-
return
|
|
315
|
+
endFns.push(fn);
|
|
316
|
+
return fakeReq;
|
|
261
317
|
});
|
|
262
|
-
|
|
263
|
-
let
|
|
264
|
-
const
|
|
265
|
-
const
|
|
266
|
-
const
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
plugin: pluginName,
|
|
273
|
-
actual_bytes: error.actualBytes,
|
|
274
|
-
maximum_bytes: error.maximumBytes,
|
|
275
|
-
});
|
|
276
|
-
resolve(responseTooLarge(error));
|
|
277
|
-
};
|
|
278
|
-
Object.defineProperty(response, "statusCode", {
|
|
279
|
-
get: () => status,
|
|
280
|
-
set: (value) => {
|
|
281
|
-
status = value;
|
|
282
|
-
},
|
|
283
|
-
});
|
|
284
|
-
response.setHeader = ((name, value) => {
|
|
285
|
-
headers[name] = Array.isArray(value) ? value.join(", ") : String(value);
|
|
286
|
-
return response;
|
|
287
|
-
});
|
|
288
|
-
response.getHeader = ((name) => headers[name]);
|
|
289
|
-
response.writeHead = ((code, values) => {
|
|
290
|
-
status = code;
|
|
291
|
-
if (values)
|
|
292
|
-
Object.assign(headers, values);
|
|
293
|
-
return response;
|
|
318
|
+
// Response collector shim
|
|
319
|
+
let statusCode = 200;
|
|
320
|
+
const resHeaders = {};
|
|
321
|
+
const chunks = [];
|
|
322
|
+
const fakeRes = Object.create(null);
|
|
323
|
+
fakeRes.writeHead = ((code, h) => {
|
|
324
|
+
statusCode = code;
|
|
325
|
+
if (h)
|
|
326
|
+
Object.assign(resHeaders, h);
|
|
327
|
+
return fakeRes;
|
|
294
328
|
});
|
|
295
|
-
|
|
296
|
-
if (
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
catch (error) {
|
|
303
|
-
if (error instanceof ResponseBodyTooLargeError) {
|
|
304
|
-
failOversizedResponse(error);
|
|
305
|
-
return false;
|
|
306
|
-
}
|
|
307
|
-
throw error;
|
|
308
|
-
}
|
|
309
|
-
});
|
|
310
|
-
response.end = ((value) => {
|
|
311
|
-
if (ended)
|
|
312
|
-
return response;
|
|
313
|
-
try {
|
|
314
|
-
if (value)
|
|
315
|
-
responseBody.append(value);
|
|
316
|
-
}
|
|
317
|
-
catch (error) {
|
|
318
|
-
if (error instanceof ResponseBodyTooLargeError) {
|
|
319
|
-
failOversizedResponse(error);
|
|
320
|
-
return response;
|
|
321
|
-
}
|
|
322
|
-
throw error;
|
|
323
|
-
}
|
|
324
|
-
ended = true;
|
|
325
|
-
const body = responseBody.toBuffer();
|
|
326
|
-
resolve(new Response(body.length === 0 ? null : body, {
|
|
327
|
-
status,
|
|
328
|
-
headers,
|
|
329
|
+
fakeRes.end = ((data) => {
|
|
330
|
+
if (data)
|
|
331
|
+
chunks.push(typeof data === "string" ? Buffer.from(data) : data);
|
|
332
|
+
const body = Buffer.concat(chunks);
|
|
333
|
+
resolve(new Response(body.length > 0 ? body : null, {
|
|
334
|
+
status: statusCode,
|
|
335
|
+
headers: resHeaders,
|
|
329
336
|
}));
|
|
330
|
-
return response;
|
|
331
337
|
});
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
reason: errorMessage(error),
|
|
340
|
-
});
|
|
341
|
-
status = 500;
|
|
342
|
-
headers["Content-Type"] = "application/problem+json";
|
|
343
|
-
response.end(JSON.stringify({
|
|
344
|
-
type: "https://temps.sh/problems/plugin-handler-failed",
|
|
345
|
-
title: "Plugin Handler Failed",
|
|
346
|
-
status: 500,
|
|
347
|
-
detail: "The plugin could not complete this request.",
|
|
348
|
-
}));
|
|
349
|
-
});
|
|
350
|
-
}
|
|
338
|
+
fakeRes.write = ((data) => {
|
|
339
|
+
chunks.push(typeof data === "string" ? Buffer.from(data) : data);
|
|
340
|
+
return true;
|
|
341
|
+
});
|
|
342
|
+
// Call the handler
|
|
343
|
+
handler(fakeReq, fakeRes);
|
|
344
|
+
// Deliver body
|
|
351
345
|
queueMicrotask(() => {
|
|
352
|
-
if (
|
|
353
|
-
for (const
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
346
|
+
if (bodyBuffer.length > 0) {
|
|
347
|
+
for (const fn of dataFns)
|
|
348
|
+
fn(bodyBuffer);
|
|
349
|
+
}
|
|
350
|
+
for (const fn of endFns)
|
|
351
|
+
fn();
|
|
357
352
|
});
|
|
358
353
|
});
|
|
359
354
|
}
|
|
360
|
-
|
|
361
|
-
|
|
355
|
+
// ---------------------------------------------------------------------------
|
|
356
|
+
// Event delivery handler (POST /_events)
|
|
357
|
+
// ---------------------------------------------------------------------------
|
|
358
|
+
async function handleEventDelivery(req, plugin, ctx) {
|
|
362
359
|
try {
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
typeof event.event_type !== "string" ||
|
|
367
|
-
typeof event.timestamp !== "string" ||
|
|
368
|
-
typeof event.data !== "object" ||
|
|
369
|
-
event.data === null) {
|
|
370
|
-
throw new Error("event is missing required fields");
|
|
360
|
+
const event = (await req.json());
|
|
361
|
+
if (ctx) {
|
|
362
|
+
plugin.onEvent?.(ctx, event);
|
|
371
363
|
}
|
|
364
|
+
return Response.json({ ok: true });
|
|
372
365
|
}
|
|
373
|
-
catch (
|
|
374
|
-
if (error instanceof RequestBodyTooLargeError)
|
|
375
|
-
return payloadTooLarge(error);
|
|
366
|
+
catch (err) {
|
|
376
367
|
return Response.json({
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
status: 400,
|
|
380
|
-
detail: "The event payload is not valid.",
|
|
368
|
+
error: "Invalid event payload",
|
|
369
|
+
detail: err instanceof Error ? err.message : String(err),
|
|
381
370
|
}, { status: 400 });
|
|
382
371
|
}
|
|
383
|
-
try {
|
|
384
|
-
await plugin.onEvent?.(context, event);
|
|
385
|
-
return new Response(null, { status: 200 });
|
|
386
|
-
}
|
|
387
|
-
catch (error) {
|
|
388
|
-
log("error", "Plugin event handler failed", {
|
|
389
|
-
plugin: context.pluginName,
|
|
390
|
-
event_type: event.event_type,
|
|
391
|
-
reason: errorMessage(error),
|
|
392
|
-
});
|
|
393
|
-
return Response.json({
|
|
394
|
-
type: "https://temps.sh/problems/plugin-event-handler-failed",
|
|
395
|
-
title: "Plugin Event Handler Failed",
|
|
396
|
-
status: 500,
|
|
397
|
-
detail: "The plugin could not process this event.",
|
|
398
|
-
}, { status: 500 });
|
|
399
|
-
}
|
|
400
372
|
}
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
373
|
+
// ---------------------------------------------------------------------------
|
|
374
|
+
// CLI argument parsing
|
|
375
|
+
// ---------------------------------------------------------------------------
|
|
376
|
+
function parseArgs(argv) {
|
|
377
|
+
const args = {};
|
|
378
|
+
for (let i = 0; i < argv.length; i++) {
|
|
379
|
+
const arg = argv[i];
|
|
380
|
+
const next = argv[i + 1];
|
|
381
|
+
switch (arg) {
|
|
382
|
+
case "--socket-path":
|
|
383
|
+
args.socketPath = next;
|
|
384
|
+
i++;
|
|
385
|
+
break;
|
|
386
|
+
case "--database-url":
|
|
387
|
+
case "--auth-secret":
|
|
388
|
+
throw new ArgsError("Privileged launch values must arrive over the protocol 2 stdin handshake; update Temps");
|
|
389
|
+
case "--data-dir":
|
|
390
|
+
args.dataDir = next;
|
|
391
|
+
i++;
|
|
392
|
+
break;
|
|
408
393
|
}
|
|
409
394
|
}
|
|
410
|
-
if (!
|
|
411
|
-
|
|
412
|
-
const reader = request.body.getReader();
|
|
413
|
-
const chunks = [];
|
|
414
|
-
let totalBytes = 0;
|
|
415
|
-
while (true) {
|
|
416
|
-
const { done, value } = await reader.read();
|
|
417
|
-
if (done)
|
|
418
|
-
break;
|
|
419
|
-
totalBytes += value.byteLength;
|
|
420
|
-
if (totalBytes > maximumBytes) {
|
|
421
|
-
await reader.cancel("plugin request body limit exceeded");
|
|
422
|
-
throw new RequestBodyTooLargeError(totalBytes, maximumBytes);
|
|
423
|
-
}
|
|
424
|
-
chunks.push(Buffer.from(value));
|
|
425
|
-
}
|
|
426
|
-
return Buffer.concat(chunks, totalBytes);
|
|
427
|
-
}
|
|
428
|
-
/** @internal Bounded response collector used by the Node-compatible bridge. */
|
|
429
|
-
export class ResponseBodyAccumulator {
|
|
430
|
-
#maximumBytes;
|
|
431
|
-
#chunks = [];
|
|
432
|
-
#totalBytes = 0;
|
|
433
|
-
constructor(maximumBytes = MAX_PLUGIN_RESPONSE_BODY_BYTES) {
|
|
434
|
-
this.#maximumBytes = maximumBytes;
|
|
435
|
-
}
|
|
436
|
-
append(value) {
|
|
437
|
-
const chunk = typeof value === "string" ? Buffer.from(value) : value;
|
|
438
|
-
const nextTotal = this.#totalBytes + chunk.byteLength;
|
|
439
|
-
if (nextTotal > this.#maximumBytes) {
|
|
440
|
-
throw new ResponseBodyTooLargeError(nextTotal, this.#maximumBytes);
|
|
441
|
-
}
|
|
442
|
-
this.#chunks.push(chunk);
|
|
443
|
-
this.#totalBytes = nextTotal;
|
|
444
|
-
}
|
|
445
|
-
toBuffer() {
|
|
446
|
-
return Buffer.concat(this.#chunks, this.#totalBytes);
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
function authenticationRequired() {
|
|
450
|
-
return Response.json({
|
|
451
|
-
type: "https://temps.sh/problems/plugin-authentication-required",
|
|
452
|
-
title: "Authentication Required",
|
|
453
|
-
status: 401,
|
|
454
|
-
detail: "This plugin route requires a request asserted by Temps.",
|
|
455
|
-
}, { status: 401, headers: { "Content-Type": "application/problem+json" } });
|
|
456
|
-
}
|
|
457
|
-
function payloadTooLarge(error) {
|
|
458
|
-
return Response.json({
|
|
459
|
-
type: "https://temps.sh/problems/plugin-request-body-too-large",
|
|
460
|
-
title: "Plugin Request Body Too Large",
|
|
461
|
-
status: 413,
|
|
462
|
-
detail: error.message,
|
|
463
|
-
maximum_bytes: error.maximumBytes,
|
|
464
|
-
}, { status: 413, headers: { "Content-Type": "application/problem+json" } });
|
|
465
|
-
}
|
|
466
|
-
function responseTooLarge(error) {
|
|
467
|
-
return Response.json({
|
|
468
|
-
type: "https://temps.sh/problems/plugin-response-body-too-large",
|
|
469
|
-
title: "Plugin Response Body Too Large",
|
|
470
|
-
status: 502,
|
|
471
|
-
detail: "The plugin produced a response larger than the runtime limit.",
|
|
472
|
-
maximum_bytes: error.maximumBytes,
|
|
473
|
-
}, { status: 502, headers: { "Content-Type": "application/problem+json" } });
|
|
474
|
-
}
|
|
475
|
-
function validateManifest(name, healthPath) {
|
|
476
|
-
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) {
|
|
477
|
-
throw new InitializationError(name, "Plugin name must be lowercase kebab-case");
|
|
478
|
-
}
|
|
479
|
-
if (!healthPath.startsWith("/") || healthPath.includes("..")) {
|
|
480
|
-
throw new InitializationError(name, `Invalid health path: ${healthPath}`);
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
function withTimeout(promise, milliseconds, error) {
|
|
484
|
-
return new Promise((resolve, reject) => {
|
|
485
|
-
const timer = setTimeout(() => reject(error), milliseconds);
|
|
486
|
-
promise.then((value) => {
|
|
487
|
-
clearTimeout(timer);
|
|
488
|
-
resolve(value);
|
|
489
|
-
}, (reason) => {
|
|
490
|
-
clearTimeout(timer);
|
|
491
|
-
reject(reason);
|
|
492
|
-
});
|
|
493
|
-
});
|
|
494
|
-
}
|
|
495
|
-
function removeSocket(path) {
|
|
496
|
-
if (!existsSync(path))
|
|
497
|
-
return;
|
|
498
|
-
try {
|
|
499
|
-
unlinkSync(path);
|
|
395
|
+
if (!args.socketPath) {
|
|
396
|
+
throw new ArgsError("--socket-path is required");
|
|
500
397
|
}
|
|
501
|
-
|
|
502
|
-
throw new
|
|
398
|
+
if (!args.dataDir) {
|
|
399
|
+
throw new ArgsError("--data-dir is required");
|
|
503
400
|
}
|
|
504
|
-
}
|
|
505
|
-
function log(level, message, fields) {
|
|
506
|
-
process.stderr.write(`${JSON.stringify({ timestamp: new Date().toISOString(), level, message, ...fields })}\n`);
|
|
507
|
-
}
|
|
508
|
-
function errorMessage(error) {
|
|
509
|
-
return error instanceof Error ? error.message : String(error);
|
|
401
|
+
return { socketPath: args.socketPath, dataDir: args.dataDir };
|
|
510
402
|
}
|
|
511
403
|
//# sourceMappingURL=runtime.js.map
|