@harnesys/sdk 0.0.0-stage → 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 +21 -0
- package/README.md +80 -2
- package/dist/addon-context-factory.d.ts +6 -0
- package/dist/addon-context-factory.js +160 -0
- package/dist/addon-context.d.ts +346 -0
- package/dist/addon-context.js +0 -0
- package/dist/define-addon.d.ts +57 -0
- package/dist/define-addon.js +53 -0
- package/dist/families/config.d.ts +14 -0
- package/dist/families/config.js +16 -0
- package/dist/families/content.d.ts +28 -0
- package/dist/families/content.js +19 -0
- package/dist/families/field-spec.d.ts +100 -0
- package/dist/families/field-spec.js +85 -0
- package/dist/families/hook.d.ts +37 -0
- package/dist/families/hook.js +25 -0
- package/dist/families/job.d.ts +45 -0
- package/dist/families/job.js +26 -0
- package/dist/families/json-schema.d.ts +36 -0
- package/dist/families/json-schema.js +101 -0
- package/dist/families/lsp.d.ts +18 -0
- package/dist/families/lsp.js +18 -0
- package/dist/families/mcp.d.ts +18 -0
- package/dist/families/mcp.js +18 -0
- package/dist/families/registry.d.ts +9 -0
- package/dist/families/registry.js +34 -0
- package/dist/families/route.d.ts +38 -0
- package/dist/families/route.js +37 -0
- package/dist/families/source-kind.d.ts +24 -0
- package/dist/families/source-kind.js +21 -0
- package/dist/families/tool-pack.d.ts +68 -0
- package/dist/families/tool-pack.js +57 -0
- package/dist/families/transport.d.ts +52 -0
- package/dist/families/transport.js +29 -0
- package/dist/families/trigger.d.ts +97 -0
- package/dist/families/trigger.js +46 -0
- package/dist/families/view.d.ts +255 -0
- package/dist/families/view.js +87 -0
- package/dist/families/viewer.d.ts +31 -0
- package/dist/families/viewer.js +26 -0
- package/dist/families/worker.d.ts +23 -0
- package/dist/families/worker.js +19 -0
- package/dist/host-client.d.ts +11 -0
- package/dist/host-client.js +30 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +35 -0
- package/dist/manifest/branding.d.ts +14 -0
- package/dist/manifest/branding.js +18 -0
- package/dist/manifest/connections.d.ts +21 -0
- package/dist/manifest/connections.js +10 -0
- package/dist/manifest/json-schema.d.ts +2 -0
- package/dist/manifest/json-schema.js +13 -0
- package/dist/manifest/l10n.d.ts +9 -0
- package/dist/manifest/l10n.js +28 -0
- package/dist/manifest/manifest.d.ts +112 -0
- package/dist/manifest/manifest.js +45 -0
- package/dist/manifest/validate.d.ts +14 -0
- package/dist/manifest/validate.js +144 -0
- package/dist/permissions/permissions.d.ts +31 -0
- package/dist/permissions/permissions.js +53 -0
- package/dist/process-entry.d.ts +26 -0
- package/dist/process-entry.js +146 -0
- package/dist/protocol/envelope.d.ts +115 -0
- package/dist/protocol/envelope.js +72 -0
- package/dist/protocol/error.d.ts +67 -0
- package/dist/protocol/error.js +61 -0
- package/dist/protocol/handshake.d.ts +55 -0
- package/dist/protocol/handshake.js +26 -0
- package/dist/protocol/map.d.ts +1090 -0
- package/dist/protocol/map.js +127 -0
- package/dist/protocol/meta.d.ts +31 -0
- package/dist/protocol/meta.js +14 -0
- package/dist/protocol/method-spec.d.ts +13 -0
- package/dist/protocol/method-spec.js +9 -0
- package/dist/protocol/org-service-methods.d.ts +135 -0
- package/dist/protocol/org-service-methods.js +106 -0
- package/dist/protocol/shared.d.ts +389 -0
- package/dist/protocol/shared.js +231 -0
- package/dist/protocol/source-methods.d.ts +218 -0
- package/dist/protocol/source-methods.js +18 -0
- package/dist/protocol/thread-service-methods.d.ts +50 -0
- package/dist/protocol/thread-service-methods.js +32 -0
- package/dist/runtime.d.ts +25 -0
- package/dist/runtime.js +229 -0
- package/dist/testing/fake-db.d.ts +15 -0
- package/dist/testing/fake-db.js +120 -0
- package/dist/testing/fake-files.d.ts +9 -0
- package/dist/testing/fake-files.js +87 -0
- package/dist/testing/fake-host.d.ts +115 -0
- package/dist/testing/fake-host.js +152 -0
- package/dist/testing/fake-services.d.ts +63 -0
- package/dist/testing/fake-services.js +277 -0
- package/dist/testing/fixtures.d.ts +4 -0
- package/dist/testing/fixtures.js +84 -0
- package/dist/testing/index.d.ts +4 -0
- package/dist/testing/index.js +2 -0
- package/package.json +66 -4
- package/src/addon-context-factory.ts +236 -0
- package/src/addon-context.ts +313 -0
- package/src/define-addon.ts +178 -0
- package/src/families/config.ts +24 -0
- package/src/families/content.ts +35 -0
- package/src/families/field-spec.ts +175 -0
- package/src/families/hook.ts +34 -0
- package/src/families/job.ts +41 -0
- package/src/families/json-schema.ts +167 -0
- package/src/families/lsp.ts +28 -0
- package/src/families/mcp.ts +28 -0
- package/src/families/registry.ts +44 -0
- package/src/families/route.ts +52 -0
- package/src/families/source-kind.ts +34 -0
- package/src/families/tool-pack.ts +92 -0
- package/src/families/transport.ts +52 -0
- package/src/families/trigger.ts +92 -0
- package/src/families/view.ts +144 -0
- package/src/families/viewer.ts +43 -0
- package/src/families/worker.ts +30 -0
- package/src/host-client.ts +52 -0
- package/src/index.ts +341 -0
- package/src/manifest/branding.ts +24 -0
- package/src/manifest/connections.ts +21 -0
- package/src/manifest/json-schema.ts +24 -0
- package/src/manifest/l10n.ts +39 -0
- package/src/manifest/manifest.ts +94 -0
- package/src/manifest/validate.ts +200 -0
- package/src/permissions/permissions.ts +79 -0
- package/src/process-entry.ts +205 -0
- package/src/protocol/envelope.ts +126 -0
- package/src/protocol/error.ts +81 -0
- package/src/protocol/handshake.ts +43 -0
- package/src/protocol/map.ts +339 -0
- package/src/protocol/meta.ts +26 -0
- package/src/protocol/method-spec.ts +40 -0
- package/src/protocol/org-service-methods.ts +148 -0
- package/src/protocol/shared.ts +345 -0
- package/src/protocol/source-methods.ts +61 -0
- package/src/protocol/thread-service-methods.ts +50 -0
- package/src/runtime.ts +332 -0
- package/src/testing/fake-db.ts +140 -0
- package/src/testing/fake-files.ts +114 -0
- package/src/testing/fake-host.ts +261 -0
- package/src/testing/fake-services.ts +345 -0
- package/src/testing/fixtures.ts +88 -0
- package/src/testing/index.ts +12 -0
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import type { AddonContext } from './addon-context.ts';
|
|
2
|
+
import type {
|
|
3
|
+
NotificationHandlers,
|
|
4
|
+
ResolvedAddonDefinition,
|
|
5
|
+
SourceBackendHandlers,
|
|
6
|
+
} from './define-addon.ts';
|
|
7
|
+
import { createAddonContextFor, type HostChannel } from './host-client.ts';
|
|
8
|
+
import { AddonError, type AddonErrorReason } from './protocol/error.ts';
|
|
9
|
+
import {
|
|
10
|
+
type InitializeParams,
|
|
11
|
+
type InitializeResult,
|
|
12
|
+
InitializeResultSchema,
|
|
13
|
+
} from './protocol/handshake.ts';
|
|
14
|
+
import { methodSpec } from './protocol/map.ts';
|
|
15
|
+
import { type CallMeta, CallMetaSchema } from './protocol/meta.ts';
|
|
16
|
+
|
|
17
|
+
export interface AddonRuntimeOptions {
|
|
18
|
+
definition: ResolvedAddonDefinition;
|
|
19
|
+
addon: { id: string; version: string };
|
|
20
|
+
channel: HostChannel;
|
|
21
|
+
now?(): number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface AddonRuntime {
|
|
25
|
+
readonly addon: { id: string; version: string };
|
|
26
|
+
readonly handlers: string[];
|
|
27
|
+
initialize(params: InitializeParams): InitializeResult;
|
|
28
|
+
handleRequest(method: string, params: unknown, signal: AbortSignal): Promise<unknown>;
|
|
29
|
+
handleNotification(method: string, params: unknown, signal: AbortSignal): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type Target = (() => unknown) | null;
|
|
33
|
+
|
|
34
|
+
export function createAddonRuntime(options: AddonRuntimeOptions): AddonRuntime {
|
|
35
|
+
const { definition, addon, channel } = options;
|
|
36
|
+
const now = options.now ?? (() => Date.now());
|
|
37
|
+
const declared = new Set(definition.handlers);
|
|
38
|
+
const activeTriggerKinds = new Map<string, string>();
|
|
39
|
+
let instanceOrgId: string | undefined;
|
|
40
|
+
|
|
41
|
+
function dispatch(method: string, params: Record<string, unknown>, ctx: AddonContext): Target {
|
|
42
|
+
const lookup = dispatchLookup(method, params, ctx);
|
|
43
|
+
if (lookup !== undefined) {
|
|
44
|
+
return lookup;
|
|
45
|
+
}
|
|
46
|
+
return dispatchManaged(method, params, ctx);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function dispatchLookup(
|
|
50
|
+
method: string,
|
|
51
|
+
params: Record<string, unknown>,
|
|
52
|
+
ctx: AddonContext,
|
|
53
|
+
): Target | undefined {
|
|
54
|
+
if (method.startsWith('source.')) {
|
|
55
|
+
return sourceLookup(method, params, ctx);
|
|
56
|
+
}
|
|
57
|
+
const lookups: Record<string, () => Target | undefined> = {
|
|
58
|
+
'tools.call': () => toolTarget(params, ctx),
|
|
59
|
+
'route.handle': () => handlerTarget(definition.routes?.[str(params.routeId)], params, ctx),
|
|
60
|
+
'job.run': () => handlerTarget(definition.jobs?.[str(params.jobId)], params, ctx),
|
|
61
|
+
'hook.deliver': () => handlerTarget(definition.hooks?.[str(params.hookId)], params, ctx),
|
|
62
|
+
};
|
|
63
|
+
return lookups[method]?.();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function toolTarget(params: Record<string, unknown>, ctx: AddonContext): Target {
|
|
67
|
+
const handler = definition.tools?.[str(params.tool)];
|
|
68
|
+
if (handler === undefined) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
return async () => ({ output: await handler(asInput(params.input), ctx) });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function sourceLookup(
|
|
75
|
+
method: string,
|
|
76
|
+
params: Record<string, unknown>,
|
|
77
|
+
ctx: AddonContext,
|
|
78
|
+
): Target | undefined {
|
|
79
|
+
const op = method.slice('source.'.length) as keyof SourceBackendHandlers;
|
|
80
|
+
const backend = definition.sources?.[str(params.sourceKind)];
|
|
81
|
+
const handler = backend?.[op];
|
|
82
|
+
return handler ? () => handler(withoutMeta(params) as never, ctx) : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function dispatchManaged(
|
|
86
|
+
method: string,
|
|
87
|
+
params: Record<string, unknown>,
|
|
88
|
+
ctx: AddonContext,
|
|
89
|
+
): Target {
|
|
90
|
+
switch (method) {
|
|
91
|
+
case 'trigger.start': {
|
|
92
|
+
const kind = str(params.kind);
|
|
93
|
+
if (kind) {
|
|
94
|
+
activeTriggerKinds.set(str(params.instanceId), kind);
|
|
95
|
+
}
|
|
96
|
+
return pairTarget(definition.triggers, kind, 'start', params, ctx);
|
|
97
|
+
}
|
|
98
|
+
case 'trigger.stop': {
|
|
99
|
+
const instanceId = str(params.instanceId);
|
|
100
|
+
const kind = activeTriggerKinds.get(instanceId) ?? '';
|
|
101
|
+
activeTriggerKinds.delete(instanceId);
|
|
102
|
+
return pairTarget(definition.triggers, kind, 'stop', params, ctx);
|
|
103
|
+
}
|
|
104
|
+
case 'worker.start':
|
|
105
|
+
return pairTarget(definition.workers, str(params.workerId), 'start', params, ctx);
|
|
106
|
+
case 'worker.stop':
|
|
107
|
+
return pairTarget(definition.workers, str(params.workerId), 'stop', params, ctx);
|
|
108
|
+
case 'transport.send':
|
|
109
|
+
return optionalTarget(definition.transport?.send, params, ctx);
|
|
110
|
+
case 'transport.edit':
|
|
111
|
+
return optionalTarget(definition.transport?.edit, params, ctx);
|
|
112
|
+
case 'transport.typing':
|
|
113
|
+
return optionalTarget(definition.transport?.typing, params, ctx);
|
|
114
|
+
case 'lifecycle.upgrade':
|
|
115
|
+
return optionalTarget(definition.lifecycle?.upgrade, params, ctx);
|
|
116
|
+
case 'ping':
|
|
117
|
+
case 'shutdown':
|
|
118
|
+
return () => ({});
|
|
119
|
+
default:
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function handleRequest(
|
|
125
|
+
method: string,
|
|
126
|
+
params: unknown,
|
|
127
|
+
signal: AbortSignal,
|
|
128
|
+
): Promise<unknown> {
|
|
129
|
+
const spec = methodSpec(method);
|
|
130
|
+
if (spec?.direction !== 'host-to-addon') {
|
|
131
|
+
throw new AddonError('unsupported', {
|
|
132
|
+
detail: `method '${method}' is not a host-to-addon request`,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
if (!declared.has(method)) {
|
|
136
|
+
throw new AddonError('unsupported', {
|
|
137
|
+
detail: `handler '${method}' was not declared in initialize.handlers`,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
const incoming = (params ?? {}) as Record<string, unknown>;
|
|
141
|
+
// Tolerant fallback (§6.3 safety net): hosts that predate mandatory _meta
|
|
142
|
+
// get a synthesized one so the schema parse below still succeeds.
|
|
143
|
+
const guarded = isCallMeta(incoming._meta)
|
|
144
|
+
? incoming
|
|
145
|
+
: { ...incoming, _meta: fallbackMeta('host-request', now() + FALLBACK_DEADLINE_MS) };
|
|
146
|
+
const parsed = parseParams(spec, guarded) as Record<string, unknown>;
|
|
147
|
+
const meta = CallMetaSchema.parse(parsed._meta);
|
|
148
|
+
if (instanceOrgId !== undefined) {
|
|
149
|
+
meta.orgId = instanceOrgId;
|
|
150
|
+
}
|
|
151
|
+
if (meta.deadline !== null && meta.deadline < now()) {
|
|
152
|
+
throw new AddonError('timeout', { detail: `deadline ${meta.deadline} has passed` });
|
|
153
|
+
}
|
|
154
|
+
const ctx = createAddonContextFor(channel, meta, signal);
|
|
155
|
+
const target = dispatch(method, parsed, ctx);
|
|
156
|
+
if (!target) {
|
|
157
|
+
throw new AddonError('unsupported', { detail: `no handler registered for '${method}'` });
|
|
158
|
+
}
|
|
159
|
+
const raw = await runWithDeadline(target(), meta.deadline, now, signal);
|
|
160
|
+
return parseResult(spec, raw);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function parseResult(
|
|
164
|
+
spec: { result: { parse(input: unknown): unknown } | null },
|
|
165
|
+
raw: unknown,
|
|
166
|
+
): unknown {
|
|
167
|
+
if (!spec.result) {
|
|
168
|
+
return raw;
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
return spec.result.parse(raw ?? {});
|
|
172
|
+
} catch (error) {
|
|
173
|
+
throw new AddonError('invalid_response', {
|
|
174
|
+
detail: error instanceof Error ? error.message : String(error),
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function parseParams(
|
|
180
|
+
spec: { params: { parse(input: unknown): unknown } },
|
|
181
|
+
params: unknown,
|
|
182
|
+
): unknown {
|
|
183
|
+
try {
|
|
184
|
+
return spec.params.parse(params);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
throw new AddonError('invalid_params', {
|
|
187
|
+
detail: `${error instanceof Error ? error.message : String(error)}`,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function handleNotification(
|
|
193
|
+
method: string,
|
|
194
|
+
params: unknown,
|
|
195
|
+
signal: AbortSignal,
|
|
196
|
+
): Promise<void> {
|
|
197
|
+
if (method === 'initialized') {
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const spec = methodSpec(method);
|
|
201
|
+
if (spec?.direction !== 'notification' || spec.sender === 'addon') {
|
|
202
|
+
throw new AddonError('unsupported', {
|
|
203
|
+
detail: `method '${method}' is not a host notification`,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const parsed = spec.params.parse(params) as Record<string, unknown>;
|
|
207
|
+
const handler = definition.notifications?.[method as keyof NotificationHandlers];
|
|
208
|
+
if (!handler) {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const ctx = createAddonContextFor(
|
|
212
|
+
channel,
|
|
213
|
+
fallbackMeta('notification', Number.MAX_SAFE_INTEGER),
|
|
214
|
+
signal,
|
|
215
|
+
);
|
|
216
|
+
await handler(parsed as never, ctx);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function initialize(params: InitializeParams): InitializeResult {
|
|
220
|
+
instanceOrgId = params.instance.orgId;
|
|
221
|
+
return InitializeResultSchema.parse({
|
|
222
|
+
addon: { id: addon.id, version: addon.version },
|
|
223
|
+
handlers: definition.handlers,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return { addon, handlers: definition.handlers, initialize, handleRequest, handleNotification };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function str(value: unknown): string {
|
|
231
|
+
return typeof value === 'string' ? value : '';
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function asInput(input: unknown): Record<string, unknown> {
|
|
235
|
+
return typeof input === 'object' && input !== null ? (input as Record<string, unknown>) : {};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function withoutMeta<P extends { _meta?: unknown }>(params: P): Omit<P, '_meta'> {
|
|
239
|
+
const copy = { ...params };
|
|
240
|
+
delete copy._meta;
|
|
241
|
+
return copy as Omit<P, '_meta'>;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function handlerTarget(
|
|
245
|
+
handler: unknown,
|
|
246
|
+
params: Record<string, unknown>,
|
|
247
|
+
ctx: AddonContext,
|
|
248
|
+
): Target {
|
|
249
|
+
if (typeof handler !== 'function') {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
return () =>
|
|
253
|
+
(handler as (p: Record<string, unknown>, c: AddonContext) => unknown)(withoutMeta(params), ctx);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const FALLBACK_DEADLINE_MS = 5 * 60_000;
|
|
257
|
+
|
|
258
|
+
function isCallMeta(value: unknown): boolean {
|
|
259
|
+
return typeof value === 'object' && value !== null && 'correlationId' in value;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function fallbackMeta(correlationId: string, deadline: number): CallMeta {
|
|
263
|
+
return {
|
|
264
|
+
correlationId,
|
|
265
|
+
deadline,
|
|
266
|
+
principal: { type: 'system' },
|
|
267
|
+
locale: 'en',
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function pairTarget(
|
|
272
|
+
table: Record<string, { start?: unknown; stop?: unknown }> | undefined,
|
|
273
|
+
key: string,
|
|
274
|
+
phase: 'start' | 'stop',
|
|
275
|
+
params: Record<string, unknown>,
|
|
276
|
+
ctx: AddonContext,
|
|
277
|
+
): Target {
|
|
278
|
+
const handler = table?.[key]?.[phase];
|
|
279
|
+
if (typeof handler !== 'function') {
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
return () => (handler as (p: unknown, c: AddonContext) => unknown)(params, ctx);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function optionalTarget(
|
|
286
|
+
handler: unknown,
|
|
287
|
+
params: Record<string, unknown>,
|
|
288
|
+
ctx: AddonContext,
|
|
289
|
+
): Target {
|
|
290
|
+
if (typeof handler !== 'function') {
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
return () => (handler as (p: unknown, c: AddonContext) => unknown)(params, ctx);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async function runWithDeadline(
|
|
297
|
+
work: unknown,
|
|
298
|
+
deadline: number | null,
|
|
299
|
+
now: () => number,
|
|
300
|
+
signal: AbortSignal,
|
|
301
|
+
): Promise<unknown> {
|
|
302
|
+
if (signal.aborted) {
|
|
303
|
+
throw new AddonError('cancelled');
|
|
304
|
+
}
|
|
305
|
+
if (deadline !== null && deadline - now() <= 0) {
|
|
306
|
+
throw new AddonError('timeout');
|
|
307
|
+
}
|
|
308
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
309
|
+
const timeout =
|
|
310
|
+
deadline === null
|
|
311
|
+
? null
|
|
312
|
+
: new Promise<never>((_resolve, reject) => {
|
|
313
|
+
timer = setTimeout(
|
|
314
|
+
() => reject(new AddonError('timeout', { detail: `deadline ${deadline} exceeded` })),
|
|
315
|
+
deadline - now(),
|
|
316
|
+
);
|
|
317
|
+
});
|
|
318
|
+
const abort = new Promise<never>((_resolve, reject) => {
|
|
319
|
+
signal.addEventListener('abort', () => reject(new AddonError('cancelled')), { once: true });
|
|
320
|
+
});
|
|
321
|
+
const contenders =
|
|
322
|
+
timeout === null ? [Promise.resolve(work), abort] : [Promise.resolve(work), timeout, abort];
|
|
323
|
+
try {
|
|
324
|
+
return await Promise.race(contenders);
|
|
325
|
+
} finally {
|
|
326
|
+
if (timer !== undefined) {
|
|
327
|
+
clearTimeout(timer);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export type { AddonErrorReason };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
import type { DbRow, DbStatement, DbWriteResult, SqlParam } from '../addon-context.ts';
|
|
3
|
+
|
|
4
|
+
type BunDatabaseCtor = new (path: string, options?: Record<string, unknown>) => Database;
|
|
5
|
+
const loadDatabase = (): BunDatabaseCtor => {
|
|
6
|
+
// bun:sqlite must not be evaluated in browser bundles — resolved lazily.
|
|
7
|
+
const mod = require('bun:sqlite') as { Database: BunDatabaseCtor };
|
|
8
|
+
return mod.Database;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const FORBIDDEN_SQL = [/\battach\b/i, /\bdetach\b/i, /\bload_extension\s*\(/i];
|
|
12
|
+
const ALLOWED_PRAGMAS = ['user_version', 'foreign_keys'] as const;
|
|
13
|
+
|
|
14
|
+
export class SqlAuthorizerError extends Error {
|
|
15
|
+
readonly reason = 'permission_denied';
|
|
16
|
+
constructor(message: string) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'SqlAuthorizerError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function guardSql(sql: string): void {
|
|
23
|
+
for (const pattern of FORBIDDEN_SQL) {
|
|
24
|
+
if (pattern.test(sql)) {
|
|
25
|
+
throw new SqlAuthorizerError(`sql statement is not allowed: ${pattern.source}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
for (const statement of splitStatements(sql)) {
|
|
29
|
+
assertStatementAllowed(statement);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Mirrors apps/server/src/app/infra/addons/storage/sql-guard.ts: the fake and the
|
|
34
|
+
// real host must accept and reject identical statements.
|
|
35
|
+
function assertStatementAllowed(statement: string): void {
|
|
36
|
+
const match = /^\s*pragma\s+([a-zA-Z_]+)\s*(=\s*(.+))?$/i.exec(statement);
|
|
37
|
+
if (!match) {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const name = (match[1] ?? '').toLowerCase();
|
|
41
|
+
if ((match[3] ?? null) !== null) {
|
|
42
|
+
throw new SqlAuthorizerError(`pragma writes are not allowed: ${statement.trim()}`);
|
|
43
|
+
}
|
|
44
|
+
if (!ALLOWED_PRAGMAS.includes(name as (typeof ALLOWED_PRAGMAS)[number])) {
|
|
45
|
+
throw new SqlAuthorizerError(`pragma is not allowed: ${statement.trim()}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function splitStatements(sql: string): string[] {
|
|
50
|
+
const statements: string[] = [];
|
|
51
|
+
let current = '';
|
|
52
|
+
let index = 0;
|
|
53
|
+
while (index < sql.length) {
|
|
54
|
+
const char = sql[index] ?? '';
|
|
55
|
+
if (char === "'" || char === '"' || char === '`') {
|
|
56
|
+
const end = quotedEnd(sql, index);
|
|
57
|
+
current += sql.slice(index, end);
|
|
58
|
+
index = end;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (char === ';') {
|
|
62
|
+
statements.push(current);
|
|
63
|
+
current = '';
|
|
64
|
+
} else {
|
|
65
|
+
current += char;
|
|
66
|
+
}
|
|
67
|
+
index += 1;
|
|
68
|
+
}
|
|
69
|
+
if (current.trim().length > 0) {
|
|
70
|
+
statements.push(current);
|
|
71
|
+
}
|
|
72
|
+
return statements.length > 0 ? statements : [sql];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Returns the index just past the closing quote of a quoted run starting at `start`.
|
|
76
|
+
function quotedEnd(sql: string, start: number): number {
|
|
77
|
+
const quote = sql[start];
|
|
78
|
+
let index = start + 1;
|
|
79
|
+
while (index < sql.length) {
|
|
80
|
+
const char = sql[index];
|
|
81
|
+
if (char !== quote) {
|
|
82
|
+
index += 1;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (sql[index + 1] === quote) {
|
|
86
|
+
index += 2;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
return index + 1;
|
|
90
|
+
}
|
|
91
|
+
return sql.length;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface FakeDb {
|
|
95
|
+
exec(sql: string): void;
|
|
96
|
+
all(sql: string, params?: SqlParam[]): DbRow[];
|
|
97
|
+
get(sql: string, params?: SqlParam[]): DbRow | null;
|
|
98
|
+
run(sql: string, params?: SqlParam[]): DbWriteResult;
|
|
99
|
+
batch(statements: DbStatement[]): DbWriteResult[];
|
|
100
|
+
close(): void;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function createFakeDb(): FakeDb {
|
|
104
|
+
const db = new (loadDatabase())(':memory:');
|
|
105
|
+
db.run('pragma foreign_keys = on');
|
|
106
|
+
return {
|
|
107
|
+
exec(sql: string): void {
|
|
108
|
+
guardSql(sql);
|
|
109
|
+
db.run(sql);
|
|
110
|
+
},
|
|
111
|
+
all(sql: string, params?: SqlParam[]): DbRow[] {
|
|
112
|
+
guardSql(sql);
|
|
113
|
+
return db.prepare(sql).all(...(params ?? [])) as DbRow[];
|
|
114
|
+
},
|
|
115
|
+
get(sql: string, params?: SqlParam[]): DbRow | null {
|
|
116
|
+
guardSql(sql);
|
|
117
|
+
return (db.prepare(sql).get(...(params ?? [])) ?? null) as DbRow | null;
|
|
118
|
+
},
|
|
119
|
+
run(sql: string, params?: SqlParam[]): DbWriteResult {
|
|
120
|
+
guardSql(sql);
|
|
121
|
+
const result = db.run(sql, params ?? []);
|
|
122
|
+
return { changes: Number(result.changes), lastInsertRowid: Number(result.lastInsertRowid) };
|
|
123
|
+
},
|
|
124
|
+
batch(statements: DbStatement[]): DbWriteResult[] {
|
|
125
|
+
const apply = (): DbWriteResult[] =>
|
|
126
|
+
statements.map((statement) => {
|
|
127
|
+
guardSql(statement.sql);
|
|
128
|
+
const result = db.run(statement.sql, statement.params ?? []);
|
|
129
|
+
return {
|
|
130
|
+
changes: Number(result.changes),
|
|
131
|
+
lastInsertRowid: Number(result.lastInsertRowid),
|
|
132
|
+
};
|
|
133
|
+
});
|
|
134
|
+
return db.transaction(apply)();
|
|
135
|
+
},
|
|
136
|
+
close(): void {
|
|
137
|
+
db.close();
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { AddonError } from '../protocol/error.ts';
|
|
2
|
+
import type { FakeHostOptions } from './fake-host.ts';
|
|
3
|
+
|
|
4
|
+
const MAX_CHUNK_BYTES = 4 * 1024 * 1024;
|
|
5
|
+
|
|
6
|
+
const MEDIA_TYPES: Record<string, string> = {
|
|
7
|
+
png: 'image/png',
|
|
8
|
+
jpg: 'image/jpeg',
|
|
9
|
+
jpeg: 'image/jpeg',
|
|
10
|
+
gif: 'image/gif',
|
|
11
|
+
webp: 'image/webp',
|
|
12
|
+
pdf: 'application/pdf',
|
|
13
|
+
json: 'application/json',
|
|
14
|
+
txt: 'text/plain',
|
|
15
|
+
md: 'text/markdown',
|
|
16
|
+
csv: 'text/csv',
|
|
17
|
+
mp4: 'video/mp4',
|
|
18
|
+
mov: 'video/quicktime',
|
|
19
|
+
webm: 'video/webm',
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export interface FakeFilesContext {
|
|
23
|
+
options: FakeHostOptions;
|
|
24
|
+
writes: Array<{ path: string; size: number }>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function executeFilesService(
|
|
28
|
+
method: string,
|
|
29
|
+
params: Record<string, unknown>,
|
|
30
|
+
context: FakeFilesContext,
|
|
31
|
+
): unknown {
|
|
32
|
+
const store = context.options.files ?? {};
|
|
33
|
+
const path = normalizePath(String(params.path));
|
|
34
|
+
if (method === 'files.write') {
|
|
35
|
+
return writeFile(store, path, params, context.writes);
|
|
36
|
+
}
|
|
37
|
+
const stored = store[path];
|
|
38
|
+
if (stored === undefined) {
|
|
39
|
+
throw new AddonError('not_found', { detail: `no such file: ${path}` });
|
|
40
|
+
}
|
|
41
|
+
if (method === 'files.stat') {
|
|
42
|
+
return statOf(path, stored, context);
|
|
43
|
+
}
|
|
44
|
+
return readChunk(path, stored, params);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function writeFile(
|
|
48
|
+
store: Record<string, string>,
|
|
49
|
+
path: string,
|
|
50
|
+
params: Record<string, unknown>,
|
|
51
|
+
writes: Array<{ path: string; size: number }>,
|
|
52
|
+
): unknown {
|
|
53
|
+
const data = decode(String(params.data));
|
|
54
|
+
if (data.byteLength > MAX_CHUNK_BYTES) {
|
|
55
|
+
throw new AddonError('invalid_params', {
|
|
56
|
+
detail: `write chunk exceeds ${MAX_CHUNK_BYTES} bytes`,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
const previous =
|
|
60
|
+
params.append === true && store[path] !== undefined ? decode(store[path]) : Buffer.alloc(0);
|
|
61
|
+
const next = Buffer.concat([previous, data]);
|
|
62
|
+
store[path] = next.toString('base64');
|
|
63
|
+
writes.push({ path, size: next.byteLength });
|
|
64
|
+
return { path, size: next.byteLength };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function statOf(path: string, stored: string, context: FakeFilesContext): unknown {
|
|
68
|
+
const bytes = decode(stored);
|
|
69
|
+
return {
|
|
70
|
+
path,
|
|
71
|
+
name: path.split('/').at(-1) ?? path,
|
|
72
|
+
size: bytes.byteLength,
|
|
73
|
+
mediaType: mediaTypeOf(path),
|
|
74
|
+
modifiedAt: new Date(context.options.now?.() ?? 0).toISOString(),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function readChunk(path: string, stored: string, params: Record<string, unknown>): unknown {
|
|
79
|
+
const bytes = decode(stored);
|
|
80
|
+
const offset = Number(params.offset ?? 0);
|
|
81
|
+
const requested = Math.min(Number(params.length ?? MAX_CHUNK_BYTES), MAX_CHUNK_BYTES);
|
|
82
|
+
const length = Math.max(0, Math.min(requested, bytes.byteLength - offset));
|
|
83
|
+
const chunk = bytes.subarray(offset, offset + length);
|
|
84
|
+
return {
|
|
85
|
+
data: chunk.toString('base64'),
|
|
86
|
+
eof: offset + length >= bytes.byteLength,
|
|
87
|
+
size: bytes.byteLength,
|
|
88
|
+
mediaType: mediaTypeOf(path),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function normalizePath(raw: string): string {
|
|
93
|
+
const normalized = raw.replace(/\\/g, '/').replace(/^\.\//, '');
|
|
94
|
+
const segments = normalized.split('/');
|
|
95
|
+
if (
|
|
96
|
+
normalized.startsWith('/') ||
|
|
97
|
+
segments.some((segment) => segment === '..' || segment === '')
|
|
98
|
+
) {
|
|
99
|
+
throw new AddonError('invalid_params', { detail: `invalid file path: ${raw}` });
|
|
100
|
+
}
|
|
101
|
+
return normalized;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function mediaTypeOf(path: string): string {
|
|
105
|
+
const extension = path.includes('.') ? path.split('.').at(-1)?.toLowerCase() : undefined;
|
|
106
|
+
if (extension === undefined) {
|
|
107
|
+
return 'application/octet-stream';
|
|
108
|
+
}
|
|
109
|
+
return MEDIA_TYPES[extension] ?? 'application/octet-stream';
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function decode(base64: string): Buffer {
|
|
113
|
+
return base64 === '' ? Buffer.alloc(0) : Buffer.from(base64, 'base64');
|
|
114
|
+
}
|