@kubohiroya/turbowarp-http-server 0.1.0 → 0.2.1
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/README.ja.md +29 -13
- package/README.md +101 -42
- package/dist/cli.js +131 -17
- package/dist/cli.js.map +1 -1
- package/dist/compiler/adapters/cloudflare.d.ts +2 -0
- package/dist/compiler/adapters/cloudflare.js +477 -0
- package/dist/compiler/adapters/cloudflare.js.map +1 -0
- package/dist/compiler/adapters/firebase.d.ts +2 -0
- package/dist/compiler/adapters/firebase.js +489 -0
- package/dist/compiler/adapters/firebase.js.map +1 -0
- package/dist/compiler/adapters/index.d.ts +2 -0
- package/dist/compiler/adapters/index.js +3 -0
- package/dist/compiler/adapters/index.js.map +1 -0
- package/dist/compiler/binary/codec.d.ts +4 -0
- package/dist/compiler/binary/codec.js +45 -0
- package/dist/compiler/binary/codec.js.map +1 -0
- package/dist/compiler/binary/error.d.ts +3 -0
- package/dist/compiler/binary/error.js +21 -0
- package/dist/compiler/binary/error.js.map +1 -0
- package/dist/compiler/binary/index.d.ts +4 -0
- package/dist/compiler/binary/index.js +5 -0
- package/dist/compiler/binary/index.js.map +1 -0
- package/dist/compiler/binary/runtime.d.ts +18 -0
- package/dist/compiler/binary/runtime.js +123 -0
- package/dist/compiler/binary/runtime.js.map +1 -0
- package/dist/compiler/binary/types.d.ts +17 -0
- package/dist/compiler/binary/types.js +2 -0
- package/dist/compiler/binary/types.js.map +1 -0
- package/dist/compiler/feature-flags.d.ts +4 -0
- package/dist/compiler/feature-flags.js +4 -0
- package/dist/compiler/feature-flags.js.map +1 -0
- package/dist/compiler/index.d.ts +35 -0
- package/dist/compiler/index.js +84 -0
- package/dist/compiler/index.js.map +1 -0
- package/dist/compiler/ir-v2/canonical.d.ts +3 -0
- package/dist/compiler/ir-v2/canonical.js +50 -0
- package/dist/compiler/ir-v2/canonical.js.map +1 -0
- package/dist/compiler/ir-v2/index.d.ts +4 -0
- package/dist/compiler/ir-v2/index.js +5 -0
- package/dist/compiler/ir-v2/index.js.map +1 -0
- package/dist/compiler/ir-v2/parse.d.ts +10 -0
- package/dist/compiler/ir-v2/parse.js +753 -0
- package/dist/compiler/ir-v2/parse.js.map +1 -0
- package/dist/compiler/ir-v2/strict-json.d.ts +4 -0
- package/dist/compiler/ir-v2/strict-json.js +133 -0
- package/dist/compiler/ir-v2/strict-json.js.map +1 -0
- package/dist/compiler/ir-v2/types.d.ts +412 -0
- package/dist/compiler/ir-v2/types.js +84 -0
- package/dist/compiler/ir-v2/types.js.map +1 -0
- package/dist/compiler/kvs/lowering.d.ts +13 -0
- package/dist/compiler/kvs/lowering.js +77 -0
- package/dist/compiler/kvs/lowering.js.map +1 -0
- package/dist/compiler/manifest/error.d.ts +7 -0
- package/dist/compiler/manifest/error.js +9 -0
- package/dist/compiler/manifest/error.js.map +1 -0
- package/dist/compiler/manifest/index.d.ts +6 -0
- package/dist/compiler/manifest/index.js +7 -0
- package/dist/compiler/manifest/index.js.map +1 -0
- package/dist/compiler/manifest/operations.d.ts +12 -0
- package/dist/compiler/manifest/operations.js +60 -0
- package/dist/compiler/manifest/operations.js.map +1 -0
- package/dist/compiler/manifest/parse.d.ts +9 -0
- package/dist/compiler/manifest/parse.js +280 -0
- package/dist/compiler/manifest/parse.js.map +1 -0
- package/dist/compiler/manifest/registry.d.ts +3 -0
- package/dist/compiler/manifest/registry.js +48 -0
- package/dist/compiler/manifest/registry.js.map +1 -0
- package/dist/compiler/manifest/resolve.d.ts +14 -0
- package/dist/compiler/manifest/resolve.js +116 -0
- package/dist/compiler/manifest/resolve.js.map +1 -0
- package/dist/compiler/manifest/types.d.ts +95 -0
- package/dist/compiler/manifest/types.js +3 -0
- package/dist/compiler/manifest/types.js.map +1 -0
- package/dist/compiler/named-body/index.d.ts +1 -0
- package/dist/compiler/named-body/index.js +2 -0
- package/dist/compiler/named-body/index.js.map +1 -0
- package/dist/compiler/named-body/lowering.d.ts +18 -0
- package/dist/compiler/named-body/lowering.js +83 -0
- package/dist/compiler/named-body/lowering.js.map +1 -0
- package/dist/compiler/pipeline/compiler.d.ts +18 -0
- package/dist/compiler/pipeline/compiler.js +105 -0
- package/dist/compiler/pipeline/compiler.js.map +1 -0
- package/dist/compiler/pipeline/core-generator.d.ts +3 -0
- package/dist/compiler/pipeline/core-generator.js +483 -0
- package/dist/compiler/pipeline/core-generator.js.map +1 -0
- package/dist/compiler/pipeline/index.d.ts +5 -0
- package/dist/compiler/pipeline/index.js +6 -0
- package/dist/compiler/pipeline/index.js.map +1 -0
- package/dist/compiler/pipeline/registry.d.ts +7 -0
- package/dist/compiler/pipeline/registry.js +17 -0
- package/dist/compiler/pipeline/registry.js.map +1 -0
- package/dist/compiler/pipeline/requirements.d.ts +9 -0
- package/dist/compiler/pipeline/requirements.js +135 -0
- package/dist/compiler/pipeline/requirements.js.map +1 -0
- package/dist/compiler/pipeline/types.d.ts +65 -0
- package/dist/compiler/pipeline/types.js +2 -0
- package/dist/compiler/pipeline/types.js.map +1 -0
- package/dist/compiler/runtime/error.d.ts +6 -0
- package/dist/compiler/runtime/error.js +9 -0
- package/dist/compiler/runtime/error.js.map +1 -0
- package/dist/compiler/runtime/index.d.ts +1 -0
- package/dist/compiler/runtime/index.js +2 -0
- package/dist/compiler/runtime/index.js.map +1 -0
- package/dist/compiler/structured-data/index.d.ts +3 -0
- package/dist/compiler/structured-data/index.js +4 -0
- package/dist/compiler/structured-data/index.js.map +1 -0
- package/dist/compiler/structured-data/lowering.d.ts +30 -0
- package/dist/compiler/structured-data/lowering.js +202 -0
- package/dist/compiler/structured-data/lowering.js.map +1 -0
- package/dist/compiler/structured-data/path.d.ts +2 -0
- package/dist/compiler/structured-data/path.js +60 -0
- package/dist/compiler/structured-data/path.js.map +1 -0
- package/dist/compiler/structured-data/runtime.d.ts +20 -0
- package/dist/compiler/structured-data/runtime.js +210 -0
- package/dist/compiler/structured-data/runtime.js.map +1 -0
- package/dist/compiler/turbowarp-v2.d.ts +8 -0
- package/dist/compiler/turbowarp-v2.js +479 -0
- package/dist/compiler/turbowarp-v2.js.map +1 -0
- package/dist/compiler/validator/index.d.ts +4 -0
- package/dist/compiler/validator/index.js +5 -0
- package/dist/compiler/validator/index.js.map +1 -0
- package/dist/compiler/validator/ir-validator.d.ts +10 -0
- package/dist/compiler/validator/ir-validator.js +463 -0
- package/dist/compiler/validator/ir-validator.js.map +1 -0
- package/dist/compiler/validator/resource-lifetime.d.ts +18 -0
- package/dist/compiler/validator/resource-lifetime.js +106 -0
- package/dist/compiler/validator/resource-lifetime.js.map +1 -0
- package/dist/compiler/validator/turbowarp-subset.d.ts +3 -0
- package/dist/compiler/validator/turbowarp-subset.js +241 -0
- package/dist/compiler/validator/turbowarp-subset.js.map +1 -0
- package/dist/compiler/validator/types.d.ts +30 -0
- package/dist/compiler/validator/types.js +7 -0
- package/dist/compiler/validator/types.js.map +1 -0
- package/dist/config.d.ts +11 -0
- package/dist/config.js +12 -0
- package/dist/config.js.map +1 -0
- package/dist/digest-cli.js +0 -0
- package/dist/extension-manifest.json +102 -0
- package/dist/named-body.d.ts +57 -0
- package/dist/named-body.js +396 -0
- package/dist/named-body.js.map +1 -0
- package/dist/named-data-namespace.d.ts +3 -0
- package/dist/named-data-namespace.js +6 -0
- package/dist/named-data-namespace.js.map +1 -0
- package/dist/protocol.d.ts +13 -1
- package/dist/protocol.js +34 -0
- package/dist/protocol.js.map +1 -1
- package/dist/resource-named-body-provider.d.ts +8 -0
- package/dist/resource-named-body-provider.js +88 -0
- package/dist/resource-named-body-provider.js.map +1 -0
- package/dist/server.d.ts +10 -1
- package/dist/server.js +37 -7
- package/dist/server.js.map +1 -1
- package/dist/turbowarp-http-server.js +516 -1
- package/docs/binary-resource-semantics.ja.md +84 -0
- package/docs/cloudflare-worker-compiler.ja.md +90 -0
- package/docs/compiler-manifest-registry.ja.md +79 -0
- package/docs/compiler-platform-pipeline.ja.md +94 -0
- package/docs/deploy-ir-v2.ja.md +123 -0
- package/docs/fixed-input-editors.ja.md +23 -0
- package/docs/index.html +80 -0
- package/docs/ir-v2-conformance.ja.md +65 -0
- package/docs/named-response-body.ja.md +120 -0
- package/docs/platform-storage-adapters.ja.md +99 -0
- package/docs/server-executable-subset.ja.md +88 -0
- package/docs/structured-data-lowering.ja.md +63 -0
- package/examples/compiler/message-app.v2.ir.json +41 -0
- package/package.json +44 -20
- package/schemas/block-editor-fixed-inputs.schema.json +85 -0
- package/schemas/compiler-extension-manifest.schema.json +126 -0
- package/schemas/compiler-manifest-lock-v1.schema.json +48 -0
- package/schemas/deploy-ir-v2.schema.json +835 -0
- package/schemas/ir-v2-conformance-fixture.schema.json +44 -0
- package/src/block-definitions.json +76 -0
- package/src/cli.ts +136 -23
- package/src/compiler/adapters/cloudflare.ts +510 -0
- package/src/compiler/adapters/firebase.ts +538 -0
- package/src/compiler/adapters/index.ts +2 -0
- package/src/compiler/binary/codec.ts +61 -0
- package/src/compiler/binary/error.ts +25 -0
- package/src/compiler/binary/index.ts +4 -0
- package/src/compiler/binary/runtime.ts +133 -0
- package/src/compiler/binary/types.ts +26 -0
- package/src/compiler/feature-flags.ts +7 -0
- package/src/compiler/index.ts +114 -0
- package/src/compiler/ir-v2/canonical.ts +46 -0
- package/src/compiler/ir-v2/index.ts +9 -0
- package/src/compiler/ir-v2/parse.ts +921 -0
- package/src/compiler/ir-v2/strict-json.ts +129 -0
- package/src/compiler/ir-v2/types.ts +462 -0
- package/src/compiler/kvs/lowering.ts +88 -0
- package/src/compiler/manifest/error.ts +29 -0
- package/src/compiler/manifest/index.ts +17 -0
- package/src/compiler/manifest/operations.ts +175 -0
- package/src/compiler/manifest/parse.ts +390 -0
- package/src/compiler/manifest/registry.ts +74 -0
- package/src/compiler/manifest/resolve.ts +159 -0
- package/src/compiler/manifest/types.ts +112 -0
- package/src/compiler/named-body/index.ts +1 -0
- package/src/compiler/named-body/lowering.ts +186 -0
- package/src/compiler/pipeline/compiler.ts +138 -0
- package/src/compiler/pipeline/core-generator.ts +486 -0
- package/src/compiler/pipeline/index.ts +5 -0
- package/src/compiler/pipeline/registry.ts +18 -0
- package/src/compiler/pipeline/requirements.ts +139 -0
- package/src/compiler/pipeline/types.ts +59 -0
- package/src/compiler/runtime/error.ts +11 -0
- package/src/compiler/runtime/index.ts +1 -0
- package/src/compiler/structured-data/index.ts +3 -0
- package/src/compiler/structured-data/lowering.ts +314 -0
- package/src/compiler/structured-data/path.ts +53 -0
- package/src/compiler/structured-data/runtime.ts +221 -0
- package/src/compiler/turbowarp-v2.ts +610 -0
- package/src/compiler/validator/index.ts +4 -0
- package/src/compiler/validator/ir-validator.ts +812 -0
- package/src/compiler/validator/resource-lifetime.ts +153 -0
- package/src/compiler/validator/turbowarp-subset.ts +387 -0
- package/src/compiler/validator/types.ts +68 -0
- package/src/extension.ts +87 -1
- package/src/fixed-input-editors.ts +181 -0
- package/src/fixed-input-schema.ts +15 -0
- package/src/named-body.ts +495 -0
- package/src/named-data-namespace.ts +6 -0
- package/src/protocol.ts +50 -1
- package/src/resource-named-body-provider.ts +106 -0
- package/src/server.ts +88 -8
- package/docs/turbowarp-http-server.architecture.visual-check.1440x900.dark.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.1440x900.light.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.dark.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.light.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.html +0 -32
- package/docs/turbowarp-http-server.architecture.visual-check.json +0 -547
- package/schemas/extension-manifest.schema.json +0 -49
- package/src/extension-manifest.ts +0 -149
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
import {canonicalizeDeployIrV2} from '../ir-v2/canonical.js';
|
|
2
|
+
import type {DeployIrV2} from '../ir-v2/types.js';
|
|
3
|
+
import type {GeneratedCore} from './types.js';
|
|
4
|
+
|
|
5
|
+
export function generateHonoCore(ir: DeployIrV2): GeneratedCore {
|
|
6
|
+
return {
|
|
7
|
+
entryModule: './core.generated.js',
|
|
8
|
+
files: {'src/core.generated.ts': coreSource(ir)}
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function coreSource(ir: DeployIrV2): string {
|
|
13
|
+
return `// Generated by turbowarp-http-server. Platform-neutral Hono core.
|
|
14
|
+
import type {Hono} from 'hono';
|
|
15
|
+
|
|
16
|
+
type StoredRecord = Record<string, unknown>;
|
|
17
|
+
export type AuthScheme = 'external-jwt' | 'trusted-access-jwt';
|
|
18
|
+
export type AuthIdentity = {id: string; claims: Record<string, unknown>};
|
|
19
|
+
export type BinaryLocator = {namespace: string; key: string};
|
|
20
|
+
export type BinaryRef = BinaryLocator & {contentType?: string; size?: number; integrity?: string; revision?: string};
|
|
21
|
+
export type BinaryMetadata = {contentType?: string; size?: number; integrity?: string; revision?: string};
|
|
22
|
+
export interface BinaryBodySource {chunks: AsyncIterable<Uint8Array>; contentType?: string; size?: number}
|
|
23
|
+
export interface BinaryObjectStore {
|
|
24
|
+
resolve(locator: BinaryLocator): Promise<BinaryRef | null>;
|
|
25
|
+
get(ref: BinaryRef): Promise<BinaryBodySource | null>;
|
|
26
|
+
put(locator: BinaryLocator, source: BinaryBodySource, metadata: BinaryMetadata, maxBytes: number): Promise<BinaryRef>;
|
|
27
|
+
delete(target: BinaryLocator | BinaryRef): Promise<boolean>;
|
|
28
|
+
}
|
|
29
|
+
export type NamedDataReference = {namespace: string; name: string; kind: 'structured' | 'document' | 'binary' | 'asset'; scope: 'target' | 'project'};
|
|
30
|
+
export type NamedBodyRequest = {reference: NamedDataReference; representation: 'json' | 'yaml' | 'html' | 'markdown' | 'raw'; targetId?: string};
|
|
31
|
+
export interface NamedBodyService {
|
|
32
|
+
respond(request: NamedBodyRequest, options: {method: string; status: number; headers: Headers; signal: AbortSignal; maxBodyBytes: number}): Promise<Response>;
|
|
33
|
+
}
|
|
34
|
+
export interface RecordStore {
|
|
35
|
+
create(collection: string, data: unknown): Promise<StoredRecord>;
|
|
36
|
+
list(collection: string): Promise<StoredRecord[]>;
|
|
37
|
+
get(id: string): Promise<StoredRecord | null>;
|
|
38
|
+
delete(id: string): Promise<boolean>;
|
|
39
|
+
}
|
|
40
|
+
export interface KeyValueStore {
|
|
41
|
+
set(namespace: string, key: string, value: string): Promise<void>;
|
|
42
|
+
get(namespace: string, key: string): Promise<string | null>;
|
|
43
|
+
has(namespace: string, key: string): Promise<boolean>;
|
|
44
|
+
delete(namespace: string, key: string): Promise<boolean>;
|
|
45
|
+
list(namespace: string): Promise<string[]>;
|
|
46
|
+
}
|
|
47
|
+
export interface CoreServices {
|
|
48
|
+
authenticate?: (context: unknown, scheme: AuthScheme) => Promise<AuthIdentity | null>;
|
|
49
|
+
records?: (context: unknown) => RecordStore;
|
|
50
|
+
keyValues?: (context: unknown) => KeyValueStore;
|
|
51
|
+
objects?: (context: unknown) => BinaryObjectStore;
|
|
52
|
+
namedBodies?: (context: unknown) => NamedBodyService;
|
|
53
|
+
clientAddress?: (context: unknown) => string;
|
|
54
|
+
}
|
|
55
|
+
type App = Hono<any>;
|
|
56
|
+
const ir: any = ${canonicalizeDeployIrV2(ir)};
|
|
57
|
+
|
|
58
|
+
export function registerCoreRoutes(app: App, services: CoreServices): void {
|
|
59
|
+
for (const route of ir.routes) {
|
|
60
|
+
const method = route.method === 'ALL' ? 'all' : route.method.toLowerCase();
|
|
61
|
+
(app as any)[method](route.path, async (c: any) => executeRoute(route, c, services));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function executeRoute(route: (typeof ir.routes)[number], c: any, services: CoreServices): Promise<Response> {
|
|
66
|
+
let status = 200;
|
|
67
|
+
const headers = new Headers();
|
|
68
|
+
const bindings = new Map<string, unknown>();
|
|
69
|
+
const handlerVariables = new Map<string, string>();
|
|
70
|
+
const iterations = new Map<string, {key: string; index: number; value: unknown}>();
|
|
71
|
+
let bodyText: string | undefined;
|
|
72
|
+
try {
|
|
73
|
+
if (route.auth === 'required') {
|
|
74
|
+
if (ir.auth.kind !== 'jwt' || services.authenticate === undefined) throw runtimeError('IR_CAPABILITY_UNAVAILABLE');
|
|
75
|
+
const identity = await services.authenticate(c, ir.auth.scheme);
|
|
76
|
+
if (identity === null) {
|
|
77
|
+
return new Response(JSON.stringify({error: {code: 'UNAUTHORIZED'}}), {
|
|
78
|
+
status: 401,
|
|
79
|
+
headers: {'content-type': 'application/json; charset=utf-8'}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const terminal = await statements(route.body);
|
|
84
|
+
if (terminal !== undefined) return terminal;
|
|
85
|
+
throw runtimeError('IR_MISSING_RESPONSE');
|
|
86
|
+
} catch (error) {
|
|
87
|
+
const fault = runtimeFault(error);
|
|
88
|
+
return new Response(JSON.stringify({error: {code: fault.code}}), {status: fault.status, headers: {'content-type': 'application/json; charset=utf-8'}});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function statements(items: readonly any[]): Promise<Response | undefined> {
|
|
92
|
+
for (const statement of items) {
|
|
93
|
+
if (statement.kind === 'set-status') status = statement.status;
|
|
94
|
+
else if (statement.kind === 'set-header') setResponseHeader(headers, statement.name, asText(await expression(statement.value)));
|
|
95
|
+
else if (statement.kind === 'remove-header') headers.delete(statement.name);
|
|
96
|
+
else if (statement.kind === 'set-handler-variable') {
|
|
97
|
+
handlerVariables.set(asText(await expression(statement.name)), asText(await expression(statement.value)));
|
|
98
|
+
} else if (statement.kind === 'change-handler-variable') {
|
|
99
|
+
const name = asText(await expression(statement.name));
|
|
100
|
+
handlerVariables.set(name, String(scratchNumber(handlerVariables.get(name) ?? '') + scratchNumber(await expression(statement.value))));
|
|
101
|
+
} else if (statement.kind === 'delete-handler-variable') {
|
|
102
|
+
handlerVariables.delete(asText(await expression(statement.name)));
|
|
103
|
+
} else if (statement.kind === 'clear-handler-variables') handlerVariables.clear();
|
|
104
|
+
else if (statement.kind === 'kvs-set-text') {
|
|
105
|
+
await requiredKeyValues().set(asText(await expression(statement.namespace)), asText(await expression(statement.key)), asText(await expression(statement.value)));
|
|
106
|
+
} else if (statement.kind === 'kvs-delete') {
|
|
107
|
+
await requiredKeyValues().delete(asText(await expression(statement.namespace)), asText(await expression(statement.key)));
|
|
108
|
+
} else if (statement.kind === 'record-create') {
|
|
109
|
+
bindings.set(statement.result.id, await requiredRecords().create(statement.collection, await expression(statement.data)));
|
|
110
|
+
} else if (statement.kind === 'record-list') {
|
|
111
|
+
bindings.set(statement.result.id, await requiredRecords().list(statement.collection));
|
|
112
|
+
} else if (statement.kind === 'record-get') {
|
|
113
|
+
bindings.set(statement.result.id, await requiredRecords().get(asText(await expression(statement.id))));
|
|
114
|
+
} else if (statement.kind === 'record-delete') {
|
|
115
|
+
bindings.set(statement.result.id, await requiredRecords().delete(asText(await expression(statement.id))));
|
|
116
|
+
} else if (statement.kind === 'asset-resolve') {
|
|
117
|
+
bindings.set(statement.result.id, await requiredObjects().resolve(statement.locator));
|
|
118
|
+
} else if (statement.kind === 'request-body-binary') {
|
|
119
|
+
bindings.set(statement.result.id, new BinaryBodyHandle(limitedBinarySource(requestBinary(c), statement.maxBytes)));
|
|
120
|
+
} else if (statement.kind === 'asset-object-get') {
|
|
121
|
+
const source = await requiredObjects().get(requiredBinaryRef(await expression(statement.ref)));
|
|
122
|
+
if (source === null) throw runtimeError('BINARY_NOT_FOUND', 404);
|
|
123
|
+
bindings.set(statement.result.id, new BinaryBodyHandle(limitedBinarySource(source, statement.maxBytes)));
|
|
124
|
+
} else if (statement.kind === 'asset-object-put') {
|
|
125
|
+
const handle = requiredBinaryBody(statement.body);
|
|
126
|
+
bindings.set(statement.result.id, await requiredObjects().put(statement.locator, handle.take(), statement.metadata, statement.maxBytes));
|
|
127
|
+
} else if (statement.kind === 'asset-object-delete') {
|
|
128
|
+
const target = statement.target.kind === 'ref' ? requiredBinaryRef(await expression(statement.target.ref)) : statement.target.locator;
|
|
129
|
+
bindings.set(statement.result.id, await requiredObjects().delete(target));
|
|
130
|
+
} else if (statement.kind === 'if') {
|
|
131
|
+
const branch = (await expression(statement.condition)) === true ? statement.then : (statement.else ?? []);
|
|
132
|
+
const terminal = await statements(branch);
|
|
133
|
+
if (terminal !== undefined) return terminal;
|
|
134
|
+
} else if (statement.kind === 'bounded-loop') {
|
|
135
|
+
for (let index = 0; index < statement.maxIterations; index += 1) {
|
|
136
|
+
const terminal = await statements(statement.body);
|
|
137
|
+
if (terminal !== undefined) return terminal;
|
|
138
|
+
}
|
|
139
|
+
} else if (statement.kind === 'json-for-each') {
|
|
140
|
+
const entries = structuredIterationEntries(await expression(statement.root), statement.path, statement.maxIterations);
|
|
141
|
+
for (const entry of entries) {
|
|
142
|
+
iterations.set(statement.loopId, entry);
|
|
143
|
+
try {
|
|
144
|
+
const terminal = await statements(statement.body);
|
|
145
|
+
if (terminal !== undefined) return terminal;
|
|
146
|
+
} finally {
|
|
147
|
+
iterations.delete(statement.loopId);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
} else if (statement.kind === 'respond-named-body') {
|
|
151
|
+
return requiredNamedBodies().respond(
|
|
152
|
+
{
|
|
153
|
+
reference: statement.reference,
|
|
154
|
+
representation: statement.representation,
|
|
155
|
+
...(statement.targetId === undefined ? {} : {targetId: statement.targetId})
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
method: c.req.method,
|
|
159
|
+
status,
|
|
160
|
+
headers: new Headers(headers),
|
|
161
|
+
signal: c.req.raw.signal,
|
|
162
|
+
maxBodyBytes: statement.maxBytes
|
|
163
|
+
}
|
|
164
|
+
);
|
|
165
|
+
} else if (statement.kind === 'respond-binary') {
|
|
166
|
+
const source = requiredBinaryBody(statement.body).take();
|
|
167
|
+
if (source.contentType !== undefined && !headers.has('content-type')) headers.set('content-type', source.contentType);
|
|
168
|
+
if (statement.disposition !== undefined) headers.set('content-disposition', contentDisposition(statement.disposition));
|
|
169
|
+
return new Response(binaryReadableStream(source.chunks), {status, headers});
|
|
170
|
+
} else if (statement.kind === 'respond') {
|
|
171
|
+
return response(statement.format, statement.body.valueType, await expression(statement.body), status, headers);
|
|
172
|
+
} else throw runtimeError('IR_OPERATION_UNSUPPORTED');
|
|
173
|
+
}
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function expression(value: any): Promise<unknown> {
|
|
178
|
+
if (value.kind === 'literal') return value.value;
|
|
179
|
+
if (value.kind === 'binding') return bindings.get(value.binding);
|
|
180
|
+
if (value.kind === 'concat') return asText(await expression(value.left)) + asText(await expression(value.right));
|
|
181
|
+
if (value.kind === 'handler-variable') return handlerVariables.get(asText(await expression(value.name))) ?? '';
|
|
182
|
+
if (value.kind === 'handler-variable-exists') return handlerVariables.has(asText(await expression(value.name)));
|
|
183
|
+
if (value.kind === 'handler-variable-names') return [...handlerVariables.keys()].join(',');
|
|
184
|
+
if (value.kind === 'kvs-get-text') return await requiredKeyValues().get(asText(await expression(value.namespace)), asText(await expression(value.key))) ?? '';
|
|
185
|
+
if (value.kind === 'kvs-has') return requiredKeyValues().has(asText(await expression(value.namespace)), asText(await expression(value.key)));
|
|
186
|
+
if (value.kind === 'kvs-list-keys') return JSON.stringify(await requiredKeyValues().list(asText(await expression(value.namespace))));
|
|
187
|
+
if (value.kind === 'request-value') {
|
|
188
|
+
if (value.source === 'query') return c.req.query(value.name) ?? '';
|
|
189
|
+
if (value.source === 'path-param') return c.req.param(value.name) ?? '';
|
|
190
|
+
return c.req.header(value.name) ?? '';
|
|
191
|
+
}
|
|
192
|
+
if (value.kind === 'request') {
|
|
193
|
+
if (value.source === 'method') return c.req.method;
|
|
194
|
+
if (value.source === 'path') return new URL(c.req.url).pathname;
|
|
195
|
+
if (value.source === 'url') return c.req.url;
|
|
196
|
+
if (value.source === 'body-text') return (bodyText ??= await c.req.text());
|
|
197
|
+
if (value.source === 'content-type') return c.req.header('content-type') ?? '';
|
|
198
|
+
return services.clientAddress?.(c) ?? '';
|
|
199
|
+
}
|
|
200
|
+
if (value.kind === 'json-text-coerce') return asText(await expression(value.input));
|
|
201
|
+
if (value.kind === 'json-parse') return parseApplicationJson(await expression(value.text));
|
|
202
|
+
if (value.kind === 'json-stringify') return stringifyApplicationJson(await expression(value.value));
|
|
203
|
+
if (value.kind === 'json-is-valid') {
|
|
204
|
+
try {parseApplicationJson(await expression(value.text)); return true;} catch {return false;}
|
|
205
|
+
}
|
|
206
|
+
if (value.kind === 'json-get') return getJsonAtPath(await expression(value.root), value.path);
|
|
207
|
+
if (value.kind === 'json-has') return hasJsonAtPath(await expression(value.root), value.path);
|
|
208
|
+
if (value.kind === 'json-set') return setJsonAtPath(await expression(value.root), value.path, await expression(value.value));
|
|
209
|
+
if (value.kind === 'json-delete') return deleteJsonAtPath(await expression(value.root), value.path);
|
|
210
|
+
if (value.kind === 'json-keys') return jsonKeysAtPath(await expression(value.root), value.path);
|
|
211
|
+
if (value.kind === 'json-length') return jsonLengthAtPath(await expression(value.root), value.path);
|
|
212
|
+
if (value.kind === 'iteration-key') return requiredIteration(value.loopId).key;
|
|
213
|
+
if (value.kind === 'iteration-index') return requiredIteration(value.loopId).index;
|
|
214
|
+
if (value.kind === 'iteration-value') return requiredIteration(value.loopId).value;
|
|
215
|
+
throw runtimeError('IR_EXPRESSION_UNSUPPORTED');
|
|
216
|
+
}
|
|
217
|
+
function requiredRecords(): RecordStore {
|
|
218
|
+
if (!services.records) throw runtimeError('IR_CAPABILITY_UNAVAILABLE');
|
|
219
|
+
return services.records(c);
|
|
220
|
+
}
|
|
221
|
+
function requiredKeyValues(): KeyValueStore {
|
|
222
|
+
if (!services.keyValues) throw runtimeError('IR_CAPABILITY_UNAVAILABLE');
|
|
223
|
+
return services.keyValues(c);
|
|
224
|
+
}
|
|
225
|
+
function requiredObjects(): BinaryObjectStore {
|
|
226
|
+
if (!services.objects) throw runtimeError('IR_CAPABILITY_UNAVAILABLE');
|
|
227
|
+
return services.objects(c);
|
|
228
|
+
}
|
|
229
|
+
function requiredNamedBodies(): NamedBodyService {
|
|
230
|
+
if (!services.namedBodies) throw runtimeError('IR_CAPABILITY_UNAVAILABLE');
|
|
231
|
+
return services.namedBodies(c);
|
|
232
|
+
}
|
|
233
|
+
function requiredBinaryBody(id: string): BinaryBodyHandle {
|
|
234
|
+
const value = bindings.get(id);
|
|
235
|
+
if (!(value instanceof BinaryBodyHandle)) throw runtimeError('BINARY_INVALID_REF', 422);
|
|
236
|
+
return value;
|
|
237
|
+
}
|
|
238
|
+
function requiredIteration(id: string): {key: string; index: number; value: unknown} {
|
|
239
|
+
const value = iterations.get(id);
|
|
240
|
+
if (value === undefined) throw runtimeError('ITERATION_CONTEXT_REQUIRED', 422);
|
|
241
|
+
return value;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
class BinaryBodyHandle {
|
|
246
|
+
private consumed = false;
|
|
247
|
+
constructor(private readonly source: BinaryBodySource) {}
|
|
248
|
+
take(): BinaryBodySource {
|
|
249
|
+
if (this.consumed) throw runtimeError('BINARY_BODY_CONSUMED');
|
|
250
|
+
this.consumed = true;
|
|
251
|
+
return this.source;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
function requiredBinaryRef(value: unknown): BinaryRef {
|
|
255
|
+
if (typeof value !== 'object' || value === null || !('namespace' in value) || !('key' in value)) {
|
|
256
|
+
throw runtimeError('BINARY_INVALID_REF', 422);
|
|
257
|
+
}
|
|
258
|
+
return value as BinaryRef;
|
|
259
|
+
}
|
|
260
|
+
function requestBinary(c: any): BinaryBodySource {
|
|
261
|
+
const stream = c.req.raw.body as ReadableStream<Uint8Array> | null;
|
|
262
|
+
const chunks = stream === null ? emptyBinaryChunks() : readableChunks(stream);
|
|
263
|
+
const sizeText = c.req.header('content-length');
|
|
264
|
+
const size = sizeText === undefined ? undefined : Number(sizeText);
|
|
265
|
+
const contentType = c.req.header('content-type');
|
|
266
|
+
return {...(typeof size === 'number' && Number.isSafeInteger(size) && size >= 0 ? {size} : {}), ...(contentType === undefined ? {} : {contentType}), chunks};
|
|
267
|
+
}
|
|
268
|
+
function limitedBinarySource(source: BinaryBodySource, maximum: number): BinaryBodySource {
|
|
269
|
+
if (source.size !== undefined && source.size > maximum) throw runtimeError('BINARY_TOO_LARGE', 413);
|
|
270
|
+
return {...source, chunks: limitedChunks(source.chunks, maximum)};
|
|
271
|
+
}
|
|
272
|
+
async function* limitedChunks(chunks: AsyncIterable<Uint8Array>, maximum: number): AsyncIterable<Uint8Array> {
|
|
273
|
+
let size = 0;
|
|
274
|
+
for await (const chunk of chunks) {
|
|
275
|
+
size += chunk.byteLength;
|
|
276
|
+
if (size > maximum) throw runtimeError('BINARY_TOO_LARGE', 413);
|
|
277
|
+
yield chunk;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
async function* readableChunks(stream: ReadableStream<Uint8Array>): AsyncIterable<Uint8Array> {
|
|
281
|
+
const reader = stream.getReader();
|
|
282
|
+
try {while (true) {const item = await reader.read(); if (item.done) return; yield item.value;}}
|
|
283
|
+
finally {reader.releaseLock();}
|
|
284
|
+
}
|
|
285
|
+
async function* emptyBinaryChunks(): AsyncIterable<Uint8Array> {}
|
|
286
|
+
function binaryReadableStream(chunks: AsyncIterable<Uint8Array>): ReadableStream<Uint8Array> {
|
|
287
|
+
const iterator = chunks[Symbol.asyncIterator]();
|
|
288
|
+
return new ReadableStream<Uint8Array>({
|
|
289
|
+
async pull(controller) {const item = await iterator.next(); if (item.done) controller.close(); else controller.enqueue(item.value);},
|
|
290
|
+
cancel() {return iterator.return?.().then(() => undefined)}
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
function contentDisposition(value: {kind: 'inline'} | {kind: 'attachment'; filename: string}): string {
|
|
294
|
+
if (value.kind === 'inline') return 'inline';
|
|
295
|
+
if (/[\\r\\n\\0]/u.test(value.filename)) throw runtimeError('BINARY_INVALID_REF', 422);
|
|
296
|
+
return "attachment; filename*=UTF-8''" + encodeURIComponent(value.filename).replace(/['()*]/gu, (item) => '%' + item.codePointAt(0)!.toString(16).toUpperCase());
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
class IrRuntimeError extends Error {
|
|
300
|
+
constructor(readonly code: string, readonly status: number) {super(code)}
|
|
301
|
+
}
|
|
302
|
+
function runtimeError(code: string, status = 500): IrRuntimeError {return new IrRuntimeError(code, status)}
|
|
303
|
+
function runtimeFault(error: unknown): {code: string; status: number} {
|
|
304
|
+
if (error instanceof IrRuntimeError) return {code: error.code, status: error.status};
|
|
305
|
+
if (typeof error !== 'object' || error === null || !('code' in error) || typeof error.code !== 'string') {
|
|
306
|
+
return {code: 'IR_RUNTIME_ERROR', status: 500};
|
|
307
|
+
}
|
|
308
|
+
const status = KNOWN_RUNTIME_STATUS[error.code];
|
|
309
|
+
return status === undefined ? {code: 'IR_RUNTIME_ERROR', status: 500} : {code: error.code, status};
|
|
310
|
+
}
|
|
311
|
+
const KNOWN_RUNTIME_STATUS: Readonly<Record<string, number>> = {
|
|
312
|
+
INVALID_JSON: 422,
|
|
313
|
+
INVALID_PATH: 422,
|
|
314
|
+
PATH_NOT_FOUND: 422,
|
|
315
|
+
TYPE_MISMATCH: 422,
|
|
316
|
+
INDEX_OUT_OF_RANGE: 422,
|
|
317
|
+
ITERATION_LIMIT_EXCEEDED: 422,
|
|
318
|
+
ITERATION_CONTEXT_REQUIRED: 422,
|
|
319
|
+
KVS_NAMESPACE_INVALID: 422,
|
|
320
|
+
KVS_KEY_INVALID: 422,
|
|
321
|
+
KVS_STORAGE_FAILURE: 502,
|
|
322
|
+
BINARY_INVALID_REF: 422,
|
|
323
|
+
BINARY_NOT_FOUND: 404,
|
|
324
|
+
BINARY_TOO_LARGE: 413,
|
|
325
|
+
BINARY_INTEGRITY_MISMATCH: 502,
|
|
326
|
+
BINARY_BODY_CONSUMED: 500,
|
|
327
|
+
BINARY_STORAGE_FAILURE: 502
|
|
328
|
+
};
|
|
329
|
+
function asText(value: unknown): string {return typeof value === 'string' ? value : JSON.stringify(value)}
|
|
330
|
+
function scratchNumber(value: unknown): number {
|
|
331
|
+
const number = Number(value);
|
|
332
|
+
return Number.isNaN(number) ? 0 : number;
|
|
333
|
+
}
|
|
334
|
+
function setResponseHeader(headers: Headers, name: string, value: string): void {
|
|
335
|
+
if (!/[\\r\\n]/u.test(value)) headers.set(name, value);
|
|
336
|
+
}
|
|
337
|
+
type JsonValue = null | boolean | number | string | JsonValue[] | {[key: string]: JsonValue};
|
|
338
|
+
type PathSegment = {kind: 'key'; value: string} | {kind: 'index'; value: number};
|
|
339
|
+
function parseApplicationJson(text: unknown): JsonValue {
|
|
340
|
+
try {
|
|
341
|
+
const value: unknown = JSON.parse(String(text));
|
|
342
|
+
assertJsonValue(value);
|
|
343
|
+
return value;
|
|
344
|
+
} catch (error) {
|
|
345
|
+
if (error instanceof IrRuntimeError) throw error;
|
|
346
|
+
throw runtimeError('INVALID_JSON', 422);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
function stringifyApplicationJson(value: unknown): string {
|
|
350
|
+
assertJsonValue(value);
|
|
351
|
+
if (Array.isArray(value)) return '[' + value.map(stringifyApplicationJson).join(',') + ']';
|
|
352
|
+
if (isJsonObject(value)) {
|
|
353
|
+
return '{' + Object.keys(value).sort(compareCodePoints).map((key) => JSON.stringify(key) + ':' + stringifyApplicationJson(value[key])).join(',') + '}';
|
|
354
|
+
}
|
|
355
|
+
return JSON.stringify(value);
|
|
356
|
+
}
|
|
357
|
+
function getJsonAtPath(root: unknown, path: readonly PathSegment[]): JsonValue {
|
|
358
|
+
assertJsonValue(root);
|
|
359
|
+
let current = root;
|
|
360
|
+
for (const segment of path) current = readSegment(current, segment);
|
|
361
|
+
return current;
|
|
362
|
+
}
|
|
363
|
+
function hasJsonAtPath(root: unknown, path: readonly PathSegment[]): boolean {
|
|
364
|
+
try {getJsonAtPath(root, path); return true;}
|
|
365
|
+
catch (error) {
|
|
366
|
+
if (error instanceof IrRuntimeError && (error.code === 'PATH_NOT_FOUND' || error.code === 'INDEX_OUT_OF_RANGE')) return false;
|
|
367
|
+
throw error;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
function setJsonAtPath(root: unknown, path: readonly PathSegment[], replacement: unknown): JsonValue {
|
|
371
|
+
assertJsonValue(root);
|
|
372
|
+
assertJsonValue(replacement);
|
|
373
|
+
if (path.length === 0) return cloneJson(replacement);
|
|
374
|
+
return updateParent(root, path, (parent, segment) => {
|
|
375
|
+
if (segment.kind === 'key') {
|
|
376
|
+
if (!isJsonObject(parent)) throw runtimeError('TYPE_MISMATCH', 422);
|
|
377
|
+
return {...parent, [segment.value]: cloneJson(replacement)};
|
|
378
|
+
}
|
|
379
|
+
if (!Array.isArray(parent)) throw runtimeError('TYPE_MISMATCH', 422);
|
|
380
|
+
if (segment.value >= parent.length) throw runtimeError('INDEX_OUT_OF_RANGE', 422);
|
|
381
|
+
const result = parent.slice();
|
|
382
|
+
result[segment.value] = cloneJson(replacement);
|
|
383
|
+
return result;
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
function deleteJsonAtPath(root: unknown, path: readonly PathSegment[]): JsonValue {
|
|
387
|
+
assertJsonValue(root);
|
|
388
|
+
if (path.length === 0) throw runtimeError('INVALID_PATH', 422);
|
|
389
|
+
return updateParent(root, path, (parent, segment) => {
|
|
390
|
+
if (segment.kind === 'key') {
|
|
391
|
+
if (!isJsonObject(parent)) throw runtimeError('TYPE_MISMATCH', 422);
|
|
392
|
+
if (!hasOwn(parent, segment.value)) throw runtimeError('PATH_NOT_FOUND', 422);
|
|
393
|
+
const result = {...parent};
|
|
394
|
+
delete result[segment.value];
|
|
395
|
+
return result;
|
|
396
|
+
}
|
|
397
|
+
if (!Array.isArray(parent)) throw runtimeError('TYPE_MISMATCH', 422);
|
|
398
|
+
if (segment.value >= parent.length) throw runtimeError('INDEX_OUT_OF_RANGE', 422);
|
|
399
|
+
const result = parent.slice();
|
|
400
|
+
result.splice(segment.value, 1);
|
|
401
|
+
return result;
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
function jsonKeysAtPath(root: unknown, path: readonly PathSegment[]): string[] {
|
|
405
|
+
const value = getJsonAtPath(root, path);
|
|
406
|
+
if (!isJsonObject(value)) throw runtimeError('TYPE_MISMATCH', 422);
|
|
407
|
+
return Object.keys(value).sort(compareCodePoints);
|
|
408
|
+
}
|
|
409
|
+
function jsonLengthAtPath(root: unknown, path: readonly PathSegment[]): number {
|
|
410
|
+
const value = getJsonAtPath(root, path);
|
|
411
|
+
if (!Array.isArray(value)) throw runtimeError('TYPE_MISMATCH', 422);
|
|
412
|
+
return value.length;
|
|
413
|
+
}
|
|
414
|
+
function structuredIterationEntries(root: unknown, path: readonly PathSegment[], maximum: number): Array<{key: string; index: number; value: JsonValue}> {
|
|
415
|
+
const value = getJsonAtPath(root, path);
|
|
416
|
+
const entries = Array.isArray(value)
|
|
417
|
+
? value.map((item, index) => ({key: String(index), index, value: item}))
|
|
418
|
+
: isJsonObject(value)
|
|
419
|
+
? Object.keys(value).sort(compareCodePoints).map((key, index) => ({key, index, value: value[key]}))
|
|
420
|
+
: (() => {throw runtimeError('TYPE_MISMATCH', 422)})();
|
|
421
|
+
if (entries.length > maximum) throw runtimeError('ITERATION_LIMIT_EXCEEDED', 422);
|
|
422
|
+
return entries;
|
|
423
|
+
}
|
|
424
|
+
function updateParent(root: JsonValue, path: readonly PathSegment[], update: (parent: JsonValue, segment: PathSegment) => JsonValue): JsonValue {
|
|
425
|
+
const [segment, ...remaining] = path;
|
|
426
|
+
if (segment === undefined) return root;
|
|
427
|
+
if (remaining.length === 0) return update(root, segment);
|
|
428
|
+
const next = updateParent(readSegment(root, segment), remaining, update);
|
|
429
|
+
if (segment.kind === 'key') {
|
|
430
|
+
if (!isJsonObject(root)) throw runtimeError('TYPE_MISMATCH', 422);
|
|
431
|
+
return {...root, [segment.value]: next};
|
|
432
|
+
}
|
|
433
|
+
if (!Array.isArray(root)) throw runtimeError('TYPE_MISMATCH', 422);
|
|
434
|
+
const result = root.slice();
|
|
435
|
+
result[segment.value] = next;
|
|
436
|
+
return result;
|
|
437
|
+
}
|
|
438
|
+
function readSegment(value: JsonValue, segment: PathSegment): JsonValue {
|
|
439
|
+
if (segment.kind === 'key') {
|
|
440
|
+
if (!isJsonObject(value)) throw runtimeError('TYPE_MISMATCH', 422);
|
|
441
|
+
if (!hasOwn(value, segment.value)) throw runtimeError('PATH_NOT_FOUND', 422);
|
|
442
|
+
return value[segment.value];
|
|
443
|
+
}
|
|
444
|
+
if (!Array.isArray(value)) throw runtimeError('TYPE_MISMATCH', 422);
|
|
445
|
+
if (segment.value >= value.length) throw runtimeError('INDEX_OUT_OF_RANGE', 422);
|
|
446
|
+
return value[segment.value];
|
|
447
|
+
}
|
|
448
|
+
function cloneJson(value: JsonValue): JsonValue {
|
|
449
|
+
if (Array.isArray(value)) return value.map(cloneJson);
|
|
450
|
+
if (isJsonObject(value)) return Object.fromEntries(Object.keys(value).map((key) => [key, cloneJson(value[key])]));
|
|
451
|
+
return value;
|
|
452
|
+
}
|
|
453
|
+
function assertJsonValue(value: unknown): asserts value is JsonValue {
|
|
454
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return;
|
|
455
|
+
if (typeof value === 'number' && Number.isFinite(value)) return;
|
|
456
|
+
if (Array.isArray(value)) {for (const item of value) assertJsonValue(item); return;}
|
|
457
|
+
if (typeof value === 'object') {for (const item of Object.values(value)) assertJsonValue(item); return;}
|
|
458
|
+
throw runtimeError('INVALID_JSON', 422);
|
|
459
|
+
}
|
|
460
|
+
function isJsonObject(value: JsonValue): value is {[key: string]: JsonValue} {
|
|
461
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
462
|
+
}
|
|
463
|
+
function hasOwn(value: object, key: PropertyKey): boolean {return Object.prototype.hasOwnProperty.call(value, key)}
|
|
464
|
+
function compareCodePoints(left: string, right: string): number {
|
|
465
|
+
const leftPoints = Array.from(left, (item) => item.codePointAt(0)!);
|
|
466
|
+
const rightPoints = Array.from(right, (item) => item.codePointAt(0)!);
|
|
467
|
+
for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index += 1) {
|
|
468
|
+
const difference = leftPoints[index]! - rightPoints[index]!;
|
|
469
|
+
if (difference !== 0) return difference;
|
|
470
|
+
}
|
|
471
|
+
return leftPoints.length - rightPoints.length;
|
|
472
|
+
}
|
|
473
|
+
function response(format: 'text' | 'html' | 'json', valueType: unknown, value: unknown, status: number, headers: Headers): Response {
|
|
474
|
+
if (!headers.has('content-type')) headers.set('content-type', format === 'json' ? 'application/json; charset=utf-8' : format === 'html' ? 'text/html; charset=utf-8' : 'text/plain; charset=utf-8');
|
|
475
|
+
let body = asText(value);
|
|
476
|
+
if (format === 'json') {
|
|
477
|
+
if (valueType === 'json-text') body = asText(value);
|
|
478
|
+
else if (valueType === 'string') {
|
|
479
|
+
try {body = stringifyApplicationJson(JSON.parse(asText(value)));}
|
|
480
|
+
catch {throw runtimeError('IR_INVALID_JSON_RESPONSE');}
|
|
481
|
+
} else body = stringifyApplicationJson(value);
|
|
482
|
+
}
|
|
483
|
+
return new Response(body, {status, headers});
|
|
484
|
+
}
|
|
485
|
+
`;
|
|
486
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type {PlatformAdapter} from './types.js';
|
|
2
|
+
|
|
3
|
+
export class PlatformAdapterRegistry {
|
|
4
|
+
private readonly adapters = new Map<string, PlatformAdapter>();
|
|
5
|
+
|
|
6
|
+
public register(adapter: PlatformAdapter): void {
|
|
7
|
+
if (this.adapters.has(adapter.id)) throw new Error(`Duplicate platform adapter: ${adapter.id}`);
|
|
8
|
+
this.adapters.set(adapter.id, adapter);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
public resolve(id: string): PlatformAdapter | undefined {
|
|
12
|
+
return this.adapters.get(id);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
public ids(): string[] {
|
|
16
|
+
return [...this.adapters.keys()].sort();
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CapabilityRequirementV2,
|
|
3
|
+
DeployIrV2,
|
|
4
|
+
ExpressionIrV2,
|
|
5
|
+
SourceRefV2,
|
|
6
|
+
StatementIrV2
|
|
7
|
+
} from '../ir-v2/types.js';
|
|
8
|
+
import type {CapabilityRequirements} from './types.js';
|
|
9
|
+
|
|
10
|
+
export interface CapabilityOrigin {
|
|
11
|
+
routeId: string;
|
|
12
|
+
sourceRef?: SourceRefV2;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type LocatedNode = {sourceRef?: SourceRefV2};
|
|
16
|
+
|
|
17
|
+
export function extractCapabilityRequirements(ir: DeployIrV2): CapabilityRequirements {
|
|
18
|
+
return {keys: [...new Set(ir.capabilities.map(capabilityKey))].sort()};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function capabilityKey(capability: CapabilityRequirementV2): string {
|
|
22
|
+
if (capability.kind === 'auth') return `auth:${capability.scheme}`;
|
|
23
|
+
if (capability.kind === 'request-metadata') return `request-metadata:${capability.field}`;
|
|
24
|
+
return capability.kind;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function findCapabilityOrigin(ir: DeployIrV2, key: string): CapabilityOrigin | undefined {
|
|
28
|
+
for (const route of ir.routes) {
|
|
29
|
+
const located = findInStatements(route.body, key);
|
|
30
|
+
if (located !== undefined) {
|
|
31
|
+
return {...(located.sourceRef === undefined ? {} : {sourceRef: located.sourceRef}), routeId: route.id};
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const fallback = ir.routes[0];
|
|
35
|
+
if (fallback === undefined) return undefined;
|
|
36
|
+
return {...(fallback.sourceRef === undefined ? {} : {sourceRef: fallback.sourceRef}), routeId: fallback.id};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function findInStatements(statements: readonly StatementIrV2[], key: string): LocatedNode | undefined {
|
|
40
|
+
for (const statement of statements) {
|
|
41
|
+
if (statementRequires(statement, key)) {
|
|
42
|
+
return statement.sourceRef === undefined ? {} : {sourceRef: statement.sourceRef};
|
|
43
|
+
}
|
|
44
|
+
for (const expression of statementExpressions(statement)) {
|
|
45
|
+
const located = findInExpression(expression, key);
|
|
46
|
+
if (located !== undefined) return located;
|
|
47
|
+
}
|
|
48
|
+
if (statement.kind === 'if') {
|
|
49
|
+
const nested = findInStatements([...statement.then, ...(statement.else ?? [])], key);
|
|
50
|
+
if (nested !== undefined) return nested;
|
|
51
|
+
} else if (statement.kind === 'bounded-loop' || statement.kind === 'json-for-each') {
|
|
52
|
+
const nested = findInStatements(statement.body, key);
|
|
53
|
+
if (nested !== undefined) return nested;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function statementRequires(statement: StatementIrV2, key: string): boolean {
|
|
60
|
+
if (key === 'record-store') return statement.kind.startsWith('record-');
|
|
61
|
+
if (key === 'key-value-store') return statement.kind.startsWith('kvs-');
|
|
62
|
+
if (key === 'object-storage') return statement.kind.startsWith('asset-');
|
|
63
|
+
if (key === 'named-body-provider') return statement.kind === 'respond-named-body';
|
|
64
|
+
if (key === 'streaming-body') {
|
|
65
|
+
return (
|
|
66
|
+
statement.kind === 'request-body-binary' ||
|
|
67
|
+
statement.kind === 'asset-object-get' ||
|
|
68
|
+
statement.kind === 'respond-binary'
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function statementExpressions(statement: StatementIrV2): ExpressionIrV2[] {
|
|
75
|
+
if (statement.kind === 'set-header') return [statement.value];
|
|
76
|
+
if (statement.kind === 'set-handler-variable' || statement.kind === 'change-handler-variable') {
|
|
77
|
+
return [statement.name, statement.value];
|
|
78
|
+
}
|
|
79
|
+
if (statement.kind === 'delete-handler-variable') return [statement.name];
|
|
80
|
+
if (statement.kind === 'kvs-set-text') return [statement.namespace, statement.key, statement.value];
|
|
81
|
+
if (statement.kind === 'kvs-delete') return [statement.namespace, statement.key];
|
|
82
|
+
if (statement.kind === 'record-create') return [statement.data];
|
|
83
|
+
if (statement.kind === 'record-get' || statement.kind === 'record-delete') return [statement.id];
|
|
84
|
+
if (statement.kind === 'asset-object-get') return [statement.ref];
|
|
85
|
+
if (statement.kind === 'asset-object-delete' && statement.target.kind === 'ref') return [statement.target.ref];
|
|
86
|
+
if (statement.kind === 'if') return [statement.condition];
|
|
87
|
+
if (statement.kind === 'json-for-each') return [statement.root];
|
|
88
|
+
if (statement.kind === 'respond') return [statement.body];
|
|
89
|
+
return [];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function findInExpression(expression: ExpressionIrV2, key: string): LocatedNode | undefined {
|
|
93
|
+
if (
|
|
94
|
+
key === 'request-metadata:client-address' &&
|
|
95
|
+
expression.kind === 'request' &&
|
|
96
|
+
expression.source === 'client-address'
|
|
97
|
+
) {
|
|
98
|
+
return expression.sourceRef === undefined ? {} : {sourceRef: expression.sourceRef};
|
|
99
|
+
}
|
|
100
|
+
if (
|
|
101
|
+
key === 'key-value-store' &&
|
|
102
|
+
(expression.kind === 'kvs-get-text' || expression.kind === 'kvs-has' || expression.kind === 'kvs-list-keys')
|
|
103
|
+
) {
|
|
104
|
+
return expression.sourceRef === undefined ? {} : {sourceRef: expression.sourceRef};
|
|
105
|
+
}
|
|
106
|
+
for (const child of childExpressions(expression)) {
|
|
107
|
+
const located = findInExpression(child, key);
|
|
108
|
+
if (located !== undefined) return located;
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function childExpressions(expression: ExpressionIrV2): ExpressionIrV2[] {
|
|
114
|
+
if (expression.kind === 'concat') return [expression.left, expression.right];
|
|
115
|
+
if (
|
|
116
|
+
expression.kind === 'handler-variable' ||
|
|
117
|
+
expression.kind === 'handler-variable-exists' ||
|
|
118
|
+
expression.kind === 'json-text-coerce'
|
|
119
|
+
) {
|
|
120
|
+
return [expression.kind === 'json-text-coerce' ? expression.input : expression.name];
|
|
121
|
+
}
|
|
122
|
+
if (expression.kind === 'json-parse' || expression.kind === 'json-is-valid') return [expression.text];
|
|
123
|
+
if (expression.kind === 'json-stringify') return [expression.value];
|
|
124
|
+
if (
|
|
125
|
+
expression.kind === 'json-get' ||
|
|
126
|
+
expression.kind === 'json-has' ||
|
|
127
|
+
expression.kind === 'json-delete' ||
|
|
128
|
+
expression.kind === 'json-keys' ||
|
|
129
|
+
expression.kind === 'json-length'
|
|
130
|
+
) {
|
|
131
|
+
return [expression.root];
|
|
132
|
+
}
|
|
133
|
+
if (expression.kind === 'json-set') return [expression.root, expression.value];
|
|
134
|
+
if (expression.kind === 'kvs-get-text' || expression.kind === 'kvs-has') {
|
|
135
|
+
return [expression.namespace, expression.key];
|
|
136
|
+
}
|
|
137
|
+
if (expression.kind === 'kvs-list-keys') return [expression.namespace];
|
|
138
|
+
return [];
|
|
139
|
+
}
|