@di-framework/cli-plugin-platform 0.0.1 → 6.0.2

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 (169) hide show
  1. package/README.md +408 -0
  2. package/dist/actor-protocol.d.ts +4 -0
  3. package/dist/actor-protocol.js +162 -0
  4. package/dist/actors.d.ts +31 -0
  5. package/dist/actors.js +296 -0
  6. package/dist/args.d.ts +15 -0
  7. package/dist/args.js +66 -0
  8. package/dist/assets/http-adapter.js +876 -0
  9. package/dist/assets/platform/.gitignore.tmpl +6 -0
  10. package/dist/assets/platform/Pulumi.yaml.tmpl +6 -0
  11. package/dist/assets/platform/README.md +208 -0
  12. package/dist/assets/platform/index.ts.tmpl +2 -0
  13. package/dist/assets/platform/package.json.tmpl +18 -0
  14. package/dist/assets/platform/tsconfig.json +11 -0
  15. package/dist/assets/queue-adapter.js +60 -0
  16. package/dist/assets/sqlite/BUILD-INFO.txt +13 -0
  17. package/dist/assets/sqlite/SHA256SUMS +2 -0
  18. package/dist/assets/sqlite/di-framework-sqlite.wasm +0 -0
  19. package/dist/assets/sqlite/di-framework-sqlite.wit +337 -0
  20. package/dist/assets/wit/deps/LICENSE.md +8 -0
  21. package/dist/assets/wit/deps/di-framework-queues/package.wit +18 -0
  22. package/dist/assets/wit/deps/di-framework-sqlite/package.wit +211 -0
  23. package/dist/assets/wit/deps/wasi-cli/package.wit +70 -0
  24. package/dist/assets/wit/deps/wasi-clocks/package.wit +42 -0
  25. package/dist/assets/wit/deps/wasi-config/package.wit +15 -0
  26. package/dist/assets/wit/deps/wasi-filesystem/package.wit +184 -0
  27. package/dist/assets/wit/deps/wasi-http/package.wit +170 -0
  28. package/dist/assets/wit/deps/wasi-random/package.wit +17 -0
  29. package/dist/assets/wit/deps/wasi-sockets/package.wit +105 -0
  30. package/dist/assets/wit/deps/wasi-tls/package.wit +26 -0
  31. package/dist/assets/wit/deps/wasmcloud-blobstore/package.wit +153 -0
  32. package/dist/assets/wit/deps/wasmcloud-keyvalue/package.wit +370 -0
  33. package/dist/assets/wit/deps/wasmcloud-messaging/package.wit +125 -0
  34. package/dist/assets/wit/deps/wasmcloud-postgres/package.wit +435 -0
  35. package/dist/assets/wit/deps/wasmcloud-secrets/package.wit +80 -0
  36. package/dist/async-transform.d.ts +3 -0
  37. package/dist/async-transform.js +60 -0
  38. package/dist/bindings.d.ts +34 -0
  39. package/dist/bindings.js +307 -0
  40. package/dist/build.d.ts +29 -0
  41. package/dist/build.js +325 -0
  42. package/dist/command.d.ts +3 -0
  43. package/dist/command.js +141 -0
  44. package/dist/control/auth.d.ts +18 -0
  45. package/dist/control/auth.js +89 -0
  46. package/dist/control/cron.d.ts +7 -0
  47. package/dist/control/cron.js +86 -0
  48. package/dist/control/index.d.ts +4 -0
  49. package/dist/control/index.js +4 -0
  50. package/dist/control/network.d.ts +12 -0
  51. package/dist/control/network.js +49 -0
  52. package/dist/control/queues.d.ts +15 -0
  53. package/dist/control/queues.js +77 -0
  54. package/dist/cron.d.ts +26 -0
  55. package/dist/cron.js +239 -0
  56. package/dist/deploy.d.ts +29 -0
  57. package/dist/deploy.js +57 -0
  58. package/dist/deps.d.ts +96 -0
  59. package/dist/deps.js +303 -0
  60. package/dist/destroy.d.ts +3 -0
  61. package/dist/destroy.js +24 -0
  62. package/dist/dev-runner.d.ts +24 -0
  63. package/dist/dev-runner.js +83 -0
  64. package/dist/dev.d.ts +8 -0
  65. package/dist/dev.js +76 -0
  66. package/dist/discovery.d.ts +15 -0
  67. package/dist/discovery.js +182 -0
  68. package/dist/doctor.d.ts +8 -0
  69. package/dist/doctor.js +82 -0
  70. package/dist/guests.d.ts +9 -0
  71. package/dist/guests.js +56 -0
  72. package/dist/host-interface.d.ts +29 -0
  73. package/dist/host-interface.js +142 -0
  74. package/dist/index.d.ts +33 -0
  75. package/dist/index.js +39 -0
  76. package/dist/kubernetes.d.ts +9 -0
  77. package/dist/kubernetes.js +17 -0
  78. package/dist/managed-bindings.d.ts +9 -0
  79. package/dist/managed-bindings.js +150 -0
  80. package/dist/manifest.d.ts +36 -0
  81. package/dist/manifest.js +257 -0
  82. package/dist/namespace.d.ts +2 -0
  83. package/dist/namespace.js +4 -0
  84. package/dist/node-compat/async-hooks.d.ts +29 -0
  85. package/dist/node-compat/async-hooks.js +80 -0
  86. package/dist/node-compat/bootstrap.d.ts +1 -0
  87. package/dist/node-compat/bootstrap.js +9 -0
  88. package/dist/node-compat/bytes.d.ts +7 -0
  89. package/dist/node-compat/bytes.js +41 -0
  90. package/dist/node-compat/crypto-hash.d.ts +27 -0
  91. package/dist/node-compat/crypto-hash.js +108 -0
  92. package/dist/node-compat/crypto-subtle.d.ts +59 -0
  93. package/dist/node-compat/crypto-subtle.js +288 -0
  94. package/dist/node-compat/crypto.d.ts +136 -0
  95. package/dist/node-compat/crypto.js +142 -0
  96. package/dist/node-compat/dgram.d.ts +49 -0
  97. package/dist/node-compat/dgram.js +197 -0
  98. package/dist/node-compat/env.d.ts +6 -0
  99. package/dist/node-compat/env.js +88 -0
  100. package/dist/node-compat/fetch-runtime.d.ts +80 -0
  101. package/dist/node-compat/fetch-runtime.js +314 -0
  102. package/dist/node-compat/fs.d.ts +84 -0
  103. package/dist/node-compat/fs.js +285 -0
  104. package/dist/node-compat/http-parser.d.ts +40 -0
  105. package/dist/node-compat/http-parser.js +185 -0
  106. package/dist/node-compat/http.d.ts +130 -0
  107. package/dist/node-compat/http.js +688 -0
  108. package/dist/node-compat/https.d.ts +28 -0
  109. package/dist/node-compat/https.js +88 -0
  110. package/dist/node-compat/module.d.ts +11 -0
  111. package/dist/node-compat/module.js +35 -0
  112. package/dist/node-compat/net.d.ts +119 -0
  113. package/dist/node-compat/net.js +441 -0
  114. package/dist/node-compat/process.d.ts +25 -0
  115. package/dist/node-compat/process.js +63 -0
  116. package/dist/node-compat/runtime-application.d.ts +4 -0
  117. package/dist/node-compat/runtime-application.js +24 -0
  118. package/dist/node-compat/seed-virtual.d.ts +6 -0
  119. package/dist/node-compat/seed-virtual.js +6 -0
  120. package/dist/node-compat/seed.d.ts +20 -0
  121. package/dist/node-compat/seed.js +106 -0
  122. package/dist/node-compat/socket-address.d.ts +35 -0
  123. package/dist/node-compat/socket-address.js +162 -0
  124. package/dist/node-compat/timers.d.ts +32 -0
  125. package/dist/node-compat/timers.js +96 -0
  126. package/dist/node-compat/tls.d.ts +57 -0
  127. package/dist/node-compat/tls.js +290 -0
  128. package/dist/node-compat/wasi-random.d.ts +2 -0
  129. package/dist/node-compat/wasi-random.js +25 -0
  130. package/dist/node-compat/wasi-sockets.d.ts +47 -0
  131. package/dist/node-compat/wasi-sockets.js +134 -0
  132. package/dist/oci.d.ts +9 -0
  133. package/dist/oci.js +9 -0
  134. package/dist/paths.d.ts +7 -0
  135. package/dist/paths.js +13 -0
  136. package/dist/platform-init.d.ts +13 -0
  137. package/dist/platform-init.js +265 -0
  138. package/dist/platform.d.ts +22 -0
  139. package/dist/platform.js +170 -0
  140. package/dist/project.d.ts +39 -0
  141. package/dist/project.js +130 -0
  142. package/dist/publish.d.ts +15 -0
  143. package/dist/publish.js +57 -0
  144. package/dist/pulumi.d.ts +4 -0
  145. package/dist/pulumi.js +27 -0
  146. package/dist/queues-module.d.ts +4 -0
  147. package/dist/queues-module.js +89 -0
  148. package/dist/queues.d.ts +16 -0
  149. package/dist/queues.js +167 -0
  150. package/dist/registry.d.ts +16 -0
  151. package/dist/registry.js +27 -0
  152. package/dist/service.d.ts +162 -0
  153. package/dist/service.js +678 -0
  154. package/dist/support.d.ts +14 -0
  155. package/dist/support.js +37 -0
  156. package/dist/target.d.ts +18 -0
  157. package/dist/target.js +45 -0
  158. package/dist/toml.d.ts +6 -0
  159. package/dist/toml.js +245 -0
  160. package/dist/wash-dev.d.ts +18 -0
  161. package/dist/wash-dev.js +80 -0
  162. package/dist/wit.d.ts +76 -0
  163. package/dist/wit.js +248 -0
  164. package/dist/workload-members.d.ts +12 -0
  165. package/dist/workload-members.js +136 -0
  166. package/dist/workload.d.ts +45 -0
  167. package/dist/workload.js +457 -0
  168. package/package.json +55 -8
  169. package/src/index.ts +0 -2
@@ -0,0 +1,876 @@
1
+ // src/control/auth.ts
2
+ var ANONYMOUS_IDENTITY = { id: "anonymous", token: "", roles: ["invoke"] };
3
+ function isIdentityEntry(entry) {
4
+ if (entry === null || typeof entry !== "object")
5
+ return false;
6
+ const candidate = entry;
7
+ return typeof candidate.id === "string" && candidate.id.length > 0 && typeof candidate.token === "string" && candidate.token.length > 0;
8
+ }
9
+ function singleTokenIdentities() {
10
+ const token = process.env.DI_CONTROL_TOKEN;
11
+ if (typeof token !== "string" || token.length === 0)
12
+ return [];
13
+ const id = typeof process.env.DI_CONTROL_IDENTITY === "string" && process.env.DI_CONTROL_IDENTITY.length > 0 ? process.env.DI_CONTROL_IDENTITY : "default";
14
+ return [{ id, token, roles: ["invoke", "admin"] }];
15
+ }
16
+ function parseIdentities() {
17
+ const raw = process.env.DI_CONTROL_IDENTITIES;
18
+ if (typeof raw === "string" && raw.trim() !== "") {
19
+ try {
20
+ const parsed = JSON.parse(raw);
21
+ if (Array.isArray(parsed)) {
22
+ const identities = parsed.filter(isIdentityEntry).map((entry) => {
23
+ const roles = Array.isArray(entry.roles) ? entry.roles.filter((role) => typeof role === "string") : [];
24
+ return {
25
+ id: entry.id,
26
+ token: entry.token,
27
+ roles: roles.length > 0 ? roles : ["invoke"]
28
+ };
29
+ });
30
+ if (identities.length > 0)
31
+ return { identities, configured: true };
32
+ }
33
+ } catch {}
34
+ return { identities: singleTokenIdentities(), configured: true };
35
+ }
36
+ const identities = singleTokenIdentities();
37
+ return { identities, configured: identities.length > 0 };
38
+ }
39
+ function hasRequiredRole(identity, requiredRoles) {
40
+ return !requiredRoles.some((role) => !identity.roles.includes(role) && !identity.roles.includes("admin"));
41
+ }
42
+ function authorizeControlRequest(request, requiredRoles = ["invoke"]) {
43
+ const { identities, configured } = parseIdentities();
44
+ if (identities.length === 0) {
45
+ if (configured || !hasRequiredRole(ANONYMOUS_IDENTITY, requiredRoles)) {
46
+ return {
47
+ ok: false,
48
+ status: configured ? 401 : 403,
49
+ error: configured ? "Missing control credentials" : "Insufficient control privileges"
50
+ };
51
+ }
52
+ return { ok: true, identity: ANONYMOUS_IDENTITY };
53
+ }
54
+ const header = request.headers.get("authorization") ?? request.headers.get("x-di-control-token");
55
+ if (!header) {
56
+ return { ok: false, status: 401, error: "Missing control credentials" };
57
+ }
58
+ const token = header.toLowerCase().startsWith("bearer ") ? header.slice("bearer ".length).trim() : header.trim();
59
+ const identity = identities.find((entry) => entry.token === token);
60
+ if (!identity) {
61
+ return { ok: false, status: 403, error: "Unauthorized control credentials" };
62
+ }
63
+ if (!hasRequiredRole(identity, requiredRoles)) {
64
+ return { ok: false, status: 403, error: "Insufficient control privileges" };
65
+ }
66
+ return { ok: true, identity };
67
+ }
68
+ function unauthorizedResponse(result) {
69
+ return new Response(JSON.stringify({ success: false, error: result.error }), {
70
+ status: result.status,
71
+ headers: { "content-type": "application/json" }
72
+ });
73
+ }
74
+
75
+ // src/actor-protocol.ts
76
+ function isActorInvocationRequest(request) {
77
+ try {
78
+ const url = new URL(request.url);
79
+ return url.pathname.startsWith("/_actors/");
80
+ } catch {
81
+ return false;
82
+ }
83
+ }
84
+ function randomRequestId() {
85
+ return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
86
+ }
87
+ async function handleActorInvocationRequest(request, runtime, dispatchFn) {
88
+ if (!runtime && !dispatchFn) {
89
+ return new Response(JSON.stringify({
90
+ success: false,
91
+ error: {
92
+ name: "ActorRuntimeError",
93
+ message: "No actor runtime or actors registered in this component"
94
+ }
95
+ }), { status: 404, headers: { "content-type": "application/json" } });
96
+ }
97
+ const auth = authorizeControlRequest(request, ["invoke"]);
98
+ if (!auth.ok)
99
+ return unauthorizedResponse(auth);
100
+ try {
101
+ let actorType;
102
+ let actorKey;
103
+ let method;
104
+ let args = [];
105
+ let requestId = randomRequestId();
106
+ let deadline;
107
+ let namespace;
108
+ const callerId = auth.identity.id;
109
+ let expectedGeneration;
110
+ const url = new URL(request.url);
111
+ const subPath = url.pathname.replace(/^\/_actors\/?/, "");
112
+ const pathParts = subPath ? subPath.split("/").filter(Boolean) : [];
113
+ if (request.method === "POST") {
114
+ const parsed = await request.json().catch(() => ({}));
115
+ const body = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
116
+ actorType = body.actorType ?? request.headers.get("x-actor-type") ?? pathParts[0];
117
+ actorKey = body.actorKey ?? request.headers.get("x-actor-key") ?? pathParts[1];
118
+ method = body.method ?? request.headers.get("x-actor-method") ?? pathParts[2];
119
+ args = Array.isArray(body.args) ? body.args : [];
120
+ if (typeof body.requestId === "string" && body.requestId)
121
+ requestId = body.requestId;
122
+ if (typeof body.deadline === "number")
123
+ deadline = body.deadline;
124
+ if (typeof body.namespace === "string")
125
+ namespace = body.namespace;
126
+ if (typeof body.expectedGeneration === "number")
127
+ expectedGeneration = body.expectedGeneration;
128
+ } else {
129
+ actorType = request.headers.get("x-actor-type") ?? pathParts[0];
130
+ actorKey = request.headers.get("x-actor-key") ?? pathParts[1];
131
+ method = request.headers.get("x-actor-method") ?? pathParts[2];
132
+ const qArgs = url.searchParams.get("args");
133
+ if (qArgs) {
134
+ try {
135
+ const parsed = JSON.parse(qArgs);
136
+ args = Array.isArray(parsed) ? parsed : [parsed];
137
+ } catch {
138
+ args = [qArgs];
139
+ }
140
+ }
141
+ const headerDeadline = request.headers.get("x-actor-deadline");
142
+ if (headerDeadline)
143
+ deadline = Number(headerDeadline);
144
+ namespace = request.headers.get("x-actor-namespace") ?? undefined;
145
+ }
146
+ if (typeof actorType !== "string" || !actorType || typeof actorKey !== "string" || !actorKey || typeof method !== "string" || !method) {
147
+ return new Response(JSON.stringify({
148
+ success: false,
149
+ error: {
150
+ name: "ActorInvocationBadRequest",
151
+ message: "actorType, actorKey, and method are required for actor invocation"
152
+ }
153
+ }), { status: 400, headers: { "content-type": "application/json" } });
154
+ }
155
+ if (runtime) {
156
+ const { ActorRpcDispatcher } = await import("@di-framework/actors/portable");
157
+ const dispatcher = new ActorRpcDispatcher({ runtime });
158
+ const rpcRequest = {
159
+ requestId,
160
+ namespace,
161
+ actorType,
162
+ actorKey,
163
+ method,
164
+ args,
165
+ callerId,
166
+ deadline,
167
+ expectedGeneration
168
+ };
169
+ const response = await dispatcher.dispatch(rpcRequest);
170
+ const status = response.success ? 200 : response.error?.name === "ActorAuthorizationError" ? 403 : response.error?.name === "ActorDeadlineExceededError" ? 504 : response.error?.name === "ActorNotRegisteredError" || response.error?.name === "ActorMethodNotFoundError" ? 404 : 500;
171
+ return new Response(JSON.stringify(response), {
172
+ status,
173
+ headers: { "content-type": "application/json" }
174
+ });
175
+ }
176
+ const invoke = dispatchFn;
177
+ const result = await invoke(actorType, actorKey, method, args);
178
+ return new Response(JSON.stringify({ requestId, success: true, result }), {
179
+ status: 200,
180
+ headers: { "content-type": "application/json" }
181
+ });
182
+ } catch (error) {
183
+ const name = [
184
+ "ActorNotRegisteredError",
185
+ "ActorMethodNotFoundError",
186
+ "ActorInvocationBadRequest",
187
+ "ActorMigrationError",
188
+ "ActorAuthorizationError",
189
+ "ActorDeadlineExceededError"
190
+ ].find((candidate) => candidate === error?.name) ?? "ActorInvocationError";
191
+ const isNotFound = name === "ActorNotRegisteredError" || name === "ActorMethodNotFoundError";
192
+ const isBadRequest = name === "ActorInvocationBadRequest";
193
+ const isUnauthorized = name === "ActorAuthorizationError";
194
+ const isDeadline = name === "ActorDeadlineExceededError";
195
+ const status = isNotFound ? 404 : isBadRequest ? 400 : isUnauthorized ? 403 : isDeadline ? 504 : 500;
196
+ return new Response(JSON.stringify({
197
+ success: false,
198
+ error: {
199
+ name,
200
+ message: "Actor invocation failed"
201
+ }
202
+ }), { status, headers: { "content-type": "application/json" } });
203
+ }
204
+ }
205
+ // src/control/cron.ts
206
+ var CRON_INVOKE_PATH_PREFIX = "/_di/cron/";
207
+ function isCronInvokeRequest(request) {
208
+ try {
209
+ const url = new URL(request.url);
210
+ return request.method === "POST" && url.pathname.startsWith(CRON_INVOKE_PATH_PREFIX);
211
+ } catch {
212
+ return false;
213
+ }
214
+ }
215
+ function cronJobIdFromRequest(request) {
216
+ try {
217
+ const url = new URL(request.url);
218
+ if (!url.pathname.startsWith(CRON_INVOKE_PATH_PREFIX))
219
+ return;
220
+ const rest = url.pathname.slice(CRON_INVOKE_PATH_PREFIX.length);
221
+ const jobId = decodeURIComponent(rest.replace(/\/$/, "").split("/")[0] ?? "");
222
+ return jobId || undefined;
223
+ } catch {
224
+ return;
225
+ }
226
+ }
227
+ var JSON_HEADERS = { "content-type": "application/json" };
228
+ function cronFailureResponse(jobId) {
229
+ return new Response(JSON.stringify({
230
+ success: false,
231
+ completed: false,
232
+ ok: false,
233
+ jobId,
234
+ error: { name: "CronInvocationError", message: "Cron job failed" }
235
+ }), { status: 500, headers: JSON_HEADERS });
236
+ }
237
+ function isFailedCronResult(result) {
238
+ if (result === null || typeof result !== "object")
239
+ return false;
240
+ const record = result;
241
+ if (record.success === false || record.ok === false || record.completed === false)
242
+ return true;
243
+ return record.status === "failure" || record.status === "skipped";
244
+ }
245
+ async function handleCronInvokeRequest(request, invoke) {
246
+ const auth = authorizeControlRequest(request, ["invoke"]);
247
+ if (!auth.ok)
248
+ return unauthorizedResponse(auth);
249
+ const jobId = cronJobIdFromRequest(request);
250
+ if (!jobId) {
251
+ return new Response(JSON.stringify({ success: false, error: "Missing cron job id" }), {
252
+ status: 400,
253
+ headers: { "content-type": "application/json" }
254
+ });
255
+ }
256
+ if (typeof invoke !== "function") {
257
+ return new Response(JSON.stringify({ success: false, error: "No cron invoker registered" }), {
258
+ status: 404,
259
+ headers: { "content-type": "application/json" }
260
+ });
261
+ }
262
+ let body = {};
263
+ try {
264
+ const parsed = await request.json();
265
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
266
+ body = parsed;
267
+ }
268
+ } catch {
269
+ body = {};
270
+ }
271
+ try {
272
+ const result = await invoke(jobId, { ...body, caller: auth.identity.id });
273
+ if (isFailedCronResult(result))
274
+ return cronFailureResponse(jobId);
275
+ return new Response(JSON.stringify({
276
+ success: true,
277
+ completed: true,
278
+ ok: true,
279
+ jobId,
280
+ result
281
+ }), { status: 200, headers: JSON_HEADERS });
282
+ } catch {
283
+ return cronFailureResponse(jobId);
284
+ }
285
+ }
286
+ // src/control/network.ts
287
+ var FORWARDED_HEADERS = [
288
+ "x-forwarded-for",
289
+ "x-forwarded-host",
290
+ "x-forwarded-proto",
291
+ "x-forwarded-by"
292
+ ];
293
+ function requestHostname(request) {
294
+ const header = request.headers.get("host");
295
+ const host = header && header.trim() !== "" ? header : new URL(request.url).host;
296
+ return host.trim().split(":")[0] ?? "";
297
+ }
298
+ function isForwardedRequest(request) {
299
+ return FORWARDED_HEADERS.some((name) => {
300
+ const value = request.headers.get(name);
301
+ return value !== null && value.trim() !== "";
302
+ });
303
+ }
304
+ function controlHttpHostList(raw = process.env.DI_CONTROL_HTTP_HOST) {
305
+ if (typeof raw !== "string")
306
+ return [];
307
+ return raw.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
308
+ }
309
+ function allowControlSurface(request) {
310
+ const rejectForwarded = process.env.DI_CONTROL_REJECT_FORWARDED === "1";
311
+ const allowedHosts = controlHttpHostList();
312
+ if (!rejectForwarded && allowedHosts.length === 0)
313
+ return true;
314
+ if (rejectForwarded && isForwardedRequest(request))
315
+ return false;
316
+ if (allowedHosts.length === 0)
317
+ return true;
318
+ return allowedHosts.includes(requestHostname(request));
319
+ }
320
+ function controlSurfaceNotFound() {
321
+ return new Response(JSON.stringify({ success: false, error: "Not found" }), {
322
+ status: 404,
323
+ headers: { "content-type": "application/json" }
324
+ });
325
+ }
326
+ // src/control/queues.ts
327
+ var QUEUE_CONTROL_PATH_PREFIX = "/_di/queues/";
328
+ function isQueueControlRequest(request) {
329
+ try {
330
+ const url = new URL(request.url);
331
+ return url.pathname.startsWith(QUEUE_CONTROL_PATH_PREFIX);
332
+ } catch {
333
+ return false;
334
+ }
335
+ }
336
+ function json(status, body) {
337
+ return new Response(JSON.stringify(body), {
338
+ status,
339
+ headers: { "content-type": "application/json" }
340
+ });
341
+ }
342
+ async function handleQueueControlRequest(request, backend) {
343
+ const auth = authorizeControlRequest(request, ["invoke"]);
344
+ if (!auth.ok)
345
+ return unauthorizedResponse(auth);
346
+ if (!backend)
347
+ return json(404, { success: false, error: "No queue backend registered" });
348
+ const url = new URL(request.url);
349
+ const parts = url.pathname.slice(QUEUE_CONTROL_PATH_PREFIX.length).split("/").filter(Boolean);
350
+ const [queueName, action, jobId] = parts;
351
+ if (!queueName) {
352
+ if (request.method === "GET") {
353
+ const queues = await backend.listQueues();
354
+ return json(200, { success: true, queues });
355
+ }
356
+ return json(400, { success: false, error: "Queue name required" });
357
+ }
358
+ if (request.method === "POST" && (action === undefined || action === "jobs") && !jobId) {
359
+ const body = await request.json().catch(() => ({}));
360
+ if (body.payload === undefined) {
361
+ return json(400, { success: false, error: "payload is required" });
362
+ }
363
+ const job = await backend.enqueue(queueName, body.payload, {
364
+ idempotencyKey: body.idempotencyKey,
365
+ priority: body.priority,
366
+ delayMs: body.delayMs,
367
+ maxRetries: body.maxRetries,
368
+ backoffMs: body.backoffMs,
369
+ timeoutMs: body.timeoutMs
370
+ });
371
+ return json(200, { success: true, job });
372
+ }
373
+ if (request.method === "GET" && action === undefined) {
374
+ const status = url.searchParams.get("status") ?? undefined;
375
+ const jobs = await backend.listJobs(queueName, {
376
+ status,
377
+ limit: Number(url.searchParams.get("limit") ?? 50)
378
+ });
379
+ return json(200, { success: true, jobs });
380
+ }
381
+ if (request.method === "GET" && (action === "jobs" || action === "inspect") && jobId) {
382
+ const job = await backend.getJob(queueName, jobId);
383
+ if (!job || job.queueName !== queueName) {
384
+ return json(404, { success: false, error: "Job not found" });
385
+ }
386
+ return json(200, { success: true, job });
387
+ }
388
+ if (request.method === "POST" && action === "retry") {
389
+ const admin = authorizeControlRequest(request, ["admin"]);
390
+ if (!admin.ok)
391
+ return unauthorizedResponse(admin);
392
+ const jobs = await backend.retryJob(queueName, jobId);
393
+ return json(200, { success: true, jobs });
394
+ }
395
+ if (request.method === "GET" && action === "info") {
396
+ const queues = await backend.listQueues();
397
+ const info = queues.find((entry) => entry.name === queueName) ?? null;
398
+ return json(200, { success: true, info });
399
+ }
400
+ return json(404, { success: false, error: "Unknown queue control route" });
401
+ }
402
+ // assets/http-adapter.ts
403
+ import"virtual:di-framework-wasmcloud-guests";
404
+ import"virtual:di-framework-wasmcloud-actors";
405
+ import application from "virtual:di-framework-application";
406
+ import { dispatchActorInvocation, getActorRuntime } from "virtual:di-framework-wasmcloud-actors";
407
+ import { invokeJob as cronInvokeJob } from "virtual:di-framework-wasmcloud-cron";
408
+ import { guests as wasmcloudGuests } from "virtual:di-framework-wasmcloud-guests";
409
+ import {
410
+ ensureQueueWorkers,
411
+ getQueueBackend,
412
+ pumpQueueWorkers
413
+ } from "virtual:di-framework-wasmcloud-queues";
414
+ import { ensureWasiEnvironment } from "virtual:di-framework-wasmcloud-runtime";
415
+ import { Fields, Request as WasiRequest, Response as WasiResponse } from "wasi:http/types@0.3.0";
416
+
417
+ // src/node-compat/fetch-runtime.ts
418
+ class TextEncoderPolyfill {
419
+ encode(input = "") {
420
+ const utf8 = unescape(encodeURIComponent(String(input)));
421
+ const bytes = new Uint8Array(utf8.length);
422
+ for (let i = 0;i < utf8.length; i++)
423
+ bytes[i] = utf8.charCodeAt(i);
424
+ return bytes;
425
+ }
426
+ }
427
+
428
+ class TextDecoderPolyfill {
429
+ decode(input) {
430
+ if (input == null)
431
+ return "";
432
+ const bytes = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
433
+ let binary = "";
434
+ for (let i = 0;i < bytes.length; i++)
435
+ binary += String.fromCharCode(bytes[i] ?? 0);
436
+ return decodeURIComponent(escape(binary));
437
+ }
438
+ }
439
+
440
+ class URLSearchParamsPolyfill {
441
+ #pairs = [];
442
+ constructor(init) {
443
+ if (typeof init === "string") {
444
+ const query = init.startsWith("?") ? init.slice(1) : init;
445
+ if (query !== "") {
446
+ for (const part of query.split("&")) {
447
+ const eq = part.indexOf("=");
448
+ const name = decodeURIComponent(eq === -1 ? part : part.slice(0, eq));
449
+ const value = decodeURIComponent(eq === -1 ? "" : part.slice(eq + 1));
450
+ this.#pairs.push([name, value]);
451
+ }
452
+ }
453
+ } else if (init instanceof URLSearchParamsPolyfill) {
454
+ this.#pairs = init.#pairs.map(([name, value]) => [name, value]);
455
+ } else if (init && typeof init === "object") {
456
+ for (const [name, value] of Object.entries(init))
457
+ this.#pairs.push([name, String(value)]);
458
+ }
459
+ }
460
+ get(name) {
461
+ const found = this.#pairs.find(([key]) => key === name);
462
+ return found ? found[1] : null;
463
+ }
464
+ *entries() {
465
+ yield* this.#pairs;
466
+ }
467
+ [Symbol.iterator]() {
468
+ return this.entries();
469
+ }
470
+ toString() {
471
+ return this.#pairs.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join("&");
472
+ }
473
+ }
474
+
475
+ class URLPolyfill {
476
+ href;
477
+ protocol;
478
+ hostname;
479
+ host;
480
+ port;
481
+ pathname;
482
+ search;
483
+ hash;
484
+ origin;
485
+ searchParams;
486
+ constructor(url, base) {
487
+ const resolved = resolveUrl(String(url), base === undefined ? undefined : String(base));
488
+ const match = resolved.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:)(\/\/)?([^/?#]*)([^?#]*)(\?[^#]*)?(#.*)?$/) ?? ["", "http:", "//", "", "/", "", ""];
489
+ this.protocol = match[1] ?? "http:";
490
+ this.host = match[3] ?? "";
491
+ const hostParts = this.host.split(":");
492
+ this.hostname = hostParts[0] ?? "";
493
+ this.port = hostParts.length > 1 ? hostParts[hostParts.length - 1] ?? "" : "";
494
+ this.pathname = match[4] || "/";
495
+ this.search = match[5] ?? "";
496
+ this.hash = match[6] ?? "";
497
+ this.origin = `${this.protocol}//${this.host}`;
498
+ this.href = resolved;
499
+ this.searchParams = new URLSearchParamsPolyfill(this.search);
500
+ }
501
+ toString() {
502
+ return this.href;
503
+ }
504
+ }
505
+ function resolveUrl(url, base) {
506
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url))
507
+ return url;
508
+ if (base === undefined)
509
+ throw new TypeError(`Invalid URL: ${url}`);
510
+ const baseUrl = new URLPolyfill(base);
511
+ if (url.startsWith("/"))
512
+ return `${baseUrl.origin}${url}`;
513
+ const directory = baseUrl.pathname.slice(0, baseUrl.pathname.lastIndexOf("/") + 1);
514
+ return `${baseUrl.origin}${directory}${url}`;
515
+ }
516
+
517
+ class HeadersPolyfill {
518
+ #map = new Map;
519
+ constructor(init) {
520
+ if (init instanceof HeadersPolyfill) {
521
+ for (const [name, value] of init.entries())
522
+ this.append(name, value);
523
+ } else if (Array.isArray(init)) {
524
+ for (const [name, value] of init)
525
+ this.append(name, value);
526
+ } else if (init) {
527
+ for (const [name, value] of Object.entries(init))
528
+ this.append(name, value);
529
+ }
530
+ }
531
+ #key(name) {
532
+ return name.toLowerCase();
533
+ }
534
+ append(name, value) {
535
+ const key = this.#key(name);
536
+ const existing = this.#map.get(key) ?? [];
537
+ existing.push(String(value));
538
+ this.#map.set(key, existing);
539
+ }
540
+ set(name, value) {
541
+ this.#map.set(this.#key(name), [String(value)]);
542
+ }
543
+ get(name) {
544
+ const values = this.#map.get(this.#key(name));
545
+ return values === undefined ? null : values.join(", ");
546
+ }
547
+ has(name) {
548
+ return this.#map.has(this.#key(name));
549
+ }
550
+ delete(name) {
551
+ this.#map.delete(this.#key(name));
552
+ }
553
+ *entries() {
554
+ for (const [name, values] of this.#map) {
555
+ for (const value of values)
556
+ yield [name, value];
557
+ }
558
+ }
559
+ forEach(callback) {
560
+ for (const [name, value] of this.entries())
561
+ callback(value, name, this);
562
+ }
563
+ [Symbol.iterator]() {
564
+ return this.entries();
565
+ }
566
+ }
567
+ function isAsyncIterable(value) {
568
+ return value != null && typeof value === "object" && Symbol.asyncIterator in value;
569
+ }
570
+ function toBodySource(body) {
571
+ if (body == null)
572
+ return null;
573
+ if (body instanceof Uint8Array)
574
+ return body;
575
+ if (body instanceof ArrayBuffer)
576
+ return new Uint8Array(body);
577
+ if (isAsyncIterable(body))
578
+ return body;
579
+ if (typeof body === "string")
580
+ return new TextEncoderPolyfill().encode(body);
581
+ return new TextEncoderPolyfill().encode(String(body));
582
+ }
583
+ async function collectBytes(source) {
584
+ if (source == null)
585
+ return new Uint8Array;
586
+ if (source instanceof Uint8Array)
587
+ return source;
588
+ const chunks = [];
589
+ let total = 0;
590
+ for await (const chunk of source) {
591
+ const bytes = chunk instanceof Uint8Array ? chunk : typeof chunk === "number" ? new Uint8Array([chunk]) : new Uint8Array(chunk);
592
+ chunks.push(bytes);
593
+ total += bytes.length;
594
+ }
595
+ const body = new Uint8Array(total);
596
+ let offset = 0;
597
+ for (const chunk of chunks) {
598
+ body.set(chunk, offset);
599
+ offset += chunk.length;
600
+ }
601
+ return body;
602
+ }
603
+ async function* bytesAsStream(bytes) {
604
+ if (bytes.length > 0)
605
+ yield bytes;
606
+ }
607
+ function bodyAsStream(source) {
608
+ if (source == null)
609
+ return null;
610
+ if (source instanceof Uint8Array)
611
+ return bytesAsStream(source);
612
+ return source;
613
+ }
614
+
615
+ class RequestPolyfill {
616
+ method;
617
+ url;
618
+ headers;
619
+ #body;
620
+ constructor(input, init = {}) {
621
+ if (input instanceof RequestPolyfill) {
622
+ this.method = String(init.method ?? input.method);
623
+ this.url = input.url;
624
+ this.headers = new HeadersPolyfill(init.headers ?? input.headers);
625
+ this.#body = init.body === undefined ? input.#body : toBodySource(init.body);
626
+ } else {
627
+ this.method = String(init.method ?? "GET").toUpperCase();
628
+ this.url = String(input);
629
+ this.headers = new HeadersPolyfill(init.headers);
630
+ this.#body = toBodySource(init.body);
631
+ }
632
+ }
633
+ get body() {
634
+ return bodyAsStream(this.#body);
635
+ }
636
+ clone() {
637
+ const body = this.#body instanceof Uint8Array ? this.#body.slice() : this.#body;
638
+ return new RequestPolyfill(this, { body });
639
+ }
640
+ async arrayBuffer() {
641
+ const bytes = await collectBytes(this.#body);
642
+ this.#body = bytes;
643
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
644
+ }
645
+ async text() {
646
+ return new TextDecoderPolyfill().decode(new Uint8Array(await this.arrayBuffer()));
647
+ }
648
+ async json() {
649
+ return JSON.parse(await this.text());
650
+ }
651
+ }
652
+
653
+ class ResponsePolyfill {
654
+ status;
655
+ statusText;
656
+ headers;
657
+ ok;
658
+ #body;
659
+ constructor(body, init = {}) {
660
+ this.status = Number(init.status ?? 200);
661
+ this.statusText = String(init.statusText ?? "");
662
+ this.headers = new HeadersPolyfill(init.headers);
663
+ this.ok = this.status >= 200 && this.status < 300;
664
+ this.#body = toBodySource(body);
665
+ }
666
+ static json(data, init = {}) {
667
+ const headers = new HeadersPolyfill(init.headers);
668
+ if (!headers.has("content-type"))
669
+ headers.set("content-type", "application/json");
670
+ return new ResponsePolyfill(JSON.stringify(data), { ...init, headers });
671
+ }
672
+ get body() {
673
+ return bodyAsStream(this.#body);
674
+ }
675
+ async arrayBuffer() {
676
+ const bytes = await collectBytes(this.#body);
677
+ this.#body = bytes;
678
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
679
+ }
680
+ async text() {
681
+ return new TextDecoderPolyfill().decode(new Uint8Array(await this.arrayBuffer()));
682
+ }
683
+ async json() {
684
+ return JSON.parse(await this.text());
685
+ }
686
+ }
687
+ var noopConsole = {
688
+ log() {},
689
+ info() {},
690
+ warn() {},
691
+ error() {},
692
+ debug() {}
693
+ };
694
+ function installFetchRuntime(force = false) {
695
+ const global = globalThis;
696
+ if (force || typeof global.TextEncoder !== "function")
697
+ global.TextEncoder = TextEncoderPolyfill;
698
+ if (force || typeof global.TextDecoder !== "function")
699
+ global.TextDecoder = TextDecoderPolyfill;
700
+ if (force || typeof global.URLSearchParams !== "function") {
701
+ global.URLSearchParams = URLSearchParamsPolyfill;
702
+ }
703
+ if (force || typeof global.URL !== "function")
704
+ global.URL = URLPolyfill;
705
+ if (force || typeof global.Headers !== "function")
706
+ global.Headers = HeadersPolyfill;
707
+ if (force || typeof global.Request !== "function")
708
+ global.Request = RequestPolyfill;
709
+ if (force || typeof global.Response !== "function")
710
+ global.Response = ResponsePolyfill;
711
+ if (force || typeof global.console !== "object" || global.console === null) {
712
+ global.console = noopConsole;
713
+ }
714
+ }
715
+ installFetchRuntime();
716
+ // assets/http-adapter.ts
717
+ function requireGuestsObject(value) {
718
+ if (typeof value !== "object" || value === null) {
719
+ throw new TypeError("wasmCloud guests module must export a guests object");
720
+ }
721
+ }
722
+ requireGuestsObject(wasmcloudGuests);
723
+ var TRAILER_FUTURE_TYPES = ["RESULT_OPTION_OTHER_ERROR_CODE"];
724
+ var VOID_RESULT_FUTURE_TYPES = ["RESULT_VOID_ERROR_CODE"];
725
+ function qjsFutureFactory() {
726
+ const future = globalThis.wit?.Future;
727
+ return typeof future === "function" ? future : undefined;
728
+ }
729
+ function pickFutureType(factory, preferred) {
730
+ for (const name of preferred) {
731
+ if (name in factory)
732
+ return factory[name];
733
+ }
734
+ const fallback = Object.keys(factory).find((key) => key !== "types" && key !== "from");
735
+ return fallback === undefined ? undefined : factory[fallback];
736
+ }
737
+ function lowerFuture(payload, preferredTypes) {
738
+ const factory = qjsFutureFactory();
739
+ if (factory === undefined)
740
+ return Promise.resolve(payload);
741
+ const pair = factory(pickFutureType(factory, preferredTypes));
742
+ pair.writable.write(payload);
743
+ return pair.readable;
744
+ }
745
+ function methodName(method) {
746
+ if (method === undefined)
747
+ return "GET";
748
+ return method.tag === "other" ? method.val ?? "GET" : method.tag.toUpperCase();
749
+ }
750
+ function firstOfTuple(value) {
751
+ if (Array.isArray(value))
752
+ return value[0];
753
+ if (value !== null && typeof value === "object" && "res" in value)
754
+ return value.res;
755
+ return value;
756
+ }
757
+ function isAsyncIterable2(value) {
758
+ return value != null && typeof value === "object" && Symbol.asyncIterator in value;
759
+ }
760
+ async function* bytesAsStream2(bytes) {
761
+ if (bytes.length > 0)
762
+ yield bytes;
763
+ }
764
+ async function toWebRequest(incoming) {
765
+ const method = methodName(incoming.getMethod());
766
+ const schemeValue = incoming.getScheme();
767
+ const scheme = schemeValue?.tag === "HTTPS" ? "https" : "http";
768
+ const authority = incoming.getAuthority() ?? "localhost";
769
+ const path = incoming.getPathWithQuery() ?? "/";
770
+ const decoder = new TextDecoder;
771
+ const headers = new Headers;
772
+ for (const [name, value] of incoming.getHeaders().copyAll()) {
773
+ headers.append(name, decoder.decode(value));
774
+ }
775
+ if (method === "GET" || method === "HEAD") {
776
+ return new Request(`${scheme}://${authority}${path}`, { method, headers });
777
+ }
778
+ let bodyBytes;
779
+ try {
780
+ const consumed = WasiRequest.consumeBody(incoming, lowerFuture({ tag: "ok", val: undefined }, VOID_RESULT_FUTURE_TYPES));
781
+ const body = firstOfTuple(consumed);
782
+ if (isAsyncIterable2(body)) {
783
+ const bytes = await collectBytes(body);
784
+ if (bytes.length > 0)
785
+ bodyBytes = bytes;
786
+ }
787
+ } catch {
788
+ bodyBytes = undefined;
789
+ }
790
+ return new Request(`${scheme}://${authority}${path}`, {
791
+ method,
792
+ headers,
793
+ body: bodyBytes
794
+ });
795
+ }
796
+ async function handleActorInvocation(request) {
797
+ const runtime = typeof getActorRuntime === "function" ? getActorRuntime() : undefined;
798
+ return handleActorInvocationRequest(request, runtime, dispatchActorInvocation);
799
+ }
800
+ async function dispatch(request) {
801
+ const handler = application;
802
+ const runtime = typeof getActorRuntime === "function" ? getActorRuntime() : undefined;
803
+ if (!handler || typeof handler !== "function" && typeof handler.fetch !== "function") {
804
+ if (runtime) {
805
+ return new Response(JSON.stringify({
806
+ name: "wasmcloud-actor-component",
807
+ actors: runtime.getRegisteredActors?.()?.map((a) => a.name) ?? [],
808
+ status: "running"
809
+ }), { status: 200, headers: { "content-type": "application/json" } });
810
+ }
811
+ throw new TypeError("The default application export must return a Web Response object");
812
+ }
813
+ const response = typeof handler === "function" ? await handler(request) : await handler.fetch(request);
814
+ if (!(response instanceof Response)) {
815
+ throw new TypeError("The default application export must return a Web Response object");
816
+ }
817
+ return response;
818
+ }
819
+ async function responseContents(response) {
820
+ const body = response.body;
821
+ if (isAsyncIterable2(body))
822
+ return body;
823
+ const bytes = new Uint8Array(await response.arrayBuffer());
824
+ return bytes.length > 0 ? bytesAsStream2(bytes) : null;
825
+ }
826
+ async function fromWebResponse(response) {
827
+ const encoder = new TextEncoder;
828
+ const headerPairs = [];
829
+ response.headers.forEach((value, name) => {
830
+ headerPairs.push([name, encoder.encode(value)]);
831
+ });
832
+ const fields = Fields.fromList(headerPairs);
833
+ const created = WasiResponse.new(fields, await responseContents(response), lowerFuture({ tag: "ok", val: null }, TRAILER_FUTURE_TYPES));
834
+ const outgoing = firstOfTuple(created);
835
+ outgoing.setStatusCode?.(response.status);
836
+ return outgoing;
837
+ }
838
+ var handler = {
839
+ async handle(incoming) {
840
+ try {
841
+ ensureWasiEnvironment();
842
+ const request = await toWebRequest(incoming);
843
+ const isControlPath = isCronInvokeRequest(request) || isQueueControlRequest(request) || isActorInvocationRequest(request);
844
+ if (isControlPath && !allowControlSurface(request)) {
845
+ return await fromWebResponse(controlSurfaceNotFound());
846
+ }
847
+ if (isCronInvokeRequest(request)) {
848
+ return await fromWebResponse(await handleCronInvokeRequest(request, cronInvokeJob));
849
+ }
850
+ if (isQueueControlRequest(request)) {
851
+ await ensureQueueWorkers();
852
+ const controlResponse = await handleQueueControlRequest(request, getQueueBackend());
853
+ try {
854
+ await pumpQueueWorkers();
855
+ } catch (error) {
856
+ console.error("Queue worker pump failed", error);
857
+ }
858
+ return await fromWebResponse(controlResponse);
859
+ }
860
+ if (isActorInvocationRequest(request)) {
861
+ return await fromWebResponse(await handleActorInvocation(request));
862
+ }
863
+ return await fromWebResponse(await dispatch(request));
864
+ } catch (error) {
865
+ console.error("Unhandled DI Framework request error", error);
866
+ return await fromWebResponse(new Response(JSON.stringify({ error: "Internal server error" }), {
867
+ status: 500,
868
+ headers: { "content-type": "application/json" }
869
+ }));
870
+ }
871
+ }
872
+ };
873
+ export {
874
+ handler,
875
+ requireGuestsObject
876
+ };