@habitat-ai/cli 0.5.15 → 0.6.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 (65) hide show
  1. package/README.md +62 -4
  2. package/dist/application-gZ8XAszE.js +80 -0
  3. package/dist/application.js +2 -18
  4. package/dist/cli-hhbbymEz.js +4738 -0
  5. package/dist/cli.js +2 -0
  6. package/dist/command-DkmTpQvc.js +74 -0
  7. package/dist/command.d.ts +36 -35
  8. package/dist/command.js +2 -45
  9. package/dist/generators/cli-command.js +263 -0
  10. package/dist/generators/cli-extension.js +192 -0
  11. package/dist/generators/init.js +20 -20
  12. package/dist/generators/preset.js +8 -7
  13. package/dist/generators/remove-hook.js +7 -4
  14. package/dist/generators/service.js +130 -139
  15. package/dist/habitat.app-Cl-58zQB.js +16615 -0
  16. package/dist/habitat.app.js +2 -0
  17. package/dist/host-BcptPYDL.js +293 -0
  18. package/dist/host.d.ts +57 -0
  19. package/dist/host.js +3 -0
  20. package/dist/index.js +8 -5
  21. package/dist/initialization-BWDg3bks.js +249 -0
  22. package/dist/migrations/0-5-7-repository-foundation.js +42 -38
  23. package/dist/nx-generators-DQDXOkMX.js +44 -0
  24. package/dist/nx-generators.js +2 -51
  25. package/dist/nx-plugin.d.ts +4 -1
  26. package/dist/nx-plugin.js +241 -15
  27. package/dist/oclif-CJS8CHjO.js +11 -0
  28. package/dist/oclif.js +3 -0
  29. package/dist/product-version-Bqc0L8lq.js +18 -0
  30. package/dist/publish-generator-tree-CgFdcykY.js +14 -0
  31. package/dist/repository-preset-DYxxe7p3.js +543 -0
  32. package/dist/verified-writes-Cne-zTxS.js +60 -0
  33. package/generators/cli-command/schema.json +20 -0
  34. package/generators/cli-extension/schema.json +20 -0
  35. package/generators/service/files/AGENTS.md.template +2 -2
  36. package/generators/service/files/habitat.toml.template +1 -1
  37. package/generators.json +10 -0
  38. package/oclif.manifest.json +1094 -27
  39. package/package.json +72 -8
  40. package/dist/application.d.ts +0 -14
  41. package/dist/commands/check.d.ts +0 -15
  42. package/dist/commands/check.js +0 -32
  43. package/dist/commands/hook.d.ts +0 -12
  44. package/dist/commands/hook.js +0 -25
  45. package/dist/commands/resolve.d.ts +0 -9
  46. package/dist/commands/resolve.js +0 -15
  47. package/dist/generators/init.d.ts +0 -3
  48. package/dist/generators/preset.d.ts +0 -4
  49. package/dist/generators/remove-hook.d.ts +0 -3
  50. package/dist/generators/service.d.ts +0 -16
  51. package/dist/index.d.ts +0 -1
  52. package/dist/lib/binding.d.ts +0 -10
  53. package/dist/lib/binding.js +0 -16
  54. package/dist/lib/output.d.ts +0 -9
  55. package/dist/lib/output.js +0 -22
  56. package/dist/migrations/0-5-7-repository-foundation.d.ts +0 -3
  57. package/dist/nx/initialization.d.ts +0 -62
  58. package/dist/nx/initialization.js +0 -265
  59. package/dist/nx/projection.d.ts +0 -29
  60. package/dist/nx/projection.js +0 -308
  61. package/dist/nx/repository-preset.d.ts +0 -22
  62. package/dist/nx/repository-preset.js +0 -596
  63. package/dist/nx-generators.d.ts +0 -42
  64. package/dist/product-version.d.ts +0 -2
  65. package/dist/product-version.js +0 -15
@@ -1,265 +0,0 @@
1
- import { isDeepStrictEqual } from "node:util";
2
- import { readJson, readNxJson, updateNxJson, writeJson, } from "@nx/devkit";
3
- import { Type } from "typebox";
4
- import { Validator } from "typebox/schema";
5
- const NX_CONFIG_PATH = "nx.json";
6
- const PACKAGE_PATH = "package.json";
7
- const CODEX_HOOKS_PATH = ".codex/hooks.json";
8
- const HabitatHookMarkerSchema = Type.Object({
9
- identity: Type.String({
10
- minLength: 1,
11
- description: "Stable package-owned identity for one Habitat hook contribution.",
12
- }),
13
- revision: Type.Integer({
14
- minimum: 0,
15
- description: "Monotonic payload revision for the named Habitat contribution.",
16
- }),
17
- }, { additionalProperties: false, description: "Habitat hook ownership marker." });
18
- const HookGroupSchema = Type.Object({
19
- _habitat: Type.Optional(HabitatHookMarkerSchema),
20
- hooks: Type.Array(Type.Unknown(), {
21
- description: "Ordered command contributions in one Codex hook group.",
22
- }),
23
- }, { additionalProperties: true, description: "One consumer-owned Codex hook group." });
24
- const HabitatHookCommandSchema = Type.Object({
25
- type: Type.Literal("command", {
26
- description: "Codex hook handler kind owned by the Habitat initializer.",
27
- }),
28
- command: Type.String({
29
- minLength: 1,
30
- description: "Installed Habitat command executed by the Codex hook.",
31
- }),
32
- statusMessage: Type.String({
33
- minLength: 1,
34
- description: "Operator-facing status rendered while Habitat checks run.",
35
- }),
36
- timeout: Type.Integer({
37
- minimum: 1,
38
- description: "Maximum seconds allowed for the Habitat hook command.",
39
- }),
40
- }, { additionalProperties: false, description: "One Habitat-owned Codex hook command." });
41
- const HabitatOwnedHookGroupSchema = Type.Object({
42
- _habitat: HabitatHookMarkerSchema,
43
- hooks: Type.Array(HabitatHookCommandSchema, {
44
- minItems: 1,
45
- description: "Commands contributed by the installed Habitat package.",
46
- }),
47
- }, { additionalProperties: false, description: "The named Habitat Codex hook contribution." });
48
- const CodexHooksSchema = Type.Object({
49
- hooks: Type.Optional(Type.Record(Type.String(), Type.Array(HookGroupSchema), {
50
- description: "Ordered hook groups keyed by Codex event identity.",
51
- })),
52
- }, { additionalProperties: true, description: "Consumer-owned Codex hook configuration." });
53
- const ConsumerPackageSchema = Type.Object({
54
- dependencies: Type.Optional(Type.Record(Type.String(), Type.String(), {
55
- description: "Runtime dependencies installed directly in the Nx consumer.",
56
- })),
57
- scripts: Type.Optional(Type.Record(Type.String(), Type.String(), {
58
- description: "Consumer-owned package lifecycle and command scripts.",
59
- })),
60
- devDependencies: Type.Optional(Type.Record(Type.String(), Type.String(), {
61
- description: "Development tools installed directly in the Nx consumer.",
62
- })),
63
- optionalDependencies: Type.Optional(Type.Record(Type.String(), Type.String(), {
64
- description: "Optional runtime dependencies installed in the Nx consumer.",
65
- })),
66
- peerDependencies: Type.Optional(Type.Record(Type.String(), Type.String(), {
67
- description: "Peer dependency contracts declared by the Nx consumer.",
68
- })),
69
- trustedDependencies: Type.Optional(Type.Array(Type.String({ minLength: 1 }), {
70
- description: "Package lifecycle scripts explicitly trusted by the Bun consumer.",
71
- })),
72
- }, { additionalProperties: true, description: "Nx consumer package metadata." });
73
- const hooksValidator = new Validator({}, CodexHooksSchema);
74
- const packageValidator = new Validator({}, ConsumerPackageSchema);
75
- /**
76
- * Converges one Nx consumer on Habitat's app-owned Nx, Codex, package, and Git-hook state.
77
- *
78
- * Every admission and compatibility decision completes before the first Tree
79
- * write, so an incompatible consumer remains byte-for-byte unchanged.
80
- */
81
- export function initializeHabitatConsumer(tree, binding) {
82
- const nxJson = requireNxJson(tree);
83
- const hooks = readHooks(tree);
84
- const packageJson = readPackage(tree);
85
- const nxPlan = planHabitatNxRegistration(nxJson, binding);
86
- const hookPlan = planHookInitialization(hooks, binding);
87
- const packagePlan = planPackageInitialization(packageJson, binding);
88
- const gitHookPlan = planGitHookInitialization(tree, binding.gitHook);
89
- if (nxPlan.changed)
90
- updateNxJson(tree, nxPlan.value);
91
- if (hookPlan.changed)
92
- writeJson(tree, CODEX_HOOKS_PATH, hookPlan.value);
93
- if (packagePlan.changed)
94
- writeJson(tree, PACKAGE_PATH, packagePlan.value);
95
- if (gitHookPlan.changed)
96
- tree.write(binding.gitHook.path, gitHookPlan.value);
97
- return { packageChanged: packagePlan.changed };
98
- }
99
- /** Removes only Habitat's named hook group while preserving installed Nx integration. */
100
- export function removeHabitatHook(tree, binding) {
101
- const hooks = readHooks(tree);
102
- const hookPlan = planHookRemoval(hooks, binding);
103
- if (hookPlan.changed)
104
- writeJson(tree, CODEX_HOOKS_PATH, hookPlan.value);
105
- }
106
- function requireNxJson(tree) {
107
- const nxJson = readNxJson(tree);
108
- if (nxJson === null) {
109
- throw new Error("Habitat initialization requires an Nx workspace with nx.json.");
110
- }
111
- return nxJson;
112
- }
113
- function readHooks(tree) {
114
- if (!tree.exists(CODEX_HOOKS_PATH))
115
- return { hooks: {} };
116
- const input = readJson(tree, CODEX_HOOKS_PATH);
117
- if (!hooksValidator.Check(input)) {
118
- throw new Error(`${CODEX_HOOKS_PATH} is not a supported Codex hook document.`);
119
- }
120
- return input;
121
- }
122
- function readPackage(tree) {
123
- if (!tree.exists(PACKAGE_PATH)) {
124
- throw new Error("Habitat initialization requires an Nx workspace package.json.");
125
- }
126
- const input = readJson(tree, PACKAGE_PATH);
127
- if (!packageValidator.Check(input)) {
128
- throw new Error("package.json is not a supported Nx consumer package document.");
129
- }
130
- return input;
131
- }
132
- /** Plans the one package-owned Nx plugin registration without mutating a Tree. */
133
- export function planHabitatNxRegistration(nxJson, binding) {
134
- const plugins = nxJson.plugins ?? [];
135
- const matches = plugins.filter((plugin) => hasPluginIdentity(plugin, binding.nxPlugin) ||
136
- binding.predecessorNxPlugins.some((predecessor) => hasPluginIdentity(plugin, typeof predecessor === "string" ? predecessor : predecessor.plugin)));
137
- if (matches.length > 1) {
138
- throw new Error("nx.json contains multiple Habitat Nx plugin registrations.");
139
- }
140
- const match = matches[0];
141
- if (match === binding.nxPlugin)
142
- return { changed: false, value: nxJson };
143
- if (match !== undefined &&
144
- !binding.predecessorNxPlugins.some((predecessor) => isDeepStrictEqual(predecessor, match))) {
145
- throw new Error("nx.json contains an incompatible Habitat Nx plugin registration.");
146
- }
147
- const nextPlugins = match === undefined
148
- ? [...plugins, binding.nxPlugin]
149
- : plugins.map((plugin) => (plugin === match ? binding.nxPlugin : plugin));
150
- return { changed: true, value: { ...nxJson, plugins: nextPlugins } };
151
- }
152
- function planHookInitialization(hooks, binding) {
153
- const location = oneOwnedHookLocation(hooks, binding);
154
- if (location !== undefined && isDeepStrictEqual(location.group, binding.hook)) {
155
- return { changed: false, value: hooks };
156
- }
157
- if (location !== undefined &&
158
- !binding.predecessorHooks.some((predecessor) => isDeepStrictEqual(predecessor, location.group))) {
159
- throw new Error(`${CODEX_HOOKS_PATH} contains an incompatible Habitat hook contribution.`);
160
- }
161
- const events = hooks.hooks ?? {};
162
- const stop = events.Stop ?? [];
163
- const nextStop = location === undefined
164
- ? [...stop, binding.hook]
165
- : stop.map((group, index) => (index === location.index ? binding.hook : group));
166
- return {
167
- changed: true,
168
- value: { ...hooks, hooks: { ...events, Stop: nextStop } },
169
- };
170
- }
171
- function planHookRemoval(hooks, binding) {
172
- const location = oneOwnedHookLocation(hooks, binding);
173
- if (location === undefined)
174
- return { changed: false, value: hooks };
175
- if (!isDeepStrictEqual(location.group, binding.hook) &&
176
- !binding.predecessorHooks.some((predecessor) => isDeepStrictEqual(predecessor, location.group))) {
177
- throw new Error(`${CODEX_HOOKS_PATH} contains an incompatible Habitat hook contribution.`);
178
- }
179
- const events = hooks.hooks ?? {};
180
- const stop = events.Stop ?? [];
181
- return {
182
- changed: true,
183
- value: {
184
- ...hooks,
185
- hooks: { ...events, Stop: stop.filter((_group, index) => index !== location.index) },
186
- },
187
- };
188
- }
189
- function planPackageInitialization(packageJson, binding) {
190
- const { gritPackage, husky } = binding;
191
- const trusted = packageJson.trustedDependencies ?? [];
192
- const matches = trusted.filter((dependency) => dependency === gritPackage);
193
- if (matches.length > 1) {
194
- throw new Error(`package.json contains duplicate ${gritPackage} trust entries.`);
195
- }
196
- const currentHuskyVersion = packageJson.devDependencies?.[husky.package];
197
- const invalidHuskyPlacement = ["dependencies", "optionalDependencies", "peerDependencies"].find((bucket) => packageJson[bucket]?.[husky.package] !== undefined);
198
- if (invalidHuskyPlacement !== undefined) {
199
- throw new Error(`package.json must declare ${husky.package} only in devDependencies; found ${invalidHuskyPlacement}.`);
200
- }
201
- if (currentHuskyVersion !== undefined && currentHuskyVersion !== husky.version) {
202
- throw new Error(`package.json contains an incompatible ${husky.package} version: ${currentHuskyVersion}.`);
203
- }
204
- const currentPrepare = packageJson.scripts?.prepare;
205
- if (currentPrepare !== undefined &&
206
- currentPrepare !== husky.prepare &&
207
- !husky.predecessorPrepareScripts.includes(currentPrepare)) {
208
- throw new Error("package.json contains an incompatible prepare script.");
209
- }
210
- const trustedChanged = matches.length === 0;
211
- const huskyChanged = currentHuskyVersion === undefined;
212
- const prepareChanged = currentPrepare !== husky.prepare;
213
- const currentCheck = packageJson.scripts?.check;
214
- if (currentCheck !== undefined && currentCheck.trim().length === 0) {
215
- throw new Error("package.json contains an empty check script.");
216
- }
217
- const checkChanged = currentCheck === undefined;
218
- if (!trustedChanged && !huskyChanged && !prepareChanged && !checkChanged) {
219
- return { changed: false, value: packageJson };
220
- }
221
- return {
222
- changed: true,
223
- value: {
224
- ...packageJson,
225
- scripts: {
226
- ...packageJson.scripts,
227
- check: currentCheck ?? binding.defaultCheckScript,
228
- prepare: husky.prepare,
229
- },
230
- devDependencies: {
231
- ...packageJson.devDependencies,
232
- [husky.package]: husky.version,
233
- },
234
- trustedDependencies: trustedChanged ? [...trusted, gritPackage] : trusted,
235
- },
236
- };
237
- }
238
- function planGitHookInitialization(tree, hook) {
239
- if (!tree.exists(hook.path))
240
- return { changed: true, value: hook.contents };
241
- const contents = tree.read(hook.path, "utf8");
242
- if (contents === null || contents.trim().length === 0) {
243
- throw new Error(`${hook.path} is empty.`);
244
- }
245
- return { changed: false, value: contents };
246
- }
247
- function oneOwnedHookLocation(hooks, binding) {
248
- const identity = binding.hook._habitat.identity;
249
- const locations = Object.entries(hooks.hooks ?? {}).flatMap(([event, groups]) => groups.flatMap((group, index) => {
250
- const marked = group._habitat?.identity === identity;
251
- const predecessor = binding.predecessorHooks.some((candidate) => isDeepStrictEqual(candidate, group));
252
- return marked || predecessor ? [{ event, group, index }] : [];
253
- }));
254
- if (locations.length > 1) {
255
- throw new Error(`${CODEX_HOOKS_PATH} contains multiple Habitat hook contributions.`);
256
- }
257
- const location = locations[0];
258
- if (location !== undefined && location.event !== "Stop") {
259
- throw new Error(`${CODEX_HOOKS_PATH} contains a Habitat hook contribution outside Stop.`);
260
- }
261
- return location;
262
- }
263
- function hasPluginIdentity(plugin, identity) {
264
- return plugin === identity || (typeof plugin === "object" && plugin.plugin === identity);
265
- }
@@ -1,29 +0,0 @@
1
- import type { HabitatClient } from "@habitat-ai/sdk";
2
- import type { CreateNodes, TargetConfiguration } from "@nx/devkit";
3
- type ResolveCatalogClient = {
4
- readonly catalog: Pick<HabitatClient["catalog"], "resolve">;
5
- };
6
- type TargetInput = NonNullable<TargetConfiguration["inputs"]>[number];
7
- /**
8
- * Supplies the ready Habitat client for the workspace being projected by Nx.
9
- *
10
- * The Habitat app owns this capability because Nx plugin options are serialized
11
- * configuration and cannot carry a client, provider, or runtime handle.
12
- */
13
- export type HabitatClientForWorkspace = (workspaceRoot: string) => ResolveCatalogClient | Promise<ResolveCatalogClient>;
14
- /** App-owned runtime and provider facts required for sound target caching. */
15
- export type HabitatNxBinding = {
16
- readonly clientForWorkspace: HabitatClientForWorkspace;
17
- readonly runtimeInputs: readonly [TargetInput, ...TargetInput[]];
18
- };
19
- /**
20
- * Projects resolved Habitat applications and compatibility rules into native Nx targets.
21
- *
22
- * The factory receives the app-owned workspace client and runtime cache facts.
23
- * It does not select providers, discover authority, execute checks, or name
24
- * projects.
25
- */
26
- export declare function createHabitatNxPlugin(binding: HabitatNxBinding): Readonly<{
27
- createNodes: CreateNodes<undefined>;
28
- }>;
29
- export {};
@@ -1,308 +0,0 @@
1
- import { posix } from "node:path";
2
- const HABITAT_CATALOG_PATHS = [
3
- ".habitat/blueprints/*/blueprint.toml",
4
- ".habitat/blueprints/*/versions/*/blueprint.toml",
5
- ".habitat/index.json",
6
- ".habitat/**/rule.json",
7
- "**/habitat.toml",
8
- ];
9
- const HABITAT_AUTHORITY_GLOB = `{${HABITAT_CATALOG_PATHS.join(",")}}`;
10
- const DEFAULT_CHECK_TARGET = "check:policy";
11
- const HABITAT_EXECUTABLE = "habitat";
12
- const PORTABLE_OWNER_PROJECT = /^[A-Za-z0-9@][A-Za-z0-9@._/+:-]*$/u;
13
- /**
14
- * Projects resolved Habitat applications and compatibility rules into native Nx targets.
15
- *
16
- * The factory receives the app-owned workspace client and runtime cache facts.
17
- * It does not select providers, discover authority, execute checks, or name
18
- * projects.
19
- */
20
- export function createHabitatNxPlugin(binding) {
21
- const createNodes = [
22
- HABITAT_AUTHORITY_GLOB,
23
- async (configFiles, _options, context) => {
24
- const matchedFiles = [...new Set(configFiles.map(normalizeWorkspacePath))].sort();
25
- const client = await binding.clientForWorkspace(context.workspaceRoot);
26
- const result = await client.catalog.resolve({});
27
- if (result._tag === "Rejected")
28
- throw rejectedCatalogError(result);
29
- return projectCatalogTargets(matchedFiles, result.catalog, binding.runtimeInputs);
30
- },
31
- ];
32
- return Object.freeze({ createNodes });
33
- }
34
- function projectCatalogTargets(matchedFiles, catalog, runtimeInputs) {
35
- if (catalog.applications.length === 0 && catalog.compatibility.rules.length === 0)
36
- return [];
37
- const authorityFiles = new Set(matchedFiles);
38
- const instances = indexInstances(catalog.instances);
39
- const rootsByOwner = new Map();
40
- const ownersByRoot = new Map();
41
- const projects = new Map();
42
- for (const [ownerProject, ownerRoot] of Object.entries(catalog.compatibility.ownerRoots).sort(([left], [right]) => compareText(left, right))) {
43
- recordOwnerRoot(ownerProject, ownerRoot, rootsByOwner, ownersByRoot);
44
- }
45
- for (const application of catalog.applications) {
46
- const instance = requireApplicationInstance(application, instances);
47
- const manifestPath = requireMatchedManifest(application.manifestPath, authorityFiles, `instance '${instance.id}'`);
48
- const root = recordOwnerRoot(application.ownerProject, projectRootFor(manifestPath), rootsByOwner, ownersByRoot);
49
- const project = projectFor(projects, root, application.ownerProject);
50
- project.applicationManifests.add(manifestPath);
51
- const targetName = applicationTargetName(application);
52
- addLeafTarget(project, targetName, applicationTarget(application, runtimeInputs));
53
- }
54
- for (const rule of catalog.compatibility.rules) {
55
- const root = rootsByOwner.get(rule.ownerProject);
56
- if (root === undefined) {
57
- throw new Error(`Habitat Nx projection rejected compatibility rule '${rule.ruleId}': owner '${rule.ownerProject}' has no root.`);
58
- }
59
- const manifestPath = requireMatchedManifest(rule.manifestPath, authorityFiles, `compatibility rule '${rule.ruleId}'`);
60
- const project = projectFor(projects, root, rule.ownerProject);
61
- project.compatibilityManifests.add(manifestPath);
62
- addLeafTarget(project, compatibilityTargetName(rule), compatibilityTarget(rule, runtimeInputs));
63
- }
64
- return [...projects.entries()]
65
- .sort(([left], [right]) => compareText(left, right))
66
- .map(([root, project]) => {
67
- project.targets[DEFAULT_CHECK_TARGET] = ownerTarget(project.ownerProject, ownerInputs(project.targets, runtimeInputs), project.compatibilityManifests.size > 0);
68
- return [
69
- projectionSource(project),
70
- {
71
- projects: {
72
- [root]: {
73
- targets: Object.fromEntries(Object.entries(project.targets).sort(([left], [right]) => compareText(left, right))),
74
- },
75
- },
76
- },
77
- ];
78
- });
79
- }
80
- function recordOwnerRoot(ownerProject, ownerRoot, rootsByOwner, ownersByRoot) {
81
- const root = normalizeWorkspacePath(ownerRoot);
82
- const priorRoot = rootsByOwner.get(ownerProject);
83
- if (priorRoot !== undefined && priorRoot !== root) {
84
- throw new Error(`Habitat Nx projection rejected owner '${ownerProject}': roots '${priorRoot}' and '${root}' collide.`);
85
- }
86
- const priorOwner = ownersByRoot.get(root);
87
- if (priorOwner !== undefined && priorOwner !== ownerProject) {
88
- throw new Error(`Habitat Nx projection rejected root '${root}': owners '${priorOwner}' and '${ownerProject}' collide.`);
89
- }
90
- rootsByOwner.set(ownerProject, root);
91
- ownersByRoot.set(root, ownerProject);
92
- return root;
93
- }
94
- function projectFor(projects, root, ownerProject) {
95
- const project = projects.get(root);
96
- if (project !== undefined) {
97
- if (project.ownerProject !== ownerProject) {
98
- throw new Error(`Habitat Nx projection rejected root '${root}': owners '${project.ownerProject}' and '${ownerProject}' collide.`);
99
- }
100
- return project;
101
- }
102
- const created = {
103
- ownerProject,
104
- applicationManifests: new Set(),
105
- compatibilityManifests: new Set(),
106
- targets: {},
107
- };
108
- projects.set(root, created);
109
- return created;
110
- }
111
- function requireMatchedManifest(path, authorityFiles, subject) {
112
- const manifestPath = normalizeWorkspacePath(path);
113
- if (!authorityFiles.has(manifestPath)) {
114
- throw new Error(`Habitat Nx projection rejected ${subject}: manifest '${manifestPath}' is outside the matched authority files.`);
115
- }
116
- return manifestPath;
117
- }
118
- function addLeafTarget(project, targetName, target) {
119
- if (Object.hasOwn(project.targets, targetName)) {
120
- throw new Error(`Habitat Nx projection rejected duplicate target '${project.ownerProject}:${targetName}'.`);
121
- }
122
- project.targets[targetName] = target;
123
- }
124
- function projectionSource(project) {
125
- const applicationManifest = [...project.applicationManifests].sort(compareText)[0];
126
- if (applicationManifest !== undefined)
127
- return applicationManifest;
128
- const compatibilityManifest = [...project.compatibilityManifests].sort(compareText)[0];
129
- if (compatibilityManifest === undefined) {
130
- throw new Error(`Habitat Nx projection rejected owner '${project.ownerProject}': projected targets have no manifest.`);
131
- }
132
- return compatibilityManifest;
133
- }
134
- function requireApplicationInstance(application, instances) {
135
- const instance = instances.get(application.instanceId);
136
- if (!instance) {
137
- throw new Error(`Habitat Nx projection rejected application '${application.ruleId}': instance '${application.instanceId}' is absent.`);
138
- }
139
- const mismatches = [
140
- instance.ownerProject === application.ownerProject
141
- ? undefined
142
- : `owner '${application.ownerProject}' does not match '${instance.ownerProject}'`,
143
- instance.blueprint === application.blueprint
144
- ? undefined
145
- : `blueprint '${application.blueprint}' does not match '${instance.blueprint}'`,
146
- instance.blueprintVersion === application.blueprintVersion
147
- ? undefined
148
- : `blueprint version '${application.blueprintVersion}' does not match '${instance.blueprintVersion}'`,
149
- normalizeWorkspacePath(instance.manifestPath) ===
150
- normalizeWorkspacePath(application.manifestPath)
151
- ? undefined
152
- : `manifest '${application.manifestPath}' does not match '${instance.manifestPath}'`,
153
- ].filter((mismatch) => mismatch !== undefined);
154
- if (mismatches.length > 0) {
155
- throw new Error(`Habitat Nx projection rejected instance '${instance.id}': ${mismatches.join("; ")}.`);
156
- }
157
- return instance;
158
- }
159
- function indexInstances(instances) {
160
- const indexed = new Map();
161
- for (const instance of instances) {
162
- if (indexed.has(instance.id)) {
163
- throw new Error(`Habitat Nx projection rejected duplicate instance '${instance.id}'.`);
164
- }
165
- indexed.set(instance.id, instance);
166
- }
167
- return indexed;
168
- }
169
- function applicationTargetName(application) {
170
- return `habitat:application:${application.instanceId}:${application.ruleId}`;
171
- }
172
- function compatibilityTargetName(rule) {
173
- return `habitat:rule:${rule.ruleId}`;
174
- }
175
- function applicationTarget(application, runtimeInputs) {
176
- return {
177
- command: `${HABITAT_EXECUTABLE} check --instance ${application.instanceId} --rule ${application.ruleId}`,
178
- cache: true,
179
- parallelism: false,
180
- inputs: applicationInputs(application, runtimeInputs),
181
- outputs: [],
182
- options: { cwd: "{workspaceRoot}" },
183
- metadata: {
184
- description: `Check Habitat application ${application.instanceId}/${application.ruleId}`,
185
- },
186
- };
187
- }
188
- function compatibilityTarget(rule, runtimeInputs) {
189
- return {
190
- command: `${HABITAT_EXECUTABLE} check --rule ${rule.ruleId}`,
191
- cache: true,
192
- parallelism: false,
193
- inputs: compatibilityInputs(rule, runtimeInputs),
194
- outputs: [],
195
- options: { cwd: "{workspaceRoot}" },
196
- metadata: { description: `Check Habitat compatibility rule ${rule.ruleId}` },
197
- };
198
- }
199
- function ownerTarget(ownerProject, inputs, hasCompatibility) {
200
- if (!PORTABLE_OWNER_PROJECT.test(ownerProject)) {
201
- throw new Error(`Habitat Nx projection rejected owner '${ownerProject}': identity is not portable as an Nx command argument.`);
202
- }
203
- return {
204
- command: `${HABITAT_EXECUTABLE} check --owner ${ownerProject}`,
205
- cache: true,
206
- parallelism: false,
207
- inputs,
208
- outputs: [],
209
- options: { cwd: "{workspaceRoot}" },
210
- metadata: {
211
- description: hasCompatibility
212
- ? `Check resolved Habitat policy owned by ${ownerProject}`
213
- : `Check resolved Habitat applications owned by ${ownerProject}`,
214
- },
215
- };
216
- }
217
- function ownerInputs(targets, runtimeInputs) {
218
- const runtimeStrings = new Set(runtimeInputs.filter((input) => typeof input === "string"));
219
- const corpusInputs = new Set();
220
- for (const target of Object.values(targets)) {
221
- for (const input of target.inputs ?? []) {
222
- if (typeof input === "string" && !runtimeStrings.has(input))
223
- corpusInputs.add(input);
224
- }
225
- }
226
- return [...runtimeInputs, ...[...corpusInputs].sort(compareText)];
227
- }
228
- function applicationInputs(application, runtimeInputs) {
229
- const files = new Set(HABITAT_CATALOG_PATHS.map(workspaceInput));
230
- if (application.runner.name === "grit") {
231
- addLocalAssetInput(files, application.runner.pattern);
232
- for (const entry of application.runner.acquisition.entries) {
233
- if (entry.source.kind === "root-pattern") {
234
- files.add(workspaceInput(entry.path));
235
- }
236
- else {
237
- addSubjectInputs(files, entry.path, entry.kind);
238
- }
239
- }
240
- }
241
- else {
242
- addLocalAssetInput(files, application.runner.structure);
243
- for (const binding of application.runner.rootBindings) {
244
- if (binding.path !== undefined)
245
- addSubjectInputs(files, binding.path, binding.kind);
246
- }
247
- }
248
- return [...runtimeInputs, ...[...files].sort()];
249
- }
250
- function compatibilityInputs(rule, runtimeInputs) {
251
- const files = new Set(HABITAT_CATALOG_PATHS.map(workspaceInput));
252
- files.add(workspaceInput(".habitat/**"));
253
- files.add(workspaceInput(rule.manifestPath));
254
- addLocalAssetInput(files, rule.baseline);
255
- for (const pattern of rule.coveragePatterns)
256
- files.add(workspaceInput(pattern));
257
- if (rule.runner.name === "grit") {
258
- addLocalAssetInput(files, rule.runner.pattern);
259
- for (const entry of rule.runner.acquisition.entries) {
260
- if (entry.kind === "directory" && entry.path === ".")
261
- continue;
262
- addSubjectInputs(files, entry.path, entry.kind);
263
- }
264
- }
265
- else {
266
- addLocalAssetInput(files, rule.runner.structure);
267
- }
268
- return [...runtimeInputs, ...[...files].sort(compareText)];
269
- }
270
- function addLocalAssetInput(target, asset) {
271
- if (asset.provenance.kind === "local")
272
- target.add(workspaceInput(asset.relativePath));
273
- }
274
- function addSubjectInputs(target, path, kind) {
275
- const exact = workspaceInput(path);
276
- if (kind === "directory" && path === ".") {
277
- target.add("{workspaceRoot}/**/*");
278
- return;
279
- }
280
- target.add(exact);
281
- if (kind === "directory")
282
- target.add(`${exact}/**/*`);
283
- }
284
- function workspaceInput(path) {
285
- const normalized = normalizeWorkspacePath(path);
286
- return normalized === "." ? "{workspaceRoot}" : `{workspaceRoot}/${normalized}`;
287
- }
288
- function projectRootFor(manifestPath) {
289
- const root = posix.dirname(manifestPath);
290
- return root === "" ? "." : root;
291
- }
292
- function normalizeWorkspacePath(path) {
293
- const slashPath = path.replaceAll("\\", "/");
294
- if (posix.isAbsolute(slashPath) || /^[A-Za-z]:\//.test(slashPath)) {
295
- throw new Error(`Habitat Nx projection requires a workspace-relative path: '${path}'.`);
296
- }
297
- const normalized = posix.normalize(slashPath).replace(/^\.\//, "");
298
- if (normalized === ".." || normalized.startsWith("../")) {
299
- throw new Error(`Habitat Nx projection path escapes the workspace: '${path}'.`);
300
- }
301
- return normalized === "" ? "." : normalized;
302
- }
303
- function rejectedCatalogError(result) {
304
- return new Error(`Habitat catalog resolution rejected during Nx projection: ${JSON.stringify(result.issues)}`);
305
- }
306
- function compareText(left, right) {
307
- return left < right ? -1 : left > right ? 1 : 0;
308
- }
@@ -1,22 +0,0 @@
1
- import { type Tree } from "@nx/devkit";
2
- import { type HabitatConsumerBinding } from "./initialization.js";
3
- /** Nx options consumed by the portable Habitat repository preset. */
4
- export type HabitatRepositoryPresetOptions = Readonly<{
5
- packageManager: string;
6
- }>;
7
- /** Reports whether dependency installation must follow repository generation. */
8
- export type HabitatRepositoryPresetResult = Readonly<{
9
- packageChanged: boolean;
10
- }>;
11
- /**
12
- * Admits package-owned initialization only for the canonical Bun consumer shape.
13
- * The check runs before the generator plans package, Nx, hook, or policy changes.
14
- */
15
- export declare function assertHabitatBunConsumer(tree: Tree): void;
16
- /**
17
- * Converges one repository on Habitat's portable Bun/Nx configuration.
18
- *
19
- * Product inventory, policy selections, documentation routers, aliases, release
20
- * policy, and hosted CI remain consumer-owned and are never generated here.
21
- */
22
- export declare function initializeHabitatBunRepository(tree: Tree, binding: HabitatConsumerBinding, options: HabitatRepositoryPresetOptions): HabitatRepositoryPresetResult;