@madebyentropy/tnl 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +28 -0
- package/NOTICE +5 -0
- package/THIRD_PARTY_LICENSES.txt +3297 -0
- package/dist/adapters/ioredis.d.ts +7 -0
- package/dist/adapters/ioredis.js +87 -0
- package/dist/adapters/node-postgres.d.ts +8 -0
- package/dist/adapters/node-postgres.js +41 -0
- package/dist/adapters/postgres-js.d.ts +7 -0
- package/dist/adapters/postgres-js.js +55 -0
- package/dist/bin/tnl.d.ts +2 -0
- package/dist/bin/tnl.js +16 -0
- package/dist/browser.d.ts +18 -0
- package/dist/browser.js +43 -0
- package/dist/bun.d.ts +9 -0
- package/dist/bun.js +6 -0
- package/dist/cloudflare.d.ts +9 -0
- package/dist/cloudflare.js +16 -0
- package/dist/config.d.ts +107 -0
- package/dist/config.gen.d.ts +1185 -0
- package/dist/config.gen.js +2 -0
- package/dist/config.js +3 -0
- package/dist/control.d.ts +5 -0
- package/dist/control.js +9 -0
- package/dist/durable-object.d.ts +51 -0
- package/dist/durable-object.js +374 -0
- package/dist/durable-object.worker.d.ts +5 -0
- package/dist/durable-object.worker.js +11 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +230 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +2 -0
- package/dist/internal/connector/cancellation.d.ts +7 -0
- package/dist/internal/connector/cancellation.js +30 -0
- package/dist/internal/connector/client.d.ts +62 -0
- package/dist/internal/connector/client.js +504 -0
- package/dist/internal/connector/client_factory.d.ts +6 -0
- package/dist/internal/connector/client_factory.js +123 -0
- package/dist/internal/connector/connection.d.ts +39 -0
- package/dist/internal/connector/connection.js +739 -0
- package/dist/internal/connector/connection_ipc.d.ts +12 -0
- package/dist/internal/connector/connection_ipc.js +198 -0
- package/dist/internal/connector/context.d.ts +28 -0
- package/dist/internal/connector/context.js +19 -0
- package/dist/internal/connector/contract.d.ts +392 -0
- package/dist/internal/connector/contract.js +56 -0
- package/dist/internal/connector/deployment_types.d.ts +27 -0
- package/dist/internal/connector/deployment_types.js +1 -0
- package/dist/internal/connector/driver_socket.d.ts +21 -0
- package/dist/internal/connector/driver_socket.js +129 -0
- package/dist/internal/connector/management.d.ts +29 -0
- package/dist/internal/connector/management.js +118 -0
- package/dist/internal/connector/native_operations.d.ts +16 -0
- package/dist/internal/connector/native_operations.js +30 -0
- package/dist/internal/connector/native_stream.d.ts +7 -0
- package/dist/internal/connector/native_stream.js +219 -0
- package/dist/internal/connector/operation_handles.d.ts +9 -0
- package/dist/internal/connector/operation_handles.js +18 -0
- package/dist/internal/connector/portable_operations.d.ts +13 -0
- package/dist/internal/connector/portable_operations.js +25 -0
- package/dist/internal/connector/snapshot.d.ts +183 -0
- package/dist/internal/connector/snapshot.js +47 -0
- package/dist/internal/connector/wasm_abi.d.ts +76 -0
- package/dist/internal/connector/wasm_abi.js +5 -0
- package/dist/internal/connector/wasm_client.d.ts +58 -0
- package/dist/internal/connector/wasm_client.js +545 -0
- package/dist/internal/connector/wasm_loader.d.ts +15 -0
- package/dist/internal/connector/wasm_loader.js +99 -0
- package/dist/internal/connector/wasm_stream.d.ts +4 -0
- package/dist/internal/connector/wasm_stream.js +177 -0
- package/dist/internal/connector/workload/contract.d.ts +54 -0
- package/dist/internal/connector/workload/contract.js +14 -0
- package/dist/internal/connector/workload/provider.d.ts +24 -0
- package/dist/internal/connector/workload/provider.js +130 -0
- package/dist/internal/enrollment_source.d.ts +4 -0
- package/dist/internal/enrollment_source.js +34 -0
- package/dist/internal/management/client/client.gen.d.ts +2 -0
- package/dist/internal/management/client/client.gen.js +216 -0
- package/dist/internal/management/client/index.d.ts +10 -0
- package/dist/internal/management/client/index.js +6 -0
- package/dist/internal/management/client/types.gen.d.ts +120 -0
- package/dist/internal/management/client/types.gen.js +2 -0
- package/dist/internal/management/client/utils.gen.d.ts +37 -0
- package/dist/internal/management/client/utils.gen.js +228 -0
- package/dist/internal/management/client.gen.d.ts +12 -0
- package/dist/internal/management/client.gen.js +3 -0
- package/dist/internal/management/core/auth.gen.d.ts +25 -0
- package/dist/internal/management/core/auth.gen.js +14 -0
- package/dist/internal/management/core/bodySerializer.gen.d.ts +25 -0
- package/dist/internal/management/core/bodySerializer.gen.js +57 -0
- package/dist/internal/management/core/params.gen.d.ts +43 -0
- package/dist/internal/management/core/params.gen.js +109 -0
- package/dist/internal/management/core/pathSerializer.gen.d.ts +33 -0
- package/dist/internal/management/core/pathSerializer.gen.js +106 -0
- package/dist/internal/management/core/queryKeySerializer.gen.d.ts +18 -0
- package/dist/internal/management/core/queryKeySerializer.gen.js +92 -0
- package/dist/internal/management/core/serverSentEvents.gen.d.ts +71 -0
- package/dist/internal/management/core/serverSentEvents.gen.js +132 -0
- package/dist/internal/management/core/types.gen.d.ts +83 -0
- package/dist/internal/management/core/types.gen.js +2 -0
- package/dist/internal/management/core/utils.gen.d.ts +19 -0
- package/dist/internal/management/core/utils.gen.js +87 -0
- package/dist/internal/management/index.d.ts +2 -0
- package/dist/internal/management/index.js +2 -0
- package/dist/internal/management/sdk.gen.d.ts +73 -0
- package/dist/internal/management/sdk.gen.js +191 -0
- package/dist/internal/management/types.gen.d.ts +464 -0
- package/dist/internal/management/types.gen.js +2 -0
- package/dist/internal/management/zod.gen.d.ts +850 -0
- package/dist/internal/management/zod.gen.js +252 -0
- package/dist/internal/native/launcher.d.ts +8 -0
- package/dist/internal/native/launcher.js +75 -0
- package/dist/internal/native/native-targets.d.ts +9 -0
- package/dist/internal/native/native-targets.js +8 -0
- package/dist/internal/portable/cloudflare-publisher-client.d.ts +54 -0
- package/dist/internal/portable/cloudflare-publisher-client.js +91 -0
- package/dist/internal/portable/cloudflare-publisher.d.ts +19 -0
- package/dist/internal/portable/cloudflare-publisher.js +210 -0
- package/dist/internal/portable/durable-deployment.d.ts +10 -0
- package/dist/internal/portable/durable-deployment.js +22 -0
- package/dist/internal/portable/enrollment.d.ts +26 -0
- package/dist/internal/portable/enrollment.js +196 -0
- package/dist/internal/portable/publication.d.ts +54 -0
- package/dist/internal/portable/publication.js +304 -0
- package/dist/internal/portable/request.d.ts +1 -0
- package/dist/internal/portable/request.js +20 -0
- package/dist/internal/portable/storage-browser.d.ts +9 -0
- package/dist/internal/portable/storage-browser.js +115 -0
- package/dist/internal/portable/storage-durable-object.d.ts +11 -0
- package/dist/internal/portable/storage-durable-object.js +110 -0
- package/dist/internal/portable/storage-host.d.ts +8 -0
- package/dist/internal/portable/storage-host.js +142 -0
- package/dist/internal/portable/storage.d.ts +15 -0
- package/dist/internal/portable/storage.js +29 -0
- package/dist/internal/project/native_runtime.d.ts +24 -0
- package/dist/internal/project/native_runtime.js +23 -0
- package/dist/internal/project/runtime.d.ts +467 -0
- package/dist/internal/project/runtime.js +183 -0
- package/dist/internal/project/service_metadata.d.ts +3 -0
- package/dist/internal/project/service_metadata.js +12 -0
- package/dist/internal/publication_certificate.d.ts +28 -0
- package/dist/internal/publication_certificate.js +32 -0
- package/dist/internal/publication_run.d.ts +8 -0
- package/dist/internal/publication_run.js +19 -0
- package/dist/internal/publisher/app.d.ts +33 -0
- package/dist/internal/publisher/app.js +317 -0
- package/dist/internal/publisher/fetch.d.ts +6 -0
- package/dist/internal/publisher/fetch.js +135 -0
- package/dist/internal/publisher/fetch_types.d.ts +1 -0
- package/dist/internal/publisher/fetch_types.js +1 -0
- package/dist/internal/publisher/framework.d.ts +27 -0
- package/dist/internal/publisher/framework.js +82 -0
- package/dist/internal/publisher/local.d.ts +39 -0
- package/dist/internal/publisher/local.js +312 -0
- package/dist/internal/publisher/native_publisher.d.ts +25 -0
- package/dist/internal/publisher/native_publisher.js +228 -0
- package/dist/internal/publisher/port.d.ts +2 -0
- package/dist/internal/publisher/port.js +15 -0
- package/dist/internal/publisher/publication.d.ts +88 -0
- package/dist/internal/publisher/publication.js +627 -0
- package/dist/internal/publisher/register.d.ts +31 -0
- package/dist/internal/publisher/register.js +136 -0
- package/dist/internal/publisher/registration.d.ts +385 -0
- package/dist/internal/publisher/registration.js +223 -0
- package/dist/internal/publisher/status.d.ts +47 -0
- package/dist/internal/publisher/status.js +137 -0
- package/dist/internal/publisher/target.d.ts +6 -0
- package/dist/internal/publisher/target.js +44 -0
- package/dist/internal/runtime_resources.d.ts +38 -0
- package/dist/internal/runtime_resources.js +52 -0
- package/dist/internal/tracing.d.ts +10 -0
- package/dist/internal/tracing.js +78 -0
- package/dist/internal/validation.d.ts +3 -0
- package/dist/internal/validation.js +9 -0
- package/dist/internal/values.d.ts +27 -0
- package/dist/internal/values.js +54 -0
- package/dist/next.d.ts +12 -0
- package/dist/next.js +82 -0
- package/dist/node.d.ts +9 -0
- package/dist/node.js +6 -0
- package/dist/project.d.ts +173 -0
- package/dist/project.js +1 -0
- package/dist/response.d.ts +1 -0
- package/dist/response.js +34 -0
- package/dist/third-party-licenses.txt +1537 -0
- package/dist/vite.d.ts +5 -0
- package/dist/vite.js +200 -0
- package/dist/wasm/build.json +16 -0
- package/dist/wasm/connector.wasm +0 -0
- package/dist/wasm/go-license.txt +27 -0
- package/dist/wasm/publisher.wasm +0 -0
- package/dist/wasm/third-party-licenses.txt +3297 -0
- package/dist/wasm/wasm_exec.d.ts +1 -0
- package/dist/wasm/wasm_exec.js +575 -0
- package/dist/workload.d.ts +11 -0
- package/dist/workload.js +4 -0
- package/package.json +159 -4
- package/readme.md +13 -0
- package/README.md +0 -3
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
export interface ServiceCertificate {
|
|
3
|
+
readonly certificatePEM: string;
|
|
4
|
+
readonly privateKeyPEM: string;
|
|
5
|
+
}
|
|
6
|
+
/** polled during publication; honor the signal and return replacement material before expiry. */
|
|
7
|
+
export type ServiceCertificateSource = ServiceCertificate | ((signal: AbortSignal) => ServiceCertificate | Promise<ServiceCertificate>);
|
|
8
|
+
export declare const serviceCertificateSchema: z.ZodReadonly<z.ZodObject<{
|
|
9
|
+
certificatePEM: z.ZodString;
|
|
10
|
+
privateKeyPEM: z.ZodString;
|
|
11
|
+
}, z.core.$strict>>;
|
|
12
|
+
export interface ExportedCertificate {
|
|
13
|
+
readonly certificate: ServiceCertificate;
|
|
14
|
+
/** the installed certificate's validity deadline in Unix milliseconds. */
|
|
15
|
+
readonly expiresAt: number;
|
|
16
|
+
}
|
|
17
|
+
export declare const exportedCertificateSchema: z.ZodReadonly<z.ZodObject<{
|
|
18
|
+
certificate: z.ZodReadonly<z.ZodObject<{
|
|
19
|
+
certificatePEM: z.ZodString;
|
|
20
|
+
privateKeyPEM: z.ZodString;
|
|
21
|
+
}, z.core.$strict>>;
|
|
22
|
+
expiresAt: z.ZodInt;
|
|
23
|
+
}, z.core.$strict>>;
|
|
24
|
+
export declare const serviceCertificateSourceSchema: z.ZodUnion<readonly [z.ZodReadonly<z.ZodObject<{
|
|
25
|
+
certificatePEM: z.ZodString;
|
|
26
|
+
privateKeyPEM: z.ZodString;
|
|
27
|
+
}, z.core.$strict>>, z.ZodCustom<(signal: AbortSignal) => ServiceCertificate | Promise<ServiceCertificate>, (signal: AbortSignal) => ServiceCertificate | Promise<ServiceCertificate>>]>;
|
|
28
|
+
export declare function resolveServiceCertificate(source: ServiceCertificateSource, signal: AbortSignal): Promise<ServiceCertificate>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { TnlError } from "../errors.js";
|
|
3
|
+
export const serviceCertificateSchema = z
|
|
4
|
+
.strictObject({
|
|
5
|
+
certificatePEM: z.string().min(1).max(131072),
|
|
6
|
+
privateKeyPEM: z.string().min(1).max(16384),
|
|
7
|
+
})
|
|
8
|
+
.readonly();
|
|
9
|
+
export const exportedCertificateSchema = z
|
|
10
|
+
.strictObject({
|
|
11
|
+
certificate: serviceCertificateSchema,
|
|
12
|
+
expiresAt: z.int().positive(),
|
|
13
|
+
})
|
|
14
|
+
.readonly();
|
|
15
|
+
export const serviceCertificateSourceSchema = z.union([
|
|
16
|
+
serviceCertificateSchema,
|
|
17
|
+
z.custom((value) => typeof value === "function"),
|
|
18
|
+
]);
|
|
19
|
+
export async function resolveServiceCertificate(source, signal) {
|
|
20
|
+
try {
|
|
21
|
+
signal.throwIfAborted();
|
|
22
|
+
const result = serviceCertificateSchema.parse(typeof source === "function" ? await source(signal) : source);
|
|
23
|
+
signal.throwIfAborted();
|
|
24
|
+
return Object.freeze(result);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
if (signal.aborted)
|
|
28
|
+
throw new DOMException("publication canceled", "AbortError");
|
|
29
|
+
// provider exceptions and parser diagnostics may contain private key bytes.
|
|
30
|
+
throw new TnlError("sdk.certificate_invalid");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
export declare const publicationRunSchema: z.ZodObject<{
|
|
3
|
+
serviceID: z.core.$ZodBranded<z.ZodTemplateLiteral<`svc_${string}`>, "ServiceID", "out">;
|
|
4
|
+
serviceRunID: z.ZodString;
|
|
5
|
+
runNumber: z.ZodString;
|
|
6
|
+
}, z.core.$strict>;
|
|
7
|
+
export type PublicationRun = Readonly<z.output<typeof publicationRunSchema>>;
|
|
8
|
+
export declare const publisherURLSchema: z.ZodTemplateLiteral<`https://${string}`>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { hostnameSchema, httpsOriginSchema, serviceIDSchema } from "./values.js";
|
|
3
|
+
export const publicationRunSchema = z.strictObject({
|
|
4
|
+
serviceID: serviceIDSchema,
|
|
5
|
+
serviceRunID: z.string().regex(/^srun_[A-Za-z0-9]{22}$/),
|
|
6
|
+
// preserve the exact counter without JavaScript number rounding.
|
|
7
|
+
runNumber: z
|
|
8
|
+
.string()
|
|
9
|
+
.max(19)
|
|
10
|
+
.regex(/^[1-9][0-9]*$/)
|
|
11
|
+
.refine((value) => value.length < 19 || value <= "9223372036854775807"),
|
|
12
|
+
});
|
|
13
|
+
export const publisherURLSchema = httpsOriginSchema.refine((url) => {
|
|
14
|
+
const hostname = URL.parse(url)?.hostname;
|
|
15
|
+
return (typeof hostname === "string" &&
|
|
16
|
+
/^p-[a-z2-7]{26}\./.test(hostname) &&
|
|
17
|
+
hostnameSchema.safeParse(hostname).success &&
|
|
18
|
+
url === `https://${hostname}`);
|
|
19
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { type LocalHTTPServer } from "./register.js";
|
|
3
|
+
import type { ProjectRuntime } from "../project/runtime.js";
|
|
4
|
+
import { type RegistrationRuntime } from "./registration.js";
|
|
5
|
+
export { startRuntime, runtimeRequest } from "./local.js";
|
|
6
|
+
export declare const prepareOptionsSchema: z.ZodObject<{
|
|
7
|
+
service: z.ZodExactOptional<z.ZodString>;
|
|
8
|
+
directory: z.ZodExactOptional<z.ZodString>;
|
|
9
|
+
stateDir: z.ZodExactOptional<z.ZodString>;
|
|
10
|
+
telemetry: z.ZodExactOptional<z.ZodBoolean>;
|
|
11
|
+
}, z.core.$strict>;
|
|
12
|
+
export type PrepareOptions = Readonly<z.output<typeof prepareOptionsSchema>>;
|
|
13
|
+
export interface PreparedService extends ProjectRuntime {
|
|
14
|
+
readonly service: string;
|
|
15
|
+
readonly hostname: string | undefined;
|
|
16
|
+
readonly publicURL: `https://${string}` | undefined;
|
|
17
|
+
/** acknowledges a bound listener; use tnl wait for public readiness. */
|
|
18
|
+
register(server: LocalHTTPServer, signal?: AbortSignal): Promise<void>;
|
|
19
|
+
/** unregisters publication without stopping the application listener. */
|
|
20
|
+
close(signal?: AbortSignal): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
type Dependencies = RegistrationRuntime;
|
|
23
|
+
interface AppRegistry {
|
|
24
|
+
readonly preparations: Map<string, Promise<PreparedService>>;
|
|
25
|
+
readonly frameworkTargets: WeakMap<PreparedService, (target: `http://${string}`, signal?: AbortSignal) => Promise<void>>;
|
|
26
|
+
}
|
|
27
|
+
declare global {
|
|
28
|
+
var __tnlAppRegistry: AppRegistry | undefined;
|
|
29
|
+
}
|
|
30
|
+
export declare function reportFrameworkTarget(handle: PreparedService, target: `http://${string}`, signal?: AbortSignal): Promise<void>;
|
|
31
|
+
type Framework = "node" | "bun" | "vite" | "next";
|
|
32
|
+
export declare function prepareService(options?: PrepareOptions, framework?: Framework, signal?: AbortSignal): Promise<PreparedService>;
|
|
33
|
+
export declare function createPreparedService(options: PrepareOptions, framework: Framework, dependencies: Dependencies, onClose?: () => void, signal?: AbortSignal): Promise<PreparedService>;
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { TnlCleanupError, TnlError } from "../../errors.js";
|
|
4
|
+
import * as z from "zod";
|
|
5
|
+
import { parseValue } from "../validation.js";
|
|
6
|
+
import { pathTextSchema, serviceNameSchema } from "../values.js";
|
|
7
|
+
import { operation, independent, scheduled, bound as observeBound } from "../tracing.js";
|
|
8
|
+
import { canonicalLoopbackTarget } from "./target.js";
|
|
9
|
+
import { startRuntime, runtimeRequest, canceledRuntimeRequest } from "./local.js";
|
|
10
|
+
import { listeningTarget, isBunServer, observeListenerClose, } from "./register.js";
|
|
11
|
+
import { NativeRegistration, recoverableRegistration as recoverable, } from "./registration.js";
|
|
12
|
+
export { startRuntime, runtimeRequest } from "./local.js";
|
|
13
|
+
export const prepareOptionsSchema = z.strictObject({
|
|
14
|
+
service: serviceNameSchema.exactOptional(),
|
|
15
|
+
directory: pathTextSchema.exactOptional(),
|
|
16
|
+
stateDir: pathTextSchema.exactOptional(),
|
|
17
|
+
telemetry: z.boolean().exactOptional(),
|
|
18
|
+
});
|
|
19
|
+
const defaultDependencies = { start: startRuntime, request: runtimeRequest };
|
|
20
|
+
function telemetryDisabled(options) {
|
|
21
|
+
return options.telemetry === false || /^(1|true)$/i.test(process.env.TNL_NO_TELEMETRY ?? "");
|
|
22
|
+
}
|
|
23
|
+
// independently loaded SDK copies must recognize the same prepared handles.
|
|
24
|
+
const registry = (globalThis.__tnlAppRegistry ??= {
|
|
25
|
+
preparations: new Map(),
|
|
26
|
+
frameworkTargets: new WeakMap(),
|
|
27
|
+
});
|
|
28
|
+
export function reportFrameworkTarget(handle, target, signal) {
|
|
29
|
+
const report = registry.frameworkTargets.get(handle);
|
|
30
|
+
if (report === undefined)
|
|
31
|
+
throw new TnlError("sdk.configuration_invalid");
|
|
32
|
+
return report(target, signal);
|
|
33
|
+
}
|
|
34
|
+
export function prepareService(options = {}, framework = "node", signal) {
|
|
35
|
+
validateOptions(options);
|
|
36
|
+
const directory = path.resolve(options.directory ?? process.cwd());
|
|
37
|
+
const key = `${directory}\0${options.service ?? ""}\0${options.stateDir ?? process.env.TNL_STATE_DIR ?? ""}\0${process.env.TNL_APP_ENDPOINT ?? ""}\0${framework}\0${telemetryDisabled(options)}\0${signal === undefined ? "required" : "optional"}`;
|
|
38
|
+
const existing = registry.preparations.get(key);
|
|
39
|
+
if (existing !== undefined)
|
|
40
|
+
return existing;
|
|
41
|
+
const evict = () => {
|
|
42
|
+
if (registry.preparations.get(key) === prepared)
|
|
43
|
+
registry.preparations.delete(key);
|
|
44
|
+
};
|
|
45
|
+
const prepared = createPreparedService(options, framework, defaultDependencies, evict, signal);
|
|
46
|
+
registry.preparations.set(key, prepared);
|
|
47
|
+
void prepared.catch(evict);
|
|
48
|
+
return prepared;
|
|
49
|
+
}
|
|
50
|
+
export function createPreparedService(options, framework, dependencies, onClose = () => { }, signal) {
|
|
51
|
+
return operation("sdk.prepare", () => createPreparedServiceUntraced(options, framework, dependencies, onClose, signal));
|
|
52
|
+
}
|
|
53
|
+
async function createPreparedServiceUntraced(options, framework, dependencies, onClose, signal) {
|
|
54
|
+
validateOptions(options);
|
|
55
|
+
const directory = path.resolve(options.directory ?? process.cwd());
|
|
56
|
+
const selection = {
|
|
57
|
+
...(options.service === undefined ? {} : { service: options.service }),
|
|
58
|
+
...(options.stateDir === undefined ? {} : { stateDir: options.stateDir }),
|
|
59
|
+
};
|
|
60
|
+
const owner = randomBytes(16).toString("hex");
|
|
61
|
+
const prepareRequest = {
|
|
62
|
+
version: 1,
|
|
63
|
+
directory,
|
|
64
|
+
...(options.service === undefined ? {} : { service: options.service }),
|
|
65
|
+
framework,
|
|
66
|
+
owner,
|
|
67
|
+
pid: process.pid,
|
|
68
|
+
telemetry_disabled: telemetryDisabled(options),
|
|
69
|
+
};
|
|
70
|
+
const native = new NativeRegistration(dependencies, directory, selection, {
|
|
71
|
+
kind: "configured",
|
|
72
|
+
request: prepareRequest,
|
|
73
|
+
});
|
|
74
|
+
await native.discover(signal);
|
|
75
|
+
signal?.throwIfAborted();
|
|
76
|
+
let shutdownUntil;
|
|
77
|
+
const beginShutdown = () => (shutdownUntil ??= new Date(Date.now() + 10_000).toISOString());
|
|
78
|
+
const captureShutdown = () => {
|
|
79
|
+
beginShutdown();
|
|
80
|
+
};
|
|
81
|
+
signal?.addEventListener("abort", captureShutdown, { once: true });
|
|
82
|
+
let assignment;
|
|
83
|
+
try {
|
|
84
|
+
assignment = parsePreparedAssignment(await native.acquire(signal));
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
signal?.removeEventListener("abort", captureShutdown);
|
|
88
|
+
}
|
|
89
|
+
if (signal?.aborted) {
|
|
90
|
+
try {
|
|
91
|
+
await native.unregister({
|
|
92
|
+
deadline: beginShutdown(),
|
|
93
|
+
signal: AbortSignal.timeout(Math.max(0, Date.parse(beginShutdown()) - Date.now())),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
catch (cleanupError) {
|
|
97
|
+
throw new TnlCleanupError(signal.reason, cleanupError);
|
|
98
|
+
}
|
|
99
|
+
signal.throwIfAborted();
|
|
100
|
+
}
|
|
101
|
+
if (native.endpoint.scope !== "app" || assignment.service !== native.endpoint.service)
|
|
102
|
+
throw new TnlError("sdk.response_invalid");
|
|
103
|
+
const initial = assignment;
|
|
104
|
+
let state = {
|
|
105
|
+
phase: "prepared",
|
|
106
|
+
native,
|
|
107
|
+
};
|
|
108
|
+
let target;
|
|
109
|
+
let server;
|
|
110
|
+
let detachListener;
|
|
111
|
+
let revision = 0;
|
|
112
|
+
let timer;
|
|
113
|
+
let pending = Promise.resolve();
|
|
114
|
+
let closing;
|
|
115
|
+
const lifetime = new AbortController();
|
|
116
|
+
const isClosed = () => state.phase === "closed";
|
|
117
|
+
const enqueue = (operation) => {
|
|
118
|
+
const result = pending.catch(() => { }).then(operation);
|
|
119
|
+
pending = result;
|
|
120
|
+
return result;
|
|
121
|
+
};
|
|
122
|
+
const reconnect = (signal) => operation("sdk.app.recover", async () => {
|
|
123
|
+
const replacementNative = new NativeRegistration(dependencies, directory, selection, {
|
|
124
|
+
kind: "configured",
|
|
125
|
+
request: prepareRequest,
|
|
126
|
+
});
|
|
127
|
+
await replacementNative.discover(signal);
|
|
128
|
+
const replacement = parsePreparedAssignment(await replacementNative.acquire(signal));
|
|
129
|
+
if (replacement.publicURL !== initial.publicURL ||
|
|
130
|
+
replacement.service !== initial.service ||
|
|
131
|
+
replacementNative.endpoint.scope !== "app" ||
|
|
132
|
+
replacement.service !== replacementNative.endpoint.service) {
|
|
133
|
+
const failure = new TnlError("sdk.response_invalid");
|
|
134
|
+
const until = beginShutdown();
|
|
135
|
+
try {
|
|
136
|
+
await replacementNative.unregister({
|
|
137
|
+
deadline: until,
|
|
138
|
+
signal: AbortSignal.timeout(Math.max(0, Date.parse(until) - Date.now())),
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
catch (cleanup) {
|
|
142
|
+
throw new TnlCleanupError(failure, cleanup);
|
|
143
|
+
}
|
|
144
|
+
throw failure;
|
|
145
|
+
}
|
|
146
|
+
if (state.phase !== "closed") {
|
|
147
|
+
shutdownUntil = undefined;
|
|
148
|
+
state = {
|
|
149
|
+
phase: "prepared",
|
|
150
|
+
native: replacementNative,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
const release = async (signal, until = beginShutdown()) => {
|
|
155
|
+
detachListener?.();
|
|
156
|
+
detachListener = undefined;
|
|
157
|
+
clearTimeout(timer);
|
|
158
|
+
const current = state.native;
|
|
159
|
+
const bounded = AbortSignal.timeout(Math.max(0, Date.parse(until) - Date.now()));
|
|
160
|
+
await current.unregister({
|
|
161
|
+
deadline: until,
|
|
162
|
+
signal: signal === undefined ? bounded : AbortSignal.any([bounded, signal]),
|
|
163
|
+
});
|
|
164
|
+
if (state.phase !== "closed")
|
|
165
|
+
state = { phase: "released", native: current };
|
|
166
|
+
};
|
|
167
|
+
const schedule = () => {
|
|
168
|
+
if (state.phase !== "prepared")
|
|
169
|
+
return;
|
|
170
|
+
clearTimeout(timer);
|
|
171
|
+
const renew = independent("sdk.app.renew", () => enqueue(async () => {
|
|
172
|
+
if (state.phase !== "prepared")
|
|
173
|
+
return;
|
|
174
|
+
try {
|
|
175
|
+
if (server !== undefined && !isBunServer(server) && !server.listening) {
|
|
176
|
+
await release();
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
await state.native.renew(lifetime.signal);
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
if (lifetime.signal.aborted && !canceledRuntimeRequest(error, lifetime.signal))
|
|
183
|
+
throw error;
|
|
184
|
+
if (recoverable(error)) {
|
|
185
|
+
try {
|
|
186
|
+
await reconnect(lifetime.signal);
|
|
187
|
+
if (state.phase === "prepared" && target !== undefined)
|
|
188
|
+
await state.native.bind(target, lifetime.signal);
|
|
189
|
+
}
|
|
190
|
+
catch (cause) {
|
|
191
|
+
if (lifetime.signal.aborted && !canceledRuntimeRequest(cause, lifetime.signal))
|
|
192
|
+
throw cause;
|
|
193
|
+
/* the next renewal retries a restarting owner. */
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
schedule();
|
|
199
|
+
}
|
|
200
|
+
}));
|
|
201
|
+
timer = setTimeout(() => {
|
|
202
|
+
void renew().catch(() => { });
|
|
203
|
+
}, 5_000);
|
|
204
|
+
timer.unref();
|
|
205
|
+
};
|
|
206
|
+
const setTarget = async (bound, listener, signal) => {
|
|
207
|
+
signal = signal === undefined ? lifetime.signal : AbortSignal.any([signal, lifetime.signal]);
|
|
208
|
+
signal?.throwIfAborted();
|
|
209
|
+
if (state.phase === "closed")
|
|
210
|
+
throw new TnlError("sdk.registration_stale");
|
|
211
|
+
if (state.phase === "released")
|
|
212
|
+
await reconnect(signal);
|
|
213
|
+
if (target !== bound || server !== listener)
|
|
214
|
+
observeBound();
|
|
215
|
+
target = bound;
|
|
216
|
+
detachListener?.();
|
|
217
|
+
server = listener;
|
|
218
|
+
const current = ++revision;
|
|
219
|
+
if (listener !== undefined) {
|
|
220
|
+
const stopped = independent("sdk.app.cleanup", async () => {
|
|
221
|
+
if (server === listener && revision === current && state.phase !== "closed")
|
|
222
|
+
return enqueue(async () => {
|
|
223
|
+
if (server === listener && revision === current)
|
|
224
|
+
await release();
|
|
225
|
+
});
|
|
226
|
+
return Promise.resolve();
|
|
227
|
+
});
|
|
228
|
+
detachListener = observeListenerClose(listener, stopped);
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
await state.native.bind(bound, signal);
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
if (!recoverable(error) || isClosed() || signal?.aborted)
|
|
235
|
+
throw error;
|
|
236
|
+
await reconnect(signal);
|
|
237
|
+
if (isClosed())
|
|
238
|
+
throw new TnlError("sdk.registration_stale");
|
|
239
|
+
await state.native.bind(bound, signal);
|
|
240
|
+
}
|
|
241
|
+
if (isClosed() || (listener !== undefined && !isBunServer(listener) && !listener.listening))
|
|
242
|
+
throw new TnlError("sdk.listener_failed");
|
|
243
|
+
schedule();
|
|
244
|
+
};
|
|
245
|
+
const close = (signal) => {
|
|
246
|
+
if (closing !== undefined)
|
|
247
|
+
return closing;
|
|
248
|
+
const until = beginShutdown();
|
|
249
|
+
state = { phase: "closed", native: state.native };
|
|
250
|
+
lifetime.abort(new TnlError("sdk.registration_stale"));
|
|
251
|
+
clearTimeout(timer);
|
|
252
|
+
process.off("beforeExit", beforeExit);
|
|
253
|
+
onClose();
|
|
254
|
+
closing = operation(framework === "next"
|
|
255
|
+
? "next.cleanup"
|
|
256
|
+
: framework === "vite"
|
|
257
|
+
? "vite.cleanup"
|
|
258
|
+
: "sdk.app.cleanup", async () => {
|
|
259
|
+
let operationFailure;
|
|
260
|
+
try {
|
|
261
|
+
await pending;
|
|
262
|
+
}
|
|
263
|
+
catch (cause) {
|
|
264
|
+
if (!canceledRuntimeRequest(cause, lifetime.signal))
|
|
265
|
+
operationFailure = cause;
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
await release(signal, until);
|
|
269
|
+
}
|
|
270
|
+
catch (cleanup) {
|
|
271
|
+
if (operationFailure !== undefined)
|
|
272
|
+
throw new TnlCleanupError(operationFailure, cleanup);
|
|
273
|
+
throw cleanup;
|
|
274
|
+
}
|
|
275
|
+
if (operationFailure !== undefined)
|
|
276
|
+
throw operationFailure;
|
|
277
|
+
});
|
|
278
|
+
return closing;
|
|
279
|
+
};
|
|
280
|
+
const exitCleanup = scheduled(close);
|
|
281
|
+
const beforeExit = () => {
|
|
282
|
+
void exitCleanup().catch(() => { });
|
|
283
|
+
};
|
|
284
|
+
process.once("beforeExit", beforeExit);
|
|
285
|
+
schedule();
|
|
286
|
+
const handle = Object.freeze({
|
|
287
|
+
...assignment.project,
|
|
288
|
+
service: assignment.service,
|
|
289
|
+
hostname: assignment.hostname,
|
|
290
|
+
publicURL: assignment.publicURL,
|
|
291
|
+
register: (listener, signal) => operation("sdk.app.register", () => enqueue(async () => {
|
|
292
|
+
await setTarget(await listeningTarget(listener, {
|
|
293
|
+
signal: signal === undefined ? lifetime.signal : AbortSignal.any([lifetime.signal, signal]),
|
|
294
|
+
}), listener, signal);
|
|
295
|
+
})),
|
|
296
|
+
close,
|
|
297
|
+
});
|
|
298
|
+
registry.frameworkTargets.set(handle, (bound, signal) => operation(framework === "next" && target !== undefined && target !== bound
|
|
299
|
+
? "next.restart"
|
|
300
|
+
: "sdk.app.register", () => enqueue(async () => {
|
|
301
|
+
const parsed = new URL(bound);
|
|
302
|
+
if (canonicalLoopbackTarget(parsed.hostname, Number(parsed.port)) !== bound)
|
|
303
|
+
throw new TnlError("sdk.target_invalid");
|
|
304
|
+
await setTarget(bound, undefined, signal);
|
|
305
|
+
})));
|
|
306
|
+
return handle;
|
|
307
|
+
}
|
|
308
|
+
function validateOptions(options) {
|
|
309
|
+
parseValue(prepareOptionsSchema, options, "sdk.configuration_invalid");
|
|
310
|
+
}
|
|
311
|
+
// acquisition may precede endpoint allocation, but app/framework preparation
|
|
312
|
+
// promises its selected canonical endpoint before the listener starts.
|
|
313
|
+
function parsePreparedAssignment(assignment) {
|
|
314
|
+
if (assignment?.hostname === undefined)
|
|
315
|
+
throw new TnlError("sdk.response_invalid");
|
|
316
|
+
return assignment;
|
|
317
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Server } from "node:http";
|
|
2
|
+
import type { FetchHandler } from "./fetch_types.js";
|
|
3
|
+
import type { LocalHTTPServer } from "./register.js";
|
|
4
|
+
export declare function createFetchServer(handler: FetchHandler): Promise<Server>;
|
|
5
|
+
export declare function isFetchServer(server: LocalHTTPServer): boolean;
|
|
6
|
+
export declare function joinFetchServer(server: LocalHTTPServer): Promise<void>;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { once } from "node:events";
|
|
2
|
+
import { createServer, Server } from "node:http";
|
|
3
|
+
import { Readable } from "node:stream";
|
|
4
|
+
import { TnlError } from "../../errors.js";
|
|
5
|
+
const copies = new WeakMap();
|
|
6
|
+
// the owned HTTP listener adapts Fetch requests without a framework or child publisher.
|
|
7
|
+
export async function createFetchServer(handler) {
|
|
8
|
+
if (typeof handler !== "function")
|
|
9
|
+
throw new TnlError("sdk.configuration_invalid");
|
|
10
|
+
const workers = new Set();
|
|
11
|
+
const server = createServer((incoming, outgoing) => {
|
|
12
|
+
const worker = serveFetch(handler, incoming, outgoing);
|
|
13
|
+
workers.add(worker);
|
|
14
|
+
void worker.finally(() => workers.delete(worker));
|
|
15
|
+
});
|
|
16
|
+
copies.set(server, workers);
|
|
17
|
+
// Fetch handlers have no portable socket takeover in Node or Bun.
|
|
18
|
+
server.on("upgrade", (_request, socket) => {
|
|
19
|
+
socket.end("HTTP/1.1 501 Not Implemented\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
20
|
+
});
|
|
21
|
+
try {
|
|
22
|
+
await new Promise((resolve, reject) => {
|
|
23
|
+
server.once("error", reject);
|
|
24
|
+
server.listen(0, "127.0.0.1", () => {
|
|
25
|
+
server.off("error", reject);
|
|
26
|
+
resolve();
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch (cause) {
|
|
31
|
+
try {
|
|
32
|
+
server.close();
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
/* the listener never opened. */
|
|
36
|
+
}
|
|
37
|
+
throw new TnlError("sdk.listener_failed", { cause });
|
|
38
|
+
}
|
|
39
|
+
return server;
|
|
40
|
+
}
|
|
41
|
+
export function isFetchServer(server) {
|
|
42
|
+
return server instanceof Server && copies.has(server);
|
|
43
|
+
}
|
|
44
|
+
export async function joinFetchServer(server) {
|
|
45
|
+
if (server instanceof Server)
|
|
46
|
+
await Promise.all(copies.get(server) ?? []);
|
|
47
|
+
}
|
|
48
|
+
async function serveFetch(handler, incoming, outgoing) {
|
|
49
|
+
const controller = new AbortController();
|
|
50
|
+
let reader;
|
|
51
|
+
outgoing.once("close", () => {
|
|
52
|
+
controller.abort();
|
|
53
|
+
// releasing the reader interrupts tnl's pending copy without waiting for
|
|
54
|
+
// an arbitrary application's stream cancellation callback.
|
|
55
|
+
reader?.releaseLock();
|
|
56
|
+
});
|
|
57
|
+
try {
|
|
58
|
+
const host = incoming.headers.host;
|
|
59
|
+
if (typeof host !== "string" ||
|
|
60
|
+
!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(host) ||
|
|
61
|
+
typeof incoming.url !== "string" ||
|
|
62
|
+
!incoming.url.startsWith("/") ||
|
|
63
|
+
incoming.url.startsWith("//")) {
|
|
64
|
+
outgoing.writeHead(400).end();
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const headers = new Headers();
|
|
68
|
+
for (const [name, value] of Object.entries(incoming.headers)) {
|
|
69
|
+
if (typeof value === "string")
|
|
70
|
+
headers.append(name, value);
|
|
71
|
+
else if (Array.isArray(value))
|
|
72
|
+
for (const entry of value)
|
|
73
|
+
headers.append(name, entry);
|
|
74
|
+
}
|
|
75
|
+
// node's stream/web reader has the same runtime shape as a DOM stream.
|
|
76
|
+
const body = incoming.method === "GET" || incoming.method === "HEAD"
|
|
77
|
+
? undefined
|
|
78
|
+
: Readable.toWeb(incoming);
|
|
79
|
+
const request = new Request(`https://${host}${incoming.url}`, {
|
|
80
|
+
method: incoming.method,
|
|
81
|
+
headers,
|
|
82
|
+
body,
|
|
83
|
+
signal: controller.signal,
|
|
84
|
+
...(body === undefined ? {} : { duplex: "half" }),
|
|
85
|
+
});
|
|
86
|
+
const interrupted = Promise.withResolvers();
|
|
87
|
+
const interrupt = () => interrupted.reject(controller.signal.reason);
|
|
88
|
+
controller.signal.addEventListener("abort", interrupt, { once: true });
|
|
89
|
+
let response;
|
|
90
|
+
try {
|
|
91
|
+
response = await Promise.race([handler(request), interrupted.promise]);
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
controller.signal.removeEventListener("abort", interrupt);
|
|
95
|
+
}
|
|
96
|
+
if (controller.signal.aborted)
|
|
97
|
+
return;
|
|
98
|
+
if (!(response instanceof Response))
|
|
99
|
+
throw new TnlError("sdk.response_invalid");
|
|
100
|
+
for (const [name, value] of response.headers) {
|
|
101
|
+
if (name !== "set-cookie")
|
|
102
|
+
outgoing.setHeader(name, value);
|
|
103
|
+
}
|
|
104
|
+
for (const cookie of response.headers.getSetCookie())
|
|
105
|
+
outgoing.appendHeader("Set-Cookie", cookie);
|
|
106
|
+
outgoing.writeHead(response.status);
|
|
107
|
+
if (response.body === null || incoming.method === "HEAD") {
|
|
108
|
+
outgoing.end();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
reader = response.body.getReader();
|
|
112
|
+
try {
|
|
113
|
+
for (;;) {
|
|
114
|
+
const result = await reader.read();
|
|
115
|
+
if (result.done || controller.signal.aborted)
|
|
116
|
+
break;
|
|
117
|
+
if (!outgoing.write(Buffer.from(result.value)))
|
|
118
|
+
await once(outgoing, "drain", { signal: controller.signal });
|
|
119
|
+
}
|
|
120
|
+
if (!controller.signal.aborted)
|
|
121
|
+
outgoing.end();
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
reader.releaseLock();
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
if (outgoing.destroyed)
|
|
129
|
+
return;
|
|
130
|
+
if (!outgoing.headersSent)
|
|
131
|
+
outgoing.writeHead(500).end("handler failed\n");
|
|
132
|
+
else
|
|
133
|
+
outgoing.destroy();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type FetchHandler = (request: Request) => Response | Promise<Response>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { prepareOptionsSchema, type PreparedService } from "./app.js";
|
|
3
|
+
declare const previewSchema: z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodEnum<{
|
|
4
|
+
auto: "auto";
|
|
5
|
+
required: "required";
|
|
6
|
+
}>]>;
|
|
7
|
+
declare const frameworkOptionsSchema: z.ZodReadonly<z.ZodObject<{
|
|
8
|
+
service: z.ZodExactOptional<z.ZodString>;
|
|
9
|
+
directory: z.ZodExactOptional<z.ZodString>;
|
|
10
|
+
stateDir: z.ZodExactOptional<z.ZodString>;
|
|
11
|
+
telemetry: z.ZodExactOptional<z.ZodBoolean>;
|
|
12
|
+
preview: z.ZodExactOptional<z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodEnum<{
|
|
13
|
+
auto: "auto";
|
|
14
|
+
required: "required";
|
|
15
|
+
}>]>>;
|
|
16
|
+
}, z.core.$strict>>;
|
|
17
|
+
export type FrameworkOptions = z.output<typeof frameworkOptionsSchema>;
|
|
18
|
+
type PreviewMode = z.output<typeof previewSchema>;
|
|
19
|
+
export declare const localRuntimePayload: string;
|
|
20
|
+
export declare function frameworkOptions(options: FrameworkOptions): {
|
|
21
|
+
preview: PreviewMode;
|
|
22
|
+
preparation: z.output<typeof prepareOptionsSchema>;
|
|
23
|
+
};
|
|
24
|
+
export declare function frameworkOperation<T>(preview: PreviewMode, operation: (signal?: AbortSignal) => Promise<T>): Promise<T | null>;
|
|
25
|
+
export declare function prepareFramework(options: FrameworkOptions, framework: "vite" | "next", target?: `http://${string}`): Promise<PreparedService | null>;
|
|
26
|
+
export declare function closeFramework(prepared: PreparedService, error: unknown): Promise<void>;
|
|
27
|
+
export {};
|