@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.
Files changed (198) hide show
  1. package/LICENSE +28 -0
  2. package/NOTICE +5 -0
  3. package/THIRD_PARTY_LICENSES.txt +3297 -0
  4. package/dist/adapters/ioredis.d.ts +7 -0
  5. package/dist/adapters/ioredis.js +87 -0
  6. package/dist/adapters/node-postgres.d.ts +8 -0
  7. package/dist/adapters/node-postgres.js +41 -0
  8. package/dist/adapters/postgres-js.d.ts +7 -0
  9. package/dist/adapters/postgres-js.js +55 -0
  10. package/dist/bin/tnl.d.ts +2 -0
  11. package/dist/bin/tnl.js +16 -0
  12. package/dist/browser.d.ts +18 -0
  13. package/dist/browser.js +43 -0
  14. package/dist/bun.d.ts +9 -0
  15. package/dist/bun.js +6 -0
  16. package/dist/cloudflare.d.ts +9 -0
  17. package/dist/cloudflare.js +16 -0
  18. package/dist/config.d.ts +107 -0
  19. package/dist/config.gen.d.ts +1185 -0
  20. package/dist/config.gen.js +2 -0
  21. package/dist/config.js +3 -0
  22. package/dist/control.d.ts +5 -0
  23. package/dist/control.js +9 -0
  24. package/dist/durable-object.d.ts +51 -0
  25. package/dist/durable-object.js +374 -0
  26. package/dist/durable-object.worker.d.ts +5 -0
  27. package/dist/durable-object.worker.js +11 -0
  28. package/dist/errors.d.ts +17 -0
  29. package/dist/errors.js +230 -0
  30. package/dist/index.d.ts +10 -0
  31. package/dist/index.js +2 -0
  32. package/dist/internal/connector/cancellation.d.ts +7 -0
  33. package/dist/internal/connector/cancellation.js +30 -0
  34. package/dist/internal/connector/client.d.ts +62 -0
  35. package/dist/internal/connector/client.js +504 -0
  36. package/dist/internal/connector/client_factory.d.ts +6 -0
  37. package/dist/internal/connector/client_factory.js +123 -0
  38. package/dist/internal/connector/connection.d.ts +39 -0
  39. package/dist/internal/connector/connection.js +739 -0
  40. package/dist/internal/connector/connection_ipc.d.ts +12 -0
  41. package/dist/internal/connector/connection_ipc.js +198 -0
  42. package/dist/internal/connector/context.d.ts +28 -0
  43. package/dist/internal/connector/context.js +19 -0
  44. package/dist/internal/connector/contract.d.ts +392 -0
  45. package/dist/internal/connector/contract.js +56 -0
  46. package/dist/internal/connector/deployment_types.d.ts +27 -0
  47. package/dist/internal/connector/deployment_types.js +1 -0
  48. package/dist/internal/connector/driver_socket.d.ts +21 -0
  49. package/dist/internal/connector/driver_socket.js +129 -0
  50. package/dist/internal/connector/management.d.ts +29 -0
  51. package/dist/internal/connector/management.js +118 -0
  52. package/dist/internal/connector/native_operations.d.ts +16 -0
  53. package/dist/internal/connector/native_operations.js +30 -0
  54. package/dist/internal/connector/native_stream.d.ts +7 -0
  55. package/dist/internal/connector/native_stream.js +219 -0
  56. package/dist/internal/connector/operation_handles.d.ts +9 -0
  57. package/dist/internal/connector/operation_handles.js +18 -0
  58. package/dist/internal/connector/portable_operations.d.ts +13 -0
  59. package/dist/internal/connector/portable_operations.js +25 -0
  60. package/dist/internal/connector/snapshot.d.ts +183 -0
  61. package/dist/internal/connector/snapshot.js +47 -0
  62. package/dist/internal/connector/wasm_abi.d.ts +76 -0
  63. package/dist/internal/connector/wasm_abi.js +5 -0
  64. package/dist/internal/connector/wasm_client.d.ts +58 -0
  65. package/dist/internal/connector/wasm_client.js +545 -0
  66. package/dist/internal/connector/wasm_loader.d.ts +15 -0
  67. package/dist/internal/connector/wasm_loader.js +99 -0
  68. package/dist/internal/connector/wasm_stream.d.ts +4 -0
  69. package/dist/internal/connector/wasm_stream.js +177 -0
  70. package/dist/internal/connector/workload/contract.d.ts +54 -0
  71. package/dist/internal/connector/workload/contract.js +14 -0
  72. package/dist/internal/connector/workload/provider.d.ts +24 -0
  73. package/dist/internal/connector/workload/provider.js +130 -0
  74. package/dist/internal/enrollment_source.d.ts +4 -0
  75. package/dist/internal/enrollment_source.js +34 -0
  76. package/dist/internal/management/client/client.gen.d.ts +2 -0
  77. package/dist/internal/management/client/client.gen.js +216 -0
  78. package/dist/internal/management/client/index.d.ts +10 -0
  79. package/dist/internal/management/client/index.js +6 -0
  80. package/dist/internal/management/client/types.gen.d.ts +120 -0
  81. package/dist/internal/management/client/types.gen.js +2 -0
  82. package/dist/internal/management/client/utils.gen.d.ts +37 -0
  83. package/dist/internal/management/client/utils.gen.js +228 -0
  84. package/dist/internal/management/client.gen.d.ts +12 -0
  85. package/dist/internal/management/client.gen.js +3 -0
  86. package/dist/internal/management/core/auth.gen.d.ts +25 -0
  87. package/dist/internal/management/core/auth.gen.js +14 -0
  88. package/dist/internal/management/core/bodySerializer.gen.d.ts +25 -0
  89. package/dist/internal/management/core/bodySerializer.gen.js +57 -0
  90. package/dist/internal/management/core/params.gen.d.ts +43 -0
  91. package/dist/internal/management/core/params.gen.js +109 -0
  92. package/dist/internal/management/core/pathSerializer.gen.d.ts +33 -0
  93. package/dist/internal/management/core/pathSerializer.gen.js +106 -0
  94. package/dist/internal/management/core/queryKeySerializer.gen.d.ts +18 -0
  95. package/dist/internal/management/core/queryKeySerializer.gen.js +92 -0
  96. package/dist/internal/management/core/serverSentEvents.gen.d.ts +71 -0
  97. package/dist/internal/management/core/serverSentEvents.gen.js +132 -0
  98. package/dist/internal/management/core/types.gen.d.ts +83 -0
  99. package/dist/internal/management/core/types.gen.js +2 -0
  100. package/dist/internal/management/core/utils.gen.d.ts +19 -0
  101. package/dist/internal/management/core/utils.gen.js +87 -0
  102. package/dist/internal/management/index.d.ts +2 -0
  103. package/dist/internal/management/index.js +2 -0
  104. package/dist/internal/management/sdk.gen.d.ts +73 -0
  105. package/dist/internal/management/sdk.gen.js +191 -0
  106. package/dist/internal/management/types.gen.d.ts +464 -0
  107. package/dist/internal/management/types.gen.js +2 -0
  108. package/dist/internal/management/zod.gen.d.ts +850 -0
  109. package/dist/internal/management/zod.gen.js +252 -0
  110. package/dist/internal/native/launcher.d.ts +8 -0
  111. package/dist/internal/native/launcher.js +75 -0
  112. package/dist/internal/native/native-targets.d.ts +9 -0
  113. package/dist/internal/native/native-targets.js +8 -0
  114. package/dist/internal/portable/cloudflare-publisher-client.d.ts +54 -0
  115. package/dist/internal/portable/cloudflare-publisher-client.js +91 -0
  116. package/dist/internal/portable/cloudflare-publisher.d.ts +19 -0
  117. package/dist/internal/portable/cloudflare-publisher.js +210 -0
  118. package/dist/internal/portable/durable-deployment.d.ts +10 -0
  119. package/dist/internal/portable/durable-deployment.js +22 -0
  120. package/dist/internal/portable/enrollment.d.ts +26 -0
  121. package/dist/internal/portable/enrollment.js +196 -0
  122. package/dist/internal/portable/publication.d.ts +54 -0
  123. package/dist/internal/portable/publication.js +304 -0
  124. package/dist/internal/portable/request.d.ts +1 -0
  125. package/dist/internal/portable/request.js +20 -0
  126. package/dist/internal/portable/storage-browser.d.ts +9 -0
  127. package/dist/internal/portable/storage-browser.js +115 -0
  128. package/dist/internal/portable/storage-durable-object.d.ts +11 -0
  129. package/dist/internal/portable/storage-durable-object.js +110 -0
  130. package/dist/internal/portable/storage-host.d.ts +8 -0
  131. package/dist/internal/portable/storage-host.js +142 -0
  132. package/dist/internal/portable/storage.d.ts +15 -0
  133. package/dist/internal/portable/storage.js +29 -0
  134. package/dist/internal/project/native_runtime.d.ts +24 -0
  135. package/dist/internal/project/native_runtime.js +23 -0
  136. package/dist/internal/project/runtime.d.ts +467 -0
  137. package/dist/internal/project/runtime.js +183 -0
  138. package/dist/internal/project/service_metadata.d.ts +3 -0
  139. package/dist/internal/project/service_metadata.js +12 -0
  140. package/dist/internal/publication_certificate.d.ts +28 -0
  141. package/dist/internal/publication_certificate.js +32 -0
  142. package/dist/internal/publication_run.d.ts +8 -0
  143. package/dist/internal/publication_run.js +19 -0
  144. package/dist/internal/publisher/app.d.ts +33 -0
  145. package/dist/internal/publisher/app.js +317 -0
  146. package/dist/internal/publisher/fetch.d.ts +6 -0
  147. package/dist/internal/publisher/fetch.js +135 -0
  148. package/dist/internal/publisher/fetch_types.d.ts +1 -0
  149. package/dist/internal/publisher/fetch_types.js +1 -0
  150. package/dist/internal/publisher/framework.d.ts +27 -0
  151. package/dist/internal/publisher/framework.js +82 -0
  152. package/dist/internal/publisher/local.d.ts +39 -0
  153. package/dist/internal/publisher/local.js +312 -0
  154. package/dist/internal/publisher/native_publisher.d.ts +25 -0
  155. package/dist/internal/publisher/native_publisher.js +228 -0
  156. package/dist/internal/publisher/port.d.ts +2 -0
  157. package/dist/internal/publisher/port.js +15 -0
  158. package/dist/internal/publisher/publication.d.ts +88 -0
  159. package/dist/internal/publisher/publication.js +627 -0
  160. package/dist/internal/publisher/register.d.ts +31 -0
  161. package/dist/internal/publisher/register.js +136 -0
  162. package/dist/internal/publisher/registration.d.ts +385 -0
  163. package/dist/internal/publisher/registration.js +223 -0
  164. package/dist/internal/publisher/status.d.ts +47 -0
  165. package/dist/internal/publisher/status.js +137 -0
  166. package/dist/internal/publisher/target.d.ts +6 -0
  167. package/dist/internal/publisher/target.js +44 -0
  168. package/dist/internal/runtime_resources.d.ts +38 -0
  169. package/dist/internal/runtime_resources.js +52 -0
  170. package/dist/internal/tracing.d.ts +10 -0
  171. package/dist/internal/tracing.js +78 -0
  172. package/dist/internal/validation.d.ts +3 -0
  173. package/dist/internal/validation.js +9 -0
  174. package/dist/internal/values.d.ts +27 -0
  175. package/dist/internal/values.js +54 -0
  176. package/dist/next.d.ts +12 -0
  177. package/dist/next.js +82 -0
  178. package/dist/node.d.ts +9 -0
  179. package/dist/node.js +6 -0
  180. package/dist/project.d.ts +173 -0
  181. package/dist/project.js +1 -0
  182. package/dist/response.d.ts +1 -0
  183. package/dist/response.js +34 -0
  184. package/dist/third-party-licenses.txt +1537 -0
  185. package/dist/vite.d.ts +5 -0
  186. package/dist/vite.js +200 -0
  187. package/dist/wasm/build.json +16 -0
  188. package/dist/wasm/connector.wasm +0 -0
  189. package/dist/wasm/go-license.txt +27 -0
  190. package/dist/wasm/publisher.wasm +0 -0
  191. package/dist/wasm/third-party-licenses.txt +3297 -0
  192. package/dist/wasm/wasm_exec.d.ts +1 -0
  193. package/dist/wasm/wasm_exec.js +575 -0
  194. package/dist/workload.d.ts +11 -0
  195. package/dist/workload.js +4 -0
  196. package/package.json +159 -4
  197. package/readme.md +13 -0
  198. package/README.md +0 -3
@@ -0,0 +1,56 @@
1
+ import * as path from "node:path";
2
+ import * as z from "zod";
3
+ import { projectRuntimeSchema } from "../project/runtime.js";
4
+ import { deadlineSchema, digestSchema, pathTextSchema } from "../values.js";
5
+ import { connectionSnapshotSchema } from "./snapshot.js";
6
+ const assertionDeadlineSchema = deadlineSchema.refine((value) => value <= Date.now() + 12 * 3600_000 + 60_000);
7
+ const sdkOwnerSchema = z.strictObject({
8
+ expires_at: deadlineSchema,
9
+ connection_handle: pathTextSchema.refine(path.isAbsolute),
10
+ executable: pathTextSchema.refine(path.isAbsolute),
11
+ });
12
+ const verificationSchema = z
13
+ .strictObject({
14
+ digest: digestSchema,
15
+ binding: digestSchema,
16
+ expires_at: assertionDeadlineSchema,
17
+ })
18
+ .transform(({ digest, binding, expires_at }) => ({ digest, binding, expires: expires_at }))
19
+ .readonly();
20
+ export const preparedConnectionSchema = z.strictObject({
21
+ schema: z.literal(1),
22
+ project_runtime: projectRuntimeSchema,
23
+ connection: connectionSnapshotSchema,
24
+ verification: verificationSchema.exactOptional(),
25
+ });
26
+ export const sdkPreparationSchema = z.union([
27
+ z.strictObject({
28
+ schema: z.literal(1),
29
+ owner: sdkOwnerSchema,
30
+ // the prepared reader validates this once, including metadata binding.
31
+ prepared: z.unknown().nonoptional(),
32
+ }),
33
+ z.strictObject({
34
+ schema: z.literal(1),
35
+ reason: z.string(),
36
+ sdk_retained_start_failure: z.boolean().exactOptional(),
37
+ sdk_failure_handle: z.string().exactOptional(),
38
+ sdk_owner_handle: pathTextSchema.exactOptional(),
39
+ }),
40
+ ]);
41
+ export const connectionHandleSchema = z.strictObject({
42
+ schema: z.literal(1),
43
+ url: z
44
+ .templateLiteral(["http://127.0.0.1:", z.string().regex(/^[1-9][0-9]{0,4}$/)])
45
+ .refine((value) => {
46
+ const url = URL.parse(value);
47
+ return url !== null && url.origin === value && Number(url.port) <= 65535;
48
+ }),
49
+ key: digestSchema,
50
+ directory: z.string().refine(path.isAbsolute),
51
+ config_digest: digestSchema,
52
+ expires_at: deadlineSchema,
53
+ executable: z.unknown().nonoptional(),
54
+ workload: z.unknown().optional(),
55
+ team_id: z.unknown().optional(),
56
+ });
@@ -0,0 +1,27 @@
1
+ import type { ServiceFacts, TnlClientFactory, TnlClientOptions } from "../../project.js";
2
+ import type { FetchHandler } from "../publisher/fetch_types.js";
3
+ import type { NamedPublicationOptions, Publication, TemporaryPublicationOptions } from "../publisher/publication.js";
4
+ export interface DeploymentOptions<Services extends ServiceFacts> {
5
+ readonly project?: string;
6
+ readonly token?: string;
7
+ readonly services?: Services;
8
+ }
9
+ export type ServiceNames<Services extends ServiceFacts> = keyof Services & string;
10
+ export type HTTPNames<Services extends ServiceFacts> = string extends keyof Services ? string : keyof Services extends never ? string : {
11
+ [Name in ServiceNames<Services>]: Services[Name]["protocol"] extends "http" ? Name : never;
12
+ }[ServiceNames<Services>];
13
+ declare const deploymentTypes: unique symbol;
14
+ export interface Deployment<Services extends ServiceFacts, Registry> {
15
+ readonly [deploymentTypes]: {
16
+ readonly services: Services;
17
+ readonly connections: Registry;
18
+ };
19
+ close(): Promise<void>;
20
+ }
21
+ export type Connect<Registry> = <Services extends ServiceFacts, Name extends ServiceNames<Services>>(owner: Deployment<Services, Registry>, name: Name) => Promise<Registry[Services[Name]["protocol"] & keyof Registry]>;
22
+ export type DriverClient<Registry> = <Services extends ServiceFacts, Name extends ServiceNames<Services>, Client>(owner: Deployment<Services, Registry>, name: Name, driver: TnlClientOptions<Registry[Services[Name]["protocol"] & keyof Registry], Client>) => TnlClientFactory<Client>;
23
+ export interface Publish<Registry, Server = never> {
24
+ <Services extends ServiceFacts>(owner: Deployment<Services, Registry>, name: HTTPNames<Services>, target: FetchHandler | Server, options?: NamedPublicationOptions): Promise<Publication>;
25
+ <Services extends ServiceFacts>(owner: Deployment<Services, Registry>, target: FetchHandler | Server, options?: TemporaryPublicationOptions): Promise<Publication>;
26
+ }
27
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { Duplex } from "node:stream";
3
+ import type { TnlOpenStream } from "../../project.js";
4
+ /** adapts one tnl application stream, not a network address. */
5
+ export declare class DriverSocket extends Duplex {
6
+ #private;
7
+ constructor(open: TnlOpenStream);
8
+ get readyState(): "opening" | "open" | "readOnly" | "writeOnly" | "closed";
9
+ connect(): this;
10
+ ready(milliseconds: number): Promise<void>;
11
+ _construct(callback: (error?: Error | null) => void): void;
12
+ destroy(error?: Error): this;
13
+ _read(): void;
14
+ _write(bytes: Buffer, _encoding: BufferEncoding, callback: (error?: Error) => void): void;
15
+ _final(callback: (error?: Error) => void): void;
16
+ _destroy(error: Error | null, callback: (error: Error | null) => void): void;
17
+ setNoDelay(): this;
18
+ setKeepAlive(): this;
19
+ ref(): this;
20
+ unref(): this;
21
+ }
@@ -0,0 +1,129 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { Duplex } from "node:stream";
3
+ import { TnlError } from "../../errors.js";
4
+ /** adapts one tnl application stream, not a network address. */
5
+ export class DriverSocket extends Duplex {
6
+ #open;
7
+ #abort = new AbortController();
8
+ #opening;
9
+ #reader;
10
+ #writer;
11
+ #reading = false;
12
+ constructor(open) {
13
+ super({ allowHalfOpen: true, highWaterMark: 64 * 1024 });
14
+ this.#open = open;
15
+ }
16
+ get readyState() {
17
+ if (this.closed)
18
+ return "closed";
19
+ if (this.#reader === undefined)
20
+ return "opening";
21
+ if (this.readable && this.writable)
22
+ return "open";
23
+ if (this.readable)
24
+ return "readOnly";
25
+ if (this.writable)
26
+ return "writeOnly";
27
+ return "closed";
28
+ }
29
+ // the driver passes an address here; only tnl can select the destination.
30
+ connect() {
31
+ this.#opening ??= Promise.resolve().then(() => this.#open({ signal: this.#abort.signal }));
32
+ return this;
33
+ }
34
+ async ready(milliseconds) {
35
+ await new Promise((resolve, reject) => {
36
+ const cleanup = () => {
37
+ clearTimeout(timer);
38
+ this.off("connect", connected).off("close", closed).off("error", failed);
39
+ };
40
+ const connected = () => {
41
+ cleanup();
42
+ resolve();
43
+ };
44
+ const failed = (error) => {
45
+ cleanup();
46
+ reject(error);
47
+ };
48
+ const closed = () => failed(new TnlError("sdk.connection_unavailable"));
49
+ const timer = milliseconds > 0
50
+ ? setTimeout(() => this.destroy(new TnlError("sdk.connection_unavailable")), milliseconds)
51
+ : undefined;
52
+ this.once("connect", connected).once("close", closed).once("error", failed);
53
+ this.connect();
54
+ });
55
+ }
56
+ _construct(callback) {
57
+ const opening = this.#opening;
58
+ if (opening === undefined) {
59
+ callback(new TnlError("sdk.connection_unavailable"));
60
+ return;
61
+ }
62
+ void opening
63
+ .then((stream) => {
64
+ if (!this.destroyed) {
65
+ this.#reader = stream.readable.getReader();
66
+ this.#writer = stream.writable.getWriter();
67
+ this.emit("connect");
68
+ }
69
+ })
70
+ .then(() => callback(), callback);
71
+ }
72
+ destroy(error) {
73
+ // _destroy is deferred until _construct finishes; interrupt the open now.
74
+ this.#abort.abort();
75
+ return super.destroy(error);
76
+ }
77
+ _read() {
78
+ if (this.#reading || this.#reader === undefined)
79
+ return;
80
+ this.#reading = true;
81
+ void this.#reader.read().then((result) => {
82
+ this.#reading = false;
83
+ if (!this.destroyed)
84
+ this.push(result.done
85
+ ? null
86
+ : Buffer.from(result.value.buffer, result.value.byteOffset, result.value.byteLength));
87
+ }, (error) => this.destroy(error));
88
+ }
89
+ _write(bytes, _encoding, callback) {
90
+ if (this.#writer === undefined)
91
+ callback(new TnlError("sdk.connection_unavailable"));
92
+ else
93
+ void this.#writer.write(bytes).then(() => callback(), callback);
94
+ }
95
+ _final(callback) {
96
+ if (this.#writer === undefined)
97
+ callback(new TnlError("sdk.connection_unavailable"));
98
+ else
99
+ void this.#writer.close().then(() => callback(), callback);
100
+ }
101
+ _destroy(error, callback) {
102
+ const cleanup = async () => {
103
+ const stream = await this.#opening?.catch(() => undefined);
104
+ try {
105
+ await stream?.close();
106
+ }
107
+ finally {
108
+ this.#reader?.releaseLock();
109
+ this.#writer?.releaseLock();
110
+ }
111
+ };
112
+ void cleanup().then(() => callback(error), (failure) => callback(error === null
113
+ ? failure
114
+ : new AggregateError([error, failure], "driver stream failed to close")));
115
+ }
116
+ // these knobs apply to TCP sockets. tnl owns the carrier configuration.
117
+ setNoDelay() {
118
+ return this;
119
+ }
120
+ setKeepAlive() {
121
+ return this;
122
+ }
123
+ ref() {
124
+ return this;
125
+ }
126
+ unref() {
127
+ return this;
128
+ }
129
+ }
@@ -0,0 +1,29 @@
1
+ import type { CreateDeploymentRequest, UpdateDeploymentRequest, CreateDeploymentPublisherEnrollmentRequest, Deployment } from "../../control.js";
2
+ export type SavedDeployment = Deployment & {
3
+ readonly etag: string;
4
+ };
5
+ export interface CreationOptions {
6
+ readonly idempotencyKey: string;
7
+ }
8
+ export interface MutationOptions {
9
+ readonly ifMatch: string;
10
+ }
11
+ export interface PageOptions {
12
+ readonly after?: string;
13
+ readonly limit?: number;
14
+ }
15
+ export declare function boundManagement(project: string | undefined, token: string | undefined): Readonly<{
16
+ deployments: Readonly<{
17
+ create(body: CreateDeploymentRequest, request: CreationOptions): Promise<SavedDeployment>;
18
+ list(page?: PageOptions): Promise<import("../management/types.gen.js").DeploymentPage>;
19
+ get(deployment: string): Promise<SavedDeployment>;
20
+ update(deployment: string, body: UpdateDeploymentRequest, request: MutationOptions): Promise<SavedDeployment>;
21
+ delete(deployment: string, request: MutationOptions): Promise<void>;
22
+ }>;
23
+ publishers: Readonly<{
24
+ createEnrollment(deployment: string, body: CreateDeploymentPublisherEnrollmentRequest, request: CreationOptions): Promise<import("../management/types.gen.js").DeploymentPublisherEnrollment>;
25
+ list(deployment: string, page?: PageOptions): Promise<import("../management/types.gen.js").DeploymentPublisherPage>;
26
+ get(deployment: string, publisher: string): Promise<import("../management/types.gen.js").DeploymentPublisher>;
27
+ revoke(deployment: string, publisher: string): Promise<void>;
28
+ }>;
29
+ }>;
@@ -0,0 +1,118 @@
1
+ import { TnlError } from "../../errors.js";
2
+ import { control, createDeployment, deleteDeployment, getDeployment, listDeployments, updateDeployment, createPublisherEnrollment, getPublisher, listPublishers, revokePublisher, } from "../../control.js";
3
+ import { deploymentAccess } from "./connection.js";
4
+ function saved(value, response) {
5
+ const etag = response.headers.get("etag");
6
+ if (etag === null || !/^"[0-9]+"$/.test(etag))
7
+ throw new TnlError("sdk.response_invalid");
8
+ return Object.freeze({ ...value, etag });
9
+ }
10
+ // bind only selection and native credential acquisition. all HTTP operations,
11
+ // wire types, validation, response/error handling remain stock generated code.
12
+ export function boundManagement(project, token) {
13
+ let current;
14
+ let loading;
15
+ let client;
16
+ const access = async () => {
17
+ if (project === undefined || token === undefined)
18
+ throw new TnlError("sdk.configuration_invalid");
19
+ if (current !== undefined && current.expires_at > Date.now() + 30_000)
20
+ return current;
21
+ loading ??= deploymentAccess(project, token)
22
+ .then((value) => {
23
+ if (current !== undefined &&
24
+ (value.server !== current.server ||
25
+ value.team_id !== current.team_id ||
26
+ value.project_key !== current.project_key))
27
+ throw new TnlError("sdk.response_invalid");
28
+ current = value;
29
+ return value;
30
+ })
31
+ .finally(() => {
32
+ loading = undefined;
33
+ });
34
+ return loading;
35
+ };
36
+ const options = async () => {
37
+ const selected = await access();
38
+ client ??= control({
39
+ baseUrl: selected.server,
40
+ auth: async () => (await access()).token,
41
+ });
42
+ return {
43
+ client,
44
+ query: { team_id: selected.team_id },
45
+ path: { project_key: selected.project_key },
46
+ throwOnError: true,
47
+ };
48
+ };
49
+ return Object.freeze({
50
+ deployments: Object.freeze({
51
+ async create(body, request) {
52
+ const result = await createDeployment({
53
+ ...(await options()),
54
+ body,
55
+ headers: { "Idempotency-Key": request.idempotencyKey },
56
+ });
57
+ return saved(result.data, result.response);
58
+ },
59
+ async list(page = {}) {
60
+ const selected = await options();
61
+ return (await listDeployments({ ...selected, query: { ...selected.query, ...page } })).data;
62
+ },
63
+ async get(deployment) {
64
+ const selected = await options();
65
+ const result = await getDeployment({
66
+ ...selected,
67
+ path: { ...selected.path, deployment },
68
+ });
69
+ return saved(result.data, result.response);
70
+ },
71
+ async update(deployment, body, request) {
72
+ const selected = await options();
73
+ const result = await updateDeployment({
74
+ ...selected,
75
+ path: { ...selected.path, deployment },
76
+ body,
77
+ headers: { "If-Match": request.ifMatch },
78
+ });
79
+ return saved(result.data, result.response);
80
+ },
81
+ async delete(deployment, request) {
82
+ const selected = await options();
83
+ await deleteDeployment({
84
+ ...selected,
85
+ path: { ...selected.path, deployment },
86
+ headers: { "If-Match": request.ifMatch },
87
+ });
88
+ },
89
+ }),
90
+ publishers: Object.freeze({
91
+ async createEnrollment(deployment, body, request) {
92
+ const selected = await options();
93
+ return (await createPublisherEnrollment({
94
+ ...selected,
95
+ path: { ...selected.path, deployment },
96
+ body,
97
+ headers: { "Idempotency-Key": request.idempotencyKey },
98
+ })).data;
99
+ },
100
+ async list(deployment, page = {}) {
101
+ const selected = await options();
102
+ return (await listPublishers({
103
+ ...selected,
104
+ path: { ...selected.path, deployment },
105
+ query: { ...selected.query, ...page },
106
+ })).data;
107
+ },
108
+ async get(deployment, publisher) {
109
+ const selected = await options();
110
+ return (await getPublisher({ ...selected, path: { ...selected.path, deployment, publisher } })).data;
111
+ },
112
+ async revoke(deployment, publisher) {
113
+ const selected = await options();
114
+ await revokePublisher({ ...selected, path: { ...selected.path, deployment, publisher } });
115
+ },
116
+ }),
117
+ });
118
+ }
@@ -0,0 +1,16 @@
1
+ import type { ServiceFacts, TnlClientOptions, TnlConnectionRegistry } from "../../project.js";
2
+ import type { FetchHandler } from "../publisher/fetch_types.js";
3
+ import type { NamedPublicationOptions, TemporaryPublicationOptions } from "../publisher/publication.js";
4
+ import type { LocalHTTPServer } from "../publisher/register.js";
5
+ import { type Publisher } from "../publisher/native_publisher.js";
6
+ import { type LocalConnectionRegistry } from "./client.js";
7
+ import type { Deployment, DeploymentOptions, Publish, ServiceNames } from "./deployment_types.js";
8
+ type NativeRegistry = TnlConnectionRegistry | LocalConnectionRegistry;
9
+ export interface NativePublish<Server> extends Publish<NativeRegistry, Server> {
10
+ (owner: Publisher, name: string, target: FetchHandler | Server, options?: NamedPublicationOptions): ReturnType<Publish<NativeRegistry, Server>>;
11
+ }
12
+ export declare function deployment<const Name extends string, const Services extends ServiceFacts = Record<never, never>>(name: Name, options: DeploymentOptions<Services>): Deployment<Services, Name extends "local" ? LocalConnectionRegistry : TnlConnectionRegistry>;
13
+ export declare function connect<Services extends ServiceFacts, Registry extends NativeRegistry, Name extends ServiceNames<Services>>(owner: Deployment<Services, Registry>, name: Name): Promise<Registry[Services[Name]["protocol"]]>;
14
+ export declare function client<Services extends ServiceFacts, Registry extends NativeRegistry, Name extends ServiceNames<Services>, Client>(owner: Deployment<Services, Registry>, name: Name, driver: TnlClientOptions<Registry[Services[Name]["protocol"]], Client>): import("../../project.js").TnlClientFactory<Client>;
15
+ export declare function publishNative(owner: object, first: string | FetchHandler | LocalHTTPServer, second?: FetchHandler | LocalHTTPServer | TemporaryPublicationOptions, third?: NamedPublicationOptions): Promise<import("../publisher/publication.js").Publication>;
16
+ export {};
@@ -0,0 +1,30 @@
1
+ import { nativePublisherOperation } from "../publisher/native_publisher.js";
2
+ import { TnlError } from "../../errors.js";
3
+ import { createClient, } from "./client.js";
4
+ import { deploymentHandles } from "./operation_handles.js";
5
+ const owners = deploymentHandles();
6
+ export function deployment(name, options) {
7
+ const owner = createClient(options).deployment(name);
8
+ return owners.handle(owner);
9
+ }
10
+ export async function connect(owner, name) {
11
+ return owners.get(owner).connect(name);
12
+ }
13
+ export function client(owner, name, driver) {
14
+ return owners.get(owner).client(name, {
15
+ create: (connection) => driver.create(connection),
16
+ close: driver.close,
17
+ });
18
+ }
19
+ export async function publishNative(owner, first, second, third) {
20
+ const learned = nativePublisherOperation(owner);
21
+ if (learned !== undefined) {
22
+ if (typeof first !== "string" || second === undefined)
23
+ throw new TnlError("sdk.configuration_invalid");
24
+ return learned(first, second, third);
25
+ }
26
+ const runtime = owners.get(owner);
27
+ return typeof first === "string"
28
+ ? runtime.publish(first, second, third)
29
+ : runtime.publish(first, second);
30
+ }
@@ -0,0 +1,7 @@
1
+ import { TnlError } from "../../errors.js";
2
+ import type { TnlOpenStream, TnlTLSStream } from "../../project.js";
3
+ import type { ConnectionSnapshot } from "./snapshot.js";
4
+ export declare function nativeStreams(): {
5
+ open(select: (signal: AbortSignal) => Promise<ConnectionSnapshot>): TnlOpenStream<TnlTLSStream>;
6
+ close(reason: TnlError): Promise<void>;
7
+ };
@@ -0,0 +1,219 @@
1
+ import { connect } from "node:net";
2
+ import { connect as tlsConnect } from "node:tls";
3
+ import { TnlError } from "../../errors.js";
4
+ import { wasmStream } from "./wasm_stream.js";
5
+ const postgresSSLRequest = Uint8Array.of(0, 0, 0, 8, 4, 210, 22, 47);
6
+ function trackSocket(socket) {
7
+ let failed = false;
8
+ socket.on("error", () => {
9
+ failed = true;
10
+ });
11
+ return {
12
+ socket,
13
+ failed: () => failed,
14
+ done: new Promise((resolve) => socket.once("close", () => resolve())),
15
+ };
16
+ }
17
+ const unavailable = () => new TnlError("sdk.connection_unavailable");
18
+ function activity({ socket, failed }, event) {
19
+ if (socket.destroyed || failed())
20
+ return Promise.reject(unavailable());
21
+ return new Promise((resolve, reject) => {
22
+ const cleanup = () => {
23
+ socket.off(event, success).off("error", failure).off("close", failure).off("end", end);
24
+ };
25
+ const success = () => {
26
+ cleanup();
27
+ resolve();
28
+ };
29
+ const failure = () => {
30
+ cleanup();
31
+ reject(unavailable());
32
+ };
33
+ const end = event === "readable" ? success : failure;
34
+ socket.once(event, success).once("error", failure).once("close", failure).once("end", end);
35
+ });
36
+ }
37
+ async function read(transport, max) {
38
+ const { socket } = transport;
39
+ for (;;) {
40
+ if (transport.failed())
41
+ throw unavailable();
42
+ const length = socket.readableLength;
43
+ if (length > 0) {
44
+ const bytes = socket.read(Math.min(max, length));
45
+ if (bytes instanceof Uint8Array)
46
+ return bytes;
47
+ }
48
+ else {
49
+ // release an empty readable event and allow Node to report EOF.
50
+ socket.read(0);
51
+ }
52
+ if (socket.readableEnded)
53
+ return null;
54
+ await activity(transport, "readable");
55
+ }
56
+ }
57
+ function write(socket, bytes) {
58
+ return new Promise((resolve, reject) => socket.write(bytes, (error) => (error ? reject(unavailable()) : resolve())));
59
+ }
60
+ async function closeWrite({ socket }) {
61
+ if (!socket.writable || socket.destroyed)
62
+ throw unavailable();
63
+ await new Promise((resolve, reject) => {
64
+ const fail = () => reject(unavailable());
65
+ socket.once("close", fail);
66
+ socket.end(() => {
67
+ socket.off("close", fail);
68
+ if (socket.writableFinished)
69
+ resolve();
70
+ else
71
+ fail();
72
+ });
73
+ });
74
+ }
75
+ function mysqlSSLRequest(bytes) {
76
+ // require one SSLRequest (sequence 1, CLIENT_PROTOCOL_41 and CLIENT_SSL)
77
+ // before sending any login bytes through this socket.
78
+ return (bytes.length === 36 &&
79
+ bytes[0] === 32 &&
80
+ bytes[1] === 0 &&
81
+ bytes[2] === 0 &&
82
+ bytes[3] === 1 &&
83
+ ((bytes[5] ?? 0) & 0x0a) === 0x0a &&
84
+ bytes.subarray(13).every((value) => value === 0));
85
+ }
86
+ async function openSocket(snapshot, signal, release) {
87
+ if (snapshot.expires <= Date.now())
88
+ throw unavailable();
89
+ signal.throwIfAborted();
90
+ const raw = trackSocket(connect({ host: snapshot.host, port: snapshot.port, allowHalfOpen: true }));
91
+ let active = raw;
92
+ let secured = false;
93
+ let mysqlRequest = new Uint8Array();
94
+ const stop = () => {
95
+ active.socket.destroy();
96
+ raw.socket.destroy();
97
+ };
98
+ const close = async () => {
99
+ stop();
100
+ await Promise.all([active.done, raw.done]);
101
+ };
102
+ const startTls = async () => {
103
+ if (snapshot.protocol === "tcp" ||
104
+ secured ||
105
+ (snapshot.protocol === "mysql" && mysqlRequest.length !== 36))
106
+ throw new TnlError("sdk.configuration_invalid");
107
+ const timer = setTimeout(stop, 10_000);
108
+ try {
109
+ if (snapshot.protocol === "postgres") {
110
+ await write(raw.socket, postgresSSLRequest);
111
+ const reply = await read(raw, 1);
112
+ if (reply?.[0] !== 83)
113
+ throw unavailable();
114
+ }
115
+ const options = {
116
+ socket: raw.socket,
117
+ ...snapshot.ssl,
118
+ allowHalfOpen: true,
119
+ minVersion: "TLSv1.2",
120
+ ...(snapshot.protocol === "http" || snapshot.protocol === "kubernetes"
121
+ ? { ALPNProtocols: ["http/1.1"] }
122
+ : {}),
123
+ };
124
+ active = trackSocket(tlsConnect(options));
125
+ await activity(active, "secureConnect");
126
+ secured = true;
127
+ mysqlRequest = new Uint8Array();
128
+ }
129
+ finally {
130
+ clearTimeout(timer);
131
+ }
132
+ };
133
+ signal.addEventListener("abort", stop, { once: true });
134
+ try {
135
+ const timer = setTimeout(stop, 10_000);
136
+ try {
137
+ await activity(raw, "connect");
138
+ }
139
+ finally {
140
+ clearTimeout(timer);
141
+ }
142
+ const stream = wasmStream({
143
+ read: (max) => read(active, max),
144
+ async write(bytes) {
145
+ if (snapshot.protocol === "mysql" && !secured) {
146
+ const length = mysqlRequest.length + bytes.length;
147
+ if (length > 36)
148
+ throw new TnlError("sdk.configuration_invalid");
149
+ const request = new Uint8Array(length);
150
+ request.set(mysqlRequest);
151
+ request.set(bytes, mysqlRequest.length);
152
+ if (length === 36 && !mysqlSSLRequest(request))
153
+ throw new TnlError("sdk.configuration_invalid");
154
+ mysqlRequest = request;
155
+ if (length < 36)
156
+ return;
157
+ await write(active.socket, request);
158
+ return;
159
+ }
160
+ await write(active.socket, bytes);
161
+ },
162
+ async closeWrite() {
163
+ if (snapshot.protocol === "mysql" && !secured)
164
+ throw new TnlError("sdk.configuration_invalid");
165
+ await closeWrite(active);
166
+ },
167
+ close,
168
+ startTls,
169
+ }, signal, release);
170
+ if (snapshot.protocol !== "tcp" && snapshot.protocol !== "mysql")
171
+ await stream.startTls();
172
+ signal.throwIfAborted();
173
+ return stream;
174
+ }
175
+ catch (error) {
176
+ await close();
177
+ if (signal.aborted)
178
+ throw signal.reason;
179
+ throw error;
180
+ }
181
+ finally {
182
+ signal.removeEventListener("abort", stop);
183
+ }
184
+ }
185
+ export function nativeStreams() {
186
+ const lifetime = new AbortController();
187
+ const streams = new Set();
188
+ const opening = new Set();
189
+ return {
190
+ open(select) {
191
+ return ({ signal } = {}) => {
192
+ if (lifetime.signal.aborted)
193
+ return Promise.reject(lifetime.signal.reason);
194
+ if (opening.size + streams.size >= 64)
195
+ return Promise.reject(new TnlError("sdk.client_capacity"));
196
+ const selected = signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal;
197
+ const pending = (async () => {
198
+ selected.throwIfAborted();
199
+ const snapshot = await select(selected);
200
+ const stream = await openSocket(snapshot, selected, () => streams.delete(stream));
201
+ streams.add(stream);
202
+ if (selected.aborted) {
203
+ await stream.close();
204
+ throw selected.reason;
205
+ }
206
+ return stream;
207
+ })();
208
+ opening.add(pending);
209
+ void pending.then(() => opening.delete(pending), () => opening.delete(pending));
210
+ return pending;
211
+ };
212
+ },
213
+ async close(reason) {
214
+ lifetime.abort(reason);
215
+ await Promise.allSettled(opening);
216
+ await Promise.all([...streams].map((stream) => stream.close()));
217
+ },
218
+ };
219
+ }
@@ -0,0 +1,9 @@
1
+ import type { ServiceFacts } from "../../project.js";
2
+ import type { Deployment } from "./deployment_types.js";
3
+ /** one opaque public handle per owner; no public operation methods or credentials. */
4
+ export declare function deploymentHandles<Owner extends {
5
+ close(): Promise<void>;
6
+ }>(): {
7
+ handle<Services extends ServiceFacts, Registry>(owner: Owner): Deployment<Services, Registry>;
8
+ get(handle: object): Owner;
9
+ };