@kitsy/cnos 1.1.1 → 1.2.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 (62) hide show
  1. package/README.md +4 -1
  2. package/dist/browser/index.cjs +94 -0
  3. package/dist/browser/index.d.cts +16 -0
  4. package/dist/browser/index.d.ts +16 -0
  5. package/dist/browser/index.js +67 -0
  6. package/dist/build/index.cjs +2100 -0
  7. package/dist/build/index.d.cts +5 -0
  8. package/dist/build/index.d.ts +5 -0
  9. package/dist/build/index.js +14 -0
  10. package/dist/{chunk-JPJ3S3CO.js → chunk-APCTXRUN.js} +620 -426
  11. package/dist/{chunk-PBU5NAX4.js → chunk-EIN55XXA.js} +1 -1
  12. package/dist/chunk-JUHPBAEH.js +20 -0
  13. package/dist/{chunk-L3HOQHCH.js → chunk-MLQGYCO7.js} +1 -1
  14. package/dist/chunk-PQ4KSV76.js +50 -0
  15. package/dist/{chunk-7GNXYEO6.js → chunk-RD5WMHPM.js} +1 -1
  16. package/dist/chunk-SO5XREEU.js +179 -0
  17. package/dist/{chunk-QKJ6QLRS.js → chunk-SXTMTACL.js} +2 -2
  18. package/dist/{chunk-X4GOXEKX.js → chunk-WHUGFPE4.js} +1 -1
  19. package/dist/{chunk-M4S6PYM5.js → chunk-ZA74BO47.js} +1 -1
  20. package/dist/{envNaming-BrOk5ndZ.d.cts → envNaming-BTJpH93W.d.cts} +1 -1
  21. package/dist/{envNaming-DCaNdnrF.d.ts → envNaming-CcsqAel3.d.ts} +1 -1
  22. package/dist/index.cjs +294 -133
  23. package/dist/index.d.cts +4 -3
  24. package/dist/index.d.ts +4 -3
  25. package/dist/index.js +14 -132
  26. package/dist/internal.cjs +479 -61
  27. package/dist/internal.d.cts +29 -3
  28. package/dist/internal.d.ts +29 -3
  29. package/dist/internal.js +27 -1
  30. package/dist/plugin/basic-schema.cjs +3 -3
  31. package/dist/plugin/basic-schema.d.cts +1 -1
  32. package/dist/plugin/basic-schema.d.ts +1 -1
  33. package/dist/plugin/basic-schema.js +2 -2
  34. package/dist/plugin/cli-args.cjs +3 -3
  35. package/dist/plugin/cli-args.d.cts +1 -1
  36. package/dist/plugin/cli-args.d.ts +1 -1
  37. package/dist/plugin/cli-args.js +2 -2
  38. package/dist/plugin/dotenv.cjs +9 -9
  39. package/dist/plugin/dotenv.d.cts +2 -2
  40. package/dist/plugin/dotenv.d.ts +2 -2
  41. package/dist/plugin/dotenv.js +2 -2
  42. package/dist/plugin/env-export.cjs +46 -64
  43. package/dist/plugin/env-export.d.cts +2 -2
  44. package/dist/plugin/env-export.d.ts +2 -2
  45. package/dist/plugin/env-export.js +2 -2
  46. package/dist/plugin/filesystem.cjs +10 -10
  47. package/dist/plugin/filesystem.d.cts +1 -1
  48. package/dist/plugin/filesystem.d.ts +1 -1
  49. package/dist/plugin/filesystem.js +2 -2
  50. package/dist/plugin/process-env.cjs +9 -9
  51. package/dist/plugin/process-env.d.cts +2 -2
  52. package/dist/plugin/process-env.d.ts +2 -2
  53. package/dist/plugin/process-env.js +2 -2
  54. package/dist/{plugin-BVNEHj19.d.cts → plugin-DkOIT5uI.d.cts} +30 -2
  55. package/dist/{plugin-BVNEHj19.d.ts → plugin-DkOIT5uI.d.ts} +30 -2
  56. package/dist/runtime/index.cjs +2288 -0
  57. package/dist/runtime/index.d.cts +23 -0
  58. package/dist/runtime/index.d.ts +23 -0
  59. package/dist/runtime/index.js +190 -0
  60. package/dist/{toPublicEnv-Gwz3xTK0.d.ts → toPublicEnv-C9clvXLo.d.ts} +1 -1
  61. package/dist/{toPublicEnv-Dd152fFy.d.cts → toPublicEnv-DvFeV3qG.d.cts} +1 -1
  62. package/package.json +16 -1
@@ -0,0 +1,2100 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/build/index.ts
31
+ var build_exports = {};
32
+ __export(build_exports, {
33
+ resolveBrowserData: () => resolveBrowserData
34
+ });
35
+ module.exports = __toCommonJS(build_exports);
36
+
37
+ // ../core/src/errors.ts
38
+ var CnosError = class extends Error {
39
+ constructor(message) {
40
+ super(message);
41
+ this.name = new.target.name;
42
+ }
43
+ };
44
+ var CnosManifestError = class extends CnosError {
45
+ constructor(message, manifestPath) {
46
+ super(manifestPath ? `${message} (${manifestPath})` : message);
47
+ this.manifestPath = manifestPath;
48
+ }
49
+ manifestPath;
50
+ };
51
+ var CnosSecurityError = class extends CnosError {
52
+ constructor(message) {
53
+ super(message);
54
+ }
55
+ };
56
+ var CnosKeyNotFoundError = class extends CnosError {
57
+ constructor(key) {
58
+ super(`Missing required CNOS config key: ${key}`);
59
+ this.key = key;
60
+ }
61
+ key;
62
+ };
63
+
64
+ // ../core/src/runtime/inspect.ts
65
+ function inspectValue(graph, key) {
66
+ const entry = graph.entries.get(key);
67
+ if (!entry) {
68
+ throw new CnosKeyNotFoundError(key);
69
+ }
70
+ return {
71
+ key: entry.key,
72
+ value: entry.value,
73
+ namespace: entry.namespace,
74
+ profile: graph.profile,
75
+ profileSource: graph.profileSource,
76
+ workspace: {
77
+ id: graph.workspace.workspaceId,
78
+ source: graph.workspace.workspaceSource,
79
+ chain: graph.workspace.workspaceChain
80
+ },
81
+ winner: {
82
+ sourceId: entry.winner.sourceId,
83
+ pluginId: entry.winner.pluginId,
84
+ workspaceId: entry.winner.workspaceId,
85
+ ...entry.winner.origin ? { origin: entry.winner.origin } : {}
86
+ },
87
+ overridden: entry.overridden.map((override) => ({
88
+ sourceId: override.sourceId,
89
+ pluginId: override.pluginId,
90
+ workspaceId: override.workspaceId,
91
+ value: override.value,
92
+ ...override.origin ? { origin: override.origin } : {}
93
+ }))
94
+ };
95
+ }
96
+
97
+ // ../core/src/inspectors/provenance.ts
98
+ function createProvenanceInspector() {
99
+ return {
100
+ id: "provenance",
101
+ kind: "inspector",
102
+ async inspect(key, graph) {
103
+ return inspectValue(graph, key);
104
+ }
105
+ };
106
+ }
107
+
108
+ // ../core/src/manifest/loadManifest.ts
109
+ var import_promises2 = require("fs/promises");
110
+ var import_node_path2 = __toESM(require("path"), 1);
111
+
112
+ // ../core/src/utils/path.ts
113
+ var import_promises = require("fs/promises");
114
+ var import_node_os = __toESM(require("os"), 1);
115
+ var import_node_path = __toESM(require("path"), 1);
116
+ var PRIMARY_CNOS_DIR = ".cnos";
117
+ var LEGACY_CNOS_DIR = "cnos";
118
+ async function exists(filePath) {
119
+ try {
120
+ await (0, import_promises.access)(filePath);
121
+ return true;
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+ async function resolveCnosRoot(root = process.cwd()) {
127
+ const basePath = import_node_path.default.resolve(root);
128
+ const candidates = [
129
+ import_node_path.default.join(basePath, PRIMARY_CNOS_DIR),
130
+ import_node_path.default.join(basePath, LEGACY_CNOS_DIR),
131
+ basePath
132
+ ];
133
+ for (const candidate of candidates) {
134
+ if (await exists(import_node_path.default.join(candidate, "cnos.yml"))) {
135
+ return candidate;
136
+ }
137
+ }
138
+ throw new CnosManifestError(
139
+ `Could not locate .cnos/cnos.yml or cnos/cnos.yml from root: ${basePath}`
140
+ );
141
+ }
142
+ async function resolveManifestRoot(root = process.cwd()) {
143
+ return resolveCnosRoot(root);
144
+ }
145
+ function interpolatePathTemplate(template, tokens) {
146
+ return Object.entries(tokens).reduce(
147
+ (result, [token, value]) => result.replaceAll(`{${token}}`, value),
148
+ template
149
+ );
150
+ }
151
+ function expandHomePath(targetPath) {
152
+ if (targetPath === "~") {
153
+ return import_node_os.default.homedir();
154
+ }
155
+ if (targetPath.startsWith("~/") || targetPath.startsWith("~\\")) {
156
+ return import_node_path.default.join(import_node_os.default.homedir(), targetPath.slice(2));
157
+ }
158
+ return targetPath;
159
+ }
160
+ function stripWorkspaceTemplatePrefix(template) {
161
+ const normalized = template.replace(/\\/g, "/").replace(/^\.\//, "");
162
+ const marker = "workspaces/{workspace}";
163
+ if (normalized === marker) {
164
+ return ".";
165
+ }
166
+ if (normalized.startsWith(`${marker}/`)) {
167
+ return normalized.slice(marker.length + 1);
168
+ }
169
+ return template;
170
+ }
171
+ function resolveWorkspaceScopedPath(workspaceRoot, template, tokens) {
172
+ const relativeTemplate = stripWorkspaceTemplatePrefix(template);
173
+ const interpolated = interpolatePathTemplate(relativeTemplate, tokens);
174
+ return import_node_path.default.resolve(workspaceRoot, interpolated);
175
+ }
176
+ function toPortablePath(targetPath) {
177
+ return targetPath.replace(/\\/g, "/");
178
+ }
179
+ function joinConfigPath(...parts) {
180
+ return parts.flatMap((part) => part.split(".")).map((part) => part.trim()).filter(Boolean).join(".");
181
+ }
182
+ function toLogicalKey(namespace, valuePath) {
183
+ return `${namespace}.${joinConfigPath(valuePath)}`;
184
+ }
185
+ function stripNamespace(key) {
186
+ return key.split(".").slice(1).join(".");
187
+ }
188
+
189
+ // ../core/src/utils/yaml.ts
190
+ var import_yaml = require("yaml");
191
+ function parseYaml(source) {
192
+ return (0, import_yaml.parse)(source);
193
+ }
194
+
195
+ // ../core/src/manifest/normalizeManifest.ts
196
+ var DEFAULT_RESOLVE_FROM = ["cli.profile", "env.CNOS_PROFILE", "default"];
197
+ var DEFAULT_LOADERS = [
198
+ "filesystem-values",
199
+ "filesystem-secrets",
200
+ "dotenv",
201
+ "process-env",
202
+ "cli-args"
203
+ ];
204
+ var DEFAULT_VALIDATORS = ["basic-schema"];
205
+ var DEFAULT_EXPORTERS = ["env", "public-env"];
206
+ var DEFAULT_INSPECTORS = ["provenance"];
207
+ var DEFAULT_FRAMEWORK_PREFIXES = {
208
+ next: "NEXT_PUBLIC_",
209
+ vite: "VITE_",
210
+ nuxt: "NUXT_PUBLIC_"
211
+ };
212
+ var DEFAULT_NAMESPACES = {
213
+ value: {
214
+ kind: "data",
215
+ shareable: true
216
+ },
217
+ secret: {
218
+ kind: "data",
219
+ shareable: false,
220
+ sensitive: true
221
+ },
222
+ meta: {
223
+ kind: "system",
224
+ shareable: false,
225
+ readonly: true
226
+ },
227
+ public: {
228
+ kind: "projection",
229
+ source: "promote",
230
+ shareable: true,
231
+ readonly: true
232
+ },
233
+ env: {
234
+ kind: "projection",
235
+ source: "envMapping",
236
+ shareable: true,
237
+ readonly: true
238
+ }
239
+ };
240
+ function validateResolveFrom(resolveFrom) {
241
+ const validValues = ["cli.profile", "env.CNOS_PROFILE", "default"];
242
+ for (const entry of resolveFrom) {
243
+ if (!validValues.includes(entry)) {
244
+ throw new CnosManifestError(`Unsupported profiles.resolveFrom entry: ${entry}`);
245
+ }
246
+ }
247
+ return resolveFrom;
248
+ }
249
+ function normalizeWorkspaceItems(items) {
250
+ return Object.fromEntries(
251
+ Object.entries(items ?? {}).map(([workspaceId, item]) => [
252
+ workspaceId,
253
+ {
254
+ extends: Array.isArray(item?.extends) ? item.extends.map((entry) => entry.trim()).filter(Boolean) : item?.extends ? [item.extends.trim()].filter(Boolean) : [],
255
+ ...item?.globalId?.trim() ? { globalId: item.globalId.trim() } : {}
256
+ }
257
+ ])
258
+ );
259
+ }
260
+ function normalizeNamespaces(namespaces) {
261
+ const normalized = Object.fromEntries(
262
+ Object.entries(namespaces ?? {}).map(([namespace, definition]) => [
263
+ namespace,
264
+ {
265
+ kind: definition.kind ?? "data",
266
+ shareable: definition.shareable ?? false,
267
+ ...definition.sensitive !== void 0 ? { sensitive: definition.sensitive } : {},
268
+ ...definition.readonly !== void 0 ? { readonly: definition.readonly } : {},
269
+ ...definition.source ? { source: definition.source } : {}
270
+ }
271
+ ])
272
+ );
273
+ return {
274
+ ...DEFAULT_NAMESPACES,
275
+ ...normalized
276
+ };
277
+ }
278
+ function normalizeVaults(vaults) {
279
+ return Object.fromEntries(
280
+ Object.entries(vaults ?? {}).map(([name, definition]) => {
281
+ const provider = definition.provider?.trim();
282
+ if (!provider) {
283
+ throw new CnosManifestError(`Vault "${name}" requires a provider`);
284
+ }
285
+ return [
286
+ name,
287
+ {
288
+ provider,
289
+ ...definition.passphrase?.trim() ? {
290
+ passphrase: definition.passphrase.trim()
291
+ } : {}
292
+ }
293
+ ];
294
+ })
295
+ );
296
+ }
297
+ function normalizeManifest(manifest) {
298
+ const version = manifest.version ?? 1;
299
+ if (version !== 1) {
300
+ throw new CnosManifestError(`Unsupported CNOS manifest version: ${version}`);
301
+ }
302
+ const projectName = manifest.project?.name?.trim();
303
+ if (!projectName) {
304
+ throw new CnosManifestError("Manifest requires project.name");
305
+ }
306
+ const defaultProfile = manifest.profiles?.default?.trim() || "base";
307
+ const workspaceItems = normalizeWorkspaceItems(manifest.workspaces?.items);
308
+ const resolveFrom = validateResolveFrom(manifest.profiles?.resolveFrom ?? DEFAULT_RESOLVE_FROM);
309
+ const filesystemValues = {
310
+ root: "./",
311
+ format: "yaml",
312
+ ...manifest.sources?.["filesystem-values"] ?? {}
313
+ };
314
+ const filesystemSecrets = {
315
+ root: "./",
316
+ format: "yaml",
317
+ ...manifest.sources?.["filesystem-secrets"] ?? {}
318
+ };
319
+ const dotenv = {
320
+ root: "./env",
321
+ ...manifest.sources?.dotenv ?? {}
322
+ };
323
+ return {
324
+ version: 1,
325
+ project: {
326
+ name: projectName
327
+ },
328
+ workspaces: {
329
+ ...manifest.workspaces?.default?.trim() ? {
330
+ default: manifest.workspaces.default.trim()
331
+ } : {},
332
+ global: {
333
+ enabled: manifest.workspaces?.global?.enabled ?? false,
334
+ ...manifest.workspaces?.global?.root?.trim() ? {
335
+ root: manifest.workspaces.global.root.trim()
336
+ } : {},
337
+ allowWrite: manifest.workspaces?.global?.allowWrite ?? false
338
+ },
339
+ items: workspaceItems
340
+ },
341
+ profiles: {
342
+ default: defaultProfile,
343
+ resolveFrom
344
+ },
345
+ plugins: {
346
+ loaders: manifest.plugins?.loaders ?? DEFAULT_LOADERS,
347
+ resolver: manifest.plugins?.resolver ?? "profile-aware",
348
+ validators: manifest.plugins?.validators ?? DEFAULT_VALIDATORS,
349
+ exporters: manifest.plugins?.exporters ?? DEFAULT_EXPORTERS,
350
+ inspectors: manifest.plugins?.inspectors ?? DEFAULT_INSPECTORS
351
+ },
352
+ sources: {
353
+ ...manifest.sources ?? {},
354
+ "filesystem-values": filesystemValues,
355
+ "filesystem-secrets": filesystemSecrets,
356
+ dotenv
357
+ },
358
+ resolution: {
359
+ precedence: manifest.resolution?.precedence ?? [
360
+ "filesystem-values",
361
+ "filesystem-secrets",
362
+ "dotenv",
363
+ "process-env",
364
+ "cli-args"
365
+ ],
366
+ arrayPolicy: manifest.resolution?.arrayPolicy ?? "replace"
367
+ },
368
+ envMapping: {
369
+ ...manifest.envMapping?.convention ? {
370
+ convention: manifest.envMapping.convention
371
+ } : {},
372
+ explicit: manifest.envMapping?.explicit ?? {}
373
+ },
374
+ public: {
375
+ promote: manifest.public?.promote ?? [],
376
+ frameworks: {
377
+ ...DEFAULT_FRAMEWORK_PREFIXES,
378
+ ...manifest.public?.frameworks ?? {}
379
+ }
380
+ },
381
+ namespaces: normalizeNamespaces(manifest.namespaces),
382
+ vaults: normalizeVaults(manifest.vaults),
383
+ writePolicy: {
384
+ define: {
385
+ defaultProfile: manifest.writePolicy?.define?.defaultProfile ?? defaultProfile,
386
+ targets: {
387
+ value: manifest.writePolicy?.define?.targets?.value ?? "./values/app.yml",
388
+ secret: manifest.writePolicy?.define?.targets?.secret ?? "./secrets/app.yml"
389
+ }
390
+ }
391
+ },
392
+ schema: manifest.schema ?? {}
393
+ };
394
+ }
395
+
396
+ // ../core/src/manifest/loadManifest.ts
397
+ async function loadManifest(options = {}) {
398
+ const manifestRoot = await resolveManifestRoot(options.root);
399
+ const manifestPath = import_node_path2.default.join(manifestRoot, "cnos.yml");
400
+ let source;
401
+ try {
402
+ source = await (0, import_promises2.readFile)(manifestPath, "utf8");
403
+ } catch {
404
+ throw new CnosManifestError("Unable to read CNOS manifest", manifestPath);
405
+ }
406
+ const rawManifest = parseYaml(source);
407
+ if (!rawManifest || typeof rawManifest !== "object") {
408
+ throw new CnosManifestError("CNOS manifest must be a YAML object", manifestPath);
409
+ }
410
+ return {
411
+ manifestRoot,
412
+ repoRoot: import_node_path2.default.dirname(manifestRoot),
413
+ manifestPath,
414
+ manifest: normalizeManifest(rawManifest),
415
+ rawManifest
416
+ };
417
+ }
418
+
419
+ // ../core/src/manifest/loadWorkspaceFile.ts
420
+ var import_promises3 = require("fs/promises");
421
+ var import_node_path3 = __toESM(require("path"), 1);
422
+ async function loadWorkspaceFile(repoRoot) {
423
+ const workspaceFilePath = import_node_path3.default.join(repoRoot, ".cnos-workspace.yml");
424
+ try {
425
+ const source = await (0, import_promises3.readFile)(workspaceFilePath, "utf8");
426
+ const parsed = parseYaml(source);
427
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
428
+ throw new CnosManifestError(".cnos-workspace.yml must be a YAML object", workspaceFilePath);
429
+ }
430
+ const config = parsed;
431
+ return {
432
+ path: workspaceFilePath,
433
+ config: {
434
+ ...config.workspace ? { workspace: config.workspace.trim() } : {},
435
+ ...config.profile ? { profile: config.profile.trim() } : {},
436
+ ...config.globalRoot ? { globalRoot: config.globalRoot.trim() } : {}
437
+ }
438
+ };
439
+ } catch (error) {
440
+ if (error.code === "ENOENT") {
441
+ return void 0;
442
+ }
443
+ throw error;
444
+ }
445
+ }
446
+
447
+ // ../core/src/profiles/expandProfileChain.ts
448
+ var import_promises4 = require("fs/promises");
449
+ var import_node_path4 = __toESM(require("path"), 1);
450
+ async function fileExists(targetPath) {
451
+ try {
452
+ await (0, import_promises4.access)(targetPath);
453
+ return true;
454
+ } catch {
455
+ return false;
456
+ }
457
+ }
458
+ function normalizeProfileDefinition(profileName, rawDefinition, filePath) {
459
+ const normalizeActivationLayer = (entry, namespace) => {
460
+ const normalized = entry.trim();
461
+ if (!normalized) {
462
+ return normalized;
463
+ }
464
+ if (normalized.includes("/") || normalized.includes("\\") || normalized.startsWith(".")) {
465
+ return normalized.replace(/\\/g, "/");
466
+ }
467
+ return `${namespace}/${normalized}`;
468
+ };
469
+ return {
470
+ name: rawDefinition?.name?.trim() || profileName,
471
+ extends: Array.isArray(rawDefinition?.extends) ? rawDefinition.extends.map((entry) => entry.trim()).filter(Boolean) : rawDefinition?.extends ? [rawDefinition.extends.trim()].filter(Boolean) : [],
472
+ activate: {
473
+ values: rawDefinition?.activate?.values?.map((entry) => normalizeActivationLayer(entry, "values")).filter(Boolean) ?? [],
474
+ secrets: rawDefinition?.activate?.secrets?.map((entry) => normalizeActivationLayer(entry, "secrets")).filter(Boolean) ?? [],
475
+ envFiles: rawDefinition?.activate?.envFiles?.map((entry) => entry.trim()).filter(Boolean) ?? []
476
+ },
477
+ ...filePath ? { filePath } : {}
478
+ };
479
+ }
480
+ async function loadProfileDefinition(profileName, options) {
481
+ const workspaceRoots = options.workspace?.workspaceRoots ?? [];
482
+ if (workspaceRoots.length === 0) {
483
+ return normalizeProfileDefinition(profileName, void 0);
484
+ }
485
+ for (const workspaceRoot of [...workspaceRoots].reverse()) {
486
+ const profilePath = import_node_path4.default.join(workspaceRoot.path, "profiles", `${profileName}.yml`);
487
+ if (!await fileExists(profilePath)) {
488
+ continue;
489
+ }
490
+ const document = await (0, import_promises4.readFile)(profilePath, "utf8");
491
+ const parsed = parseYaml(document);
492
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
493
+ throw new CnosManifestError("Profile definition must be a YAML object", profilePath);
494
+ }
495
+ const definition = normalizeProfileDefinition(
496
+ profileName,
497
+ parsed,
498
+ options.manifestRoot ? toPortablePath(import_node_path4.default.relative(import_node_path4.default.dirname(options.manifestRoot), profilePath)) : toPortablePath(profilePath)
499
+ );
500
+ if (definition.name !== profileName) {
501
+ throw new CnosManifestError(
502
+ `Profile file name mismatch: expected "${profileName}" but found "${definition.name}"`,
503
+ profilePath
504
+ );
505
+ }
506
+ return definition;
507
+ }
508
+ return normalizeProfileDefinition(profileName, void 0);
509
+ }
510
+ function pushUnique(target, values) {
511
+ for (const value of values) {
512
+ if (!target.includes(value)) {
513
+ target.push(value);
514
+ }
515
+ }
516
+ }
517
+ function buildFallbackActivation(activeProfile, orderedProfiles) {
518
+ const overlayProfiles = orderedProfiles.filter((profile) => profile !== "base");
519
+ return {
520
+ values: [
521
+ "values",
522
+ ...activeProfile !== "base" ? ["values/base"] : [],
523
+ ...overlayProfiles.flatMap((profile) => [`profiles/${profile}/values`, `values/${profile}`])
524
+ ],
525
+ secrets: [
526
+ "secrets",
527
+ ...overlayProfiles.flatMap((profile) => [`profiles/${profile}/secrets`, `secrets/${profile}`])
528
+ ],
529
+ envFiles: activeProfile === "base" ? [".env"] : [".env", `.env.${activeProfile}`]
530
+ };
531
+ }
532
+ async function expandProfileChain(activeProfile, options = {}) {
533
+ const visiting = /* @__PURE__ */ new Set();
534
+ const resolved = /* @__PURE__ */ new Set();
535
+ const orderedProfiles = [];
536
+ const definitions = /* @__PURE__ */ new Map();
537
+ const visit = async (profileName) => {
538
+ if (resolved.has(profileName)) {
539
+ return;
540
+ }
541
+ if (visiting.has(profileName)) {
542
+ throw new CnosManifestError(`Detected profile inheritance cycle involving "${profileName}"`);
543
+ }
544
+ visiting.add(profileName);
545
+ const definition = await loadProfileDefinition(profileName, options);
546
+ definitions.set(profileName, definition);
547
+ for (const parent of definition.extends) {
548
+ await visit(parent);
549
+ }
550
+ visiting.delete(profileName);
551
+ resolved.add(profileName);
552
+ orderedProfiles.push(profileName);
553
+ };
554
+ await visit(activeProfile);
555
+ const activation = {
556
+ values: [],
557
+ secrets: [],
558
+ envFiles: []
559
+ };
560
+ for (const profileName of orderedProfiles) {
561
+ const definition = definitions.get(profileName);
562
+ if (!definition) {
563
+ continue;
564
+ }
565
+ pushUnique(activation.values, definition.activate.values);
566
+ pushUnique(activation.secrets, definition.activate.secrets);
567
+ pushUnique(activation.envFiles, definition.activate.envFiles);
568
+ }
569
+ const fallback = buildFallbackActivation(activeProfile, orderedProfiles);
570
+ if (activation.values.length === 0) {
571
+ activation.values = fallback.values;
572
+ }
573
+ if (activation.secrets.length === 0) {
574
+ activation.secrets = fallback.secrets;
575
+ }
576
+ if (activation.envFiles.length === 0) {
577
+ activation.envFiles = fallback.envFiles;
578
+ }
579
+ return {
580
+ activeProfile,
581
+ profiles: orderedProfiles,
582
+ activation
583
+ };
584
+ }
585
+
586
+ // ../core/src/promotions/validatePromotion.ts
587
+ var DEFAULT_DATA_NAMESPACE = {
588
+ kind: "data",
589
+ shareable: false
590
+ };
591
+ function getNamespaceNameForKey(key) {
592
+ const [namespace] = key.split(".");
593
+ if (!namespace || !key.includes(".")) {
594
+ throw new CnosManifestError(`Logical key must be namespace-qualified: ${key}`);
595
+ }
596
+ return namespace;
597
+ }
598
+ function getNamespaceDefinition(manifest, namespaceOrKey) {
599
+ const namespace = namespaceOrKey.includes(".") ? getNamespaceNameForKey(namespaceOrKey) : namespaceOrKey;
600
+ return manifest.namespaces[namespace] ?? DEFAULT_DATA_NAMESPACE;
601
+ }
602
+ function ensureProjectionAllowed(manifest, key, target) {
603
+ const namespace = getNamespaceNameForKey(key);
604
+ const definition = getNamespaceDefinition(manifest, namespace);
605
+ if (definition.kind !== "data") {
606
+ throw new CnosManifestError(
607
+ `Cannot promote ${key} to ${target} because namespace "${namespace}" is not a data namespace.`
608
+ );
609
+ }
610
+ if (definition.sensitive) {
611
+ throw new CnosSecurityError(
612
+ `Cannot promote ${key} to ${target} because namespace "${namespace}" is sensitive.`
613
+ );
614
+ }
615
+ if (!definition.shareable) {
616
+ throw new CnosSecurityError(
617
+ `Cannot promote ${key} to ${target} because namespace "${namespace}" is not shareable.`
618
+ );
619
+ }
620
+ }
621
+
622
+ // ../core/src/promotions/promoteToPublic.ts
623
+ function toPublicKey(key) {
624
+ const namespace = getNamespaceNameForKey(key);
625
+ return namespace === "value" ? `public.${stripNamespace(key)}` : `public.${key}`;
626
+ }
627
+ function toPromotedConfigEntry(entry, key, promotedFrom) {
628
+ return {
629
+ ...entry,
630
+ key,
631
+ namespace: "public",
632
+ sourceId: "public-promote",
633
+ pluginId: "core",
634
+ metadata: {
635
+ ...entry.metadata ?? {},
636
+ promotedFrom
637
+ }
638
+ };
639
+ }
640
+ function toPromotedResolvedEntry(entry) {
641
+ const key = toPublicKey(entry.key);
642
+ return {
643
+ key,
644
+ value: entry.value,
645
+ namespace: "public",
646
+ winner: toPromotedConfigEntry(entry.winner, key, entry.key),
647
+ overridden: entry.overridden.map((override) => toPromotedConfigEntry(override, key, entry.key))
648
+ };
649
+ }
650
+ function promoteToPublic(graph, manifest) {
651
+ const entries = new Map(graph.entries);
652
+ for (const key of manifest.public.promote) {
653
+ ensureProjectionAllowed(manifest, key, "public");
654
+ const resolved = graph.entries.get(key);
655
+ if (!resolved) {
656
+ continue;
657
+ }
658
+ entries.set(toPublicKey(key), toPromotedResolvedEntry(resolved));
659
+ }
660
+ return {
661
+ ...graph,
662
+ entries
663
+ };
664
+ }
665
+
666
+ // ../core/src/profiles/resolveActiveProfile.ts
667
+ function resolveActiveProfile(manifest, options = {}) {
668
+ for (const source of manifest.profiles.resolveFrom) {
669
+ if (source === "cli.profile" && options.profile) {
670
+ return {
671
+ profile: options.profile,
672
+ source: "cli"
673
+ };
674
+ }
675
+ if (source === "env.CNOS_PROFILE") {
676
+ if (options.workspaceFile?.profile) {
677
+ return {
678
+ profile: options.workspaceFile.profile,
679
+ source: "workspace-file"
680
+ };
681
+ }
682
+ const envProfile = options.processEnv?.CNOS_PROFILE;
683
+ if (envProfile) {
684
+ return {
685
+ profile: envProfile,
686
+ source: "env"
687
+ };
688
+ }
689
+ }
690
+ if (source === "default") {
691
+ return {
692
+ profile: manifest.profiles.default,
693
+ source: "manifest-default"
694
+ };
695
+ }
696
+ }
697
+ return {
698
+ profile: manifest.profiles.default,
699
+ source: "manifest-default"
700
+ };
701
+ }
702
+
703
+ // ../core/src/utils/deepMerge.ts
704
+ function isPlainObject(value) {
705
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
706
+ }
707
+ function deepMerge(base, override) {
708
+ const merged = { ...base };
709
+ for (const [key, value] of Object.entries(override)) {
710
+ const currentValue = merged[key];
711
+ if (isPlainObject(currentValue) && isPlainObject(value)) {
712
+ merged[key] = deepMerge(currentValue, value);
713
+ continue;
714
+ }
715
+ merged[key] = value;
716
+ }
717
+ return merged;
718
+ }
719
+
720
+ // ../core/src/resolvers/profileAwareResolver.ts
721
+ function mergeResolvedValue(currentValue, nextValue, arrayPolicy) {
722
+ if (Array.isArray(currentValue) && Array.isArray(nextValue)) {
723
+ if (arrayPolicy === "append") {
724
+ return [...currentValue, ...nextValue];
725
+ }
726
+ if (arrayPolicy === "unique-append") {
727
+ return [.../* @__PURE__ */ new Set([...currentValue, ...nextValue])];
728
+ }
729
+ return [...nextValue];
730
+ }
731
+ if (isPlainObject(currentValue) && isPlainObject(nextValue)) {
732
+ return deepMerge(currentValue, nextValue);
733
+ }
734
+ return nextValue;
735
+ }
736
+ function createProfileAwareResolver() {
737
+ return {
738
+ id: "profile-aware",
739
+ kind: "resolver",
740
+ async resolve(entries, context) {
741
+ const precedence = new Map(context.precedenceOrder.map((sourceId, index) => [sourceId, index]));
742
+ const sortedEntries = entries.map((entry, index) => ({
743
+ entry,
744
+ index,
745
+ precedence: precedence.get(entry.sourceId) ?? context.precedenceOrder.length
746
+ })).sort((left, right) => left.precedence - right.precedence || left.index - right.index);
747
+ const resolvedEntries = /* @__PURE__ */ new Map();
748
+ for (const { entry } of sortedEntries) {
749
+ const current = resolvedEntries.get(entry.key);
750
+ if (!current) {
751
+ resolvedEntries.set(entry.key, {
752
+ key: entry.key,
753
+ value: entry.value,
754
+ namespace: entry.namespace,
755
+ winner: entry,
756
+ overridden: []
757
+ });
758
+ continue;
759
+ }
760
+ resolvedEntries.set(entry.key, {
761
+ key: entry.key,
762
+ value: mergeResolvedValue(current.value, entry.value, context.manifest.resolution.arrayPolicy),
763
+ namespace: current.namespace,
764
+ winner: entry,
765
+ overridden: [...current.overridden, current.winner]
766
+ });
767
+ }
768
+ return {
769
+ entries: resolvedEntries,
770
+ profile: context.profile,
771
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
772
+ profileSource: "manifest-default",
773
+ workspace: context.workspace
774
+ };
775
+ }
776
+ };
777
+ }
778
+
779
+ // ../core/src/workspaces/resolveWorkspaceContext.ts
780
+ var import_promises5 = require("fs/promises");
781
+ var import_node_path5 = __toESM(require("path"), 1);
782
+
783
+ // ../core/src/workspaces/expandWorkspaceChain.ts
784
+ function expandWorkspaceChain(workspaceId, items) {
785
+ if (Object.keys(items).length === 0) {
786
+ return [workspaceId];
787
+ }
788
+ if (!items[workspaceId]) {
789
+ throw new CnosManifestError(`Unknown workspace "${workspaceId}"`);
790
+ }
791
+ const visiting = /* @__PURE__ */ new Set();
792
+ const resolved = /* @__PURE__ */ new Set();
793
+ const chain = [];
794
+ const visit = (currentWorkspaceId) => {
795
+ if (resolved.has(currentWorkspaceId)) {
796
+ return;
797
+ }
798
+ if (visiting.has(currentWorkspaceId)) {
799
+ throw new CnosManifestError(`Detected workspace inheritance cycle involving "${currentWorkspaceId}"`);
800
+ }
801
+ const item = items[currentWorkspaceId];
802
+ if (!item) {
803
+ throw new CnosManifestError(`Unknown workspace "${currentWorkspaceId}"`);
804
+ }
805
+ visiting.add(currentWorkspaceId);
806
+ for (const parentWorkspaceId of item.extends) {
807
+ visit(parentWorkspaceId);
808
+ }
809
+ visiting.delete(currentWorkspaceId);
810
+ resolved.add(currentWorkspaceId);
811
+ chain.push(currentWorkspaceId);
812
+ };
813
+ visit(workspaceId);
814
+ return chain;
815
+ }
816
+
817
+ // ../core/src/workspaces/resolveWorkspaceContext.ts
818
+ async function exists2(targetPath) {
819
+ try {
820
+ await (0, import_promises5.access)(targetPath);
821
+ return true;
822
+ } catch {
823
+ return false;
824
+ }
825
+ }
826
+ async function resolveLocalWorkspaceRoot(manifestRoot, workspaceId) {
827
+ const workspaceRoot = import_node_path5.default.join(manifestRoot, "workspaces", workspaceId);
828
+ if (await exists2(workspaceRoot)) {
829
+ return workspaceRoot;
830
+ }
831
+ const legacyMarkers = ["values", "secrets", "env", "profiles"].map(
832
+ (segment) => import_node_path5.default.join(manifestRoot, segment)
833
+ );
834
+ if ((await Promise.all(legacyMarkers.map((marker) => exists2(marker)))).some(Boolean)) {
835
+ return manifestRoot;
836
+ }
837
+ return workspaceRoot;
838
+ }
839
+ function resolveWorkspaceSelection(manifest, workspaceFile, workspaceOption) {
840
+ if (workspaceOption) {
841
+ return {
842
+ workspaceId: workspaceOption,
843
+ source: "cli"
844
+ };
845
+ }
846
+ if (workspaceFile?.workspace) {
847
+ return {
848
+ workspaceId: workspaceFile.workspace,
849
+ source: "workspace-file"
850
+ };
851
+ }
852
+ if (manifest.workspaces.default) {
853
+ return {
854
+ workspaceId: manifest.workspaces.default,
855
+ source: "manifest-default"
856
+ };
857
+ }
858
+ if (Object.keys(manifest.workspaces.items).length === 0) {
859
+ return {
860
+ workspaceId: "default",
861
+ source: "implicit"
862
+ };
863
+ }
864
+ throw new CnosManifestError(
865
+ "Workspace selection requires --workspace, .cnos-workspace.yml, or workspaces.default when workspaces.items are defined"
866
+ );
867
+ }
868
+ function resolveGlobalRoot(manifest, workspaceFile, options) {
869
+ if (!manifest.workspaces.global.enabled) {
870
+ return {};
871
+ }
872
+ if (options.globalRoot) {
873
+ return {
874
+ value: import_node_path5.default.resolve(expandHomePath(options.globalRoot)),
875
+ source: "cli"
876
+ };
877
+ }
878
+ if (workspaceFile?.globalRoot) {
879
+ return {
880
+ value: import_node_path5.default.resolve(expandHomePath(workspaceFile.globalRoot)),
881
+ source: "workspace-file"
882
+ };
883
+ }
884
+ if (manifest.workspaces.global.root) {
885
+ return {
886
+ value: import_node_path5.default.resolve(expandHomePath(manifest.workspaces.global.root)),
887
+ source: "manifest"
888
+ };
889
+ }
890
+ const cnosHome = options.processEnv?.CNOS_HOME;
891
+ if (cnosHome) {
892
+ return {
893
+ value: import_node_path5.default.resolve(expandHomePath(cnosHome)),
894
+ source: "CNOS_HOME"
895
+ };
896
+ }
897
+ return {};
898
+ }
899
+ async function resolveWorkspaceContext(manifest, options) {
900
+ const selectedWorkspace = resolveWorkspaceSelection(manifest, options.workspaceFile, options.workspace);
901
+ const workspaceChain = expandWorkspaceChain(selectedWorkspace.workspaceId, manifest.workspaces.items);
902
+ const globalRoot = resolveGlobalRoot(manifest, options.workspaceFile, options);
903
+ const workspaceRoots = [];
904
+ if (globalRoot.value) {
905
+ for (const chainWorkspaceId of workspaceChain) {
906
+ const globalWorkspaceId = manifest.workspaces.items[chainWorkspaceId]?.globalId ?? chainWorkspaceId;
907
+ workspaceRoots.push({
908
+ scope: "global",
909
+ workspaceId: chainWorkspaceId,
910
+ path: import_node_path5.default.join(globalRoot.value, "workspaces", globalWorkspaceId)
911
+ });
912
+ }
913
+ }
914
+ for (const chainWorkspaceId of workspaceChain) {
915
+ workspaceRoots.push({
916
+ scope: "local",
917
+ workspaceId: chainWorkspaceId,
918
+ path: await resolveLocalWorkspaceRoot(options.manifestRoot, chainWorkspaceId)
919
+ });
920
+ }
921
+ return {
922
+ workspaceId: selectedWorkspace.workspaceId,
923
+ workspaceSource: selectedWorkspace.source,
924
+ ...globalRoot.value ? { globalRoot: globalRoot.value } : {},
925
+ ...globalRoot.source ? { globalRootSource: globalRoot.source } : {},
926
+ workspaceChain,
927
+ workspaceRoots
928
+ };
929
+ }
930
+
931
+ // ../core/src/validation/basicSchema.ts
932
+ function describeValueType(value) {
933
+ if (Array.isArray(value)) {
934
+ return "array";
935
+ }
936
+ if (value === null) {
937
+ return "null";
938
+ }
939
+ return typeof value;
940
+ }
941
+ function coerceBoolean(value) {
942
+ if (value === "true") {
943
+ return true;
944
+ }
945
+ if (value === "false") {
946
+ return false;
947
+ }
948
+ return void 0;
949
+ }
950
+ function coerceValue(value, rule) {
951
+ if (typeof value !== "string" || !rule.type) {
952
+ return value;
953
+ }
954
+ switch (rule.type) {
955
+ case "number": {
956
+ const parsed = Number(value);
957
+ return Number.isNaN(parsed) ? value : parsed;
958
+ }
959
+ case "boolean":
960
+ return coerceBoolean(value) ?? value;
961
+ case "object":
962
+ case "array": {
963
+ try {
964
+ const parsed = JSON.parse(value);
965
+ if (rule.type === "array" && Array.isArray(parsed)) {
966
+ return parsed;
967
+ }
968
+ if (rule.type === "object" && parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
969
+ return parsed;
970
+ }
971
+ return value;
972
+ } catch {
973
+ return value;
974
+ }
975
+ }
976
+ default:
977
+ return value;
978
+ }
979
+ }
980
+ function matchesType(value, type) {
981
+ if (!type) {
982
+ return true;
983
+ }
984
+ switch (type) {
985
+ case "array":
986
+ return Array.isArray(value);
987
+ case "object":
988
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
989
+ default:
990
+ return typeof value === type;
991
+ }
992
+ }
993
+ function enumMatches(value, allowed) {
994
+ const serialized = JSON.stringify(value);
995
+ return allowed.some((candidate) => JSON.stringify(candidate) === serialized);
996
+ }
997
+ function applySchemaRules(graph, schema) {
998
+ const nextEntries = new Map(graph.entries);
999
+ const issues = [];
1000
+ for (const [key, rule] of Object.entries(schema).sort(([left], [right]) => left.localeCompare(right))) {
1001
+ const resolvedEntry = nextEntries.get(key);
1002
+ if (!resolvedEntry) {
1003
+ if (rule.default !== void 0) {
1004
+ const defaultEntry = {
1005
+ key,
1006
+ value: rule.default,
1007
+ namespace: key.startsWith("secret.") ? "secret" : key.startsWith("meta.") ? "meta" : "value",
1008
+ sourceId: "schema-default",
1009
+ pluginId: "basic-schema",
1010
+ workspaceId: graph.workspace.workspaceId,
1011
+ metadata: {
1012
+ schemaDefault: true
1013
+ }
1014
+ };
1015
+ nextEntries.set(key, {
1016
+ key,
1017
+ value: rule.default,
1018
+ namespace: defaultEntry.namespace,
1019
+ winner: defaultEntry,
1020
+ overridden: []
1021
+ });
1022
+ continue;
1023
+ }
1024
+ if (rule.required) {
1025
+ issues.push({
1026
+ code: "schema.required",
1027
+ key,
1028
+ message: `Missing required config key: ${key}`
1029
+ });
1030
+ }
1031
+ continue;
1032
+ }
1033
+ const coercedValue = coerceValue(resolvedEntry.value, rule);
1034
+ const nextResolvedEntry = coercedValue === resolvedEntry.value ? resolvedEntry : {
1035
+ ...resolvedEntry,
1036
+ value: coercedValue
1037
+ };
1038
+ if (!matchesType(coercedValue, rule.type)) {
1039
+ issues.push({
1040
+ code: "schema.type",
1041
+ key,
1042
+ message: `Config key ${key} expected type ${rule.type} but got ${describeValueType(coercedValue)}`
1043
+ });
1044
+ }
1045
+ if (rule.enum && !enumMatches(coercedValue, rule.enum)) {
1046
+ issues.push({
1047
+ code: "schema.enum",
1048
+ key,
1049
+ message: `Config key ${key} must be one of ${rule.enum.map((entry) => JSON.stringify(entry)).join(", ")}`
1050
+ });
1051
+ }
1052
+ if (rule.pattern) {
1053
+ if (typeof coercedValue !== "string") {
1054
+ issues.push({
1055
+ code: "schema.pattern",
1056
+ key,
1057
+ message: `Config key ${key} must be a string to match pattern ${rule.pattern}`
1058
+ });
1059
+ } else if (!new RegExp(rule.pattern).test(coercedValue)) {
1060
+ issues.push({
1061
+ code: "schema.pattern",
1062
+ key,
1063
+ message: `Config key ${key} does not match pattern ${rule.pattern}`
1064
+ });
1065
+ }
1066
+ }
1067
+ nextEntries.set(key, nextResolvedEntry);
1068
+ }
1069
+ return {
1070
+ graph: {
1071
+ ...graph,
1072
+ entries: nextEntries
1073
+ },
1074
+ issues
1075
+ };
1076
+ }
1077
+
1078
+ // ../core/src/orchestrator/pipeline.ts
1079
+ async function runPipeline(options) {
1080
+ const collectedEntries = await Promise.all(
1081
+ options.plugins.map(
1082
+ (plugin) => plugin.load({
1083
+ manifestConfig: {
1084
+ ...options.manifest.sources[plugin.id] ?? {},
1085
+ envMapping: options.manifest.envMapping
1086
+ },
1087
+ profile: options.profile,
1088
+ profileChain: options.profileChain,
1089
+ profileActivation: options.profileActivation,
1090
+ manifestRoot: options.manifestRoot,
1091
+ workspace: options.workspace,
1092
+ ...options.cliArgs ? { cliArgs: options.cliArgs } : {},
1093
+ ...options.processEnv ? { processEnv: options.processEnv } : {}
1094
+ })
1095
+ )
1096
+ );
1097
+ return collectedEntries.flat();
1098
+ }
1099
+
1100
+ // ../core/src/runtime/projection.ts
1101
+ function setNestedValue(target, pathSegments, value) {
1102
+ const [head, ...tail] = pathSegments;
1103
+ if (!head) {
1104
+ return;
1105
+ }
1106
+ if (tail.length === 0) {
1107
+ target[head] = value;
1108
+ return;
1109
+ }
1110
+ const current = target[head];
1111
+ const nextTarget = current && typeof current === "object" && !Array.isArray(current) ? current : {};
1112
+ target[head] = nextTarget;
1113
+ setNestedValue(nextTarget, tail, value);
1114
+ }
1115
+ function toNamespaceObject(graph, namespace) {
1116
+ const output = {};
1117
+ const resolvedEntries = Array.from(graph.entries.values()).sort(
1118
+ (left, right) => left.key.localeCompare(right.key)
1119
+ );
1120
+ for (const entry of resolvedEntries) {
1121
+ if (namespace && entry.namespace !== namespace) {
1122
+ continue;
1123
+ }
1124
+ const valuePath = namespace ? stripNamespace(entry.key) : entry.key;
1125
+ setNestedValue(output, valuePath.split("."), entry.value);
1126
+ }
1127
+ return output;
1128
+ }
1129
+
1130
+ // ../core/src/runtime/read.ts
1131
+ function readValue(graph, key) {
1132
+ return graph.entries.get(key)?.value;
1133
+ }
1134
+
1135
+ // ../core/src/runtime/readOr.ts
1136
+ function readOrValue(graph, key, fallback) {
1137
+ const value = readValue(graph, key);
1138
+ return value === void 0 ? fallback : value;
1139
+ }
1140
+
1141
+ // ../core/src/runtime/require.ts
1142
+ function requireValue(graph, key) {
1143
+ const value = readValue(graph, key);
1144
+ if (value === void 0) {
1145
+ throw new CnosKeyNotFoundError(key);
1146
+ }
1147
+ return value;
1148
+ }
1149
+
1150
+ // ../core/src/utils/secretStore.ts
1151
+ var import_node_crypto = require("crypto");
1152
+ var import_promises6 = require("fs/promises");
1153
+ var import_node_path6 = __toESM(require("path"), 1);
1154
+ function isObject(value) {
1155
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1156
+ }
1157
+ function isSecretReference(value) {
1158
+ return isObject(value) && typeof value.provider === "string" && value.provider.trim().length > 0 && typeof value.ref === "string" && value.ref.trim().length > 0 && (value.vault === void 0 && true || typeof value.vault === "string" && value.vault.trim().length > 0) && Object.keys(value).every((key) => ["provider", "ref", "vault"].includes(key));
1159
+ }
1160
+ function resolveSecretStoreRoot(processEnv = process.env) {
1161
+ return import_node_path6.default.resolve(expandHomePath(processEnv.CNOS_SECRET_HOME ?? "~/.cnos/secrets"));
1162
+ }
1163
+ function resolveSecretStoreFile(storeRoot, ref, vault = "default") {
1164
+ return import_node_path6.default.join(storeRoot, "vaults", vault, "store", ...ref.split("/")).concat(".json");
1165
+ }
1166
+ function deriveKey(passphrase, salt) {
1167
+ return (0, import_node_crypto.scryptSync)(passphrase, salt, 32);
1168
+ }
1169
+ function resolveSecretPassphrase(vault = "default", processEnv = process.env) {
1170
+ const vaultToken = vault.replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase();
1171
+ return processEnv[`CNOS_SECRET_PASSPHRASE_${vaultToken}`] ?? processEnv.CNOS_SECRET_PASSPHRASE;
1172
+ }
1173
+ function decryptDocument(document, passphrase) {
1174
+ const salt = Buffer.from(document.salt, "base64");
1175
+ const iv = Buffer.from(document.iv, "base64");
1176
+ const tag = Buffer.from(document.tag, "base64");
1177
+ const ciphertext = Buffer.from(document.ciphertext, "base64");
1178
+ const key = deriveKey(passphrase, salt);
1179
+ const decipher = (0, import_node_crypto.createDecipheriv)("aes-256-gcm", key, iv);
1180
+ decipher.setAuthTag(tag);
1181
+ const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
1182
+ return plaintext.toString("utf8");
1183
+ }
1184
+ async function readLocalSecret(storeRoot, ref, passphrase, vault = "default") {
1185
+ if (!passphrase) {
1186
+ throw new CnosManifestError(
1187
+ `Missing CNOS secret passphrase for local secret ref "${ref}". Set CNOS_SECRET_PASSPHRASE or pass processEnv explicitly.`
1188
+ );
1189
+ }
1190
+ const filePath = resolveSecretStoreFile(storeRoot, ref, vault);
1191
+ const source = await (0, import_promises6.readFile)(filePath, "utf8");
1192
+ const document = JSON.parse(source);
1193
+ if (document.version !== 1 || document.algorithm !== "aes-256-gcm" || typeof document.salt !== "string" || typeof document.iv !== "string" || typeof document.tag !== "string" || typeof document.ciphertext !== "string") {
1194
+ throw new CnosManifestError("Invalid local secret document", filePath);
1195
+ }
1196
+ return decryptDocument(document, passphrase);
1197
+ }
1198
+
1199
+ // ../core/src/runtime/toEnv.ts
1200
+ function normalizeEnvValue(value) {
1201
+ if (value === void 0 || value === null) {
1202
+ return "";
1203
+ }
1204
+ if (typeof value === "string") {
1205
+ return value;
1206
+ }
1207
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
1208
+ return String(value);
1209
+ }
1210
+ return JSON.stringify(value);
1211
+ }
1212
+ function toEnv(graph, manifest, options = {}) {
1213
+ const includeSecrets = options.includeSecrets ?? true;
1214
+ const output = {};
1215
+ const mappedEntries = Object.entries(manifest.envMapping.explicit).sort(
1216
+ ([left], [right]) => left.localeCompare(right)
1217
+ );
1218
+ for (const [envVar, logicalKey] of mappedEntries) {
1219
+ const entry = graph.entries.get(logicalKey);
1220
+ if (!entry) {
1221
+ continue;
1222
+ }
1223
+ const namespaceDefinition = getNamespaceDefinition(manifest, entry.namespace);
1224
+ if (namespaceDefinition.kind !== "data" || !namespaceDefinition.shareable || namespaceDefinition.sensitive) {
1225
+ continue;
1226
+ }
1227
+ if (entry.namespace === "secret" && !includeSecrets) {
1228
+ continue;
1229
+ }
1230
+ if (isSecretReference(entry.value)) {
1231
+ continue;
1232
+ }
1233
+ output[envVar] = normalizeEnvValue(entry.value);
1234
+ }
1235
+ return output;
1236
+ }
1237
+
1238
+ // ../core/src/runtime/toPublicEnv.ts
1239
+ function fallbackPublicEnvVar(valuePath) {
1240
+ return valuePath.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "").toUpperCase();
1241
+ }
1242
+ function normalizeEnvValue2(value) {
1243
+ if (value === void 0 || value === null) {
1244
+ return "";
1245
+ }
1246
+ if (typeof value === "string") {
1247
+ return value;
1248
+ }
1249
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
1250
+ return String(value);
1251
+ }
1252
+ return JSON.stringify(value);
1253
+ }
1254
+ function resolvePublicPrefix(manifest, options) {
1255
+ if (options.prefix) {
1256
+ return options.prefix;
1257
+ }
1258
+ if (!options.framework) {
1259
+ return "";
1260
+ }
1261
+ const configuredPrefix = manifest.public.frameworks[options.framework];
1262
+ if (!configuredPrefix) {
1263
+ throw new CnosManifestError(`Unknown public framework prefix: ${options.framework}`);
1264
+ }
1265
+ return configuredPrefix;
1266
+ }
1267
+ function toPublicEnv(graph, manifest, options = {}) {
1268
+ const prefix = resolvePublicPrefix(manifest, options);
1269
+ const output = {};
1270
+ const promotions = Array.from(graph.entries.values()).filter((entry) => entry.namespace === "public").sort((left, right) => left.key.localeCompare(right.key));
1271
+ for (const resolved of promotions) {
1272
+ const baseEnvVar = fallbackPublicEnvVar(stripNamespace(resolved.key));
1273
+ const envVar = prefix && !baseEnvVar.startsWith(prefix) ? `${prefix}${baseEnvVar}` : baseEnvVar;
1274
+ output[envVar] = normalizeEnvValue2(resolved.value);
1275
+ }
1276
+ return output;
1277
+ }
1278
+
1279
+ // ../core/src/orchestrator/runtime.ts
1280
+ function createRuntime(manifest, graph, plugins = []) {
1281
+ return {
1282
+ manifest,
1283
+ plugins,
1284
+ graph,
1285
+ read(key) {
1286
+ return readValue(graph, key);
1287
+ },
1288
+ require(key) {
1289
+ return requireValue(graph, key);
1290
+ },
1291
+ readOr(key, fallback) {
1292
+ return readOrValue(graph, key, fallback);
1293
+ },
1294
+ value(path10) {
1295
+ return readValue(graph, toLogicalKey("value", path10));
1296
+ },
1297
+ secret(path10) {
1298
+ return readValue(graph, toLogicalKey("secret", path10));
1299
+ },
1300
+ meta(path10) {
1301
+ return readValue(graph, toLogicalKey("meta", path10));
1302
+ },
1303
+ inspect(key) {
1304
+ return inspectValue(graph, key);
1305
+ },
1306
+ toObject() {
1307
+ return toNamespaceObject(graph);
1308
+ },
1309
+ toNamespace(namespace) {
1310
+ return toNamespaceObject(graph, namespace);
1311
+ },
1312
+ toEnv(options) {
1313
+ return toEnv(graph, manifest, options);
1314
+ },
1315
+ toPublicEnv(options) {
1316
+ return toPublicEnv(graph, manifest, options);
1317
+ }
1318
+ };
1319
+ }
1320
+
1321
+ // ../core/src/orchestrator/createCnos.ts
1322
+ function buildMetaEntries(graph, cnosVersion) {
1323
+ return [
1324
+ {
1325
+ key: "meta.profile",
1326
+ value: graph.profile,
1327
+ namespace: "meta",
1328
+ sourceId: "profile-resolver",
1329
+ pluginId: "core",
1330
+ workspaceId: graph.workspace.workspaceId
1331
+ },
1332
+ {
1333
+ key: "meta.cnos.version",
1334
+ value: cnosVersion ?? "0.0.0-dev",
1335
+ namespace: "meta",
1336
+ sourceId: "core",
1337
+ pluginId: "core",
1338
+ workspaceId: graph.workspace.workspaceId
1339
+ },
1340
+ {
1341
+ key: "meta.resolved.at",
1342
+ value: graph.resolvedAt,
1343
+ namespace: "meta",
1344
+ sourceId: "core",
1345
+ pluginId: "core",
1346
+ workspaceId: graph.workspace.workspaceId
1347
+ },
1348
+ {
1349
+ key: "meta.resolved.from",
1350
+ value: graph.profileSource,
1351
+ namespace: "meta",
1352
+ sourceId: "profile-resolver",
1353
+ pluginId: "core",
1354
+ workspaceId: graph.workspace.workspaceId
1355
+ },
1356
+ {
1357
+ key: "meta.workspace",
1358
+ value: graph.workspace.workspaceId,
1359
+ namespace: "meta",
1360
+ sourceId: "workspace-resolver",
1361
+ pluginId: "core",
1362
+ workspaceId: graph.workspace.workspaceId
1363
+ },
1364
+ {
1365
+ key: "meta.workspace.source",
1366
+ value: graph.workspace.workspaceSource,
1367
+ namespace: "meta",
1368
+ sourceId: "workspace-resolver",
1369
+ pluginId: "core",
1370
+ workspaceId: graph.workspace.workspaceId
1371
+ },
1372
+ {
1373
+ key: "meta.workspace.chain",
1374
+ value: graph.workspace.workspaceChain,
1375
+ namespace: "meta",
1376
+ sourceId: "workspace-resolver",
1377
+ pluginId: "core",
1378
+ workspaceId: graph.workspace.workspaceId
1379
+ },
1380
+ {
1381
+ key: "meta.globalRoot",
1382
+ value: graph.workspace.globalRoot ?? null,
1383
+ namespace: "meta",
1384
+ sourceId: "workspace-resolver",
1385
+ pluginId: "core",
1386
+ workspaceId: graph.workspace.workspaceId
1387
+ },
1388
+ {
1389
+ key: "meta.global.enabled",
1390
+ value: Boolean(graph.workspace.globalRoot),
1391
+ namespace: "meta",
1392
+ sourceId: "workspace-resolver",
1393
+ pluginId: "core",
1394
+ workspaceId: graph.workspace.workspaceId
1395
+ }
1396
+ ];
1397
+ }
1398
+ function appendMetaEntries(graph, cnosVersion) {
1399
+ const nextEntries = new Map(graph.entries);
1400
+ for (const entry of buildMetaEntries(graph, cnosVersion)) {
1401
+ nextEntries.set(entry.key, {
1402
+ key: entry.key,
1403
+ value: entry.value,
1404
+ namespace: entry.namespace,
1405
+ winner: entry,
1406
+ overridden: []
1407
+ });
1408
+ }
1409
+ return {
1410
+ ...graph,
1411
+ entries: nextEntries
1412
+ };
1413
+ }
1414
+ async function createCnos(options = {}) {
1415
+ const loadedManifest = await loadManifest(options.root ? { root: options.root } : {});
1416
+ for (const key of loadedManifest.manifest.public.promote) {
1417
+ ensureProjectionAllowed(loadedManifest.manifest, key, "public");
1418
+ }
1419
+ const workspaceFile = await loadWorkspaceFile(loadedManifest.repoRoot);
1420
+ const workspace = await resolveWorkspaceContext(loadedManifest.manifest, {
1421
+ manifestRoot: loadedManifest.manifestRoot,
1422
+ ...workspaceFile ? { workspaceFile: workspaceFile.config } : {},
1423
+ ...options.workspace ? { workspace: options.workspace } : {},
1424
+ ...options.globalRoot ? { globalRoot: options.globalRoot } : {},
1425
+ ...options.processEnv ? { processEnv: options.processEnv } : {}
1426
+ });
1427
+ const activeProfile = resolveActiveProfile(loadedManifest.manifest, {
1428
+ ...options.profile ? { profile: options.profile } : {},
1429
+ ...workspaceFile ? { workspaceFile: workspaceFile.config } : {},
1430
+ ...options.processEnv ? { processEnv: options.processEnv } : {}
1431
+ });
1432
+ const profileChain = await expandProfileChain(activeProfile.profile, {
1433
+ manifestRoot: loadedManifest.manifestRoot,
1434
+ workspace
1435
+ });
1436
+ const plugins = options.plugins ?? [];
1437
+ const loaderPlugins = plugins.filter((plugin) => plugin.kind === "loader");
1438
+ const resolverPlugin = plugins.find((plugin) => plugin.kind === "resolver") ?? createProfileAwareResolver();
1439
+ const entries = await runPipeline({
1440
+ manifestRoot: loadedManifest.manifestRoot,
1441
+ manifest: loadedManifest.manifest,
1442
+ profile: activeProfile.profile,
1443
+ profileChain: profileChain.profiles,
1444
+ profileActivation: profileChain.activation,
1445
+ workspace,
1446
+ plugins: loaderPlugins,
1447
+ ...options.cliArgs ? { cliArgs: options.cliArgs } : {},
1448
+ ...options.processEnv ? { processEnv: options.processEnv } : {}
1449
+ });
1450
+ const graph = await resolverPlugin.resolve(entries, {
1451
+ manifest: loadedManifest.manifest,
1452
+ profile: activeProfile.profile,
1453
+ profileChain: profileChain.profiles,
1454
+ precedenceOrder: loadedManifest.manifest.resolution.precedence,
1455
+ workspace
1456
+ });
1457
+ const schemaApplied = applySchemaRules(graph, loadedManifest.manifest.schema);
1458
+ const promotedGraph = promoteToPublic(schemaApplied.graph, loadedManifest.manifest);
1459
+ return createRuntime(
1460
+ loadedManifest.manifest,
1461
+ appendMetaEntries({
1462
+ ...promotedGraph,
1463
+ profileSource: activeProfile.source
1464
+ }, options.cnosVersion),
1465
+ plugins
1466
+ );
1467
+ }
1468
+
1469
+ // ../core/src/runtime/dump.ts
1470
+ var import_promises7 = require("fs/promises");
1471
+ var import_node_path7 = __toESM(require("path"), 1);
1472
+
1473
+ // ../core/src/utils/envNaming.ts
1474
+ function normalizeMappingConfig(config = {}) {
1475
+ return {
1476
+ convention: config.convention,
1477
+ explicit: config.explicit ?? {}
1478
+ };
1479
+ }
1480
+ function fromScreamingSnake(path10) {
1481
+ return path10.split("_").map((segment) => segment.trim().toLowerCase()).filter(Boolean).join(".");
1482
+ }
1483
+ function envVarToLogicalKey(envVar, config = {}) {
1484
+ const normalized = normalizeMappingConfig(config);
1485
+ const explicitMatch = normalized.explicit[envVar];
1486
+ if (explicitMatch) {
1487
+ return explicitMatch;
1488
+ }
1489
+ if (normalized.convention !== "SCREAMING_SNAKE") {
1490
+ return void 0;
1491
+ }
1492
+ if (envVar.startsWith("SECRET_")) {
1493
+ const stripped = envVar.slice("SECRET_".length);
1494
+ if (!stripped) {
1495
+ return void 0;
1496
+ }
1497
+ return `secret.${fromScreamingSnake(stripped)}`;
1498
+ }
1499
+ if (!/^[A-Z][A-Z0-9_]*$/.test(envVar)) {
1500
+ return void 0;
1501
+ }
1502
+ return `value.${fromScreamingSnake(envVar)}`;
1503
+ }
1504
+
1505
+ // package.json
1506
+ var package_default = {
1507
+ name: "@kitsy/cnos",
1508
+ version: "1.2.0",
1509
+ description: "Batteries-included CNOS runtime package wired with the official plugins.",
1510
+ type: "module",
1511
+ main: "./dist/index.cjs",
1512
+ module: "./dist/index.js",
1513
+ types: "./dist/index.d.ts",
1514
+ exports: {
1515
+ ".": {
1516
+ types: "./dist/index.d.ts",
1517
+ import: "./dist/index.js",
1518
+ require: "./dist/index.cjs"
1519
+ },
1520
+ "./internal": {
1521
+ types: "./dist/internal.d.ts",
1522
+ import: "./dist/internal.js",
1523
+ require: "./dist/internal.cjs"
1524
+ },
1525
+ "./runtime": {
1526
+ types: "./dist/runtime/index.d.ts",
1527
+ import: "./dist/runtime/index.js",
1528
+ require: "./dist/runtime/index.cjs"
1529
+ },
1530
+ "./browser": {
1531
+ types: "./dist/browser/index.d.ts",
1532
+ import: "./dist/browser/index.js",
1533
+ require: "./dist/browser/index.cjs"
1534
+ },
1535
+ "./build": {
1536
+ types: "./dist/build/index.d.ts",
1537
+ import: "./dist/build/index.js",
1538
+ require: "./dist/build/index.cjs"
1539
+ },
1540
+ "./plugins/filesystem": {
1541
+ types: "./dist/plugin/filesystem.d.ts",
1542
+ import: "./dist/plugin/filesystem.js",
1543
+ require: "./dist/plugin/filesystem.cjs"
1544
+ },
1545
+ "./plugins/dotenv": {
1546
+ types: "./dist/plugin/dotenv.d.ts",
1547
+ import: "./dist/plugin/dotenv.js",
1548
+ require: "./dist/plugin/dotenv.cjs"
1549
+ },
1550
+ "./plugins/process-env": {
1551
+ types: "./dist/plugin/process-env.d.ts",
1552
+ import: "./dist/plugin/process-env.js",
1553
+ require: "./dist/plugin/process-env.cjs"
1554
+ },
1555
+ "./plugins/cli-args": {
1556
+ types: "./dist/plugin/cli-args.d.ts",
1557
+ import: "./dist/plugin/cli-args.js",
1558
+ require: "./dist/plugin/cli-args.cjs"
1559
+ },
1560
+ "./plugins/basic-schema": {
1561
+ types: "./dist/plugin/basic-schema.d.ts",
1562
+ import: "./dist/plugin/basic-schema.js",
1563
+ require: "./dist/plugin/basic-schema.cjs"
1564
+ },
1565
+ "./plugins/env-export": {
1566
+ types: "./dist/plugin/env-export.d.ts",
1567
+ import: "./dist/plugin/env-export.js",
1568
+ require: "./dist/plugin/env-export.cjs"
1569
+ }
1570
+ },
1571
+ files: [
1572
+ "dist"
1573
+ ],
1574
+ license: "MIT",
1575
+ repository: {
1576
+ type: "git",
1577
+ url: "https://github.com/kitsyai/cnos.git",
1578
+ directory: "packages/cnos"
1579
+ },
1580
+ homepage: "https://github.com/kitsyai/cnos/tree/main/packages/cnos",
1581
+ bugs: {
1582
+ url: "https://github.com/kitsyai/cnos/issues"
1583
+ },
1584
+ keywords: [
1585
+ "cnos",
1586
+ "config",
1587
+ "runtime"
1588
+ ],
1589
+ publishConfig: {
1590
+ access: "public"
1591
+ },
1592
+ dependencies: {
1593
+ yaml: "^2.8.3"
1594
+ },
1595
+ scripts: {
1596
+ build: "rimraf dist && tsup --config tsup.config.ts",
1597
+ clean: "rimraf dist",
1598
+ dev: "tsup --config tsup.config.ts --watch",
1599
+ lint: "eslint src test",
1600
+ prepack: "pnpm build",
1601
+ test: "vitest run",
1602
+ typecheck: "tsc -p tsconfig.json --noEmit"
1603
+ }
1604
+ };
1605
+
1606
+ // ../../plugins/basic-schema/src/index.ts
1607
+ function createBasicSchemaPlugin() {
1608
+ return {
1609
+ id: "@kitsy/cnos/plugins/basic-schema",
1610
+ kind: "validator",
1611
+ async validate(graph, context) {
1612
+ const result = applySchemaRules(graph, context.schema ?? {});
1613
+ return {
1614
+ pluginId: "@kitsy/cnos/plugins/basic-schema",
1615
+ valid: result.issues.length === 0,
1616
+ issues: result.issues
1617
+ };
1618
+ }
1619
+ };
1620
+ }
1621
+
1622
+ // ../../plugins/cli-args/src/index.ts
1623
+ var CLI_ARGS_PLUGIN_ID = "@kitsy/cnos/plugins/cli-args";
1624
+ function isNamespaceName(value) {
1625
+ return value === "value" || value === "secret";
1626
+ }
1627
+ function parseCliArgs(args) {
1628
+ const parsed = [];
1629
+ for (let index = 0; index < args.length; index += 1) {
1630
+ const arg = args[index];
1631
+ if (!arg?.startsWith("--")) {
1632
+ continue;
1633
+ }
1634
+ if (arg === "--profile") {
1635
+ index += 1;
1636
+ continue;
1637
+ }
1638
+ if (arg.startsWith("--profile=")) {
1639
+ continue;
1640
+ }
1641
+ const body = arg.slice(2);
1642
+ const separatorIndex = body.indexOf("=");
1643
+ if (separatorIndex >= 0) {
1644
+ parsed.push({
1645
+ key: body.slice(0, separatorIndex),
1646
+ value: body.slice(separatorIndex + 1),
1647
+ raw: arg
1648
+ });
1649
+ continue;
1650
+ }
1651
+ const nextValue = args[index + 1];
1652
+ if (nextValue && !nextValue.startsWith("--")) {
1653
+ parsed.push({
1654
+ key: body,
1655
+ value: nextValue,
1656
+ raw: `${arg} ${nextValue}`
1657
+ });
1658
+ index += 1;
1659
+ }
1660
+ }
1661
+ return parsed;
1662
+ }
1663
+ function cliArgEntriesFromArgs(args, workspaceId = "default") {
1664
+ return parseCliArgs(args).flatMap(({ key, value, raw }) => {
1665
+ const [candidateNamespace = "", ...pathSegments] = key.split(".");
1666
+ if (!isNamespaceName(candidateNamespace) || pathSegments.length === 0) {
1667
+ return [];
1668
+ }
1669
+ const namespace = candidateNamespace;
1670
+ const logicalKey = `${namespace}.${joinConfigPath(pathSegments.join("."))}`;
1671
+ return [
1672
+ {
1673
+ key: logicalKey,
1674
+ value,
1675
+ namespace,
1676
+ sourceId: "cli-args",
1677
+ pluginId: CLI_ARGS_PLUGIN_ID,
1678
+ workspaceId,
1679
+ origin: {
1680
+ cliArg: raw
1681
+ }
1682
+ }
1683
+ ];
1684
+ });
1685
+ }
1686
+ function createCliArgsPlugin() {
1687
+ return {
1688
+ id: "cli-args",
1689
+ kind: "loader",
1690
+ async load(context) {
1691
+ return cliArgEntriesFromArgs(context.cliArgs ?? [], context.workspace.workspaceId);
1692
+ }
1693
+ };
1694
+ }
1695
+
1696
+ // ../../plugins/dotenv/src/index.ts
1697
+ var import_promises8 = require("fs/promises");
1698
+ var import_node_path8 = __toESM(require("path"), 1);
1699
+ var DOTENV_PLUGIN_ID = "@kitsy/cnos/plugins/dotenv";
1700
+ function parseDoubleQuoted(value) {
1701
+ return value.replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, " ").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
1702
+ }
1703
+ function parseDotenv(document) {
1704
+ const parsed = {};
1705
+ for (const rawLine of document.split(/\r?\n/)) {
1706
+ const line = rawLine.trim();
1707
+ if (!line || line.startsWith("#")) {
1708
+ continue;
1709
+ }
1710
+ const withoutExport = line.startsWith("export ") ? line.slice("export ".length).trim() : line;
1711
+ const separatorIndex = withoutExport.indexOf("=");
1712
+ if (separatorIndex <= 0) {
1713
+ continue;
1714
+ }
1715
+ const envVar = withoutExport.slice(0, separatorIndex).trim();
1716
+ let value = withoutExport.slice(separatorIndex + 1).trim();
1717
+ if (!envVar) {
1718
+ continue;
1719
+ }
1720
+ if (value.startsWith('"') && value.endsWith('"')) {
1721
+ value = parseDoubleQuoted(value.slice(1, -1));
1722
+ } else if (value.startsWith("'") && value.endsWith("'")) {
1723
+ value = value.slice(1, -1);
1724
+ } else {
1725
+ value = value.replace(/\s+#.*$/, "").trim();
1726
+ }
1727
+ parsed[envVar] = value;
1728
+ }
1729
+ return parsed;
1730
+ }
1731
+ function dotenvEntriesFromObject(values, mapping = {}, originFile, workspaceId = "default") {
1732
+ return Object.entries(values).flatMap(([envVar, value]) => {
1733
+ const logicalKey = envVarToLogicalKey(envVar, mapping);
1734
+ if (!logicalKey) {
1735
+ return [];
1736
+ }
1737
+ return [
1738
+ {
1739
+ key: logicalKey,
1740
+ value,
1741
+ namespace: logicalKey.startsWith("secret.") ? "secret" : "value",
1742
+ sourceId: "dotenv",
1743
+ pluginId: DOTENV_PLUGIN_ID,
1744
+ workspaceId,
1745
+ origin: {
1746
+ envVar,
1747
+ ...originFile ? { file: originFile } : {}
1748
+ }
1749
+ }
1750
+ ];
1751
+ });
1752
+ }
1753
+ async function readIfPresent(filePath) {
1754
+ try {
1755
+ return await (0, import_promises8.readFile)(filePath, "utf8");
1756
+ } catch {
1757
+ return void 0;
1758
+ }
1759
+ }
1760
+ function createDotenvPlugin() {
1761
+ return {
1762
+ id: "dotenv",
1763
+ kind: "loader",
1764
+ async load(context) {
1765
+ const config = context.manifestConfig;
1766
+ const rootTemplate = config.root ?? "./env";
1767
+ const fileNames = context.profileActivation.envFiles;
1768
+ const entries = [];
1769
+ for (const workspaceRoot of context.workspace.workspaceRoots) {
1770
+ const envRoot = resolveWorkspaceScopedPath(workspaceRoot.path, rootTemplate, {
1771
+ workspace: workspaceRoot.workspaceId
1772
+ });
1773
+ for (const fileName of fileNames) {
1774
+ const absolutePath = import_node_path8.default.join(envRoot, fileName);
1775
+ const document = await readIfPresent(absolutePath);
1776
+ if (!document) {
1777
+ continue;
1778
+ }
1779
+ entries.push(
1780
+ ...dotenvEntriesFromObject(
1781
+ parseDotenv(document),
1782
+ config.envMapping,
1783
+ toPortablePath(import_node_path8.default.relative(import_node_path8.default.dirname(context.manifestRoot), absolutePath)),
1784
+ workspaceRoot.workspaceId
1785
+ )
1786
+ );
1787
+ }
1788
+ }
1789
+ return entries;
1790
+ }
1791
+ };
1792
+ }
1793
+
1794
+ // ../../plugins/env-export/src/index.ts
1795
+ function createEnvExportPlugin() {
1796
+ return {
1797
+ id: "@kitsy/cnos/plugins/env-export",
1798
+ kind: "exporter",
1799
+ async export(graph, context) {
1800
+ return {
1801
+ pluginId: "@kitsy/cnos/plugins/env-export",
1802
+ value: toEnv(graph, context.manifest)
1803
+ };
1804
+ }
1805
+ };
1806
+ }
1807
+ function createPublicEnvExportPlugin() {
1808
+ return {
1809
+ id: "@kitsy/cnos/plugins/public-env-export",
1810
+ kind: "exporter",
1811
+ async export(graph, context) {
1812
+ return {
1813
+ pluginId: "@kitsy/cnos/plugins/public-env-export",
1814
+ value: toPublicEnv(graph, context.manifest)
1815
+ };
1816
+ }
1817
+ };
1818
+ }
1819
+
1820
+ // ../../plugins/filesystem/src/filesystemSecretsReader.ts
1821
+ var import_promises10 = require("fs/promises");
1822
+
1823
+ // ../../plugins/filesystem/src/helpers.ts
1824
+ var import_promises9 = require("fs/promises");
1825
+ var import_node_path9 = __toESM(require("path"), 1);
1826
+ var YAML_EXTENSIONS = /* @__PURE__ */ new Set([".yml", ".yaml"]);
1827
+ var FILESYSTEM_PLUGIN_ID = "@kitsy/cnos/plugins/filesystem";
1828
+ async function existsDirectory(targetPath) {
1829
+ try {
1830
+ const stat = await (0, import_promises9.readdir)(targetPath);
1831
+ void stat;
1832
+ return true;
1833
+ } catch {
1834
+ return false;
1835
+ }
1836
+ }
1837
+ async function collectYamlFiles(root) {
1838
+ const entries = await (0, import_promises9.readdir)(root, { withFileTypes: true });
1839
+ const results = [];
1840
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
1841
+ const absolutePath = import_node_path9.default.join(root, entry.name);
1842
+ if (entry.isDirectory()) {
1843
+ results.push(...await collectYamlFiles(absolutePath));
1844
+ continue;
1845
+ }
1846
+ if (entry.isFile() && YAML_EXTENSIONS.has(import_node_path9.default.extname(entry.name).toLowerCase())) {
1847
+ results.push(absolutePath);
1848
+ }
1849
+ }
1850
+ return results;
1851
+ }
1852
+ async function collectFilesystemLayerFiles(manifestRoot, workspaceRoots, sourceRoot, activeLayers) {
1853
+ const files = [];
1854
+ const repoRoot = import_node_path9.default.dirname(manifestRoot);
1855
+ for (const workspaceRoot of workspaceRoots) {
1856
+ const resolvedRoot = import_node_path9.default.resolve(workspaceRoot.path, sourceRoot);
1857
+ for (const layer of activeLayers) {
1858
+ const layerRoot = import_node_path9.default.join(resolvedRoot, layer);
1859
+ if (!await existsDirectory(layerRoot)) {
1860
+ continue;
1861
+ }
1862
+ for (const absolutePath of await collectYamlFiles(layerRoot)) {
1863
+ const relativePath = import_node_path9.default.relative(repoRoot, absolutePath);
1864
+ files.push({
1865
+ absolutePath,
1866
+ relativePath: toPortablePath(relativePath.startsWith("..") ? absolutePath : relativePath),
1867
+ workspaceId: workspaceRoot.workspaceId
1868
+ });
1869
+ }
1870
+ }
1871
+ }
1872
+ return files;
1873
+ }
1874
+ function assertObjectDocument(value, filePath) {
1875
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1876
+ throw new CnosManifestError("Filesystem loader expected a YAML object document", filePath);
1877
+ }
1878
+ return value;
1879
+ }
1880
+ function flattenConfigObject(value, options = {}, prefix = "") {
1881
+ return Object.entries(value).reduce((accumulator, [key, nestedValue]) => {
1882
+ const nextKey = prefix ? `${prefix}.${key}` : key;
1883
+ if (nestedValue && typeof nestedValue === "object" && !Array.isArray(nestedValue) && !options.stopAtLeaf?.(nestedValue)) {
1884
+ Object.assign(
1885
+ accumulator,
1886
+ flattenConfigObject(nestedValue, options, nextKey)
1887
+ );
1888
+ return accumulator;
1889
+ }
1890
+ accumulator[nextKey] = nestedValue;
1891
+ return accumulator;
1892
+ }, {});
1893
+ }
1894
+ function yamlObjectToEntries(document, filePath, namespace, sourceId, workspaceId = "default") {
1895
+ const parsed = assertObjectDocument(parseYaml(document), filePath);
1896
+ const flattened = flattenConfigObject(parsed, {
1897
+ ...namespace === "secret" ? {
1898
+ stopAtLeaf: isSecretReference
1899
+ } : {}
1900
+ });
1901
+ return Object.entries(flattened).map(([key, value]) => ({
1902
+ key: `${namespace}.${key}`,
1903
+ value,
1904
+ namespace,
1905
+ sourceId,
1906
+ pluginId: FILESYSTEM_PLUGIN_ID,
1907
+ workspaceId,
1908
+ origin: {
1909
+ file: filePath
1910
+ }
1911
+ }));
1912
+ }
1913
+ async function resolveSecretValue(value, processEnv) {
1914
+ if (!isSecretReference(value)) {
1915
+ return value;
1916
+ }
1917
+ if (value.provider === "local") {
1918
+ const passphrase = resolveSecretPassphrase(value.vault, processEnv);
1919
+ if (!passphrase) {
1920
+ return value;
1921
+ }
1922
+ return readLocalSecret(
1923
+ resolveSecretStoreRoot(processEnv),
1924
+ value.ref,
1925
+ passphrase,
1926
+ value.vault
1927
+ );
1928
+ }
1929
+ if (value.provider === "env" || value.provider === "github-secrets") {
1930
+ const resolved = processEnv?.[value.ref];
1931
+ if (resolved === void 0) {
1932
+ return value;
1933
+ }
1934
+ return resolved;
1935
+ }
1936
+ return value;
1937
+ }
1938
+ function toSecretReferenceMetadata(value) {
1939
+ if (!isSecretReference(value)) {
1940
+ return void 0;
1941
+ }
1942
+ return {
1943
+ secretRef: value
1944
+ };
1945
+ }
1946
+
1947
+ // ../../plugins/filesystem/src/filesystemSecretsReader.ts
1948
+ function filesystemSecretsReader(filePath, document, workspaceId = "default") {
1949
+ return yamlObjectToEntries(document, filePath, "secret", "filesystem-secrets", workspaceId);
1950
+ }
1951
+ function createFilesystemSecretsPlugin() {
1952
+ return {
1953
+ id: "filesystem-secrets",
1954
+ kind: "loader",
1955
+ async load(context) {
1956
+ const sourceRoot = String(context.manifestConfig.root ?? "./");
1957
+ const files = await collectFilesystemLayerFiles(
1958
+ context.manifestRoot,
1959
+ context.workspace.workspaceRoots,
1960
+ sourceRoot,
1961
+ context.profileActivation.secrets
1962
+ );
1963
+ const entries = [];
1964
+ for (const file of files) {
1965
+ const document = await (0, import_promises10.readFile)(file.absolutePath, "utf8");
1966
+ const fileEntries = filesystemSecretsReader(file.relativePath, document, file.workspaceId);
1967
+ for (const entry of fileEntries) {
1968
+ const metadata = toSecretReferenceMetadata(entry.value);
1969
+ const resolvedValue = await resolveSecretValue(entry.value, context.processEnv);
1970
+ entries.push({
1971
+ ...entry,
1972
+ value: resolvedValue,
1973
+ ...metadata ? { metadata } : {}
1974
+ });
1975
+ }
1976
+ }
1977
+ return entries;
1978
+ }
1979
+ };
1980
+ }
1981
+
1982
+ // ../../plugins/filesystem/src/filesystemValuesReader.ts
1983
+ var import_promises11 = require("fs/promises");
1984
+ function filesystemValuesReader(filePath, document, workspaceId = "default") {
1985
+ return yamlObjectToEntries(document, filePath, "value", "filesystem-values", workspaceId);
1986
+ }
1987
+ function createFilesystemValuesPlugin() {
1988
+ return {
1989
+ id: "filesystem-values",
1990
+ kind: "loader",
1991
+ async load(context) {
1992
+ const sourceRoot = String(context.manifestConfig.root ?? "./");
1993
+ const files = await collectFilesystemLayerFiles(
1994
+ context.manifestRoot,
1995
+ context.workspace.workspaceRoots,
1996
+ sourceRoot,
1997
+ context.profileActivation.values
1998
+ );
1999
+ const entries = [];
2000
+ for (const file of files) {
2001
+ const document = await (0, import_promises11.readFile)(file.absolutePath, "utf8");
2002
+ entries.push(...filesystemValuesReader(file.relativePath, document, file.workspaceId));
2003
+ }
2004
+ return entries;
2005
+ }
2006
+ };
2007
+ }
2008
+
2009
+ // ../../plugins/process-env/src/index.ts
2010
+ var PROCESS_ENV_PLUGIN_ID = "@kitsy/cnos/plugins/process-env";
2011
+ function processEnvEntriesFromObject(env, mapping = {}, workspaceId = "default") {
2012
+ return Object.entries(env).flatMap(([envVar, value]) => {
2013
+ if (typeof value !== "string") {
2014
+ return [];
2015
+ }
2016
+ const logicalKey = envVarToLogicalKey(envVar, mapping);
2017
+ if (!logicalKey) {
2018
+ return [];
2019
+ }
2020
+ return [
2021
+ {
2022
+ key: logicalKey,
2023
+ value,
2024
+ namespace: logicalKey.startsWith("secret.") ? "secret" : "value",
2025
+ sourceId: "process-env",
2026
+ pluginId: PROCESS_ENV_PLUGIN_ID,
2027
+ workspaceId,
2028
+ origin: {
2029
+ envVar
2030
+ }
2031
+ }
2032
+ ];
2033
+ });
2034
+ }
2035
+ function createProcessEnvPlugin() {
2036
+ return {
2037
+ id: "process-env",
2038
+ kind: "loader",
2039
+ async load(context) {
2040
+ const config = context.manifestConfig;
2041
+ return processEnvEntriesFromObject(
2042
+ context.processEnv ?? process.env,
2043
+ config.envMapping,
2044
+ context.workspace.workspaceId
2045
+ );
2046
+ }
2047
+ };
2048
+ }
2049
+
2050
+ // src/defaultPlugins.ts
2051
+ function defaultPlugins() {
2052
+ return [
2053
+ createFilesystemValuesPlugin(),
2054
+ createFilesystemSecretsPlugin(),
2055
+ createDotenvPlugin(),
2056
+ createProcessEnvPlugin(),
2057
+ createCliArgsPlugin(),
2058
+ createBasicSchemaPlugin(),
2059
+ createEnvExportPlugin(),
2060
+ createPublicEnvExportPlugin(),
2061
+ createProvenanceInspector()
2062
+ ];
2063
+ }
2064
+
2065
+ // src/runtime/state.ts
2066
+ var singletonRuntime;
2067
+ var singletonReady;
2068
+ function setSingletonRuntime(runtime) {
2069
+ singletonRuntime = runtime;
2070
+ singletonReady = Promise.resolve(runtime);
2071
+ return runtime;
2072
+ }
2073
+
2074
+ // src/createCnos.ts
2075
+ async function createCnos2(options = {}) {
2076
+ const runtime = await createCnos({
2077
+ ...options,
2078
+ cnosVersion: package_default.version,
2079
+ plugins: [...defaultPlugins(), ...options.plugins ?? []]
2080
+ });
2081
+ setSingletonRuntime(runtime);
2082
+ return runtime;
2083
+ }
2084
+
2085
+ // src/build/index.ts
2086
+ async function resolveBrowserData(options = {}) {
2087
+ const runtime = await createCnos2(options);
2088
+ const browserData = {};
2089
+ for (const [key, entry] of runtime.graph.entries) {
2090
+ if (!key.startsWith("public.")) {
2091
+ continue;
2092
+ }
2093
+ browserData[key] = entry.value;
2094
+ }
2095
+ return browserData;
2096
+ }
2097
+ // Annotate the CommonJS export names for ESM import in node:
2098
+ 0 && (module.exports = {
2099
+ resolveBrowserData
2100
+ });