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

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 (69) hide show
  1. package/README.md +196 -21
  2. package/dist/args.d.ts +2 -1
  3. package/dist/args.js +9 -5
  4. package/dist/assets/http-adapter.js +63 -0
  5. package/dist/assets/platform/README.md +22 -6
  6. package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
  7. package/dist/assets/wit/deps/wasi-clocks-0.2.12/package.wit +43 -0
  8. package/dist/assets/wit/deps/wasi-filesystem-0.2.12/package.wit +196 -0
  9. package/dist/assets/wit/deps/wasi-io-0.2.12/package.wit +66 -0
  10. package/dist/assets/wit/deps/wasi-logging/package.wit +36 -0
  11. package/dist/build.d.ts +3 -1
  12. package/dist/build.js +4 -2
  13. package/dist/command.js +31 -13
  14. package/dist/console/auth.d.ts +20 -0
  15. package/dist/console/auth.js +82 -0
  16. package/dist/console/catalog.d.ts +196 -0
  17. package/dist/console/catalog.js +821 -0
  18. package/dist/console/cluster.d.ts +30 -0
  19. package/dist/console/cluster.js +299 -0
  20. package/dist/console/errors.d.ts +10 -0
  21. package/dist/console/errors.js +32 -0
  22. package/dist/console/run.d.ts +18 -0
  23. package/dist/console/run.js +102 -0
  24. package/dist/console/server.d.ts +25 -0
  25. package/dist/console/server.js +668 -0
  26. package/dist/console/services.d.ts +47 -0
  27. package/dist/console/services.js +111 -0
  28. package/dist/console-ui/app.css +1 -0
  29. package/dist/console-ui/app.js +260 -0
  30. package/dist/console-ui/di-framework-mark.png +0 -0
  31. package/dist/console-ui/index.html +13 -0
  32. package/dist/deps.d.ts +2 -0
  33. package/dist/deps.js +5 -3
  34. package/dist/dev.js +10 -5
  35. package/dist/egress.d.ts +40 -0
  36. package/dist/egress.js +214 -0
  37. package/dist/host-interface.js +2 -1
  38. package/dist/index.d.ts +1 -0
  39. package/dist/index.js +1 -0
  40. package/dist/manifest.d.ts +7 -0
  41. package/dist/manifest.js +35 -8
  42. package/dist/node-compat/console.d.ts +18 -0
  43. package/dist/node-compat/console.js +42 -0
  44. package/dist/node-compat/env.js +6 -0
  45. package/dist/node-compat/events.d.ts +20 -0
  46. package/dist/node-compat/events.js +55 -0
  47. package/dist/node-compat/fetch-runtime.d.ts +31 -0
  48. package/dist/node-compat/fetch-runtime.js +62 -0
  49. package/dist/node-compat/fs-promises.d.ts +30 -0
  50. package/dist/node-compat/fs-promises.js +3 -0
  51. package/dist/node-compat/fs.d.ts +79 -0
  52. package/dist/node-compat/fs.js +112 -5
  53. package/dist/node-compat/net.d.ts +2 -1
  54. package/dist/node-compat/net.js +3 -1
  55. package/dist/node-compat/storage.d.ts +87 -0
  56. package/dist/node-compat/storage.js +244 -0
  57. package/dist/node-compat/stream.d.ts +24 -0
  58. package/dist/node-compat/stream.js +70 -0
  59. package/dist/platform.js +2 -4
  60. package/dist/project.d.ts +5 -0
  61. package/dist/project.js +4 -0
  62. package/dist/service.d.ts +21 -2
  63. package/dist/service.js +71 -5
  64. package/dist/target.js +6 -1
  65. package/dist/wit.d.ts +8 -0
  66. package/dist/wit.js +28 -0
  67. package/dist/workload.d.ts +45 -0
  68. package/dist/workload.js +98 -26
  69. package/package.json +14 -4
@@ -0,0 +1,13 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>DI Framework console</title>
7
+ <link rel="stylesheet" href="/assets/app.css" />
8
+ </head>
9
+ <body>
10
+ <div id="root"></div>
11
+ <script src="/assets/app.js"></script>
12
+ </body>
13
+ </html>
package/dist/deps.d.ts CHANGED
@@ -23,6 +23,8 @@ export type BundleOptions = {
23
23
  cronPath?: string;
24
24
  queuesPath?: string;
25
25
  projectRoot?: string;
26
+ /** Link the wasi:logging console. Off for local runners that cannot provide it. */
27
+ guestLogging?: boolean;
26
28
  files?: Record<string, string>;
27
29
  env?: Record<string, string | undefined>;
28
30
  cwd?: string;
package/dist/deps.js CHANGED
@@ -224,7 +224,7 @@ export const DEFAULT_DEPS = {
224
224
  return { exitCode: await child.exited, stdout, stderr };
225
225
  },
226
226
  wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
227
- bundler: async ({ adapterPath, entryPath, outFile, guestsPath, actorsPath, cronPath, queuesPath, projectRoot, files, env, cwd, }) => {
227
+ bundler: async ({ adapterPath, entryPath, outFile, guestsPath, actorsPath, cronPath, queuesPath, projectRoot, guestLogging, files, env, cwd, }) => {
228
228
  const nodeEnv = wasmcloudNodeEnv();
229
229
  const bundle = await rolldown({
230
230
  input: 'virtual:di-framework-runtime-entry',
@@ -239,8 +239,10 @@ export const DEFAULT_DEPS = {
239
239
  },
240
240
  load(id) {
241
241
  if (id === '\0virtual:di-framework-runtime-entry') {
242
- const bootstrap = join(dirname(fileURLToPath(import.meta.url)), 'node-compat', `bootstrap.${import.meta.url.endsWith('.ts') ? 'ts' : 'js'}`);
243
- return `import ${JSON.stringify(bootstrap)}; export * from ${JSON.stringify(adapterPath)};`;
242
+ const runtimeFile = (name) => join(dirname(fileURLToPath(import.meta.url)), 'node-compat', `${name}.${import.meta.url.endsWith('.ts') ? 'ts' : 'js'}`);
243
+ // The console import comes after bootstrap so it replaces the noop console.
244
+ const console = guestLogging === false ? '' : `import ${JSON.stringify(runtimeFile('console'))}; `;
245
+ return `import ${JSON.stringify(runtimeFile('bootstrap'))}; ${console}export * from ${JSON.stringify(adapterPath)};`;
244
246
  }
245
247
  },
246
248
  },
package/dist/dev.js CHANGED
@@ -8,6 +8,7 @@ import { requiresWasmCloudHost, resolveDevRunner } from './dev-runner.js';
8
8
  import { loadProject } from './project.js';
9
9
  import { invalidUsage, readOptionValue, toolFailed } from './support.js';
10
10
  import { writeWashDevConfig } from './wash-dev.js';
11
+ import { guestLoggingRequirement } from './wit.js';
11
12
  export function parseDevArgs(args) {
12
13
  let host;
13
14
  let port;
@@ -33,21 +34,25 @@ export function parseDevArgs(args) {
33
34
  export async function runWasmcloudDev(args, io, deps = DEFAULT_DEPS) {
34
35
  const options = parseDevArgs(args);
35
36
  const project = loadProject(deps.cwd());
36
- await buildComponent(project, io, deps);
37
+ const projectRequirements = requirementsForProject(project, deps);
38
+ const runner = resolveDevRunner(deps, {
39
+ wasmCloudHost: requiresWasmCloudHost(projectRequirements),
40
+ });
41
+ // Only wash provides wasi:logging locally; other runners keep the noop console.
42
+ await buildComponent(project, io, deps, { guestLogging: runner.kind === 'wash' });
37
43
  const lockPath = join(project.projectRoot, '.di-framework', 'wit.lock.json');
38
44
  let tls;
39
- let wasmCloudHost;
40
45
  try {
41
46
  const lock = JSON.parse(readFileSync(lockPath, 'utf8'));
42
47
  tls = lock.requirements.some((requirement) => requirement.package === 'wasi:tls');
43
- wasmCloudHost = requiresWasmCloudHost(lock.requirements);
44
48
  }
45
49
  catch (error) {
46
50
  throw new CommandFailure('WASMCLOUD_WIT_LOCK_INVALID', `Cannot read generated WIT requirements from ${lockPath}. Rerun platform build before starting the dev server.`, 3, { path: lockPath, cause: String(error) });
47
51
  }
48
- const runner = resolveDevRunner(deps, { wasmCloudHost });
49
52
  const washConfigPath = runner.kind === 'wash'
50
- ? writeWashDevConfig(project, requirementsForProject(project, deps), discoverBindings(project, deps), {
53
+ ? writeWashDevConfig(project, project.logs === false
54
+ ? projectRequirements
55
+ : [...projectRequirements, guestLoggingRequirement()], discoverBindings(project, deps), {
51
56
  host: options.host,
52
57
  port: options.port,
53
58
  postgresUrl: deps.env.WASMCLOUD_POSTGRES_URL,
@@ -0,0 +1,40 @@
1
+ import { type CliIo } from '@di-framework/cli-extension';
2
+ import type { WasmcloudDeps } from './deps.js';
3
+ import type { WasmcloudProject } from './project.js';
4
+ import type { ClusterConnection } from './target.js';
5
+ /**
6
+ * Tenant workloads cannot name outbound hosts themselves. The CLI turns the project's
7
+ * `allowedIpNameLookups` into an egress BackingService plus a ServiceBinding; the platform
8
+ * approves the destinations against its class policy and patches the WorkloadDeployment.
9
+ */
10
+ export declare const EGRESS_BINDING_NAME = "egress";
11
+ /** Marks the BackingService the CLI owns for one WorkloadDeployment. */
12
+ export declare const EGRESS_WORKLOAD_LABEL = "di-framework.dev/egress-workload";
13
+ /** Tag marker for a tenant host image built with a wasi:tls provider. */
14
+ export declare const TLS_HOST_IMAGE_MARKER = "wasi-tls";
15
+ /** A tenant target names its host group; outbound access is a platform grant there. */
16
+ export declare function usesPlatformEgress(connection: Pick<ClusterConnection, 'hostgroup'>): boolean;
17
+ /** BackingService and ServiceBinding name for a WorkloadDeployment's egress grant. */
18
+ export declare function egressResourceName(workloadName: string): string;
19
+ /**
20
+ * Ensure the egress BackingService and ServiceBinding for a tenant deploy. Returns the
21
+ * ServiceBinding name to keep, or undefined when the target or project has no egress.
22
+ */
23
+ export declare function applyWorkloadEgress(project: WasmcloudProject, connection: ClusterConnection, deps: WasmcloudDeps): Promise<string | undefined>;
24
+ /**
25
+ * Remove the deploy-owned egress BackingService once its binding is gone. Only resources
26
+ * labelled for this WorkloadDeployment are touched.
27
+ */
28
+ export declare function removeWorkloadEgress(project: WasmcloudProject, connection: ClusterConnection, deps: WasmcloudDeps): Promise<void>;
29
+ /**
30
+ * Tell the developer whether the platform approved the egress destinations. A missing
31
+ * approval never fails the deploy: the workload runs, its outbound calls stay blocked.
32
+ */
33
+ export declare function reportEgressStatus(project: WasmcloudProject, connection: ClusterConnection, io: CliIo, deps: WasmcloudDeps): Promise<void>;
34
+ /**
35
+ * Warn when a component that imports wasi:tls goes to a tenant host without a TLS provider.
36
+ * The host image is read from the tenant host pods in `di-runtime-<tenant>`; a tag carrying
37
+ * `wasi-tls` (e.g. `…:2.8.0-wasi-tls`) counts as TLS-capable. Stock wash images do not.
38
+ * Anything unreadable stays silent.
39
+ */
40
+ export declare function warnIfTenantHostLacksTls(project: WasmcloudProject, connection: ClusterConnection, io: CliIo, deps: WasmcloudDeps): Promise<void>;
package/dist/egress.js ADDED
@@ -0,0 +1,214 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { CommandFailure } from '@di-framework/cli-extension';
4
+ import { captureKubectl, runKubectl } from './kubernetes.js';
5
+ import { ASSOCIATION_WORKLOAD_LABEL } from './managed-bindings.js';
6
+ import { BACKING_SERVICE_API_VERSION, BACKING_SERVICE_KIND, BACKING_SERVICE_RESOURCE, isBackingServiceName, } from './service.js';
7
+ /**
8
+ * Tenant workloads cannot name outbound hosts themselves. The CLI turns the project's
9
+ * `allowedIpNameLookups` into an egress BackingService plus a ServiceBinding; the platform
10
+ * approves the destinations against its class policy and patches the WorkloadDeployment.
11
+ */
12
+ export const EGRESS_BINDING_NAME = 'egress';
13
+ /** Marks the BackingService the CLI owns for one WorkloadDeployment. */
14
+ export const EGRESS_WORKLOAD_LABEL = 'di-framework.dev/egress-workload';
15
+ const BINDING_RESOURCE = 'servicebindings.platform.di-framework.dev';
16
+ /** kubectl's wording when the CRD itself is absent, as opposed to a missing object. */
17
+ const MISSING_RESOURCE_TYPE = /the server doesn't have a resource type|could not find the requested resource/i;
18
+ const STATUS_ATTEMPTS = 5;
19
+ const STATUS_INTERVAL_MS = 2_000;
20
+ /** Tag marker for a tenant host image built with a wasi:tls provider. */
21
+ export const TLS_HOST_IMAGE_MARKER = 'wasi-tls';
22
+ /** A tenant target names its host group; outbound access is a platform grant there. */
23
+ export function usesPlatformEgress(connection) {
24
+ return connection.hostgroup !== undefined;
25
+ }
26
+ /** BackingService and ServiceBinding name for a WorkloadDeployment's egress grant. */
27
+ export function egressResourceName(workloadName) {
28
+ return `${workloadName}-egress`;
29
+ }
30
+ function egressFailure(message, details = {}) {
31
+ throw new CommandFailure('WASMCLOUD_EGRESS_FAILED', message, 2, details);
32
+ }
33
+ function ownedBy(document, label, workload) {
34
+ const labels = document.metadata?.labels;
35
+ return labels?.['app.kubernetes.io/managed-by'] === 'di-framework' && labels[label] === workload;
36
+ }
37
+ async function assertAdoptable(project, connection, resource, kind, name, label, deps) {
38
+ const result = await captureKubectl(deps, connection, ['get', resource, name, '-o', 'json', '--ignore-not-found'], project.projectRoot);
39
+ if (result.exitCode !== 0) {
40
+ const detail = (result.stderr.trim() ||
41
+ result.stdout.trim() ||
42
+ `kubectl exited ${result.exitCode}`)
43
+ .split('\n')
44
+ .slice(0, 12)
45
+ .join('\n');
46
+ egressFailure(MISSING_RESOURCE_TYPE.test(detail)
47
+ ? `Cannot read ${kind} ${name}: the cluster has no ${kind} resource type; install the platform backing-service CRDs`
48
+ : `Cannot read ${kind} ${name}: ${detail}`, { name, namespace: connection.namespace, stderr: detail });
49
+ }
50
+ if (!result.stdout.trim())
51
+ return;
52
+ const document = JSON.parse(result.stdout);
53
+ if (!ownedBy(document, label, project.witName))
54
+ egressFailure(`Refusing to adopt ${kind} ${name}; it was not created by di-framework deploy for ${project.witName}`, { name, namespace: connection.namespace });
55
+ }
56
+ /**
57
+ * Ensure the egress BackingService and ServiceBinding for a tenant deploy. Returns the
58
+ * ServiceBinding name to keep, or undefined when the target or project has no egress.
59
+ */
60
+ export async function applyWorkloadEgress(project, connection, deps) {
61
+ const destinations = project.allowedIpNameLookups ?? [];
62
+ if (!usesPlatformEgress(connection) || destinations.length === 0)
63
+ return undefined;
64
+ if (destinations.includes('*'))
65
+ egressFailure('allowedIpNameLookups "*" cannot be granted on a tenant target; list the hosts or *.suffix names the workload calls');
66
+ const workload = project.witName;
67
+ const name = egressResourceName(workload);
68
+ if (!isBackingServiceName(name))
69
+ egressFailure(`Egress BackingService name ${name} is longer than 40 characters; shorten the application name to use allowedIpNameLookups on a tenant target`, { name });
70
+ await assertAdoptable(project, connection, BACKING_SERVICE_RESOURCE, 'BackingService', name, EGRESS_WORKLOAD_LABEL, deps);
71
+ await assertAdoptable(project, connection, BINDING_RESOURCE, 'ServiceBinding', name, ASSOCIATION_WORKLOAD_LABEL, deps);
72
+ const items = [
73
+ {
74
+ apiVersion: BACKING_SERVICE_API_VERSION,
75
+ kind: BACKING_SERVICE_KIND,
76
+ metadata: {
77
+ name,
78
+ namespace: connection.namespace,
79
+ labels: {
80
+ 'app.kubernetes.io/managed-by': 'di-framework',
81
+ [EGRESS_WORKLOAD_LABEL]: workload,
82
+ },
83
+ },
84
+ spec: { type: 'egress', destinations: [...destinations] },
85
+ },
86
+ {
87
+ apiVersion: BACKING_SERVICE_API_VERSION,
88
+ kind: 'ServiceBinding',
89
+ metadata: {
90
+ name,
91
+ namespace: connection.namespace,
92
+ labels: {
93
+ 'app.kubernetes.io/managed-by': 'di-framework',
94
+ [ASSOCIATION_WORKLOAD_LABEL]: workload,
95
+ },
96
+ },
97
+ spec: {
98
+ serviceName: name,
99
+ bindingName: EGRESS_BINDING_NAME,
100
+ capability: 'egress',
101
+ workloadName: workload,
102
+ },
103
+ },
104
+ ];
105
+ const directory = join(project.projectRoot, '.di-framework', 'deploy');
106
+ mkdirSync(directory, { recursive: true });
107
+ const path = join(directory, 'egress.json');
108
+ writeFileSync(path, JSON.stringify({ apiVersion: 'v1', kind: 'List', items }, null, 2));
109
+ await runKubectl(deps, connection, ['apply', '-f', path], project.projectRoot);
110
+ return name;
111
+ }
112
+ /**
113
+ * Remove the deploy-owned egress BackingService once its binding is gone. Only resources
114
+ * labelled for this WorkloadDeployment are touched.
115
+ */
116
+ export async function removeWorkloadEgress(project, connection, deps) {
117
+ if (!usesPlatformEgress(connection))
118
+ return;
119
+ const result = await captureKubectl(deps, connection, [
120
+ 'delete',
121
+ BACKING_SERVICE_RESOURCE,
122
+ '-l',
123
+ `${EGRESS_WORKLOAD_LABEL}=${project.witName},app.kubernetes.io/managed-by=di-framework`,
124
+ '--ignore-not-found',
125
+ '--wait=true',
126
+ '--timeout=180s',
127
+ ], project.projectRoot);
128
+ if (result.exitCode !== 0 && !MISSING_RESOURCE_TYPE.test(result.stderr))
129
+ egressFailure(`Cannot remove the egress BackingService for ${project.witName}`, {
130
+ name: egressResourceName(project.witName),
131
+ });
132
+ }
133
+ /**
134
+ * Tell the developer whether the platform approved the egress destinations. A missing
135
+ * approval never fails the deploy: the workload runs, its outbound calls stay blocked.
136
+ */
137
+ export async function reportEgressStatus(project, connection, io, deps) {
138
+ const name = egressResourceName(project.witName);
139
+ let condition;
140
+ let approved = [];
141
+ for (let attempt = 0; attempt < STATUS_ATTEMPTS; attempt++) {
142
+ const result = await captureKubectl(deps, connection, ['get', BACKING_SERVICE_RESOURCE, name, '-o', 'json'], project.projectRoot);
143
+ if (result.exitCode === 0) {
144
+ try {
145
+ const document = JSON.parse(result.stdout);
146
+ condition = document.status?.conditions?.find((entry) => entry.type === 'Ready');
147
+ approved = document.status?.approved ?? [];
148
+ }
149
+ catch {
150
+ condition = undefined;
151
+ }
152
+ }
153
+ if (condition?.status === 'True' || condition?.reason === 'NotApproved')
154
+ break;
155
+ await deps.wait(STATUS_INTERVAL_MS);
156
+ }
157
+ if (condition?.status === 'True') {
158
+ io.stdout.write(`Egress approved for ${project.witName}: ${approved.join(', ')}\n`);
159
+ return;
160
+ }
161
+ if (condition?.reason === 'NotApproved') {
162
+ io.stderr.write(`Note: egress for ${project.witName} is not approved${condition.message ? ` (${condition.message})` : ''}. ` +
163
+ "A platform admin must allow the destination in the platform's egressAllowedDestinations; " +
164
+ 'until then outbound connections from this workload stay blocked.\n');
165
+ return;
166
+ }
167
+ io.stderr.write(`Note: egress BackingService ${name} is not Ready yet` +
168
+ (condition?.message ? ` (${condition.message})` : '') +
169
+ `; check it with: di-framework platform service get ${name}\n`);
170
+ }
171
+ function importsWasiTls(project) {
172
+ try {
173
+ const lock = JSON.parse(readFileSync(join(project.projectRoot, '.di-framework', 'wit.lock.json'), 'utf8'));
174
+ return lock.requirements.some((requirement) => requirement.package === 'wasi:tls' && requirement.direction === 'import');
175
+ }
176
+ catch {
177
+ return false;
178
+ }
179
+ }
180
+ /**
181
+ * Warn when a component that imports wasi:tls goes to a tenant host without a TLS provider.
182
+ * The host image is read from the tenant host pods in `di-runtime-<tenant>`; a tag carrying
183
+ * `wasi-tls` (e.g. `…:2.8.0-wasi-tls`) counts as TLS-capable. Stock wash images do not.
184
+ * Anything unreadable stays silent.
185
+ */
186
+ export async function warnIfTenantHostLacksTls(project, connection, io, deps) {
187
+ const hostgroup = connection.hostgroup;
188
+ if (hostgroup === undefined || !hostgroup.startsWith('tenant-'))
189
+ return;
190
+ if (!importsWasiTls(project))
191
+ return;
192
+ const runtime = { ...connection, namespace: `di-runtime-${hostgroup.slice('tenant-'.length)}` };
193
+ const result = await captureKubectl(deps, runtime, ['get', 'pods', '-l', `wasmcloud.com/hostgroup=${hostgroup}`, '-o', 'json'], project.projectRoot);
194
+ if (result.exitCode !== 0)
195
+ return;
196
+ let images;
197
+ try {
198
+ const list = JSON.parse(result.stdout);
199
+ images = (list.items ?? []).flatMap((pod) => (pod.spec?.containers ?? []).flatMap((container) => typeof container.image === 'string' ? [container.image] : []));
200
+ }
201
+ catch {
202
+ return;
203
+ }
204
+ const image = images[0];
205
+ if (image === undefined || images.some(hasTlsTag))
206
+ return;
207
+ io.stderr.write(`Warning: ${project.applicationName} imports wasi:tls, but host group ${hostgroup} runs ${image}, ` +
208
+ `which has no wasi:tls provider. TLS connections from this workload will fail until a platform ` +
209
+ `admin switches the tenant host to an image built with wasi-tls (tagged *-${TLS_HOST_IMAGE_MARKER}).\n`);
210
+ }
211
+ function hasTlsTag(image) {
212
+ const tag = image.split('@')[0]?.split('/').pop()?.split(':')[1];
213
+ return tag?.includes(TLS_HOST_IMAGE_MARKER) === true;
214
+ }
@@ -1,4 +1,4 @@
1
- import { aggregateRequirements, parsePackageId, WASI_HTTP_INTERFACE, WASI_HTTP_PACKAGE, WASI_RANDOM_PACKAGE, WASI_SOCKETS_PACKAGE, } from './wit.js';
1
+ import { aggregateRequirements, parsePackageId, WASI_FILESYSTEM_PACKAGE, WASI_HTTP_INTERFACE, WASI_HTTP_PACKAGE, WASI_RANDOM_PACKAGE, WASI_SOCKETS_PACKAGE, } from './wit.js';
2
2
  // These providers link QuickJS's unlabeled imports through their default route.
3
3
  // Supplying a name selects the implements route, which cannot link those imports.
4
4
  const UNLABELED_HOST_PACKAGES = new Set([
@@ -40,6 +40,7 @@ export function hostInterfacesFromRequirements(requirements, options = {}, overl
40
40
  const entries = aggregateRequirements(requirements)
41
41
  .filter((requirement) => requirement.package !== WASI_SOCKETS_PACKAGE &&
42
42
  requirement.package !== WASI_RANDOM_PACKAGE &&
43
+ requirement.package !== WASI_FILESYSTEM_PACKAGE &&
43
44
  requirement.package !== 'wasi:tls' &&
44
45
  requirement.package !== 'wasi:clocks')
45
46
  .map((requirement) => {
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ export { parseAppCommandArgs, parsePlatformCommandArgs, parsePlatformInitArgs }
4
4
  export { type BindingRecord, defaultSecretName, discoverBindings, parseBindingsFile, requirementsFromBindings, } from './bindings.js';
5
5
  export { BUILD_PROFILE, buildComponent, canonicalBuildDigest, requirementsForProject, runWasmcloudBuild, WASI_HTTP_INTERFACE, WASI_HTTP_VERSION, } from './build.js';
6
6
  export { createWasmcloudCommand } from './command.js';
7
+ export { runWasmcloudConsole } from './console/run.js';
7
8
  export { runWasmcloudDeploy, type WasmcloudDeployData, type WasmcloudDeployResult, } from './deploy.js';
8
9
  export { type BundleOptions, COMPONENT_IMPORT_EXTERNAL, COMPONENTIZE_QJS_ENV, COMPONENTIZE_QJS_PACKAGE, componentizeQjsPlatformPackageName, DEFAULT_DEPS, findInstalledComponentizeQjsCli, nativeComponentizeQjsOnPath, nodeCompatibilityPlugin, resolveComponentizeQjsPath, type WasmcloudDeps, } from './deps.js';
9
10
  export { runWasmcloudDestroy } from './destroy.js';
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export { parseAppCommandArgs, parsePlatformCommandArgs, parsePlatformInitArgs }
6
6
  export { defaultSecretName, discoverBindings, parseBindingsFile, requirementsFromBindings, } from './bindings.js';
7
7
  export { BUILD_PROFILE, buildComponent, canonicalBuildDigest, requirementsForProject, runWasmcloudBuild, WASI_HTTP_INTERFACE, WASI_HTTP_VERSION, } from './build.js';
8
8
  export { createWasmcloudCommand } from './command.js';
9
+ export { runWasmcloudConsole } from './console/run.js';
9
10
  export { runWasmcloudDeploy, } from './deploy.js';
10
11
  export { COMPONENT_IMPORT_EXTERNAL, COMPONENTIZE_QJS_ENV, COMPONENTIZE_QJS_PACKAGE, componentizeQjsPlatformPackageName, DEFAULT_DEPS, findInstalledComponentizeQjsCli, nativeComponentizeQjsOnPath, nodeCompatibilityPlugin, resolveComponentizeQjsPath, } from './deps.js';
11
12
  export { runWasmcloudDestroy } from './destroy.js';
@@ -15,6 +15,8 @@ export type ManagedTarget = {
15
15
  export type ExternalTarget = {
16
16
  kind: 'external';
17
17
  name: string;
18
+ /** Platform tenant this target deploys into; derives namespace and hostgroup when they are unset. */
19
+ tenant?: string;
18
20
  kubeconfig: string;
19
21
  namespace: string;
20
22
  registry: RegistryInput;
@@ -30,6 +32,11 @@ export type DeployManifest = {
30
32
  discovery: DiscoveryConfig;
31
33
  targets: Record<string, DeployTarget>;
32
34
  };
35
+ export declare function isTenantName(value: string): boolean;
36
+ /** Workload namespace the platform creates for a tenant. */
37
+ export declare function tenantNamespace(tenant: string): string;
38
+ /** Host group the platform creates for a tenant. */
39
+ export declare function tenantHostgroup(tenant: string): string;
33
40
  export declare function findDeployManifest(startDirectory: string): string | undefined;
34
41
  export declare function loadDeployManifest(startDirectory: string, env: Record<string, string | undefined>): DeployManifest;
35
42
  export declare function parseDeployManifest(path: string, source: string, env: Record<string, string | undefined>): DeployManifest;
package/dist/manifest.js CHANGED
@@ -7,6 +7,20 @@ import { parseToml, TomlParseError } from './toml.js';
7
7
  export const DEPLOY_MANIFEST_NAME = 'di-framework.deploy.toml';
8
8
  export const DEFAULT_DISCOVERY_EXCLUDE = ['dist/**', 'coverage/**', '**/dist/**', '**/coverage/**'];
9
9
  export const ALWAYS_SKIP_DIRECTORIES = new Set(['.git', 'node_modules', '.di-framework']);
10
+ /** Tenant names follow the platform's Tenant resource: a DNS label of at most 40 characters. */
11
+ const TENANT_NAME = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
12
+ const TENANT_NAME_MAX_LENGTH = 40;
13
+ export function isTenantName(value) {
14
+ return value.length <= TENANT_NAME_MAX_LENGTH && TENANT_NAME.test(value);
15
+ }
16
+ /** Workload namespace the platform creates for a tenant. */
17
+ export function tenantNamespace(tenant) {
18
+ return `di-tenant-${tenant}`;
19
+ }
20
+ /** Host group the platform creates for a tenant. */
21
+ export function tenantHostgroup(tenant) {
22
+ return `tenant-${tenant}`;
23
+ }
10
24
  const ENV_TOKEN = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
11
25
  function manifestInvalid(message, details) {
12
26
  throw new CommandFailure('WASMCLOUD_DEPLOY_MANIFEST_INVALID', message, 2, details);
@@ -116,6 +130,10 @@ function parseTarget(name, value, manifestPath) {
116
130
  const stack = optionalString(value.stack, `targets.${name}.stack`, manifestPath);
117
131
  const kubeconfig = optionalString(value.kubeconfig, `targets.${name}.kubeconfig`, manifestPath);
118
132
  const context = optionalString(value.context, `targets.${name}.context`, manifestPath);
133
+ const tenant = optionalString(value.tenant, `targets.${name}.tenant`, manifestPath);
134
+ if (tenant !== undefined && !isTenantName(tenant)) {
135
+ manifestInvalid(`targets.${name}.tenant must be a platform tenant name: 1-40 lowercase letters, digits, and single hyphens, starting with a letter (got "${tenant}")`, { manifestPath, target: name, tenant });
136
+ }
119
137
  const hostgroup = optionalString(value.hostgroup, `targets.${name}.hostgroup`, manifestPath);
120
138
  const storageHostgroup = optionalString(value['storage-hostgroup'], `targets.${name}.storage-hostgroup`, manifestPath);
121
139
  for (const [field, group] of [
@@ -138,6 +156,7 @@ function parseTarget(name, value, manifestPath) {
138
156
  'stack',
139
157
  'kubeconfig',
140
158
  'context',
159
+ 'tenant',
141
160
  'namespace',
142
161
  'registry',
143
162
  'hostgroup',
@@ -145,19 +164,20 @@ function parseTarget(name, value, manifestPath) {
145
164
  ]);
146
165
  const unknown = Object.keys(value).filter((key) => !known.has(key));
147
166
  if (unknown.length > 0) {
148
- manifestInvalid(`Target "${name}" has unsupported fields: ${unknown.join(', ')}. Managed targets accept platform and stack; external targets accept kubeconfig, context, namespace, registry, hostgroup, and storage-hostgroup.`, { manifestPath, target: name, fields: unknown });
167
+ manifestInvalid(`Target "${name}" has unsupported fields: ${unknown.join(', ')}. Managed targets accept platform and stack; external targets accept kubeconfig, context, tenant, namespace, registry, hostgroup, and storage-hostgroup.`, { manifestPath, target: name, fields: unknown });
149
168
  }
150
169
  const managedFields = [platform ? 'platform' : undefined, stack ? 'stack' : undefined].filter((field) => field !== undefined);
151
170
  const externalFields = [
152
171
  kubeconfig ? 'kubeconfig' : undefined,
153
172
  context ? 'context' : undefined,
173
+ tenant ? 'tenant' : undefined,
154
174
  hostgroup ? 'hostgroup' : undefined,
155
175
  storageHostgroup ? 'storage-hostgroup' : undefined,
156
176
  namespace ? 'namespace' : undefined,
157
177
  registry ? 'registry' : undefined,
158
178
  ].filter((field) => field !== undefined);
159
179
  if (managedFields.length > 0 && externalFields.length > 0) {
160
- manifestInvalid(`Target "${name}" mixes managed-platform and kubeconfig fields (${[...managedFields, ...externalFields].join(', ')}). Use either platform (and optional stack), or kubeconfig + namespace + registry.`, { manifestPath, target: name });
180
+ manifestInvalid(`Target "${name}" mixes managed-platform and kubeconfig fields (${[...managedFields, ...externalFields].join(', ')}). Use either platform (and optional stack), or kubeconfig + registry + tenant or namespace.`, { manifestPath, target: name });
161
181
  }
162
182
  if (stack !== undefined && platform === undefined) {
163
183
  manifestInvalid(`Target "${name}" sets stack without platform. stack is only valid on managed Pulumi targets.`, { manifestPath, target: name });
@@ -165,27 +185,34 @@ function parseTarget(name, value, manifestPath) {
165
185
  if (platform !== undefined) {
166
186
  return { kind: 'managed', name, platform, stack: stack ?? 'dev' };
167
187
  }
168
- if (kubeconfig !== undefined || namespace !== undefined || registry !== undefined) {
188
+ if (kubeconfig !== undefined ||
189
+ tenant !== undefined ||
190
+ namespace !== undefined ||
191
+ registry !== undefined) {
192
+ // Explicit namespace/hostgroup win over the values a tenant derives.
193
+ const resolvedNamespace = namespace ?? (tenant === undefined ? undefined : tenantNamespace(tenant));
194
+ const resolvedHostgroup = hostgroup ?? (tenant === undefined ? undefined : tenantHostgroup(tenant));
169
195
  const missing = [
170
196
  kubeconfig === undefined ? 'kubeconfig' : undefined,
171
- namespace === undefined ? 'namespace' : undefined,
197
+ resolvedNamespace === undefined ? 'tenant or namespace' : undefined,
172
198
  registry === undefined ? 'registry' : undefined,
173
199
  ].filter((field) => field !== undefined);
174
200
  if (missing.length > 0) {
175
- manifestInvalid(`Target "${name}" is incomplete; external targets require kubeconfig, namespace, and registry. Missing: ${missing.join(', ')}.`, { manifestPath, target: name, missing });
201
+ manifestInvalid(`Target "${name}" is incomplete; external targets require kubeconfig, registry, and either tenant (deploys into the platform tenant's di-tenant-<tenant> namespace and tenant-<tenant> host group) or namespace. Missing: ${missing.join(', ')}.`, { manifestPath, target: name, missing });
176
202
  }
177
203
  return {
178
204
  kind: 'external',
179
205
  name,
180
206
  kubeconfig: kubeconfig,
181
- namespace: namespace,
207
+ namespace: resolvedNamespace,
182
208
  registry: registry,
183
209
  context,
184
- ...(hostgroup ? { hostgroup } : {}),
210
+ ...(tenant ? { tenant } : {}),
211
+ ...(resolvedHostgroup ? { hostgroup: resolvedHostgroup } : {}),
185
212
  ...(storageHostgroup ? { storageHostgroup } : {}),
186
213
  };
187
214
  }
188
- manifestInvalid(`Target "${name}" is empty. Set platform (and optional stack) for a managed Pulumi platform, or kubeconfig, namespace, and registry for an external cluster.`, { manifestPath, target: name });
215
+ manifestInvalid(`Target "${name}" is empty. Set platform (and optional stack) for a managed Pulumi platform, or kubeconfig, registry, and tenant (or namespace) for an external cluster.`, { manifestPath, target: name });
189
216
  }
190
217
  function optionalString(value, label, manifestPath) {
191
218
  if (value === undefined)
@@ -0,0 +1,18 @@
1
+ type Level = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'critical';
2
+ type LogWriter = (level: Level, context: string, message: string) => void;
3
+ /** Context passed with every guest console line; the host tags it with the workload. */
4
+ export declare const CONSOLE_LOG_CONTEXT = "console";
5
+ /**
6
+ * QuickJS has no console. Route each line through wasi:logging, the only guest output
7
+ * that wash 2.8 attributes to a workload; raw stdio reaches the host log unlabeled.
8
+ */
9
+ export declare function createWasiConsole(write: LogWriter): {
10
+ log: (...values: unknown[]) => void;
11
+ info: (...values: unknown[]) => void;
12
+ debug: (...values: unknown[]) => void;
13
+ trace: (...values: unknown[]) => void;
14
+ warn: (...values: unknown[]) => void;
15
+ error: (...values: unknown[]) => void;
16
+ };
17
+ export declare function installWasiConsole(write?: LogWriter): void;
18
+ export {};
@@ -0,0 +1,42 @@
1
+ import { log } from 'wasi:logging/logging@0.1.0-draft';
2
+ /** Context passed with every guest console line; the host tags it with the workload. */
3
+ export const CONSOLE_LOG_CONTEXT = 'console';
4
+ function formatValue(value) {
5
+ if (typeof value === 'string')
6
+ return value;
7
+ if (value instanceof Error)
8
+ return value.stack ?? `${value.name}: ${value.message}`;
9
+ if (typeof value !== 'object' || value === null)
10
+ return String(value);
11
+ try {
12
+ return JSON.stringify(value);
13
+ }
14
+ catch {
15
+ return String(value);
16
+ }
17
+ }
18
+ /**
19
+ * QuickJS has no console. Route each line through wasi:logging, the only guest output
20
+ * that wash 2.8 attributes to a workload; raw stdio reaches the host log unlabeled.
21
+ */
22
+ export function createWasiConsole(write) {
23
+ const emit = (level) => (...values) => {
24
+ const lines = values.map(formatValue).join(' ').split(/\r?\n/);
25
+ if (lines.length > 1 && lines[lines.length - 1] === '')
26
+ lines.pop();
27
+ for (const line of lines)
28
+ write(level, CONSOLE_LOG_CONTEXT, line);
29
+ };
30
+ return {
31
+ log: emit('info'),
32
+ info: emit('info'),
33
+ debug: emit('debug'),
34
+ trace: emit('trace'),
35
+ warn: emit('warn'),
36
+ error: emit('error'),
37
+ };
38
+ }
39
+ export function installWasiConsole(write = log) {
40
+ globalThis.console = createWasiConsole(write);
41
+ }
42
+ installWasiConsole();
@@ -17,10 +17,16 @@ export function wasmcloudUnenvPreset(fsPath = runtimeFile('fs'), processPath = r
17
17
  alias: {
18
18
  async_hooks: runtimeFile('async-hooks'),
19
19
  'node:async_hooks': runtimeFile('async-hooks'),
20
+ events: runtimeFile('events'),
21
+ 'node:events': runtimeFile('events'),
22
+ stream: runtimeFile('stream'),
23
+ 'node:stream': runtimeFile('stream'),
20
24
  timers: runtimeFile('timers'),
21
25
  'node:timers': runtimeFile('timers'),
22
26
  fs: fsPath,
23
27
  'node:fs': fsPath,
28
+ 'fs/promises': runtimeFile('fs-promises'),
29
+ 'node:fs/promises': runtimeFile('fs-promises'),
24
30
  process: processPath,
25
31
  'node:process': processPath,
26
32
  module: modulePath,
@@ -0,0 +1,20 @@
1
+ import { EventEmitter as UnenvEventEmitter } from 'unenv/node/events';
2
+ export * from 'unenv/node/events';
3
+ declare const kCapture: unique symbol;
4
+ declare const kShapeMode: unique symbol;
5
+ type EmitterState = {
6
+ _events?: object;
7
+ _eventsCount?: number;
8
+ _maxListeners?: number;
9
+ [kCapture]?: boolean;
10
+ [kShapeMode]?: boolean;
11
+ };
12
+ type EmitterOptions = {
13
+ captureRejections?: boolean;
14
+ } | undefined;
15
+ /** `EventEmitter.init.call(this)`, the older spelling of `EventEmitter.call(this)`. */
16
+ export declare function init(this: EmitterState, options?: EmitterOptions): void;
17
+ export declare const EventEmitter: typeof UnenvEventEmitter;
18
+ export declare const setMaxListeners: typeof UnenvEventEmitter.setMaxListeners;
19
+ export declare const listenerCount: typeof UnenvEventEmitter.listenerCount;
20
+ export default EventEmitter;