@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,223 @@
1
+ import * as z from "zod";
2
+ import { TnlError } from "../../errors.js";
3
+ import { projectRuntimeSchema } from "../project/runtime.js";
4
+ import { parseValue } from "../validation.js";
5
+ import { hostnameSchema, httpsOriginSchema, registrationIDSchema, serviceNameSchema, } from "../values.js";
6
+ import { exportedCertificateSchema, } from "../publication_certificate.js";
7
+ const assignmentSchema = z
8
+ .strictObject({
9
+ version: z.literal(1),
10
+ registration_id: registrationIDSchema,
11
+ service: serviceNameSchema,
12
+ hostname: z.union([hostnameSchema, z.literal("")]),
13
+ public_url: z.union([httpsOriginSchema, z.literal("")]),
14
+ project: projectRuntimeSchema,
15
+ })
16
+ .refine(({ service, hostname, public_url, project }) => {
17
+ const metadata = project.services[service];
18
+ return (project.dev &&
19
+ (hostname === ""
20
+ ? public_url === "" && metadata === undefined
21
+ : metadata?.protocol === "http" &&
22
+ metadata.hostname === hostname &&
23
+ metadata.url === `https://${hostname}` &&
24
+ public_url === (metadata.public ? metadata.url : "")));
25
+ })
26
+ .transform(({ registration_id, service, hostname, public_url, project }) => ({
27
+ registrationID: registration_id,
28
+ service,
29
+ hostname: hostname === "" ? undefined : hostname,
30
+ publicURL: public_url === "" ? undefined : public_url,
31
+ project,
32
+ }))
33
+ .readonly();
34
+ export function parseAssignment(value) {
35
+ return parseValue(assignmentSchema, value, "sdk.response_invalid");
36
+ }
37
+ const registrationSchema = z
38
+ .strictObject({
39
+ version: z.literal(1),
40
+ registration_id: registrationIDSchema,
41
+ owner: z.string(),
42
+ target: z.string(),
43
+ })
44
+ .readonly();
45
+ const installedCertificateSchema = z.strictObject({
46
+ certificate: z.strictObject({
47
+ certificate_pem: z.string(),
48
+ private_key_pem: z.string(),
49
+ }),
50
+ expires_at: z.number(),
51
+ });
52
+ export function recoverableRegistration(cause) {
53
+ return (cause instanceof TnlError &&
54
+ (cause.code === "sdk.dev_unavailable" || cause.code === "sdk.registration_stale"));
55
+ }
56
+ export function publicationCleanupFailed(cause) {
57
+ return cause instanceof TnlError && cause.code === "sdk.publication_cleanup_failed";
58
+ }
59
+ // owns one native acquisition and its exact cleanup identity. callers serialize
60
+ // mutations and join their renewal/observation loops before unregistering.
61
+ export class NativeRegistration {
62
+ currentEndpoint;
63
+ current;
64
+ uncertain = false;
65
+ unregisterReplyLost = false;
66
+ acquisition;
67
+ runtime;
68
+ directory;
69
+ selection;
70
+ constructor(runtime, directory, selection, acquisition) {
71
+ // capture nested policy and deployment inputs, not caller-owned objects.
72
+ this.acquisition = structuredClone(acquisition);
73
+ this.runtime = runtime;
74
+ this.directory = directory;
75
+ this.selection = {
76
+ ...selection,
77
+ ...(selection.environment === undefined ? {} : { environment: { ...selection.environment } }),
78
+ };
79
+ }
80
+ get endpoint() {
81
+ if (this.currentEndpoint === undefined)
82
+ throw new TnlError("sdk.registration_stale");
83
+ return this.currentEndpoint;
84
+ }
85
+ get registration() {
86
+ return this.current;
87
+ }
88
+ async discover(signal) {
89
+ this.currentEndpoint = await this.runtime.start(this.directory, undefined, this.selection, signal);
90
+ }
91
+ async acquire(signal) {
92
+ this.uncertain = true;
93
+ try {
94
+ const { kind, request } = this.acquisition;
95
+ if (kind === "configured") {
96
+ const assignment = parseAssignment(await this.runtime.request(this.endpoint, "prepare", structuredClone(request), signal));
97
+ // retain the acknowledgment before caller-specific endpoint validation.
98
+ this.current = {
99
+ version: 1,
100
+ registration_id: assignment.registrationID,
101
+ owner: request.owner,
102
+ ...(this.acquisition.kind === "configured" && this.acquisition.target !== undefined
103
+ ? { target: this.acquisition.target }
104
+ : {}),
105
+ };
106
+ this.uncertain = false;
107
+ return assignment;
108
+ }
109
+ const registration = parseValue(registrationSchema, await this.runtime.request(this.endpoint, "publications/register", structuredClone(request), signal), "sdk.response_invalid");
110
+ if (registration.owner !== request.owner || registration.target !== request.target)
111
+ throw new TnlError("sdk.response_invalid");
112
+ this.current = registration;
113
+ this.uncertain = false;
114
+ return undefined;
115
+ }
116
+ catch (cause) {
117
+ if (cause instanceof TnlError &&
118
+ !["sdk.dev_unavailable", "sdk.registration_stale", "sdk.response_invalid"].includes(cause.code))
119
+ this.uncertain = false;
120
+ throw cause;
121
+ }
122
+ }
123
+ async bind(target, signal) {
124
+ if (this.current === undefined)
125
+ throw new TnlError("sdk.registration_stale");
126
+ this.current = { ...this.current, target };
127
+ await this.runtime.request(this.endpoint, "register", this.current, signal);
128
+ }
129
+ async renew(signal, certificate) {
130
+ if (certificate !== undefined && this.acquisition.kind !== "invocation")
131
+ throw new TnlError("sdk.capability_unsupported");
132
+ const request = certificate === undefined
133
+ ? this.current
134
+ : {
135
+ ...this.current,
136
+ certificate: {
137
+ certificate_pem: certificate.certificatePEM,
138
+ private_key_pem: certificate.privateKeyPEM,
139
+ },
140
+ };
141
+ await this.runtime.request(this.endpoint, "renew", request, signal);
142
+ }
143
+ async status(signal) {
144
+ return this.runtime.request(this.endpoint, "status", undefined, signal);
145
+ }
146
+ async exportCertificate(signal) {
147
+ if (signal.aborted)
148
+ throw new TnlError("sdk.certificate_unavailable");
149
+ if (this.acquisition.kind !== "invocation")
150
+ throw new TnlError("sdk.capability_unsupported");
151
+ const registration = this.current;
152
+ if (registration === undefined)
153
+ throw new TnlError("sdk.certificate_unavailable");
154
+ const endpoint = this.endpoint;
155
+ let value;
156
+ try {
157
+ value = await this.runtime.request(endpoint, "publications/certificate", registration, signal);
158
+ }
159
+ catch (cause) {
160
+ if (signal.aborted)
161
+ throw new TnlError("sdk.certificate_unavailable");
162
+ throw cause;
163
+ }
164
+ if (signal.aborted || this.current !== registration || this.currentEndpoint !== endpoint)
165
+ throw new TnlError("sdk.certificate_unavailable");
166
+ const { certificate, expires_at } = parseValue(installedCertificateSchema, value, "sdk.response_invalid");
167
+ return parseValue(exportedCertificateSchema, {
168
+ certificate: {
169
+ certificatePEM: certificate.certificate_pem,
170
+ privateKeyPEM: certificate.private_key_pem,
171
+ },
172
+ expiresAt: expires_at,
173
+ }, "sdk.response_invalid");
174
+ }
175
+ async unregister(budget, retry) {
176
+ budget.signal.throwIfAborted();
177
+ const attempts = retry === undefined ? 1 : 3;
178
+ if (this.uncertain && this.acquisition.kind === "configured" && this.current === undefined)
179
+ throw new TnlError("sdk.dev_unavailable");
180
+ // only invocation acquisition has an exact idempotent replay contract.
181
+ for (let attempt = 0; this.uncertain && this.acquisition.kind === "invocation"; attempt++) {
182
+ try {
183
+ await this.acquire(budget.signal);
184
+ }
185
+ catch (cause) {
186
+ if (attempt + 1 >= attempts || !unavailable(cause))
187
+ throw cause;
188
+ await this.discover(budget.signal);
189
+ }
190
+ }
191
+ if (this.current === undefined)
192
+ return;
193
+ for (let attempt = 0;; attempt++) {
194
+ try {
195
+ await this.runtime.request(this.endpoint, "unregister", { ...this.current, shutdown_deadline: budget.deadline }, budget.signal);
196
+ break;
197
+ }
198
+ catch (cause) {
199
+ if (publicationCleanupFailed(cause)) {
200
+ this.current = undefined;
201
+ this.uncertain = false;
202
+ this.unregisterReplyLost = false;
203
+ }
204
+ if (this.unregisterReplyLost &&
205
+ cause instanceof TnlError &&
206
+ cause.code === "sdk.registration_stale")
207
+ throw new TnlError("sdk.dev_unavailable");
208
+ if (unavailable(cause) ||
209
+ (cause instanceof TnlError && cause.code === "sdk.response_invalid"))
210
+ this.unregisterReplyLost = true;
211
+ if (attempt + 1 >= attempts || !unavailable(cause))
212
+ throw cause;
213
+ await retry?.pause(100, budget.signal);
214
+ }
215
+ }
216
+ this.current = undefined;
217
+ this.uncertain = false;
218
+ this.unregisterReplyLost = false;
219
+ }
220
+ }
221
+ function unavailable(cause) {
222
+ return cause instanceof TnlError && cause.code === "sdk.dev_unavailable";
223
+ }
@@ -0,0 +1,47 @@
1
+ import * as z from "zod";
2
+ import { type PublicationRun } from "../publication_run.js";
3
+ declare const serviceStatusSchema: z.ZodObject<{
4
+ project: z.ZodOptional<z.ZodString>;
5
+ service: z.ZodString;
6
+ service_protocol: z.ZodOptional<z.ZodLiteral<"http">>;
7
+ directory: z.ZodString;
8
+ tunnel_id: z.ZodOptional<z.ZodString>;
9
+ public_url: z.ZodOptional<z.ZodTemplateLiteral<`https://${string}`>>;
10
+ registration_id: z.ZodOptional<z.ZodString>;
11
+ target: z.ZodOptional<z.ZodString>;
12
+ framework: z.ZodOptional<z.ZodString>;
13
+ registered: z.ZodBoolean;
14
+ routable: z.ZodBoolean;
15
+ ready: z.ZodBoolean;
16
+ run_number: z.ZodOptional<z.ZodInt>;
17
+ provisioning_stage: z.ZodOptional<z.ZodString>;
18
+ readiness: z.ZodObject<{
19
+ path: z.ZodString;
20
+ }, z.core.$strict>;
21
+ observation: z.ZodOptional<z.ZodObject<{
22
+ registration_id: z.ZodString;
23
+ run_number: z.ZodInt;
24
+ checked_at: z.ZodString;
25
+ status: z.ZodOptional<z.ZodInt>;
26
+ ready: z.ZodBoolean;
27
+ reason: z.ZodOptional<z.ZodString>;
28
+ readiness: z.ZodObject<{
29
+ path: z.ZodString;
30
+ }, z.core.$strict>;
31
+ }, z.core.$strict>>;
32
+ failure: z.ZodOptional<z.ZodString>;
33
+ }, z.core.$strict>;
34
+ declare function publicationStatus(item: z.output<typeof serviceStatusSchema>): {
35
+ registered: boolean;
36
+ routable: boolean;
37
+ ready: boolean;
38
+ publicURL?: `https://${string}`;
39
+ publishRunNumber?: number;
40
+ failure?: string;
41
+ };
42
+ export type PublicationStatus = Readonly<ReturnType<typeof publicationStatus> & {
43
+ run?: PublicationRun;
44
+ publisherURL?: `https://${string}`;
45
+ }>;
46
+ export declare function parseStatus(value: unknown, service: string, registrationID: string, target: string): PublicationStatus | undefined;
47
+ export {};
@@ -0,0 +1,137 @@
1
+ import * as z from "zod";
2
+ import { TnlError } from "../../errors.js";
3
+ import { parseValue } from "../validation.js";
4
+ import { publicationRunSchema, publisherURLSchema, } from "../publication_run.js";
5
+ import { hostnameSchema, httpsOriginSchema, invocationIDSchema, serviceIDSchema, timestampSchema, } from "../values.js";
6
+ const textSchema = z.string().max(4096);
7
+ const runNumberSchema = z.int().positive();
8
+ const publicationSchema = z.strictObject({
9
+ tunnel_id: textSchema,
10
+ command: z.enum(["publish", "dev"]),
11
+ state: z.enum(["starting", "provisioning", "ready", "draining", "stopped", "failed", "stale"]),
12
+ process_id: runNumberSchema,
13
+ server: textSchema,
14
+ project: textSchema,
15
+ service: textSchema.exactOptional(),
16
+ service_protocol: textSchema.exactOptional(),
17
+ service_id: serviceIDSchema.exactOptional(),
18
+ service_run_id: publicationRunSchema.shape.serviceRunID.exactOptional(),
19
+ run_hostname: hostnameSchema
20
+ .refine((hostname) => publisherURLSchema.safeParse(`https://${hostname}`).success)
21
+ .exactOptional(),
22
+ publish_run_number: runNumberSchema.exactOptional(),
23
+ public_port: runNumberSchema.exactOptional(),
24
+ hostname: textSchema.exactOptional(),
25
+ public_url: textSchema.exactOptional(),
26
+ target: textSchema.exactOptional(),
27
+ framework: textSchema.exactOptional(),
28
+ started_at: textSchema,
29
+ updated_at: textSchema,
30
+ heartbeat_at: textSchema,
31
+ lease_expires_at: textSchema,
32
+ failure: textSchema.exactOptional(),
33
+ });
34
+ const observationSchema = z.strictObject({
35
+ registration_id: z.string(),
36
+ run_number: runNumberSchema,
37
+ checked_at: timestampSchema,
38
+ status: z.int().min(100).max(599).optional(),
39
+ ready: z.boolean(),
40
+ reason: z.string().optional(),
41
+ readiness: z.strictObject({ path: z.string() }),
42
+ });
43
+ const serviceStatusSchema = z.strictObject({
44
+ project: textSchema.optional(),
45
+ service: z.string(),
46
+ service_protocol: z.literal("http").optional(),
47
+ directory: textSchema,
48
+ tunnel_id: textSchema.optional(),
49
+ public_url: httpsOriginSchema
50
+ .refine((url) => {
51
+ const hostname = URL.parse(url)?.hostname;
52
+ return hostnameSchema.safeParse(hostname).success && url === `https://${hostname}`;
53
+ })
54
+ .optional(),
55
+ registration_id: textSchema.optional(),
56
+ target: textSchema.optional(),
57
+ framework: textSchema.optional(),
58
+ registered: z.boolean(),
59
+ routable: z.boolean(),
60
+ ready: z.boolean(),
61
+ run_number: runNumberSchema.optional(),
62
+ provisioning_stage: textSchema.optional(),
63
+ readiness: z.strictObject({ path: z.string().startsWith("/").max(4096) }),
64
+ observation: observationSchema.optional(),
65
+ failure: textSchema.optional(),
66
+ });
67
+ const statusSchema = z.strictObject({
68
+ schema_version: z.literal(1),
69
+ project: textSchema,
70
+ cursor: z.string().max(128),
71
+ observed_at: timestampSchema,
72
+ services: z.array(serviceStatusSchema).max(1),
73
+ publications: z.array(publicationSchema).max(64).optional(),
74
+ });
75
+ function publicationStatus(item) {
76
+ return {
77
+ registered: item.registered,
78
+ routable: item.routable,
79
+ ready: item.ready,
80
+ ...(item.public_url === undefined ? {} : { publicURL: item.public_url }),
81
+ ...(item.run_number === undefined ? {} : { publishRunNumber: item.run_number }),
82
+ ...(item.failure === undefined ? {} : { failure: item.failure }),
83
+ };
84
+ }
85
+ export function parseStatus(value, service, registrationID, target) {
86
+ const snapshot = parseValue(statusSchema, value, "sdk.response_invalid");
87
+ const item = snapshot.services[0];
88
+ if (snapshot.publications?.some((publication) => publication.service !== service &&
89
+ !(invocationIDSchema.safeParse(service).success &&
90
+ publication.service === undefined &&
91
+ item?.tunnel_id === publication.tunnel_id)))
92
+ throw new TnlError("sdk.response_invalid");
93
+ if (item === undefined)
94
+ return undefined;
95
+ if (item.service !== service ||
96
+ (item.ready &&
97
+ (item.observation === undefined ||
98
+ item.observation.registration_id !== registrationID ||
99
+ item.observation.run_number !== item.run_number ||
100
+ !item.observation.ready)))
101
+ throw new TnlError("sdk.response_invalid");
102
+ if (item.registration_id !== registrationID || item.target !== target)
103
+ return undefined;
104
+ if (item.routable && (!item.registered || item.run_number === undefined))
105
+ throw new TnlError("sdk.response_invalid");
106
+ const matching = snapshot.publications?.filter((candidate) => candidate.tunnel_id === item.tunnel_id);
107
+ if (matching !== undefined && matching.length > 1)
108
+ throw new TnlError("sdk.response_invalid");
109
+ const publication = matching?.[0];
110
+ if (publication?.run_hostname !== undefined &&
111
+ (publication.service_run_id === undefined ||
112
+ item.public_url === undefined ||
113
+ `https://${publication.run_hostname}` === item.public_url))
114
+ throw new TnlError("sdk.response_invalid");
115
+ if (publication?.service_run_id !== undefined &&
116
+ (publication.service_id === undefined ||
117
+ publication.publish_run_number === undefined ||
118
+ publication.publish_run_number !== item.run_number))
119
+ throw new TnlError("sdk.response_invalid");
120
+ return {
121
+ ...publicationStatus(item),
122
+ ...(publication?.service_run_id === undefined || publication.service_id === undefined
123
+ ? {}
124
+ : {
125
+ run: Object.freeze({
126
+ serviceID: publication.service_id,
127
+ serviceRunID: publication.service_run_id,
128
+ runNumber: String(publication.publish_run_number),
129
+ }),
130
+ }),
131
+ ...(publication?.run_hostname === undefined
132
+ ? {}
133
+ : {
134
+ publisherURL: `https://${publication.run_hostname}`,
135
+ }),
136
+ };
137
+ }
@@ -0,0 +1,6 @@
1
+ export type CanonicalTarget = `http://${string}` | `https://${string}`;
2
+ export declare function canonicalListenerTarget<Protocol extends "http" | "https">(host: string, port: number, scheme: Protocol): `${Protocol}://${string}`;
3
+ export declare function canonicalListenerTarget(host: string, port: number): `http://${string}`;
4
+ export declare function canonicalLoopbackTarget(host: string, port: number): `http://${string}`;
5
+ /** parses a decimal listener port from 1 through 65535. */
6
+ export declare function parseListenerPort(value: string): number;
@@ -0,0 +1,44 @@
1
+ import { isIP } from "node:net";
2
+ import { TnlError } from "../../errors.js";
3
+ import * as z from "zod";
4
+ import { parseValue } from "../validation.js";
5
+ import { portSchema } from "../values.js";
6
+ export function canonicalListenerTarget(host, port, scheme = "http") {
7
+ parseValue(portSchema, port, "sdk.target_invalid");
8
+ const hostname = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
9
+ const lowerHostname = hostname.toLowerCase();
10
+ if (hostname === "0.0.0.0") {
11
+ return `${scheme}://127.0.0.1:${port}`;
12
+ }
13
+ if (hostname === "::") {
14
+ return `${scheme}://[::1]:${port}`;
15
+ }
16
+ if (lowerHostname === "localhost") {
17
+ return `${scheme}://${scheme === "http" ? "127.0.0.1" : "localhost"}:${port}`;
18
+ }
19
+ if (isIP(hostname) === 4) {
20
+ return `${scheme}://${hostname}:${port}`;
21
+ }
22
+ if (isIP(hostname) === 6) {
23
+ return `${scheme}://[${hostname.toLowerCase()}]:${port}`;
24
+ }
25
+ if (lowerHostname.length <= 253 &&
26
+ lowerHostname
27
+ .split(".")
28
+ .every((label) => label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label))) {
29
+ return `${scheme}://${lowerHostname}:${port}`;
30
+ }
31
+ throw new TnlError("sdk.target_invalid");
32
+ }
33
+ export function canonicalLoopbackTarget(host, port) {
34
+ return canonicalListenerTarget(host, port, "http");
35
+ }
36
+ const listenerPortSchema = z
37
+ .string()
38
+ .regex(/^[0-9]+$/)
39
+ .transform(Number)
40
+ .pipe(portSchema);
41
+ /** parses a decimal listener port from 1 through 65535. */
42
+ export function parseListenerPort(value) {
43
+ return parseValue(listenerPortSchema, value, "sdk.target_invalid");
44
+ }
@@ -0,0 +1,38 @@
1
+ import * as z from "zod";
2
+ export declare const connectorResourcesSchema: z.ZodObject<{
3
+ streams: z.ZodExactOptional<z.ZodNumber>;
4
+ receiveBytes: z.ZodExactOptional<z.ZodNumber>;
5
+ }, z.core.$strict>;
6
+ export declare const publisherResourcesSchema: z.ZodObject<{
7
+ streams: z.ZodExactOptional<z.ZodNumber>;
8
+ connectorPeers: z.ZodExactOptional<z.ZodNumber>;
9
+ connectorWorkers: z.ZodExactOptional<z.ZodNumber>;
10
+ connectorPending: z.ZodExactOptional<z.ZodNumber>;
11
+ httpPending: z.ZodExactOptional<z.ZodNumber>;
12
+ httpPendingRelay: z.ZodExactOptional<z.ZodNumber>;
13
+ httpPendingSource: z.ZodExactOptional<z.ZodNumber>;
14
+ connector: z.ZodExactOptional<z.ZodObject<{
15
+ streams: z.ZodExactOptional<z.ZodNumber>;
16
+ receiveBytes: z.ZodExactOptional<z.ZodNumber>;
17
+ }, z.core.$strict>>;
18
+ }, z.core.$strict>;
19
+ export type ConnectorResources = z.input<typeof connectorResourcesSchema>;
20
+ export type PublisherResources = z.input<typeof publisherResourcesSchema>;
21
+ export declare function connectorResourceSelection(value: ConnectorResources): {
22
+ streams?: number;
23
+ receive_bytes?: number;
24
+ };
25
+ export declare function publisherResourceSelection(value: PublisherResources): {
26
+ streams?: number;
27
+ connector_peers?: number;
28
+ connector_workers?: number;
29
+ connector_pending?: number;
30
+ http_pending?: number;
31
+ http_pending_relay?: number;
32
+ http_pending_source?: number;
33
+ connector?: {
34
+ streams?: number;
35
+ receive_bytes?: number;
36
+ };
37
+ };
38
+ export declare function publisherResourceEnvironment(value: PublisherResources): Record<string, string>;
@@ -0,0 +1,52 @@
1
+ import * as z from "zod";
2
+ const count = z.number().int().positive().max(2147483647);
3
+ export const connectorResourcesSchema = z.strictObject({
4
+ streams: count.exactOptional(),
5
+ receiveBytes: z.number().int().positive().exactOptional(),
6
+ });
7
+ export const publisherResourcesSchema = z.strictObject({
8
+ streams: count.max(1048576).exactOptional(),
9
+ connectorPeers: count.exactOptional(),
10
+ connectorWorkers: count.exactOptional(),
11
+ connectorPending: count.exactOptional(),
12
+ httpPending: count.exactOptional(),
13
+ httpPendingRelay: count.exactOptional(),
14
+ httpPendingSource: count.exactOptional(),
15
+ connector: connectorResourcesSchema.exactOptional(),
16
+ });
17
+ export function connectorResourceSelection(value) {
18
+ return {
19
+ ...(value.streams === undefined ? {} : { streams: value.streams }),
20
+ ...(value.receiveBytes === undefined ? {} : { receive_bytes: value.receiveBytes }),
21
+ };
22
+ }
23
+ export function publisherResourceSelection(value) {
24
+ return {
25
+ ...(value.streams === undefined ? {} : { streams: value.streams }),
26
+ ...(value.connectorPeers === undefined ? {} : { connector_peers: value.connectorPeers }),
27
+ ...(value.connectorWorkers === undefined ? {} : { connector_workers: value.connectorWorkers }),
28
+ ...(value.connectorPending === undefined ? {} : { connector_pending: value.connectorPending }),
29
+ ...(value.httpPending === undefined ? {} : { http_pending: value.httpPending }),
30
+ ...(value.httpPendingRelay === undefined ? {} : { http_pending_relay: value.httpPendingRelay }),
31
+ ...(value.httpPendingSource === undefined
32
+ ? {}
33
+ : { http_pending_source: value.httpPendingSource }),
34
+ ...(value.connector === undefined
35
+ ? {}
36
+ : { connector: connectorResourceSelection(value.connector) }),
37
+ };
38
+ }
39
+ export function publisherResourceEnvironment(value) {
40
+ const result = {};
41
+ for (const [name, selected] of Object.entries(publisherResourceSelection(value))) {
42
+ if (typeof selected === "number") {
43
+ result[`TNL_PUBLISHER_${name.toUpperCase()}`] = String(selected);
44
+ }
45
+ else {
46
+ for (const [part, amount] of Object.entries(selected)) {
47
+ result[`TNL_PUBLISHER_CONNECTOR_${part.toUpperCase()}`] = String(amount);
48
+ }
49
+ }
50
+ }
51
+ return result;
52
+ }
@@ -0,0 +1,10 @@
1
+ type Operation = "sdk.prepare" | "sdk.connect" | "sdk.publish" | "sdk.app.register" | "sdk.app.renew" | "sdk.app.recover" | "sdk.app.cleanup" | "sdk.publish.recover" | "sdk.publish.renew" | "sdk.publish.status" | "sdk.publish.cleanup" | "sdk.native.command" | "sdk.native.request" | "vite.prepare" | "vite.register" | "vite.restart" | "vite.cleanup" | "next.register" | "next.restart" | "next.cleanup";
2
+ export declare function traceparent(): string | undefined;
3
+ export declare function launchEnvironment(base?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
4
+ export declare function traceHeaders(): Readonly<Record<string, string>>;
5
+ export declare function operation<T>(name: Operation, work: () => Promise<T>): Promise<T>;
6
+ export declare function independent<T>(name: Operation, work: () => Promise<T>): () => Promise<T>;
7
+ export declare function scheduled<T>(work: () => T): () => T;
8
+ export declare function background<T>(work: () => T): T;
9
+ export declare function bound(): void;
10
+ export {};
@@ -0,0 +1,78 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { context, trace, ROOT_CONTEXT, SpanStatusCode, isSpanContextValid, createContextKey, } from "@opentelemetry/api";
3
+ // use the host's OTel provider without installing globals or exporters. local
4
+ // async scope also carries native launch parents when the host has no manager.
5
+ const local = new AsyncLocalStorage();
6
+ const tracer = trace.getTracer("@madebyentropy/tnl");
7
+ const schedulingLinks = createContextKey("tnl scheduling links");
8
+ function options(name, parent) {
9
+ const links = trace.getSpanContext(parent) === undefined
10
+ ? parent.getValue(schedulingLinks)
11
+ : undefined;
12
+ return {
13
+ attributes: { "tnl.operation": name, "tnl.component": "client" },
14
+ ...(links === undefined ? {} : { links }),
15
+ };
16
+ }
17
+ function active() {
18
+ return local.getStore() ?? context.active();
19
+ }
20
+ function runContext(scope, work) {
21
+ return local.run(scope, () => context.with(scope, work));
22
+ }
23
+ export function traceparent() {
24
+ const sc = trace.getSpanContext(active());
25
+ if (sc === undefined || !isSpanContextValid(sc))
26
+ return undefined;
27
+ return `00-${sc.traceId}-${sc.spanId}-${(sc.traceFlags & 1) === 1 ? "01" : "00"}`;
28
+ }
29
+ export function launchEnvironment(base = process.env) {
30
+ const environment = { ...base };
31
+ delete environment.TNL_TRACEPARENT;
32
+ const parent = traceparent();
33
+ if (parent !== undefined)
34
+ environment.TNL_TRACEPARENT = parent;
35
+ return environment;
36
+ }
37
+ export function traceHeaders() {
38
+ const parent = traceparent();
39
+ return parent === undefined ? {} : { traceparent: parent };
40
+ }
41
+ export async function operation(name, work) {
42
+ const parent = active();
43
+ const span = tracer.startSpan(name, options(name, parent), parent);
44
+ return runContext(trace.setSpan(parent, span), async () => {
45
+ try {
46
+ const result = await work();
47
+ span.setAttribute("tnl.outcome", "success");
48
+ return result;
49
+ }
50
+ catch (cause) {
51
+ span.setAttribute("tnl.outcome", "error");
52
+ span.setStatus({ code: SpanStatusCode.ERROR, message: "error" });
53
+ throw cause;
54
+ }
55
+ finally {
56
+ span.end();
57
+ }
58
+ });
59
+ }
60
+ // scheduled work retains only a bounded causal link. it does not retain a
61
+ // request's context, baggage, tracestate, or authenticated application values.
62
+ export function independent(name, work) {
63
+ return scheduled(() => operation(name, work));
64
+ }
65
+ export function scheduled(work) {
66
+ const sc = trace.getSpanContext(active());
67
+ const links = sc === undefined || !isSpanContextValid(sc)
68
+ ? []
69
+ : [{ context: { traceId: sc.traceId, spanId: sc.spanId, traceFlags: sc.traceFlags } }];
70
+ const root = ROOT_CONTEXT.setValue(schedulingLinks, links);
71
+ return () => runContext(root, work);
72
+ }
73
+ export function background(work) {
74
+ return runContext(ROOT_CONTEXT, work);
75
+ }
76
+ export function bound() {
77
+ trace.getSpan(active())?.addEvent("bound", { "tnl.event": "bound" });
78
+ }
@@ -0,0 +1,3 @@
1
+ import * as z from "zod";
2
+ import { type TnlErrorCode } from "../errors.js";
3
+ export declare function parseValue<T>(schema: z.ZodType<T>, value: unknown, code: TnlErrorCode): T;
@@ -0,0 +1,9 @@
1
+ import * as z from "zod";
2
+ import { privateTnlError } from "../errors.js";
3
+ // schema issues can contain capabilities or assertions; keep them out of public errors.
4
+ export function parseValue(schema, value, code) {
5
+ const result = schema.safeParse(value);
6
+ if (!result.success)
7
+ throw privateTnlError(code, result.error);
8
+ return result.data;
9
+ }