@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,627 @@
1
+ import { randomBytes, randomInt } from "node:crypto";
2
+ import * as path from "node:path";
3
+ import { isIP } from "node:net";
4
+ import { setTimeout as pause } from "node:timers/promises";
5
+ import { TnlCleanupError, TnlError } from "../../errors.js";
6
+ import { operation, independent, scheduled, background, bound } from "../tracing.js";
7
+ import { startRuntime, runtimeRequest, canceledRuntimeRequest } from "./local.js";
8
+ import { closeServer, listeningTarget, isBunServer, observeListenerClose, } from "./register.js";
9
+ import * as z from "zod";
10
+ import { parseValue } from "../validation.js";
11
+ import { httpsOriginSchema, pathTextSchema } from "../values.js";
12
+ import { parseStatus } from "./status.js";
13
+ import { NativeRegistration, publicationCleanupFailed, } from "./registration.js";
14
+ import { resolveServiceCertificate, serviceCertificateSourceSchema, } from "../publication_certificate.js";
15
+ export function validatePublicationOptions(options, named) {
16
+ validateOptions(options);
17
+ const allowed = new Set(named
18
+ ? ["targetHostname", "signal", "telemetry", "certificate"]
19
+ : [
20
+ "targetHostname",
21
+ "signal",
22
+ "telemetry",
23
+ "certificate",
24
+ "requirePostQuantum",
25
+ "access",
26
+ "limits",
27
+ "public",
28
+ ]);
29
+ if (Object.keys(options).some((key) => !allowed.has(key)))
30
+ throw new TnlError("sdk.configuration_invalid");
31
+ }
32
+ export const nativePublicationRuntime = {
33
+ start: startRuntime,
34
+ request: runtimeRequest,
35
+ pause: async (milliseconds, signal) => {
36
+ await pause(milliseconds, undefined, {
37
+ ref: false,
38
+ ...(signal === undefined ? {} : { signal }),
39
+ });
40
+ },
41
+ };
42
+ function publicationShutdown(original) {
43
+ const controller = new AbortController();
44
+ const deadline = original ?? new Date(Date.now() + 10_000).toISOString();
45
+ const abort = () => controller.abort(new DOMException("publication shutdown timed out; remote cleanup may be unconfirmed", "TimeoutError"));
46
+ const remaining = Date.parse(deadline) - Date.now();
47
+ const timer = setTimeout(abort, Math.max(0, remaining));
48
+ if (remaining <= 0)
49
+ abort();
50
+ return { signal: controller.signal, deadline, finish: () => clearTimeout(timer) };
51
+ }
52
+ // registration acknowledges a listener; filtered status identifies its exact run.
53
+ export function publishServer(server, options = {}, runtime = nativePublicationRuntime, publication, shutdown) {
54
+ return operation("sdk.publish", () => publishServerUntraced(server, options, runtime, publication, shutdown));
55
+ }
56
+ async function publishServerUntraced(server, options, runtime, publication, shutdown) {
57
+ validateOptions(options);
58
+ const target = await listeningTarget(server, options);
59
+ bound();
60
+ const directory = path.resolve(options.directory ?? process.cwd());
61
+ const environment = publication?.environment ?? process.env;
62
+ const localService = publication?.kind === "local" ? publication.service : undefined;
63
+ if (localService !== undefined && options.certificate !== undefined)
64
+ throw new TnlError("sdk.capability_unsupported");
65
+ const certificate = options.certificate === undefined
66
+ ? undefined
67
+ : await resolveServiceCertificate(options.certificate, options.signal ?? new AbortController().signal);
68
+ const owner = randomBytes(16).toString("hex");
69
+ const invocationID = `ivk_${Array.from({ length: 22 }, () => "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[randomInt(62)]).join("")}`;
70
+ // the SDK process may receive this environment variable after the native
71
+ // owner starts. pass the path, never the credential contents, to that owner.
72
+ const publisherCredentialFile = localService === undefined &&
73
+ publication?.kind !== "deployment" &&
74
+ publication?.kind !== "enrolled" &&
75
+ options.publisherIdentityID === undefined
76
+ ? (options.publisherCredentialFile ?? environment.TNL_PUBLISHER_CREDENTIAL_FILE)
77
+ : undefined;
78
+ if (publisherCredentialFile !== undefined &&
79
+ !validPublisherCredentialFile(publisherCredentialFile))
80
+ throw new TnlError("sdk.configuration_invalid");
81
+ const request = {
82
+ version: 1,
83
+ invocation_id: invocationID,
84
+ owner,
85
+ pid: process.pid,
86
+ target,
87
+ ...(certificate === undefined
88
+ ? {}
89
+ : {
90
+ certificate: {
91
+ certificate_pem: certificate.certificatePEM,
92
+ private_key_pem: certificate.privateKeyPEM,
93
+ },
94
+ }),
95
+ ...(publication?.kind !== "deployment"
96
+ ? {}
97
+ : {
98
+ deployment: {
99
+ project: publication.project,
100
+ name: publication.name,
101
+ credential: publication.credential,
102
+ ...(publication.service === undefined ? {} : { service: publication.service }),
103
+ },
104
+ }),
105
+ ...(publication?.kind === "enrolled" ? { enrolled_service: publication.service } : {}),
106
+ telemetry_disabled: options.telemetry === false || /^(1|true)$/i.test(environment.TNL_NO_TELEMETRY ?? ""),
107
+ ...(options.server === undefined ? {} : { server_url: options.server }),
108
+ ...(options.publisherIdentityID === undefined
109
+ ? {}
110
+ : { publisher_identity_id: options.publisherIdentityID }),
111
+ ...(publisherCredentialFile === undefined
112
+ ? {}
113
+ : { publisher_credential_file: publisherCredentialFile }),
114
+ ...(options.access === undefined
115
+ ? {}
116
+ : {
117
+ access_mode: typeof options.access === "string"
118
+ ? options.access
119
+ : (options.access.mode ?? "restricted"),
120
+ ...(typeof options.access === "string" || options.access.ip === undefined
121
+ ? {}
122
+ : { ip: [...options.access.ip] }),
123
+ }),
124
+ ...(options.limits === undefined
125
+ ? {}
126
+ : {
127
+ limits: {
128
+ ...(options.limits.requests === undefined ? {} : { total: options.limits.requests }),
129
+ ...(options.limits.concurrency === undefined
130
+ ? {}
131
+ : { concurrency: options.limits.concurrency }),
132
+ ...(options.limits.rate === undefined
133
+ ? {}
134
+ : { rate: { count: options.limits.rate.requests, per: options.limits.rate.per } }),
135
+ },
136
+ }),
137
+ ...(options.requirePostQuantum === undefined
138
+ ? {}
139
+ : { require_post_quantum: options.requirePostQuantum }),
140
+ ...(options.public === undefined ? {} : { public: options.public }),
141
+ };
142
+ const selection = {
143
+ ...(localService === undefined ? { invocationID } : { service: localService }),
144
+ environment,
145
+ ...(publication?.kind === "deployment" ? { publications: true } : {}),
146
+ ...(options.stateDir === undefined ? {} : { stateDir: options.stateDir }),
147
+ };
148
+ const native = new NativeRegistration(runtime, directory, selection, localService === undefined
149
+ ? { kind: "invocation", request }
150
+ : {
151
+ kind: "configured",
152
+ target,
153
+ request: {
154
+ version: 1,
155
+ directory,
156
+ service: localService,
157
+ framework: isBunServer(server) ? "bun" : "node",
158
+ owner,
159
+ pid: process.pid,
160
+ telemetry_disabled: request.telemetry_disabled,
161
+ },
162
+ });
163
+ await native.discover(options.signal);
164
+ if (options.signal?.aborted)
165
+ throw aborted();
166
+ let currentURL;
167
+ let currentRun;
168
+ let currentPublisherURL;
169
+ let shutdownBudget;
170
+ let shutdownUntil;
171
+ const beginShutdown = () => {
172
+ if (shutdown !== undefined)
173
+ return shutdown();
174
+ const parent = publication?.shutdownDeadline?.();
175
+ if (parent !== undefined && (shutdownUntil === undefined || parent < shutdownUntil))
176
+ shutdownUntil = parent;
177
+ shutdownBudget ??= publicationShutdown(shutdownUntil);
178
+ shutdownUntil = shutdownBudget.deadline;
179
+ return shutdownBudget;
180
+ };
181
+ const finishShutdown = () => {
182
+ shutdownBudget?.finish();
183
+ shutdownBudget = undefined;
184
+ };
185
+ const lifetime = new AbortController();
186
+ const abortLifetime = () => lifetime.abort(options.signal?.reason);
187
+ options.signal?.addEventListener("abort", abortLifetime, { once: true });
188
+ const register = async (signal = lifetime.signal) => {
189
+ const assignment = await native.acquire(signal);
190
+ if (assignment === undefined)
191
+ return;
192
+ if (native.endpoint.scope !== "app" ||
193
+ assignment.service !== localService ||
194
+ native.endpoint.service !== localService ||
195
+ (assignment.publicURL !== undefined &&
196
+ currentURL !== undefined &&
197
+ currentURL !== assignment.publicURL))
198
+ throw new TnlError("sdk.response_invalid");
199
+ if (assignment.publicURL !== undefined)
200
+ currentURL = assignment.publicURL;
201
+ await native.bind(target, signal);
202
+ };
203
+ const unregister = async (budget = beginShutdown()) => {
204
+ try {
205
+ await native.unregister(budget, runtime);
206
+ }
207
+ finally {
208
+ if (shutdown === undefined)
209
+ finishShutdown();
210
+ }
211
+ };
212
+ try {
213
+ await register();
214
+ }
215
+ catch (cause) {
216
+ options.signal?.removeEventListener("abort", abortLifetime);
217
+ try {
218
+ await unregister();
219
+ }
220
+ catch (cleanup) {
221
+ if (!publicationCleanupFailed(cleanup))
222
+ publication?.retainCleanup?.(() => unregister());
223
+ throw new TnlCleanupError(cause, cleanup);
224
+ }
225
+ throw cause;
226
+ }
227
+ let closed = false;
228
+ let resolveClosing;
229
+ const closingSignal = new Promise((resolve) => {
230
+ resolveClosing = resolve;
231
+ });
232
+ let terminal = false;
233
+ let readyReached = false;
234
+ let closePromise;
235
+ let detachListener;
236
+ let resolveReady;
237
+ let rejectReady;
238
+ const ready = new Promise((resolve, reject) => {
239
+ resolveReady = resolve;
240
+ rejectReady = reject;
241
+ });
242
+ const onListenerClose = () => {
243
+ if (!closed)
244
+ fail(new TnlError("sdk.listener_failed"));
245
+ };
246
+ let resolveDone;
247
+ let rejectDone;
248
+ const done = new Promise((resolve, reject) => {
249
+ resolveDone = resolve;
250
+ rejectDone = reject;
251
+ });
252
+ // a handle may finish before its caller starts waiting.
253
+ void done.catch(() => { });
254
+ const close = () => {
255
+ if (closePromise !== undefined)
256
+ return closePromise;
257
+ closed = true;
258
+ resolveClosing();
259
+ options.signal?.removeEventListener("abort", onAbort);
260
+ options.signal?.removeEventListener("abort", abortLifetime);
261
+ process.off("beforeExit", beforeExit);
262
+ detachListener?.();
263
+ if (!terminal && !readyReached)
264
+ rejectReady(aborted());
265
+ closePromise = operation("sdk.publish.cleanup", async () => {
266
+ const budget = beginShutdown();
267
+ lifetime.abort(aborted());
268
+ let monitorFailure;
269
+ try {
270
+ await monitoring;
271
+ }
272
+ catch (cause) {
273
+ monitorFailure = cause;
274
+ }
275
+ try {
276
+ await unregister(budget);
277
+ }
278
+ catch (cleanup) {
279
+ if (monitorFailure !== undefined)
280
+ throw new TnlCleanupError(monitorFailure, cleanup);
281
+ throw cleanup;
282
+ }
283
+ finally {
284
+ if (shutdown === undefined)
285
+ finishShutdown();
286
+ }
287
+ if (monitorFailure !== undefined)
288
+ throw monitorFailure;
289
+ }).then(() => {
290
+ if (!terminal) {
291
+ terminal = true;
292
+ resolveDone();
293
+ }
294
+ }, (cause) => {
295
+ if (!terminal) {
296
+ terminal = true;
297
+ rejectDone(cause);
298
+ }
299
+ closePromise = undefined;
300
+ throw cause;
301
+ });
302
+ return closePromise;
303
+ };
304
+ const fail = (cause) => {
305
+ if (terminal)
306
+ return;
307
+ terminal = true;
308
+ if (!readyReached)
309
+ rejectReady(cause);
310
+ rejectDone(cause);
311
+ void close().catch(() => { });
312
+ };
313
+ const onAbort = () => {
314
+ fail(aborted());
315
+ };
316
+ const exitCleanup = scheduled(close);
317
+ const beforeExit = () => {
318
+ void exitCleanup().catch(() => { });
319
+ };
320
+ options.signal?.addEventListener("abort", onAbort, { once: true });
321
+ process.once("beforeExit", beforeExit);
322
+ let lastRenew = Date.now();
323
+ let lastRun = 0;
324
+ const observe = (status) => {
325
+ if (status.publicURL !== undefined) {
326
+ if (options.public === false || (currentURL !== undefined && currentURL !== status.publicURL))
327
+ throw new TnlError("sdk.response_invalid");
328
+ currentURL = status.publicURL;
329
+ }
330
+ if (status.publishRunNumber !== undefined) {
331
+ if (status.publishRunNumber < lastRun)
332
+ throw new TnlError("sdk.response_invalid");
333
+ lastRun = status.publishRunNumber;
334
+ }
335
+ currentRun = status.run;
336
+ currentPublisherURL = status.publisherURL;
337
+ if (status.routable) {
338
+ const named = localService !== undefined || publication?.service !== undefined;
339
+ if (status.publicURL === undefined &&
340
+ (currentURL !== undefined || (!named && options.public !== false)))
341
+ throw new TnlError("sdk.response_invalid");
342
+ if (!readyReached) {
343
+ readyReached = true;
344
+ resolveReady(Object.freeze({
345
+ ...(currentURL === undefined
346
+ ? {}
347
+ : {
348
+ url: currentURL,
349
+ get publisherURL() {
350
+ return currentPublisherURL;
351
+ },
352
+ }),
353
+ get run() {
354
+ return currentRun;
355
+ },
356
+ async exportCertificate() {
357
+ if (closed || terminal || lifetime.signal.aborted)
358
+ throw new TnlError("sdk.certificate_unavailable");
359
+ return native.exportCertificate(lifetime.signal);
360
+ },
361
+ close,
362
+ wait: () => done,
363
+ [Symbol.asyncDispose]: close,
364
+ }));
365
+ }
366
+ }
367
+ else if (status.failure)
368
+ fail(new TnlError("sdk.publication_failed"));
369
+ };
370
+ // registering acknowledges the listener, not routability.
371
+ const statusRequest = independent("sdk.publish.status", () => native.status(lifetime.signal));
372
+ const renew = independent("sdk.publish.renew", async () => {
373
+ if (typeof options.certificate === "function") {
374
+ let certificate;
375
+ try {
376
+ certificate = await resolveServiceCertificate(options.certificate, AbortSignal.any([lifetime.signal, AbortSignal.timeout(2_000)]));
377
+ }
378
+ catch (cause) {
379
+ if (lifetime.signal.aborted)
380
+ throw cause;
381
+ }
382
+ if (certificate !== undefined) {
383
+ try {
384
+ await native.renew(lifetime.signal, certificate);
385
+ return;
386
+ }
387
+ catch (cause) {
388
+ if (!(cause instanceof TnlError) || cause.code !== "sdk.certificate_invalid")
389
+ throw cause;
390
+ }
391
+ }
392
+ }
393
+ return native.renew(lifetime.signal);
394
+ });
395
+ const recover = independent("sdk.publish.recover", async () => {
396
+ await native.discover(lifetime.signal);
397
+ await register();
398
+ });
399
+ const monitoring = background(async () => {
400
+ while (!closed && !terminal) {
401
+ try {
402
+ if (!isBunServer(server) && !server.listening)
403
+ throw new TnlError("sdk.listener_failed");
404
+ const registration = native.registration;
405
+ if (registration === undefined)
406
+ throw new TnlError("sdk.response_invalid");
407
+ const status = parseStatus(await statusRequest(), localService ?? invocationID, registration.registration_id, target);
408
+ if (status !== undefined)
409
+ observe(status);
410
+ if (closed || terminal)
411
+ break;
412
+ await Promise.race([runtime.pause(250, lifetime.signal), closingSignal]);
413
+ if (closed || terminal)
414
+ break;
415
+ if (Date.now() - lastRenew >= 5_000) {
416
+ await renew();
417
+ lastRenew = Date.now();
418
+ }
419
+ }
420
+ catch (cause) {
421
+ if (closed || terminal) {
422
+ if (!canceledRuntimeRequest(cause, lifetime.signal))
423
+ throw cause;
424
+ break;
425
+ }
426
+ if (cause instanceof TnlError &&
427
+ (cause.code === "sdk.dev_unavailable" || cause.code === "sdk.registration_stale")) {
428
+ try {
429
+ await recover();
430
+ continue;
431
+ }
432
+ catch (restartError) {
433
+ if (closed || terminal) {
434
+ if (!canceledRuntimeRequest(restartError, lifetime.signal))
435
+ throw restartError;
436
+ break;
437
+ }
438
+ if (restartError instanceof TnlError &&
439
+ (restartError.code === "sdk.dev_unavailable" ||
440
+ restartError.code === "sdk.registration_stale")) {
441
+ await Promise.race([runtime.pause(1_000, lifetime.signal), closingSignal]);
442
+ continue;
443
+ }
444
+ fail(restartError);
445
+ break;
446
+ }
447
+ }
448
+ fail(cause);
449
+ break;
450
+ }
451
+ }
452
+ });
453
+ detachListener = observeListenerClose(server, async () => {
454
+ onListenerClose();
455
+ await close();
456
+ });
457
+ if (options.signal?.aborted)
458
+ onAbort();
459
+ try {
460
+ return await ready;
461
+ }
462
+ catch (cause) {
463
+ try {
464
+ await close();
465
+ }
466
+ catch (cleanupError) {
467
+ if (!publicationCleanupFailed(cleanupError))
468
+ publication?.retainCleanup?.(close);
469
+ throw new TnlCleanupError(cause, cleanupError);
470
+ }
471
+ throw cause;
472
+ }
473
+ }
474
+ const credentialFileSchema = pathTextSchema.refine(path.isAbsolute);
475
+ const networkSchema = z
476
+ .string()
477
+ .max(64)
478
+ .refine((value) => {
479
+ const parts = value.split("/");
480
+ const ip = isIP(parts[0] ?? "");
481
+ return (ip !== 0 &&
482
+ parts.length <= 2 &&
483
+ (parts.length === 1 ||
484
+ (/^(0|[1-9][0-9]*)$/.test(parts[1] ?? "") && Number(parts[1]) <= (ip === 4 ? 32 : 128))));
485
+ });
486
+ const accessModeSchema = z.enum(["restricted", "anonymous"]);
487
+ const invocationOptionsSchema = z
488
+ .strictObject({
489
+ publisherCredentialFile: credentialFileSchema.optional(),
490
+ publisherIdentityID: z
491
+ .string()
492
+ .regex(/^pub_[A-Za-z0-9]{22}$/)
493
+ .optional(),
494
+ server: httpsOriginSchema.refine((value) => value.length <= 4096).optional(),
495
+ directory: pathTextSchema.optional(),
496
+ stateDir: pathTextSchema.optional(),
497
+ targetHostname: z.string().min(1).optional(),
498
+ certificate: serviceCertificateSourceSchema.optional(),
499
+ requirePostQuantum: z.boolean().optional(),
500
+ public: z.boolean().optional(),
501
+ telemetry: z.boolean().optional(),
502
+ access: z
503
+ .union([
504
+ accessModeSchema,
505
+ z.strictObject({
506
+ mode: accessModeSchema.optional(),
507
+ ip: z.array(networkSchema).min(1).max(32).optional(),
508
+ }),
509
+ ])
510
+ .optional(),
511
+ // control owns limit normalization, including the generated rate-period contract.
512
+ limits: z.unknown().optional(),
513
+ signal: z.instanceof(AbortSignal).optional(),
514
+ })
515
+ .refine((options) => options.publisherCredentialFile === undefined || options.publisherIdentityID === undefined);
516
+ function validateOptions(options) {
517
+ parseValue(invocationOptionsSchema, options, "sdk.configuration_invalid");
518
+ }
519
+ function validPublisherCredentialFile(value) {
520
+ return credentialFileSchema.safeParse(value).success;
521
+ }
522
+ function aborted() {
523
+ return new DOMException("publication was aborted", "AbortError");
524
+ }
525
+ async function closeOwnedPublication(server, cleanup, budget) {
526
+ // detach native monitoring before stopping the owned listener. both phases
527
+ // start now and share the same deadline; arbitrary Fetch handlers are not joined.
528
+ const native = cleanup();
529
+ const results = await Promise.allSettled([native, closeServer(server, budget.signal)]);
530
+ const { joinFetchServer } = await import("./fetch.js");
531
+ await joinFetchServer(server);
532
+ const failures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
533
+ if (failures.length > 1)
534
+ throw new TnlCleanupError(failures[0], failures[1]);
535
+ if (failures.length === 1)
536
+ throw failures[0];
537
+ }
538
+ // inline Fetch handlers own their Node listener; a supplied server is never closed.
539
+ export async function publishFetch(handler, options = {}, runtime = nativePublicationRuntime, publication) {
540
+ validateOptions(options);
541
+ const { createFetchServer } = await import("./fetch.js");
542
+ const server = await createFetchServer(handler);
543
+ let shutdown;
544
+ let shutdownUntil;
545
+ const budget = () => {
546
+ const parent = publication?.shutdownDeadline?.();
547
+ if (parent !== undefined && (shutdownUntil === undefined || parent < shutdownUntil))
548
+ shutdownUntil = parent;
549
+ shutdown ??= publicationShutdown(shutdownUntil);
550
+ shutdownUntil = shutdown.deadline;
551
+ return shutdown;
552
+ };
553
+ const finish = () => {
554
+ shutdown?.finish();
555
+ shutdown = undefined;
556
+ };
557
+ let base;
558
+ try {
559
+ base = await publishServer(server, options, runtime, publication === undefined
560
+ ? undefined
561
+ : {
562
+ ...publication,
563
+ retainCleanup: (cleanup) => {
564
+ publication.retainCleanup?.(() => closeOwnedPublication(server, cleanup, budget()).finally(finish));
565
+ },
566
+ }, budget);
567
+ }
568
+ catch (cause) {
569
+ try {
570
+ await closeServer(server, budget().signal);
571
+ }
572
+ catch (cleanupError) {
573
+ throw new TnlCleanupError(cause, cleanupError);
574
+ }
575
+ finally {
576
+ finish();
577
+ }
578
+ throw cause;
579
+ }
580
+ let closing;
581
+ const close = () => {
582
+ if (closing !== undefined)
583
+ return closing;
584
+ closing = closeOwnedPublication(server, base.close, budget())
585
+ .finally(finish)
586
+ .catch((cause) => {
587
+ closing = undefined;
588
+ throw cause;
589
+ });
590
+ return closing;
591
+ };
592
+ return Object.freeze({
593
+ ...(base.url === undefined
594
+ ? {}
595
+ : {
596
+ url: base.url,
597
+ get publisherURL() {
598
+ return base.publisherURL;
599
+ },
600
+ }),
601
+ get run() {
602
+ return base.run;
603
+ },
604
+ exportCertificate: () => base.exportCertificate(),
605
+ close,
606
+ async wait() {
607
+ let failure;
608
+ try {
609
+ await base.wait();
610
+ }
611
+ catch (cause) {
612
+ failure = cause;
613
+ }
614
+ try {
615
+ await close();
616
+ }
617
+ catch (cause) {
618
+ if (failure !== undefined && failure !== cause)
619
+ throw new TnlCleanupError(failure, cause);
620
+ throw cause;
621
+ }
622
+ if (failure !== undefined)
623
+ throw failure;
624
+ },
625
+ [Symbol.asyncDispose]: close,
626
+ });
627
+ }
@@ -0,0 +1,31 @@
1
+ export interface BunHTTPServer {
2
+ readonly hostname?: string | undefined;
3
+ readonly port?: number | undefined;
4
+ readonly url: URL;
5
+ stop(closeActiveConnections?: boolean): Promise<void> | void;
6
+ }
7
+ /** Small structural surface shared by Node HTTP servers, without Node types in browser declarations. */
8
+ export interface NodeHTTPServer {
9
+ readonly listening: boolean;
10
+ address(): unknown;
11
+ once(event: "listening", listener: () => void): unknown;
12
+ once(event: "error", listener: (error: Error) => void): unknown;
13
+ once(event: "close", listener: () => void): unknown;
14
+ off(event: "listening", listener: () => void): unknown;
15
+ off(event: "error", listener: (error: Error) => void): unknown;
16
+ off(event: "close", listener: () => void): unknown;
17
+ close(callback?: (error?: Error) => void): unknown;
18
+ closeAllConnections?(): void;
19
+ }
20
+ export type LocalHTTPServer = NodeHTTPServer | BunHTTPServer;
21
+ type StopObserver = () => Promise<void>;
22
+ export declare function observeListenerClose(server: LocalHTTPServer, callback: StopObserver): () => void;
23
+ export interface RegistrationOptions {
24
+ /** hostname used to reach the listener, including for HTTPS certificate verification. */
25
+ readonly targetHostname?: string;
26
+ readonly signal?: AbortSignal;
27
+ }
28
+ export declare function listeningTarget(server: LocalHTTPServer, options?: RegistrationOptions): Promise<`http://${string}` | `https://${string}`>;
29
+ export declare function closeServer(server: LocalHTTPServer, signal?: AbortSignal): Promise<void>;
30
+ export declare function isBunServer(server: LocalHTTPServer): server is BunHTTPServer;
31
+ export {};