@exagone313/dsh-podman 1.6.1 → 1.8.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 (117) hide show
  1. package/cordis.patch.yml +3 -1
  2. package/dist/approval-reasons.d.ts +37 -0
  3. package/dist/approval-reasons.js +128 -0
  4. package/dist/approval-template-summary.d.ts +8 -0
  5. package/dist/approval-template-summary.js +163 -0
  6. package/dist/approval.d.ts +8 -4
  7. package/dist/approval.js +104 -10
  8. package/dist/client/ContainerCard.js +8 -2
  9. package/dist/client/container-card-controller.d.ts +13 -5
  10. package/dist/client/container-card-controller.js +60 -24
  11. package/dist/client/container-card-create-config.d.ts +23 -0
  12. package/dist/client/container-card-create-config.js +48 -0
  13. package/dist/client/container-card-create-modal.d.ts +9 -1
  14. package/dist/client/container-card-create-modal.js +37 -41
  15. package/dist/client/container-card-create-volume.d.ts +10 -0
  16. package/dist/client/container-card-create-volume.js +34 -0
  17. package/dist/client/container-card-dialog-styles.d.ts +4 -2
  18. package/dist/client/container-card-dialog-styles.js +47 -4
  19. package/dist/client/container-card-edit-modal.d.ts +5 -1
  20. package/dist/client/container-card-edit-modal.js +55 -19
  21. package/dist/client/container-card-editors.d.ts +9 -0
  22. package/dist/client/container-card-editors.js +300 -43
  23. package/dist/client/container-card-form.d.ts +2 -1
  24. package/dist/client/container-card-form.js +26 -8
  25. package/dist/client/container-card-images.js +9 -31
  26. package/dist/client/container-card-mount-actions.d.ts +12 -0
  27. package/dist/client/container-card-mount-actions.js +35 -0
  28. package/dist/client/container-card-mount-sources.d.ts +34 -0
  29. package/dist/client/container-card-mount-sources.js +180 -0
  30. package/dist/client/container-card-names.d.ts +2 -0
  31. package/dist/client/container-card-names.js +12 -0
  32. package/dist/client/container-card-row.d.ts +16 -1
  33. package/dist/client/container-card-row.js +69 -25
  34. package/dist/client/container-card-secrets.d.ts +2 -0
  35. package/dist/client/container-card-secrets.js +60 -17
  36. package/dist/client/container-card-shared.d.ts +17 -9
  37. package/dist/client/container-card-shared.js +122 -93
  38. package/dist/client/container-card-styles.d.ts +6 -0
  39. package/dist/client/container-card-styles.js +22 -0
  40. package/dist/client/container-card-table-styles.d.ts +2 -1
  41. package/dist/client/container-card-table-styles.js +14 -0
  42. package/dist/client/container-card-templates.d.ts +81 -0
  43. package/dist/client/container-card-templates.js +1004 -0
  44. package/dist/client/container-card-toast.js +1 -1
  45. package/dist/client/container-card-volumes.js +6 -20
  46. package/dist/client/container-card-workspace.d.ts +10 -2
  47. package/dist/client/container-card-workspace.js +98 -5
  48. package/dist/client/container-template-ui.d.ts +163 -0
  49. package/dist/client/container-template-ui.js +579 -0
  50. package/dist/client/download.d.ts +1 -0
  51. package/dist/client/download.js +23 -0
  52. package/dist/client/image-facts.d.ts +18 -0
  53. package/dist/client/image-facts.js +44 -0
  54. package/dist/client/index.js +13478 -3438
  55. package/dist/client/locales.d.ts +1 -1
  56. package/dist/client/locales.js +120 -0
  57. package/dist/client/podman-containers.js +47 -18
  58. package/dist/client/podman-terminal-guide.js +4 -2
  59. package/dist/client/podman-terminal.js +4 -2
  60. package/dist/client/template-client.d.ts +9 -0
  61. package/dist/client/template-client.js +52 -0
  62. package/dist/client/template-protocol.d.ts +60 -0
  63. package/dist/client/template-protocol.js +4 -0
  64. package/dist/client/terminal-errors.d.ts +11 -0
  65. package/dist/client/terminal-errors.js +26 -0
  66. package/dist/client/terminal-protocol.d.ts +5 -0
  67. package/dist/client/terminal-protocol.js +5 -0
  68. package/dist/client/terminal-styles.d.ts +2 -1
  69. package/dist/client/terminal-styles.js +9 -1
  70. package/dist/client/terminal-transport.d.ts +17 -2
  71. package/dist/client/terminal-transport.js +31 -8
  72. package/dist/client/tool-presentations.d.ts +32 -0
  73. package/dist/client/tool-presentations.js +33 -0
  74. package/dist/client/tool-views.js +17 -7
  75. package/dist/client/workspace-target.d.ts +54 -0
  76. package/dist/client/workspace-target.js +86 -0
  77. package/dist/container-template.d.ts +153 -0
  78. package/dist/container-template.js +1058 -0
  79. package/dist/generated/version.d.ts +2 -2
  80. package/dist/generated/version.js +2 -2
  81. package/dist/grpc/proto/dshguest/v1/guest.proto +11 -0
  82. package/dist/guest-rpc.d.ts +1 -0
  83. package/dist/guest-rpc.js +12 -0
  84. package/dist/index.js +7 -1
  85. package/dist/mount-enums.d.ts +2 -0
  86. package/dist/mount-enums.js +17 -0
  87. package/dist/mount-order.d.ts +14 -0
  88. package/dist/mount-order.js +49 -0
  89. package/dist/project-path.d.ts +14 -0
  90. package/dist/project-path.js +25 -0
  91. package/dist/template-apply.d.ts +21 -0
  92. package/dist/template-apply.js +102 -0
  93. package/dist/template-files.d.ts +23 -0
  94. package/dist/template-files.js +186 -0
  95. package/dist/template-image.d.ts +22 -0
  96. package/dist/template-image.js +80 -0
  97. package/dist/template-route.d.ts +9 -0
  98. package/dist/template-route.js +278 -0
  99. package/dist/terminal-route.js +49 -7
  100. package/dist/tool-defs.js +27 -1
  101. package/dist/tool-handlers.js +69 -1
  102. package/dist/tool-params.d.ts +38 -0
  103. package/dist/tool-params.js +30 -0
  104. package/docs/README.md +4 -3
  105. package/docs/architecture.md +42 -12
  106. package/docs/architecture.zh.md +22 -8
  107. package/docs/configuration.md +19 -20
  108. package/docs/configuration.zh.md +3 -4
  109. package/docs/development-prompt.md +49 -45
  110. package/docs/development-prompt.zh.md +47 -43
  111. package/docs/development.md +45 -28
  112. package/docs/development.zh.md +59 -46
  113. package/docs/uninstall.md +3 -3
  114. package/docs/uninstall.zh.md +2 -2
  115. package/docs/usage.md +155 -23
  116. package/docs/usage.zh.md +104 -14
  117. package/package.json +34 -33
@@ -0,0 +1,1058 @@
1
+ // SPDX-FileCopyrightText: 2026 Elouan Martinet <exa@elou.world>
2
+ //
3
+ // SPDX-License-Identifier: MIT
4
+ // The container-template format: a strict, versioned YAML document that
5
+ // describes one container's image, environment, secrets, mounts, PATH
6
+ // additions and published ports. This module is the single implementation of
7
+ // the format: the host parses and renders templates, the browser bundles the
8
+ // same code for the load popup and the export dialog, so an accepted template
9
+ // means the same thing everywhere.
10
+ //
11
+ // Everything here is pure and browser-safe: no node imports, and the one
12
+ // asynchronous helper (the image id) uses the Web Crypto API, which Node also
13
+ // exposes.
14
+ import { parseAllDocuments } from "yaml";
15
+ import { GIT_IDENTITY_KEYS } from "./container-env.js";
16
+ import { defaultMountMode, mountKindRank, normalizeMountKind, normalizeMountMode, } from "./mount-enums.js";
17
+ import { isPrimaryProjectMount } from "./mount-order.js";
18
+ import { portProtocolFromProto } from "./publish-port.js";
19
+ export const TEMPLATE_VERSION = 1;
20
+ export const TEMPLATE_KIND = "dsh-podman/container-template";
21
+ export const TEMPLATE_DIRECTORY = ".dsh-podman";
22
+ export const TEMPLATE_EXTENSION = ".yml";
23
+ // The only base images a template may name. They are the orchestrator's fixed
24
+ // base registry (see docs/usage.md); a template never names a custom image other
25
+ // than the one it builds itself.
26
+ export const BASE_IMAGES = ["archlinux", "ubuntu", "alpine"];
27
+ // The built-in packages each base image ships. A template package list is
28
+ // canonical: a package already in this list is dropped, so a template that only
29
+ // names built-ins refers to the base image and never triggers a build. Keep in
30
+ // sync with internal/orchestrator/images/images.go and docs/usage.md.
31
+ export const BASE_IMAGE_PACKAGES = {
32
+ archlinux: [
33
+ "base-devel",
34
+ "ca-certificates",
35
+ "curl",
36
+ "diffutils",
37
+ "fd",
38
+ "git",
39
+ "inetutils",
40
+ "jq",
41
+ "less",
42
+ "openbsd-netcat",
43
+ "openssh",
44
+ "patch",
45
+ "procps-ng",
46
+ "python",
47
+ "ripgrep",
48
+ "tree",
49
+ "unzip",
50
+ "wget",
51
+ "zstd",
52
+ ],
53
+ ubuntu: [
54
+ "build-essential",
55
+ "ca-certificates",
56
+ "curl",
57
+ "diffutils",
58
+ "fd-find",
59
+ "git",
60
+ "jq",
61
+ "less",
62
+ "netcat-openbsd",
63
+ "openssh-client",
64
+ "patch",
65
+ "procps",
66
+ "python3",
67
+ "ripgrep",
68
+ "tree",
69
+ "unzip",
70
+ "wget",
71
+ "zstd",
72
+ ],
73
+ alpine: [
74
+ "bash",
75
+ "build-base",
76
+ "ca-certificates",
77
+ "curl",
78
+ "diffutils",
79
+ "fd",
80
+ "git",
81
+ "jq",
82
+ "less",
83
+ "openssh-client",
84
+ "patch",
85
+ "procps",
86
+ "python3",
87
+ "ripgrep",
88
+ "tree",
89
+ "unzip",
90
+ "wget",
91
+ "zstd",
92
+ ],
93
+ };
94
+ export function isBaseImage(value) {
95
+ return typeof value === "string" &&
96
+ BASE_IMAGES.includes(value);
97
+ }
98
+ // A template failure: the YAML could not be parsed, or the document broke one of
99
+ // the format's rules. The message names the offending field so the user can fix
100
+ // it in place.
101
+ export class TemplateError extends Error {
102
+ path;
103
+ constructor(message, path = "") {
104
+ super(path === "" ? message : `${path}: ${message}`);
105
+ this.name = "TemplateError";
106
+ this.path = path;
107
+ }
108
+ }
109
+ const PACKAGE_PATTERN = /^[A-Za-z0-9@+._:][A-Za-z0-9@+._:-]*$/;
110
+ const SECRET_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
111
+ const IMAGE_ID_PATTERN = /^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,63}$/;
112
+ const SPEC_KEYS = new Set([
113
+ "image",
114
+ "imageTemplate",
115
+ "env",
116
+ "secretEnv",
117
+ "mounts",
118
+ "paths",
119
+ "ports",
120
+ ]);
121
+ const IMAGE_KEYS = new Set(["base", "packages"]);
122
+ const MOUNT_KEYS = {
123
+ project: new Set(["kind", "project", "mode"]),
124
+ volume: new Set(["kind", "volume", "destination", "mode"]),
125
+ secret: new Set(["kind", "secret", "destination"]),
126
+ tmpfs: new Set(["kind", "destination"]),
127
+ };
128
+ const PORT_KEYS = new Set(["container", "host", "protocol"]);
129
+ // canonicalPackages normalizes an imageTemplate package list: invalid names are
130
+ // refused, duplicates collapse, the base's built-in packages are dropped, and
131
+ // the result is sorted so two spellings of the same package set compare equal.
132
+ export function canonicalPackages(base, packages) {
133
+ const builtins = new Set(BASE_IMAGE_PACKAGES[base]);
134
+ const result = new Set();
135
+ for (const value of packages) {
136
+ if (typeof value !== "string" || !validPackageName(value)) {
137
+ throw new TemplateError(`invalid package name ${JSON.stringify(value)}`, "spec.imageTemplate.packages");
138
+ }
139
+ if (!builtins.has(value))
140
+ result.add(value);
141
+ }
142
+ return [...result].sort();
143
+ }
144
+ function validPackageName(value) {
145
+ return value !== "." && value !== ".." && PACKAGE_PATTERN.test(value);
146
+ }
147
+ // cleanAbsolutePath normalizes an absolute POSIX path lexically, or returns
148
+ // undefined when the value is not an absolute, already-clean path. Templates
149
+ // never name "/" itself or a path carrying "..", "." or a trailing slash.
150
+ export function cleanAbsolutePath(value) {
151
+ if (typeof value !== "string" || !value.startsWith("/"))
152
+ return undefined;
153
+ if (/[\0\n\r]/.test(value))
154
+ return undefined;
155
+ const segments = [];
156
+ for (const segment of value.split("/")) {
157
+ if (segment === "" || segment === ".")
158
+ continue;
159
+ if (segment === "..")
160
+ return undefined;
161
+ segments.push(segment);
162
+ }
163
+ if (segments.length === 0)
164
+ return undefined;
165
+ const cleaned = `/${segments.join("/")}`;
166
+ return cleaned === value ? cleaned : undefined;
167
+ }
168
+ // normalizeProjectPath normalizes a project path (a path under the projects
169
+ // root): relative, no empty or "." segments, and no ".." that climbs above the
170
+ // root. Returns undefined when the value names no directory inside the root.
171
+ export function normalizeProjectPath(value) {
172
+ if (typeof value !== "string")
173
+ return undefined;
174
+ if (/[\0\n\r]/.test(value) || value.startsWith("/"))
175
+ return undefined;
176
+ const segments = [];
177
+ for (const segment of value.split("/")) {
178
+ if (segment === "" || segment === ".")
179
+ continue;
180
+ if (segment === "..") {
181
+ if (segments.length === 0)
182
+ return undefined;
183
+ segments.pop();
184
+ continue;
185
+ }
186
+ segments.push(segment);
187
+ }
188
+ return segments.length === 0 ? undefined : segments.join("/");
189
+ }
190
+ function isMapping(value) {
191
+ return typeof value === "object" && value !== null && !Array.isArray(value);
192
+ }
193
+ function ownEntries(value) {
194
+ return Object.entries(value).filter(([key]) => key !== "__proto__");
195
+ }
196
+ function rejectUnknown(value, allowed, path) {
197
+ for (const [key] of ownEntries(value)) {
198
+ if (!allowed.has(key)) {
199
+ throw new TemplateError(`unknown key ${JSON.stringify(key)}`, path === "" ? key : `${path}.${key}`);
200
+ }
201
+ }
202
+ }
203
+ function stringValue(value, path) {
204
+ if (typeof value !== "string") {
205
+ throw new TemplateError("expected a string", path);
206
+ }
207
+ return value;
208
+ }
209
+ function nonEmptyString(value, path) {
210
+ const text = stringValue(value, path);
211
+ if (text === "")
212
+ throw new TemplateError("expected a non-empty string", path);
213
+ return text;
214
+ }
215
+ function envKey(value, path) {
216
+ if (value === "")
217
+ throw new TemplateError("env key is empty", path);
218
+ if (value.includes("=")) {
219
+ throw new TemplateError(`env key ${JSON.stringify(value)} contains "="`);
220
+ }
221
+ if (value.includes("\0")) {
222
+ throw new TemplateError(`env key ${JSON.stringify(value)} contains a NUL byte`, path);
223
+ }
224
+ if (value.startsWith("DSH_PODMAN")) {
225
+ throw new TemplateError(`env key ${JSON.stringify(value)} is reserved (DSH_PODMAN prefix)`, path);
226
+ }
227
+ return value;
228
+ }
229
+ function secretName(value, path) {
230
+ const name = nonEmptyString(value, path);
231
+ if (!SECRET_PATTERN.test(name)) {
232
+ throw new TemplateError(`invalid secret name ${JSON.stringify(name)}`, path);
233
+ }
234
+ return name;
235
+ }
236
+ function stringMap(value, path, keyCheck, valueCheck) {
237
+ if (value === undefined)
238
+ return {};
239
+ if (!isMapping(value)) {
240
+ throw new TemplateError("expected a mapping", path);
241
+ }
242
+ const result = Object.create(null);
243
+ for (const [key, item] of ownEntries(value)) {
244
+ const checkedKey = keyCheck(key, `${path}.${key}`);
245
+ result[checkedKey] = valueCheck(item, `${path}.${key}`);
246
+ }
247
+ return result;
248
+ }
249
+ function parseMount(value, path) {
250
+ if (!isMapping(value)) {
251
+ throw new TemplateError("expected a mount mapping", path);
252
+ }
253
+ const kind = nonEmptyString(value.kind, `${path}.kind`);
254
+ const allowed = MOUNT_KEYS[kind];
255
+ if (allowed === undefined) {
256
+ throw new TemplateError(`unknown mount kind ${JSON.stringify(kind)}`, `${path}.kind`);
257
+ }
258
+ // A key that belongs to another kind is named as such instead of reading as
259
+ // a generic unknown key, so the user knows which mount shape was expected.
260
+ const forbidden = kind === "project"
261
+ ? ["destination", "volume", "secret"]
262
+ : kind === "tmpfs"
263
+ ? ["project", "volume", "secret", "size", "mode"]
264
+ : kind === "secret"
265
+ ? ["mode"]
266
+ : [];
267
+ for (const key of forbidden) {
268
+ if (key in value) {
269
+ throw new TemplateError(`a ${kind} mount does not take ${JSON.stringify(key)}`, `${path}.${key}`);
270
+ }
271
+ }
272
+ rejectUnknown(value, allowed, path);
273
+ if (kind === "project") {
274
+ const project = normalizeProjectPath(value.project);
275
+ if (project === undefined) {
276
+ throw new TemplateError("expected a project path under the projects root", `${path}.project`);
277
+ }
278
+ return {
279
+ kind,
280
+ project,
281
+ mode: parseMountMode(value.mode, `${path}.mode`, kind),
282
+ };
283
+ }
284
+ if (kind === "tmpfs") {
285
+ const destination = cleanAbsolutePath(value.destination);
286
+ if (destination === undefined) {
287
+ throw new TemplateError("expected an absolute, clean destination", `${path}.destination`);
288
+ }
289
+ return { kind, destination };
290
+ }
291
+ const destination = cleanAbsolutePath(value.destination);
292
+ if (destination === undefined) {
293
+ throw new TemplateError("expected an absolute, clean destination", `${path}.destination`);
294
+ }
295
+ if (kind === "secret") {
296
+ return {
297
+ kind,
298
+ secret: secretName(value.secret, `${path}.secret`),
299
+ destination,
300
+ };
301
+ }
302
+ const volume = nonEmptyString(value.volume, `${path}.volume`);
303
+ if (!SECRET_PATTERN.test(volume)) {
304
+ throw new TemplateError(`invalid volume name ${JSON.stringify(volume)}`, `${path}.volume`);
305
+ }
306
+ return {
307
+ kind: "volume",
308
+ volume,
309
+ destination,
310
+ mode: parseMountMode(value.mode, `${path}.mode`, "volume"),
311
+ };
312
+ }
313
+ // parseMountMode reads the mode of a project or volume mount. It accepts only
314
+ // the two logical spellings and defaults, like the editor's new-mount draft, to
315
+ // read-only when the document omits it.
316
+ function parseMountMode(value, path, kind) {
317
+ if (value === undefined)
318
+ return defaultMountMode(kind);
319
+ if (value !== "read_only" && value !== "read_write") {
320
+ throw new TemplateError(`invalid mount mode ${JSON.stringify(value)}`, path);
321
+ }
322
+ return value;
323
+ }
324
+ function parsePort(value, path) {
325
+ if (!isMapping(value)) {
326
+ throw new TemplateError("expected a port mapping", path);
327
+ }
328
+ rejectUnknown(value, PORT_KEYS, path);
329
+ const container = value.container;
330
+ if (typeof container !== "number" || !Number.isInteger(container) ||
331
+ container < 1 || container > 65535) {
332
+ throw new TemplateError("container port must be an integer between 1 and 65535", `${path}.container`);
333
+ }
334
+ if (value.protocol === undefined) {
335
+ throw new TemplateError("protocol is required (only tcp is implemented)", `${path}.protocol`);
336
+ }
337
+ if (value.protocol !== "tcp") {
338
+ throw new TemplateError(`unsupported protocol ${JSON.stringify(value.protocol)}: only tcp is implemented`, `${path}.protocol`);
339
+ }
340
+ let host;
341
+ if (value.host !== undefined) {
342
+ host = value.host;
343
+ if (typeof host !== "number" || !Number.isInteger(host) ||
344
+ host < 1024 || host > 65535) {
345
+ throw new TemplateError("host port must be an integer between 1024 and 65535", `${path}.host`);
346
+ }
347
+ }
348
+ return {
349
+ container,
350
+ ...(host === undefined ? {} : { host }),
351
+ protocol: "tcp",
352
+ };
353
+ }
354
+ // parseContainerTemplate parses and validates a template document, returning the
355
+ // canonical form: a template whose package list only names base built-ins is
356
+ // normalized to `image: <base>` so loading it never builds anything.
357
+ export function parseContainerTemplate(text) {
358
+ let docs;
359
+ try {
360
+ docs = parseAllDocuments(text, { uniqueKeys: true });
361
+ }
362
+ catch (error) {
363
+ throw new TemplateError(`invalid YAML: ${error instanceof Error ? error.message : String(error)}`);
364
+ }
365
+ const failures = docs.flatMap((doc) => doc.errors);
366
+ if (failures.length > 0) {
367
+ const first = failures[0];
368
+ throw new TemplateError(`invalid YAML: ${first.message}`);
369
+ }
370
+ if (docs.length === 0) {
371
+ throw new TemplateError("the document is empty");
372
+ }
373
+ if (docs.length > 1) {
374
+ throw new TemplateError("only one YAML document is allowed");
375
+ }
376
+ let raw;
377
+ try {
378
+ raw = docs[0].toJS({ maxAliasCount: 100 });
379
+ }
380
+ catch (error) {
381
+ throw new TemplateError(`invalid YAML: ${error instanceof Error ? error.message : String(error)}`);
382
+ }
383
+ return validateTemplate(raw);
384
+ }
385
+ // The Git identity variables the default environment injects. A template must
386
+ // never carry them: exporting one would freeze the machine's identity, and a
387
+ // hand-edited file could pin it, so both directions drop them silently.
388
+ const GIT_IDENTITY_KEY_SET = new Set(GIT_IDENTITY_KEYS);
389
+ function withoutGitIdentity(value) {
390
+ // Keep the map's existing shape (and its null prototype for a parsed map)
391
+ // when there is nothing to drop, so a template without identity variables is
392
+ // returned exactly as it was read.
393
+ let found = false;
394
+ for (const key of Object.keys(value)) {
395
+ if (GIT_IDENTITY_KEY_SET.has(key)) {
396
+ found = true;
397
+ break;
398
+ }
399
+ }
400
+ if (!found)
401
+ return value;
402
+ const result = Object.create(null);
403
+ for (const [key, item] of Object.entries(value)) {
404
+ if (GIT_IDENTITY_KEY_SET.has(key))
405
+ continue;
406
+ result[key] = item;
407
+ }
408
+ return result;
409
+ }
410
+ // validateTemplate checks an already-parsed value against the format, so the
411
+ // same rules apply to a YAML document and to a structured request.
412
+ export function validateTemplate(raw) {
413
+ if (!isMapping(raw)) {
414
+ throw new TemplateError("the document must be a mapping");
415
+ }
416
+ rejectUnknown(raw, new Set(["version", "kind", "spec"]), "");
417
+ if (raw.version !== TEMPLATE_VERSION) {
418
+ throw new TemplateError(`unsupported version ${JSON.stringify(raw.version)} (expected ${TEMPLATE_VERSION})`, "version");
419
+ }
420
+ if (raw.kind !== TEMPLATE_KIND) {
421
+ throw new TemplateError(`unsupported kind ${JSON.stringify(raw.kind)} (expected ${JSON.stringify(TEMPLATE_KIND)})`, "kind");
422
+ }
423
+ if (!isMapping(raw.spec)) {
424
+ throw new TemplateError("expected a mapping", "spec");
425
+ }
426
+ const spec = raw.spec;
427
+ rejectUnknown(spec, SPEC_KEYS, "spec");
428
+ const hasImage = spec.image !== undefined && spec.image !== null;
429
+ const hasTemplate = spec.imageTemplate !== undefined &&
430
+ spec.imageTemplate !== null;
431
+ if (hasImage && hasTemplate) {
432
+ throw new TemplateError("exactly one of image and imageTemplate is allowed, not both", "spec");
433
+ }
434
+ if (!hasImage && !hasTemplate) {
435
+ throw new TemplateError("exactly one of image and imageTemplate is required", "spec");
436
+ }
437
+ let image;
438
+ let imageTemplate;
439
+ if (hasImage) {
440
+ if (!isBaseImage(spec.image)) {
441
+ throw new TemplateError(`unsupported base image ${JSON.stringify(spec.image)} (expected one of ${BASE_IMAGES.join(", ")})`, "spec.image");
442
+ }
443
+ image = spec.image;
444
+ }
445
+ else {
446
+ const value = spec.imageTemplate;
447
+ if (!isMapping(value)) {
448
+ throw new TemplateError("expected a mapping", "spec.imageTemplate");
449
+ }
450
+ rejectUnknown(value, IMAGE_KEYS, "spec.imageTemplate");
451
+ if (!isBaseImage(value.base)) {
452
+ throw new TemplateError(`unsupported base image ${JSON.stringify(value.base)} (expected one of ${BASE_IMAGES.join(", ")})`, "spec.imageTemplate.base");
453
+ }
454
+ if (!Array.isArray(value.packages)) {
455
+ throw new TemplateError("expected a list of package names", "spec.imageTemplate.packages");
456
+ }
457
+ const packages = canonicalPackages(value.base, value.packages);
458
+ if (packages.length === 0) {
459
+ // A list that only repeats the base's built-ins refers to the base image.
460
+ image = value.base;
461
+ }
462
+ else {
463
+ imageTemplate = { base: value.base, packages };
464
+ }
465
+ }
466
+ const env = withoutGitIdentity(stringMap(spec.env, "spec.env", (key, at) => envKey(key, at), (value, at) => {
467
+ const text = stringValue(value, at);
468
+ if (text.includes("\0")) {
469
+ throw new TemplateError(`env value for key contains a NUL byte`, at);
470
+ }
471
+ return text;
472
+ }));
473
+ const secretEnv = withoutGitIdentity(stringMap(spec.secretEnv, "spec.secretEnv", (key, at) => envKey(key, at), (value, at) => secretName(value, at)));
474
+ for (const key of Object.keys(secretEnv)) {
475
+ if (key in env) {
476
+ throw new TemplateError(`variable ${JSON.stringify(key)} is used as both an env and a secret env variable`, "spec");
477
+ }
478
+ }
479
+ const mounts = parseList(spec.mounts, "spec.mounts", parseMount);
480
+ const paths = parseList(spec.paths, "spec.paths", parsePath);
481
+ const ports = parseList(spec.ports, "spec.ports", parsePort);
482
+ return {
483
+ version: TEMPLATE_VERSION,
484
+ kind: TEMPLATE_KIND,
485
+ spec: {
486
+ ...(image === undefined ? {} : { image }),
487
+ ...(imageTemplate === undefined ? {} : { imageTemplate }),
488
+ env,
489
+ secretEnv,
490
+ mounts,
491
+ paths,
492
+ ports,
493
+ },
494
+ };
495
+ }
496
+ function parseList(value, path, parseItem) {
497
+ if (value === undefined)
498
+ return [];
499
+ if (!Array.isArray(value)) {
500
+ throw new TemplateError("expected a list", path);
501
+ }
502
+ return value.map((item, index) => parseItem(item, `${path}[${index}]`));
503
+ }
504
+ function parsePath(value, path) {
505
+ const text = stringValue(value, path);
506
+ if (text.includes(":") || /[\0\n\r]/.test(text)) {
507
+ throw new TemplateError("a path must not contain ':', NUL, or a newline", path);
508
+ }
509
+ const cleaned = cleanAbsolutePath(text);
510
+ if (cleaned === undefined) {
511
+ throw new TemplateError("expected an absolute, clean directory", path);
512
+ }
513
+ return cleaned;
514
+ }
515
+ // effectiveImage returns the image a template refers to after the canonical
516
+ // rules: base-only templates name the base, everything else a base plus the
517
+ // extra packages.
518
+ export function effectiveImage(template) {
519
+ const { image, imageTemplate } = template.spec;
520
+ if (imageTemplate !== undefined) {
521
+ return {
522
+ kind: "template",
523
+ base: imageTemplate.base,
524
+ packages: canonicalPackages(imageTemplate.base, imageTemplate.packages),
525
+ };
526
+ }
527
+ if (image === undefined) {
528
+ throw new TemplateError("a template must name an image");
529
+ }
530
+ return { kind: "base", base: image };
531
+ }
532
+ // templateExportImage resolves the base and extra packages an existing image
533
+ // would export as. A custom image is walked up to its root base and its package
534
+ // lists are unioned, then the base's built-ins are dropped. A broken parent
535
+ // chain is an error rather than a silently truncated export.
536
+ export function templateExportImage(imageId, images) {
537
+ if (isBaseImage(imageId))
538
+ return { kind: "base", base: imageId };
539
+ const byId = new Map(images.map((image) => [image.imageId, image]));
540
+ const seen = new Set();
541
+ let current = imageId;
542
+ let base;
543
+ const packages = [];
544
+ for (;;) {
545
+ if (seen.has(current)) {
546
+ throw new TemplateError(`image ${JSON.stringify(imageId)} has a cyclic parent chain`);
547
+ }
548
+ seen.add(current);
549
+ if (isBaseImage(current)) {
550
+ base = current;
551
+ break;
552
+ }
553
+ const row = byId.get(current);
554
+ if (row === undefined) {
555
+ throw new TemplateError(current === imageId
556
+ ? `image ${JSON.stringify(imageId)} is not listed`
557
+ : `image ${JSON.stringify(current)} is not listed`);
558
+ }
559
+ packages.push(...row.packages);
560
+ if (row.parent === "" || row.parent === undefined) {
561
+ throw new TemplateError(`image ${JSON.stringify(current)} has no parent, so it has no base image`);
562
+ }
563
+ current = row.parent;
564
+ }
565
+ const canonical = canonicalPackages(base, packages);
566
+ return canonical.length === 0
567
+ ? { kind: "base", base }
568
+ : { kind: "template", base, packages: canonical };
569
+ }
570
+ // templateImagePlan compares a template's effective image with the images the
571
+ // orchestrator reports. The template image id is deterministic (see
572
+ // templateImageId), so a listed image with that id is this template's own and
573
+ // can be reused exactly when its parent and package list match. A custom record
574
+ // the orchestrator reports as "missing" is stale — podman no longer stores the
575
+ // image — so it is planned exactly like an absent image.
576
+ export function templateImagePlan(effective, imageId, images) {
577
+ if (effective.kind === "base") {
578
+ // A base-only template runs the base image itself, so the plan states
579
+ // whether that base is actually provisioned: a record podman reports as
580
+ // missing, or no record at all, is a build exactly like a custom image.
581
+ const base = images.find((image) => image.imageId === effective.base);
582
+ if (base === undefined ||
583
+ (base.status !== "built" && base.status !== "pulled")) {
584
+ return {
585
+ effective,
586
+ imageId: effective.base,
587
+ builtAt: "",
588
+ present: false,
589
+ rebuild: false,
590
+ needsBuild: true,
591
+ reason: "missing",
592
+ };
593
+ }
594
+ return {
595
+ effective,
596
+ imageId: effective.base,
597
+ builtAt: base.builtAt ?? "",
598
+ present: true,
599
+ rebuild: false,
600
+ needsBuild: false,
601
+ reason: "ready",
602
+ };
603
+ }
604
+ const listed = images.find((image) => image.imageId === imageId);
605
+ // A record can outlive the image podman stores: the orchestrator keeps the
606
+ // custom entry and marks it "missing". Any such hit is a build, not a reuse.
607
+ if (listed === undefined || listed.status === "missing") {
608
+ return {
609
+ effective,
610
+ imageId,
611
+ builtAt: "",
612
+ present: false,
613
+ rebuild: false,
614
+ needsBuild: true,
615
+ reason: "missing",
616
+ };
617
+ }
618
+ const builtAt = listed.builtAt ?? "";
619
+ const parentMatches = listed.parent === effective.base;
620
+ const listedPackages = [...listed.packages].sort();
621
+ if (!parentMatches) {
622
+ return {
623
+ effective,
624
+ imageId,
625
+ builtAt,
626
+ present: true,
627
+ rebuild: true,
628
+ needsBuild: true,
629
+ reason: "parent",
630
+ };
631
+ }
632
+ if (listedPackages.length !== effective.packages.length ||
633
+ listedPackages.some((pkg, index) => pkg !== effective.packages[index])) {
634
+ return {
635
+ effective,
636
+ imageId,
637
+ builtAt,
638
+ present: true,
639
+ rebuild: true,
640
+ needsBuild: true,
641
+ reason: "packages",
642
+ };
643
+ }
644
+ return {
645
+ effective,
646
+ imageId,
647
+ builtAt,
648
+ present: true,
649
+ rebuild: false,
650
+ needsBuild: false,
651
+ reason: "ready",
652
+ };
653
+ }
654
+ // sanitizedTemplateName turns a template file's basename into the readable part
655
+ // of its image id: letters, digits, "_", "." and "-" only, starting with an
656
+ // alphanumeric character or "_", short enough to leave room for the prefix and
657
+ // digest.
658
+ export function sanitizedTemplateName(name) {
659
+ const base = name.replace(/\.(ya?ml)$/i, "");
660
+ let sanitized = base
661
+ .replace(/[^A-Za-z0-9_.-]+/g, "-")
662
+ .replace(/^[^A-Za-z0-9_]+/, "")
663
+ .replace(/[.-]+$/g, "");
664
+ if (sanitized === "")
665
+ sanitized = "template";
666
+ sanitized = sanitized.slice(0, 40);
667
+ return sanitized;
668
+ }
669
+ // templateImageId derives the short image id of a template: the sanitized file
670
+ // basename plus the first 8 hex characters of sha256(absolute template path).
671
+ // The path, not the name, makes two same-named templates in different projects
672
+ // distinct, so one project's build never overwrites another's.
673
+ export async function templateImageId(name, absolutePath) {
674
+ return templateImageIdFromDigest(name, await sha256Hex(absolutePath));
675
+ }
676
+ export function templateImageIdFromDigest(name, digestHex) {
677
+ const id = `template-${sanitizedTemplateName(name)}-${digestHex.slice(0, 8).toLowerCase()}`;
678
+ if (!IMAGE_ID_PATTERN.test(id)) {
679
+ throw new TemplateError(`cannot derive an image id from ${JSON.stringify(name)}`);
680
+ }
681
+ return id;
682
+ }
683
+ // sha256Hex hashes a string with the Web Crypto API, which both Node and the
684
+ // browser expose.
685
+ export async function sha256Hex(value) {
686
+ const bytes = new TextEncoder().encode(value);
687
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
688
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
689
+ }
690
+ // templateRequirements reports what a template expects of its workspace: the
691
+ // project mount directories that do not exist, the mounted volumes that are
692
+ // absent, and the named secrets that are absent. A missing secret or volume is
693
+ // reported once per name, even when several variables or mounts use it.
694
+ export function templateRequirements(template, options = {}) {
695
+ const warnings = [];
696
+ if (options.projectExists !== undefined) {
697
+ for (const mount of template.spec.mounts) {
698
+ if (mount.kind !== "project")
699
+ continue;
700
+ if (options.projectExists(mount.project))
701
+ continue;
702
+ warnings.push({
703
+ kind: "project_missing",
704
+ project: mount.project,
705
+ path: mount.project,
706
+ });
707
+ }
708
+ }
709
+ if (options.secrets !== undefined) {
710
+ const known = new Set(options.secrets);
711
+ const reported = new Set();
712
+ for (const [env, secret] of Object.entries(template.spec.secretEnv)) {
713
+ if (known.has(secret))
714
+ continue;
715
+ warnings.push({ kind: "secret_env_missing", env, secret });
716
+ reported.add(secret);
717
+ }
718
+ for (const mount of template.spec.mounts) {
719
+ if (mount.kind !== "secret" || known.has(mount.secret))
720
+ continue;
721
+ if (reported.has(mount.secret))
722
+ continue;
723
+ warnings.push({ kind: "secret_missing", secret: mount.secret });
724
+ reported.add(mount.secret);
725
+ }
726
+ }
727
+ if (options.volumes !== undefined) {
728
+ const known = new Set(options.volumes);
729
+ const reported = new Set();
730
+ for (const mount of template.spec.mounts) {
731
+ if (mount.kind !== "volume" || known.has(mount.volume))
732
+ continue;
733
+ if (reported.has(mount.volume))
734
+ continue;
735
+ warnings.push({ kind: "volume_missing", volume: mount.volume });
736
+ reported.add(mount.volume);
737
+ }
738
+ }
739
+ return warnings;
740
+ }
741
+ // exportMountDestination reads the destination a volume, secret or tmpfs mount
742
+ // must carry. Project mounts never reach it: their path is derived from the
743
+ // projects root, so demanding a destination on every mount would reject every
744
+ // container that has one.
745
+ function exportMountDestination(containerName, value) {
746
+ const destination = cleanAbsolutePath(value);
747
+ if (destination === undefined) {
748
+ throw new TemplateError(`container ${JSON.stringify(containerName)} has a mount without a valid destination`);
749
+ }
750
+ return destination;
751
+ }
752
+ // exportContainerTemplate builds a template from a container and the image list
753
+ // it runs from. The image is exported as the root base plus the recursive union
754
+ // of packages minus the base's built-ins, so a custom image that only has base
755
+ // packages exports as `image: <base>`. `mainProject` is the workspace's own
756
+ // project name: the mount naming it is listed first, as the container editor
757
+ // lists it, whatever order the container's mounts arrived in.
758
+ export function exportContainerTemplate(container, images, mainProject = "") {
759
+ const effective = templateExportImage(container.imageId, images);
760
+ const mounts = [];
761
+ for (const mount of container.mounts ?? []) {
762
+ // A container row carries the control plane's proto spelling while a card
763
+ // snapshot carries the short one; normalise either before applying the
764
+ // per-kind rules, as the editor does.
765
+ const kind = normalizeMountKind(mount.kind);
766
+ if (kind === "project") {
767
+ // A project mount carries no destination of its own: the project path is
768
+ // mirrored under the projects root, so a destination a view derived is
769
+ // never exported.
770
+ const project = normalizeProjectPath(mount.projectName);
771
+ if (project === undefined) {
772
+ throw new TemplateError(`container ${JSON.stringify(container.containerName)} has an invalid project mount`);
773
+ }
774
+ mounts.push({
775
+ kind: "project",
776
+ project,
777
+ mode: exportMountMode(mount.mode),
778
+ });
779
+ continue;
780
+ }
781
+ if (kind === "volume") {
782
+ const destination = exportMountDestination(container.containerName, mount.destination);
783
+ if (mount.volume === undefined || mount.volume === "") {
784
+ throw new TemplateError(`container ${JSON.stringify(container.containerName)} has a volume mount without a volume`);
785
+ }
786
+ mounts.push({
787
+ kind: "volume",
788
+ volume: mount.volume,
789
+ destination,
790
+ mode: exportMountMode(mount.mode),
791
+ });
792
+ continue;
793
+ }
794
+ if (kind === "secret") {
795
+ const destination = exportMountDestination(container.containerName, mount.destination);
796
+ if (mount.secret === undefined || mount.secret === "") {
797
+ throw new TemplateError(`container ${JSON.stringify(container.containerName)} has a secret mount without a secret`);
798
+ }
799
+ mounts.push({ kind: "secret", secret: mount.secret, destination });
800
+ continue;
801
+ }
802
+ if (kind === "tmpfs") {
803
+ mounts.push({
804
+ kind: "tmpfs",
805
+ destination: exportMountDestination(container.containerName, mount.destination),
806
+ });
807
+ continue;
808
+ }
809
+ throw new TemplateError(`container ${JSON.stringify(container.containerName)} has an unsupported mount kind ${JSON.stringify(kind)}`);
810
+ }
811
+ const ports = [];
812
+ for (const port of container.publishedPorts ?? []) {
813
+ // A container view may carry the proto enum spelling or the card's logical
814
+ // one; both mean TCP here, and anything else is refused rather than
815
+ // mislabelled.
816
+ const protocol = portProtocolFromProto(port.protocol) ??
817
+ port.protocol ?? "tcp";
818
+ if (protocol !== "tcp") {
819
+ throw new TemplateError(`container ${JSON.stringify(container.containerName)} publishes an unsupported protocol ${JSON.stringify(port.protocol)}`);
820
+ }
821
+ const host = Number(port.hostPort ?? 0);
822
+ ports.push({
823
+ container: Number(port.port),
824
+ ...(host >= 1024 && host <= 65535 ? { host } : {}),
825
+ protocol: "tcp",
826
+ });
827
+ }
828
+ const template = {
829
+ version: TEMPLATE_VERSION,
830
+ kind: TEMPLATE_KIND,
831
+ spec: {
832
+ ...(effective.kind === "base" ? { image: effective.base } : {
833
+ imageTemplate: {
834
+ base: effective.base,
835
+ packages: [...effective.packages],
836
+ },
837
+ }),
838
+ env: orderedStringMap(withoutGitIdentity(container.env ?? {})),
839
+ secretEnv: orderedStringMap(withoutGitIdentity(container.secretEnv ?? {})),
840
+ mounts: orderedTemplateMounts(mounts, mainProject),
841
+ paths: [...(container.paths ?? [])],
842
+ ports,
843
+ },
844
+ };
845
+ const name = sanitizedTemplateName(container.containerName);
846
+ return {
847
+ filename: `${name}${TEMPLATE_EXTENSION}`,
848
+ yaml: renderContainerTemplate(template, mainProject),
849
+ template,
850
+ };
851
+ }
852
+ function orderedStringMap(value) {
853
+ const result = Object.create(null);
854
+ for (const key of Object.keys(value).sort())
855
+ result[key] = value[key];
856
+ return result;
857
+ }
858
+ // renderContainerTemplate writes the canonical YAML form. Key order is fixed so
859
+ // exporting a container twice produces the same document, and the document is
860
+ // block style throughout: one key per line, every sequence as `- ` items, and
861
+ // two spaces per nesting level. Empty groups are omitted rather than written as
862
+ // `{}` or `[]`; the parser fills them back in with their defaults. Only the
863
+ // renderer is opinionated: parsing accepts flow style just as happily. When
864
+ // `mainProject` is given, the mount naming it renders first, matching the
865
+ // container editor.
866
+ export function renderContainerTemplate(template, mainProject = "") {
867
+ const { spec } = template;
868
+ const lines = [
869
+ `version: ${TEMPLATE_VERSION}`,
870
+ `kind: ${TEMPLATE_KIND}`,
871
+ "spec:",
872
+ ];
873
+ if (spec.image !== undefined) {
874
+ lines.push(` image: ${yamlScalar(spec.image)}`);
875
+ }
876
+ else if (spec.imageTemplate !== undefined) {
877
+ lines.push(" imageTemplate:");
878
+ lines.push(` base: ${yamlScalar(spec.imageTemplate.base)}`);
879
+ lines.push(" packages:");
880
+ lines.push(...blockList(spec.imageTemplate.packages, 6));
881
+ }
882
+ // Environment variable order carries no meaning, so it is sorted to keep the
883
+ // rendering canonical whatever order the parsed document used.
884
+ const env = Object.keys(spec.env).sort();
885
+ if (env.length > 0) {
886
+ lines.push(" env:");
887
+ lines.push(...blockMap(env, spec.env, 4));
888
+ }
889
+ const secretEnv = Object.keys(spec.secretEnv).sort();
890
+ if (secretEnv.length > 0) {
891
+ lines.push(" secretEnv:");
892
+ lines.push(...blockMap(secretEnv, spec.secretEnv, 4));
893
+ }
894
+ const mounts = orderedTemplateMounts(spec.mounts, mainProject);
895
+ if (mounts.length > 0) {
896
+ lines.push(" mounts:");
897
+ lines.push(...blockListMap(mounts.map(mountFields), 4));
898
+ }
899
+ if (spec.paths.length > 0) {
900
+ lines.push(" paths:");
901
+ lines.push(...blockList(spec.paths, 4));
902
+ }
903
+ if (spec.ports.length > 0) {
904
+ lines.push(" ports:");
905
+ lines.push(...blockListMap(spec.ports.map(portFields), 4));
906
+ }
907
+ return `${lines.join("\n")}\n`;
908
+ }
909
+ // orderedTemplateMounts groups mounts the way the container editor lists them:
910
+ // the workspace's primary project mount first, then project mounts, volumes,
911
+ // secrets and tmpfs. The sort is stable, so mounts of one kind keep the order
912
+ // they already had.
913
+ function orderedTemplateMounts(mounts, mainProject) {
914
+ const rank = (mount) => isPrimaryProjectMount(mount, mainProject)
915
+ ? 0
916
+ : 1 + mountKindRank(mount.kind);
917
+ return mounts
918
+ .map((mount, index) => ({ mount, index }))
919
+ .sort((left, right) => rank(left.mount) - rank(right.mount) || left.index - right.index)
920
+ .map(({ mount }) => mount);
921
+ }
922
+ function blockMap(keys, fields, indent) {
923
+ return keys.map((key) => `${indentOf(indent)}${yamlScalar(key)}: ${yamlScalar(fields[key])}`);
924
+ }
925
+ function blockList(values, indent) {
926
+ return values.map((value) => `${indentOf(indent)}- ${yamlScalar(value)}`);
927
+ }
928
+ // blockListMap writes a sequence of mappings, one field per line: the first
929
+ // field shares the `- ` marker and the rest line up under it.
930
+ function blockListMap(items, indent) {
931
+ const lines = [];
932
+ for (const fields of items) {
933
+ let first = true;
934
+ for (const [key, value] of Object.entries(fields)) {
935
+ const marker = first ? "- " : " ";
936
+ lines.push(`${indentOf(indent)}${marker}${yamlScalar(key)}: ${yamlScalar(value)}`);
937
+ first = false;
938
+ }
939
+ }
940
+ return lines;
941
+ }
942
+ function indentOf(width) {
943
+ return " ".repeat(width);
944
+ }
945
+ // exportMountMode reads a container mount's mode, which may arrive as the
946
+ // logical spelling or as a proto enum name, and falls back to read-only when
947
+ // the row carries none. Secret and tmpfs mounts never reach here.
948
+ function exportMountMode(mode) {
949
+ if (mode === undefined || mode === "")
950
+ return "read_only";
951
+ return normalizeMountMode(mode) === "read_write" ? "read_write" : "read_only";
952
+ }
953
+ function mountFields(mount) {
954
+ switch (mount.kind) {
955
+ case "project":
956
+ return { kind: "project", project: mount.project, mode: mount.mode };
957
+ case "volume":
958
+ return {
959
+ kind: "volume",
960
+ volume: mount.volume,
961
+ destination: mount.destination,
962
+ mode: mount.mode,
963
+ };
964
+ case "secret":
965
+ return {
966
+ kind: "secret",
967
+ secret: mount.secret,
968
+ destination: mount.destination,
969
+ };
970
+ case "tmpfs":
971
+ return { kind: "tmpfs", destination: mount.destination };
972
+ }
973
+ }
974
+ function portFields(port) {
975
+ return {
976
+ container: port.container,
977
+ ...(port.host === undefined ? {} : { host: port.host }),
978
+ protocol: port.protocol,
979
+ };
980
+ }
981
+ const PLAIN_SCALAR = /^[A-Za-z0-9_./+][A-Za-z0-9_./+:-]*$/;
982
+ const RESERVED_SCALARS = new Set([
983
+ "null",
984
+ "~",
985
+ "true",
986
+ "false",
987
+ "yes",
988
+ "no",
989
+ "on",
990
+ "off",
991
+ "y",
992
+ "n",
993
+ ]);
994
+ function yamlScalar(value) {
995
+ if (typeof value === "number")
996
+ return String(value);
997
+ if (PLAIN_SCALAR.test(value) &&
998
+ !RESERVED_SCALARS.has(value.toLowerCase()) &&
999
+ !/^[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?$/i.test(value)) {
1000
+ return value;
1001
+ }
1002
+ return JSON.stringify(value);
1003
+ }
1004
+ // templateMountInputs converts a template's mounts to that shared shape. Project
1005
+ // and volume mounts keep their mode, secret mounts carry no mode, and tmpfs
1006
+ // mounts are read-write. Passing the workspace project forces that one project
1007
+ // mount first, keeping the mode the template declared for it and defaulting to
1008
+ // read-write only when the template does not list it.
1009
+ export function templateMountInputs(template, workspaceProject) {
1010
+ const mounts = template.spec.mounts.map((mount) => {
1011
+ switch (mount.kind) {
1012
+ case "project":
1013
+ return mountInput("project", mount.project, "", mount.mode);
1014
+ case "volume":
1015
+ return {
1016
+ ...mountInput("volume", "", mount.destination, mount.mode),
1017
+ volume: mount.volume,
1018
+ };
1019
+ case "secret":
1020
+ return {
1021
+ ...mountInput("secret", "", mount.destination, "read_only"),
1022
+ secret: mount.secret,
1023
+ };
1024
+ case "tmpfs":
1025
+ return mountInput("tmpfs", "", mount.destination, "read_write");
1026
+ }
1027
+ });
1028
+ if (workspaceProject === undefined)
1029
+ return mounts;
1030
+ return withForcedProjectMount(mounts, workspaceProject);
1031
+ }
1032
+ function mountInput(kind, project, destination, mode) {
1033
+ return {
1034
+ kind,
1035
+ project,
1036
+ destination,
1037
+ mode,
1038
+ volume: "",
1039
+ secret: "",
1040
+ };
1041
+ }
1042
+ // withForcedProjectMount makes the workspace's own project mount the first mount,
1043
+ // silently replacing any same-project entry the template carried. It is the mount
1044
+ // a loaded template cannot remove: the container's project directory is what
1045
+ // every tool operates on. The template still chooses the mount's mode when it
1046
+ // declares it; a template that omits the mount gets the read-write default.
1047
+ export function withForcedProjectMount(mounts, workspaceProject) {
1048
+ const project = normalizeProjectPath(workspaceProject);
1049
+ if (project === undefined) {
1050
+ throw new TemplateError(`invalid workspace project ${JSON.stringify(workspaceProject)}`);
1051
+ }
1052
+ const declared = mounts.find((mount) => mount.kind === "project" && mount.project === project);
1053
+ const mode = declared === undefined
1054
+ ? "read_write"
1055
+ : normalizeMountMode(declared.mode);
1056
+ const rest = mounts.filter((mount) => !(mount.kind === "project" && mount.project === project));
1057
+ return [mountInput("project", project, "", mode), ...rest];
1058
+ }