@kb-labs/shared 1.1.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 (232) hide show
  1. package/.cursorrules +32 -0
  2. package/.github/workflows/ci.yml +13 -0
  3. package/.github/workflows/deploy.yml +28 -0
  4. package/.github/workflows/docker-build.yml +25 -0
  5. package/.github/workflows/drift-check.yml +10 -0
  6. package/.github/workflows/profiles-validate.yml +16 -0
  7. package/.github/workflows/release.yml +8 -0
  8. package/.kb/devkit/agents/devkit-maintainer/context.globs +15 -0
  9. package/.kb/devkit/agents/devkit-maintainer/permissions.yml +17 -0
  10. package/.kb/devkit/agents/devkit-maintainer/prompt.md +28 -0
  11. package/.kb/devkit/agents/devkit-maintainer/runbook.md +31 -0
  12. package/.kb/devkit/agents/docs-crafter/prompt.md +24 -0
  13. package/.kb/devkit/agents/docs-crafter/runbook.md +18 -0
  14. package/.kb/devkit/agents/release-manager/context.globs +7 -0
  15. package/.kb/devkit/agents/release-manager/prompt.md +27 -0
  16. package/.kb/devkit/agents/release-manager/runbook.md +17 -0
  17. package/.kb/devkit/agents/test-generator/context.globs +7 -0
  18. package/.kb/devkit/agents/test-generator/prompt.md +27 -0
  19. package/.kb/devkit/agents/test-generator/runbook.md +18 -0
  20. package/.vscode/settings.json +23 -0
  21. package/CHANGELOG.md +33 -0
  22. package/CONTRIBUTING.md +117 -0
  23. package/LICENSE +21 -0
  24. package/README.md +306 -0
  25. package/docs/DECLARATIVE-FLAGS-AND-ENV.md +622 -0
  26. package/docs/DOCUMENTATION.md +70 -0
  27. package/docs/adr/0000-template.md +52 -0
  28. package/docs/adr/0001-architecture-and-repository-layout.md +31 -0
  29. package/docs/adr/0002-plugins-and-extensibility.md +44 -0
  30. package/docs/adr/0003-package-and-module-boundaries.md +35 -0
  31. package/docs/adr/0004-versioning-and-release-policy.md +36 -0
  32. package/docs/adr/0005-reactive-loader-pattern.md +179 -0
  33. package/docs/adr/0006-declarative-flags-and-env-systems.md +376 -0
  34. package/eslint.config.js +27 -0
  35. package/kb-labs.config.json +5 -0
  36. package/package.json +88 -0
  37. package/package.json.bin +25 -0
  38. package/package.json.lib +30 -0
  39. package/packages/shared-cli-ui/CHANGELOG.md +20 -0
  40. package/packages/shared-cli-ui/README.md +342 -0
  41. package/packages/shared-cli-ui/docs/ARCHITECTURE.md +105 -0
  42. package/packages/shared-cli-ui/eslint.config.js +27 -0
  43. package/packages/shared-cli-ui/package.json +72 -0
  44. package/packages/shared-cli-ui/src/__tests__/artifacts-display.spec.ts +89 -0
  45. package/packages/shared-cli-ui/src/__tests__/format.spec.ts +44 -0
  46. package/packages/shared-cli-ui/src/__tests__/loader-json-mode.test.ts +119 -0
  47. package/packages/shared-cli-ui/src/artifacts-display.ts +266 -0
  48. package/packages/shared-cli-ui/src/cli-auto-discovery.ts +120 -0
  49. package/packages/shared-cli-ui/src/colors.ts +142 -0
  50. package/packages/shared-cli-ui/src/command-discovery.ts +72 -0
  51. package/packages/shared-cli-ui/src/command-output.ts +153 -0
  52. package/packages/shared-cli-ui/src/command-result.ts +267 -0
  53. package/packages/shared-cli-ui/src/command-runner.ts +310 -0
  54. package/packages/shared-cli-ui/src/command-suggestions.ts +204 -0
  55. package/packages/shared-cli-ui/src/debug/components/output.ts +141 -0
  56. package/packages/shared-cli-ui/src/debug/components/trace.ts +101 -0
  57. package/packages/shared-cli-ui/src/debug/components/tree.ts +88 -0
  58. package/packages/shared-cli-ui/src/debug/formatters/ai.ts +17 -0
  59. package/packages/shared-cli-ui/src/debug/formatters/human.ts +98 -0
  60. package/packages/shared-cli-ui/src/debug/formatters/timeline.ts +94 -0
  61. package/packages/shared-cli-ui/src/debug/index.ts +56 -0
  62. package/packages/shared-cli-ui/src/debug/types.ts +57 -0
  63. package/packages/shared-cli-ui/src/debug/utilities.ts +203 -0
  64. package/packages/shared-cli-ui/src/dynamic-command-discovery.ts +131 -0
  65. package/packages/shared-cli-ui/src/format.ts +412 -0
  66. package/packages/shared-cli-ui/src/index.ts +34 -0
  67. package/packages/shared-cli-ui/src/loader.ts +196 -0
  68. package/packages/shared-cli-ui/src/manifest-parser.ts +151 -0
  69. package/packages/shared-cli-ui/src/modern-format.ts +271 -0
  70. package/packages/shared-cli-ui/src/multi-cli-suggestions.ts +159 -0
  71. package/packages/shared-cli-ui/src/table.ts +134 -0
  72. package/packages/shared-cli-ui/src/timing-tracker.ts +68 -0
  73. package/packages/shared-cli-ui/src/utils/context.ts +12 -0
  74. package/packages/shared-cli-ui/src/utils/env.ts +164 -0
  75. package/packages/shared-cli-ui/src/utils/flags.ts +269 -0
  76. package/packages/shared-cli-ui/src/utils/path.ts +8 -0
  77. package/packages/shared-cli-ui/tsconfig.build.json +15 -0
  78. package/packages/shared-cli-ui/tsconfig.json +9 -0
  79. package/packages/shared-cli-ui/tsup.config.ts +11 -0
  80. package/packages/shared-cli-ui/vitest.config.ts +15 -0
  81. package/packages/shared-command-kit/CHANGELOG.md +20 -0
  82. package/packages/shared-command-kit/LICENSE +22 -0
  83. package/packages/shared-command-kit/README.md +1030 -0
  84. package/packages/shared-command-kit/docs/HIGH-LEVEL-API.md +89 -0
  85. package/packages/shared-command-kit/docs/LOW-LEVEL-API.md +105 -0
  86. package/packages/shared-command-kit/docs/MIGRATION-GUIDE.md +135 -0
  87. package/packages/shared-command-kit/eslint.config.js +27 -0
  88. package/packages/shared-command-kit/eslint.config.ts +14 -0
  89. package/packages/shared-command-kit/package.json +76 -0
  90. package/packages/shared-command-kit/prettierrc.json +5 -0
  91. package/packages/shared-command-kit/src/__tests__/define-command.spec.ts +294 -0
  92. package/packages/shared-command-kit/src/__tests__/define-route.test.ts +285 -0
  93. package/packages/shared-command-kit/src/__tests__/define-system-command.spec.ts +508 -0
  94. package/packages/shared-command-kit/src/__tests__/define-webhook.test.ts +156 -0
  95. package/packages/shared-command-kit/src/__tests__/define-websocket.test.ts +316 -0
  96. package/packages/shared-command-kit/src/__tests__/errors.spec.ts +45 -0
  97. package/packages/shared-command-kit/src/__tests__/flags.spec.ts +353 -0
  98. package/packages/shared-command-kit/src/__tests__/platform-api.test.ts +135 -0
  99. package/packages/shared-command-kit/src/__tests__/plugin-context-v3.snapshot.spec.ts +240 -0
  100. package/packages/shared-command-kit/src/__tests__/ws-types.test.ts +359 -0
  101. package/packages/shared-command-kit/src/analytics/index.ts +6 -0
  102. package/packages/shared-command-kit/src/analytics/with-analytics.ts +195 -0
  103. package/packages/shared-command-kit/src/define-action.ts +100 -0
  104. package/packages/shared-command-kit/src/define-command.ts +113 -0
  105. package/packages/shared-command-kit/src/define-route.ts +113 -0
  106. package/packages/shared-command-kit/src/define-system-command.ts +362 -0
  107. package/packages/shared-command-kit/src/define-webhook.ts +115 -0
  108. package/packages/shared-command-kit/src/define-websocket.ts +308 -0
  109. package/packages/shared-command-kit/src/errors/factory.ts +282 -0
  110. package/packages/shared-command-kit/src/errors/format-validation.ts +144 -0
  111. package/packages/shared-command-kit/src/errors/format.ts +92 -0
  112. package/packages/shared-command-kit/src/errors/index.ts +9 -0
  113. package/packages/shared-command-kit/src/errors/types.ts +32 -0
  114. package/packages/shared-command-kit/src/flags/define.ts +92 -0
  115. package/packages/shared-command-kit/src/flags/index.ts +9 -0
  116. package/packages/shared-command-kit/src/flags/types.ts +153 -0
  117. package/packages/shared-command-kit/src/flags/validate.ts +358 -0
  118. package/packages/shared-command-kit/src/helpers/context.ts +8 -0
  119. package/packages/shared-command-kit/src/helpers/flags.ts +84 -0
  120. package/packages/shared-command-kit/src/helpers/index.ts +42 -0
  121. package/packages/shared-command-kit/src/helpers/patterns.ts +464 -0
  122. package/packages/shared-command-kit/src/helpers/platform.ts +335 -0
  123. package/packages/shared-command-kit/src/helpers/use-analytics.ts +95 -0
  124. package/packages/shared-command-kit/src/helpers/use-cache.ts +97 -0
  125. package/packages/shared-command-kit/src/helpers/use-config.ts +99 -0
  126. package/packages/shared-command-kit/src/helpers/use-embeddings.ts +49 -0
  127. package/packages/shared-command-kit/src/helpers/use-llm.ts +316 -0
  128. package/packages/shared-command-kit/src/helpers/use-logger.ts +77 -0
  129. package/packages/shared-command-kit/src/helpers/use-platform.ts +111 -0
  130. package/packages/shared-command-kit/src/helpers/use-resource-broker.ts +106 -0
  131. package/packages/shared-command-kit/src/helpers/use-storage.ts +71 -0
  132. package/packages/shared-command-kit/src/helpers/use-vector-store.ts +49 -0
  133. package/packages/shared-command-kit/src/helpers/validation.ts +398 -0
  134. package/packages/shared-command-kit/src/index.ts +410 -0
  135. package/packages/shared-command-kit/src/jobs.ts +132 -0
  136. package/packages/shared-command-kit/src/lifecycle/define-handlers.ts +366 -0
  137. package/packages/shared-command-kit/src/lifecycle/index.ts +6 -0
  138. package/packages/shared-command-kit/src/manifest.ts +127 -0
  139. package/packages/shared-command-kit/src/rest/define-handler.ts +187 -0
  140. package/packages/shared-command-kit/src/rest/index.ts +11 -0
  141. package/packages/shared-command-kit/src/studio/index.ts +12 -0
  142. package/packages/shared-command-kit/src/validation/index.ts +6 -0
  143. package/packages/shared-command-kit/src/validation/schema-builders.ts +409 -0
  144. package/packages/shared-command-kit/src/ws-types.ts +106 -0
  145. package/packages/shared-command-kit/tsconfig.build.json +15 -0
  146. package/packages/shared-command-kit/tsconfig.json +9 -0
  147. package/packages/shared-command-kit/tsup.config.ts +30 -0
  148. package/packages/shared-command-kit/vitest.config.ts +4 -0
  149. package/packages/shared-http/package.json +67 -0
  150. package/packages/shared-http/src/__tests__/log-correlation.test.ts +81 -0
  151. package/packages/shared-http/src/__tests__/operation-metrics-tracker.test.ts +55 -0
  152. package/packages/shared-http/src/http-observability-collector.ts +363 -0
  153. package/packages/shared-http/src/index.ts +36 -0
  154. package/packages/shared-http/src/log-correlation.ts +89 -0
  155. package/packages/shared-http/src/operation-metrics-tracker.ts +107 -0
  156. package/packages/shared-http/src/register-openapi.ts +108 -0
  157. package/packages/shared-http/src/resolve-schema-ref.ts +75 -0
  158. package/packages/shared-http/src/schemas.ts +29 -0
  159. package/packages/shared-http/src/service-observability.ts +63 -0
  160. package/packages/shared-http/tsconfig.build.json +15 -0
  161. package/packages/shared-http/tsconfig.json +9 -0
  162. package/packages/shared-http/tsup.config.ts +23 -0
  163. package/packages/shared-http/vitest.config.ts +13 -0
  164. package/packages/shared-perm-presets/CHANGELOG.md +20 -0
  165. package/packages/shared-perm-presets/README.md +78 -0
  166. package/packages/shared-perm-presets/eslint.config.js +27 -0
  167. package/packages/shared-perm-presets/package.json +45 -0
  168. package/packages/shared-perm-presets/src/__tests__/combine.test.ts +403 -0
  169. package/packages/shared-perm-presets/src/__tests__/presets.test.ts +205 -0
  170. package/packages/shared-perm-presets/src/combine.ts +278 -0
  171. package/packages/shared-perm-presets/src/index.ts +18 -0
  172. package/packages/shared-perm-presets/src/presets/ci-environment.ts +34 -0
  173. package/packages/shared-perm-presets/src/presets/full-env.ts +16 -0
  174. package/packages/shared-perm-presets/src/presets/git-workflow.ts +40 -0
  175. package/packages/shared-perm-presets/src/presets/index.ts +8 -0
  176. package/packages/shared-perm-presets/src/presets/kb-platform.ts +30 -0
  177. package/packages/shared-perm-presets/src/presets/llm-access.ts +29 -0
  178. package/packages/shared-perm-presets/src/presets/minimal.ts +21 -0
  179. package/packages/shared-perm-presets/src/presets/npm-publish.ts +48 -0
  180. package/packages/shared-perm-presets/src/presets/vector-store.ts +40 -0
  181. package/packages/shared-perm-presets/src/types.ts +192 -0
  182. package/packages/shared-perm-presets/tsconfig.build.json +15 -0
  183. package/packages/shared-perm-presets/tsconfig.json +9 -0
  184. package/packages/shared-perm-presets/tsup.config.ts +8 -0
  185. package/packages/shared-perm-presets/vitest.config.ts +9 -0
  186. package/packages/shared-testing/CHANGELOG.md +20 -0
  187. package/packages/shared-testing/README.md +430 -0
  188. package/packages/shared-testing/package.json +51 -0
  189. package/packages/shared-testing/src/__tests__/create-test-context.test.ts +199 -0
  190. package/packages/shared-testing/src/__tests__/mock-cache.test.ts +174 -0
  191. package/packages/shared-testing/src/__tests__/mock-llm.test.ts +212 -0
  192. package/packages/shared-testing/src/__tests__/setup-platform.test.ts +90 -0
  193. package/packages/shared-testing/src/__tests__/test-command.test.ts +557 -0
  194. package/packages/shared-testing/src/create-test-context.ts +550 -0
  195. package/packages/shared-testing/src/index.ts +77 -0
  196. package/packages/shared-testing/src/mock-cache.ts +179 -0
  197. package/packages/shared-testing/src/mock-llm.ts +319 -0
  198. package/packages/shared-testing/src/mock-logger.ts +97 -0
  199. package/packages/shared-testing/src/mock-storage.ts +108 -0
  200. package/packages/shared-testing/src/setup-platform.ts +101 -0
  201. package/packages/shared-testing/src/test-command.ts +288 -0
  202. package/packages/shared-testing/tsconfig.build.json +15 -0
  203. package/packages/shared-testing/tsconfig.json +9 -0
  204. package/packages/shared-testing/tsup.config.ts +20 -0
  205. package/packages/shared-testing/vitest.config.ts +3 -0
  206. package/packages/shared-tool-kit/CHANGELOG.md +20 -0
  207. package/packages/shared-tool-kit/package.json +47 -0
  208. package/packages/shared-tool-kit/src/__tests__/factory.test.ts +103 -0
  209. package/packages/shared-tool-kit/src/__tests__/mock-tool.test.ts +95 -0
  210. package/packages/shared-tool-kit/src/factory.ts +126 -0
  211. package/packages/shared-tool-kit/src/index.ts +32 -0
  212. package/packages/shared-tool-kit/src/testing/index.ts +84 -0
  213. package/packages/shared-tool-kit/tsconfig.build.json +15 -0
  214. package/packages/shared-tool-kit/tsconfig.json +9 -0
  215. package/packages/shared-tool-kit/tsup.config.ts +21 -0
  216. package/pnpm-workspace.yaml +11070 -0
  217. package/prettierrc.json +1 -0
  218. package/scripts/devkit-sync.mjs +37 -0
  219. package/scripts/hooks/post-push +9 -0
  220. package/scripts/hooks/pre-commit +9 -0
  221. package/scripts/hooks/pre-push +9 -0
  222. package/tsconfig.base.json +9 -0
  223. package/tsconfig.build.json +15 -0
  224. package/tsconfig.json +9 -0
  225. package/tsconfig.paths.json +50 -0
  226. package/tsconfig.tools.json +18 -0
  227. package/tsup.config.bin.ts +34 -0
  228. package/tsup.config.cli.ts +41 -0
  229. package/tsup.config.dual.ts +46 -0
  230. package/tsup.config.ts +36 -0
  231. package/tsup.external.json +104 -0
  232. package/vitest.config.ts +48 -0
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Timing tracker utility for CLI commands
3
+ * Provides checkpoint-based timing measurement
4
+ */
5
+
6
+ export class TimingTracker {
7
+ private start: number;
8
+ private checkpoints: Record<string, number> = {};
9
+
10
+ constructor() {
11
+ this.start = Date.now();
12
+ }
13
+
14
+ /**
15
+ * Record a timing checkpoint
16
+ */
17
+ checkpoint(name: string): void {
18
+ this.checkpoints[name] = Date.now() - this.start;
19
+ }
20
+
21
+ /**
22
+ * Get total elapsed time in milliseconds
23
+ */
24
+ total(): number {
25
+ return Date.now() - this.start;
26
+ }
27
+
28
+ /**
29
+ * Get timing breakdown including total
30
+ */
31
+ breakdown(): Record<string, number> {
32
+ return { ...this.checkpoints, total: this.total() };
33
+ }
34
+
35
+ /**
36
+ * Get timing breakdown without total
37
+ */
38
+ checkpointsOnly(): Record<string, number> {
39
+ return { ...this.checkpoints };
40
+ }
41
+
42
+ /**
43
+ * Reset the timer
44
+ */
45
+ reset(): void {
46
+ this.start = Date.now();
47
+ this.checkpoints = {};
48
+ }
49
+
50
+ /**
51
+ * Get elapsed time since last checkpoint or start
52
+ */
53
+ sinceLastCheckpoint(): number {
54
+ const lastCheckpointTime = Math.max(...Object.values(this.checkpoints), 0);
55
+ return Date.now() - this.start - lastCheckpointTime;
56
+ }
57
+
58
+ /**
59
+ * Get elapsed time since a specific checkpoint
60
+ */
61
+ sinceCheckpoint(checkpointName: string): number | null {
62
+ const checkpointTime = this.checkpoints[checkpointName];
63
+ if (checkpointTime === undefined) {
64
+ return null;
65
+ }
66
+ return Date.now() - this.start - checkpointTime;
67
+ }
68
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Resolve the current working directory from a CLI context-like object.
3
+ * Falls back to the process cwd when the context does not provide one.
4
+ */
5
+ export function getContextCwd(input: { cwd?: string } | undefined): string {
6
+ if (input && typeof input.cwd === "string" && input.cwd.length > 0) {
7
+ return input.cwd;
8
+ }
9
+ return process.cwd();
10
+ }
11
+
12
+
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Environment variable system for declarative env definition with type safety
3
+ *
4
+ * Usage:
5
+ * ```typescript
6
+ * // In contracts
7
+ * export const myEnv = defineEnv({
8
+ * MY_API_KEY: { type: 'string', description: 'API key for service' },
9
+ * MY_ENABLED: { type: 'boolean', default: true },
10
+ * MY_TIMEOUT: { type: 'number', default: 5000 },
11
+ * });
12
+ *
13
+ * // In command
14
+ * export default defineCommand({
15
+ * handler: {
16
+ * async execute(ctx, input) {
17
+ * const env = myEnv.parse(ctx.runtime);
18
+ * console.log(env.MY_API_KEY); // string | undefined
19
+ * console.log(env.MY_ENABLED); // boolean
20
+ * }
21
+ * }
22
+ * });
23
+ * ```
24
+ */
25
+
26
+ import {
27
+ type FlagSpec,
28
+ type FlagsSchema,
29
+ type InferFlagsType,
30
+ parseBoolean,
31
+ parseString,
32
+ parseNumber,
33
+ } from './flags.js';
34
+
35
+ /**
36
+ * Runtime API interface (minimal for env parsing)
37
+ * Avoids dependency on @kb-labs/plugin-contracts
38
+ */
39
+ export interface RuntimeLike {
40
+ env(key: string): string | undefined;
41
+ }
42
+
43
+ // ============================================================================
44
+ // Types
45
+ // ============================================================================
46
+
47
+ /**
48
+ * Environment variable schema (reuses FlagSpec types)
49
+ */
50
+ export type EnvSchema = FlagsSchema;
51
+
52
+ /**
53
+ * Environment variable definition with parse method
54
+ */
55
+ export interface EnvDefinition<T extends EnvSchema> {
56
+ /** Schema for documentation and validation */
57
+ schema: T;
58
+ /** Inferred TypeScript type */
59
+ type: InferFlagsType<T>;
60
+ /** Parse environment variables from RuntimeLike */
61
+ parse: (runtime: RuntimeLike) => InferFlagsType<T>;
62
+ }
63
+
64
+ // ============================================================================
65
+ // defineEnv - main API
66
+ // ============================================================================
67
+
68
+ /**
69
+ * Define environment variables with type safety and validation
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * export const commitEnv = defineEnv({
74
+ * KB_COMMIT_LLM_ENABLED: {
75
+ * type: 'boolean',
76
+ * default: true,
77
+ * description: 'Enable LLM analysis',
78
+ * },
79
+ * KB_COMMIT_LLM_TEMPERATURE: {
80
+ * type: 'number',
81
+ * default: 0.3,
82
+ * description: 'LLM temperature (0-1)',
83
+ * validate: (v) => {
84
+ * if (v < 0 || v > 1) throw new Error('Must be 0-1');
85
+ * },
86
+ * },
87
+ * });
88
+ *
89
+ * // Use in command
90
+ * const env = commitEnv.parse(ctx.runtime);
91
+ * // Type: { KB_COMMIT_LLM_ENABLED: boolean; KB_COMMIT_LLM_TEMPERATURE: number }
92
+ * ```
93
+ */
94
+ export function defineEnv<T extends EnvSchema>(schema: T): EnvDefinition<T> {
95
+ return {
96
+ schema,
97
+ type: {} as InferFlagsType<T>,
98
+ parse: (runtime: RuntimeLike) => parseEnvFromRuntime(runtime, schema),
99
+ };
100
+ }
101
+
102
+ // ============================================================================
103
+ // Runtime parsing
104
+ // ============================================================================
105
+
106
+ /**
107
+ * Parse environment variables from RuntimeLike with validation and defaults
108
+ */
109
+ export function parseEnvFromRuntime<T extends EnvSchema>(
110
+ runtime: RuntimeLike,
111
+ schema: T
112
+ ): InferFlagsType<T> {
113
+ const result: any = {};
114
+
115
+ for (const [key, spec] of Object.entries(schema)) {
116
+ const rawValue = runtime.env(key);
117
+
118
+ // Apply default if undefined
119
+ if (rawValue === undefined) {
120
+ if ('default' in spec) {
121
+ result[key] = spec.default;
122
+ }
123
+ continue;
124
+ }
125
+
126
+ // Parse based on type (reuse parsers from flags)
127
+ result[key] = parseEnvValue(rawValue, key, spec);
128
+ }
129
+
130
+ return result;
131
+ }
132
+
133
+ /**
134
+ * Parse single env value with type validation
135
+ */
136
+ function parseEnvValue(value: string | undefined, key: string, spec: FlagSpec): any {
137
+ if (value === undefined) {
138
+ return undefined;
139
+ }
140
+
141
+ switch (spec.type) {
142
+ case 'boolean':
143
+ return parseBoolean(value, key);
144
+
145
+ case 'string':
146
+ const strValue = parseString(value, key);
147
+ // Custom validation for string
148
+ if (spec.validate) {
149
+ spec.validate(strValue);
150
+ }
151
+ return strValue;
152
+
153
+ case 'number':
154
+ const numValue = parseNumber(value, key);
155
+ // Custom validation for number
156
+ if (spec.validate) {
157
+ spec.validate(numValue);
158
+ }
159
+ return numValue;
160
+
161
+ default:
162
+ return value;
163
+ }
164
+ }
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Flag system for declarative CLI flag definition with type safety
3
+ *
4
+ * Usage:
5
+ * ```typescript
6
+ * // In contracts
7
+ * export const myFlags = defineFlags({
8
+ * scope: { type: 'string', description: 'Filter by scope' },
9
+ * verbose: { type: 'boolean', default: false },
10
+ * });
11
+ *
12
+ * // In command
13
+ * export default defineCommand({
14
+ * flags: myFlags,
15
+ * handler: {
16
+ * async execute(ctx, input: typeof myFlags.type) {
17
+ * const { scope, verbose } = input;
18
+ * }
19
+ * }
20
+ * });
21
+ * ```
22
+ */
23
+
24
+ // ============================================================================
25
+ // Types
26
+ // ============================================================================
27
+
28
+ export type FlagType = 'string' | 'boolean' | 'number';
29
+
30
+ export interface BaseFlagSpec<T extends FlagType> {
31
+ type: T;
32
+ description?: string;
33
+ examples?: string[];
34
+ deprecated?: boolean | string;
35
+ }
36
+
37
+ export interface StringFlagSpec extends BaseFlagSpec<'string'> {
38
+ default?: string;
39
+ validate?: (value: string) => void | Promise<void>;
40
+ }
41
+
42
+ export interface BooleanFlagSpec extends BaseFlagSpec<'boolean'> {
43
+ default?: boolean;
44
+ }
45
+
46
+ export interface NumberFlagSpec extends BaseFlagSpec<'number'> {
47
+ default?: number;
48
+ validate?: (value: number) => void | Promise<void>;
49
+ }
50
+
51
+ export type FlagSpec = StringFlagSpec | BooleanFlagSpec | NumberFlagSpec;
52
+
53
+ export type FlagsSchema = Record<string, FlagSpec>;
54
+
55
+ // ============================================================================
56
+ // Type inference
57
+ // ============================================================================
58
+
59
+ type InferFlagType<T extends FlagSpec> =
60
+ T extends StringFlagSpec
61
+ ? T extends { default: string } ? string : string | undefined
62
+ : T extends BooleanFlagSpec
63
+ ? T extends { default: boolean } ? boolean : boolean | undefined
64
+ : T extends NumberFlagSpec
65
+ ? T extends { default: number } ? number : number | undefined
66
+ : never;
67
+
68
+ export type InferFlagsType<T extends FlagsSchema> = {
69
+ [K in keyof T]: InferFlagType<T[K]>;
70
+ };
71
+
72
+ // ============================================================================
73
+ // defineFlags - main API
74
+ // ============================================================================
75
+
76
+ export interface FlagsDefinition<T extends FlagsSchema> {
77
+ /** Schema for manifest */
78
+ schema: T;
79
+ /** Inferred TypeScript type */
80
+ type: InferFlagsType<T>;
81
+ /** Parse and validate flags from raw input */
82
+ parse: (input: unknown) => InferFlagsType<T>;
83
+ }
84
+
85
+ /**
86
+ * Define CLI flags with type safety and validation
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * export const commitFlags = defineFlags({
91
+ * scope: {
92
+ * type: 'string',
93
+ * description: 'Limit to package or path',
94
+ * examples: ['@kb-labs/core', 'packages/**'],
95
+ * },
96
+ * 'dry-run': {
97
+ * type: 'boolean',
98
+ * description: 'Preview without applying',
99
+ * default: false,
100
+ * },
101
+ * });
102
+ *
103
+ * // Use in command
104
+ * type MyInput = typeof commitFlags.type;
105
+ * // Result: { scope?: string; 'dry-run': boolean }
106
+ * ```
107
+ */
108
+ export function defineFlags<T extends FlagsSchema>(schema: T): FlagsDefinition<T> {
109
+ return {
110
+ schema,
111
+ type: {} as InferFlagsType<T>,
112
+ parse: (input: unknown) => parseFlagsFromInput(input, schema),
113
+ };
114
+ }
115
+
116
+ // ============================================================================
117
+ // Runtime parsing and validation
118
+ // ============================================================================
119
+
120
+ /**
121
+ * Parse flags from raw input with type validation and defaults
122
+ */
123
+ export function parseFlagsFromInput<T extends FlagsSchema>(
124
+ input: unknown,
125
+ schema: T
126
+ ): InferFlagsType<T> {
127
+ const result: any = {};
128
+ const rawInput = input as Record<string, unknown>;
129
+
130
+ for (const [key, spec] of Object.entries(schema)) {
131
+ const value = rawInput?.[key];
132
+
133
+ // Apply default if value is undefined
134
+ if (value === undefined) {
135
+ if ('default' in spec) {
136
+ result[key] = spec.default;
137
+ }
138
+ continue;
139
+ }
140
+
141
+ // Type validation and coercion
142
+ switch (spec.type) {
143
+ case 'boolean':
144
+ result[key] = parseBoolean(value, key);
145
+ break;
146
+ case 'string':
147
+ result[key] = parseString(value, key);
148
+ // Custom validation for string
149
+ if (spec.validate && result[key] !== undefined) {
150
+ spec.validate(result[key]);
151
+ }
152
+ break;
153
+ case 'number':
154
+ result[key] = parseNumber(value, key);
155
+ // Custom validation for number
156
+ if (spec.validate && result[key] !== undefined) {
157
+ spec.validate(result[key]);
158
+ }
159
+ break;
160
+ }
161
+ }
162
+
163
+ return result;
164
+ }
165
+
166
+ // ============================================================================
167
+ // Type parsers (exported for reuse in env.ts)
168
+ // ============================================================================
169
+
170
+ export function parseBoolean(value: unknown, flagName: string): boolean {
171
+ if (typeof value === 'boolean') {
172
+ return value;
173
+ }
174
+
175
+ if (typeof value === 'string') {
176
+ const lower = value.toLowerCase();
177
+ if (lower === 'true' || lower === '1' || lower === 'yes') {return true;}
178
+ if (lower === 'false' || lower === '0' || lower === 'no') {return false;}
179
+ }
180
+
181
+ throw new Error(
182
+ `Flag "${flagName}" must be boolean, got ${typeof value}. ` +
183
+ `Use true/false or 1/0 or yes/no.`
184
+ );
185
+ }
186
+
187
+ export function parseString(value: unknown, flagName: string): string {
188
+ if (typeof value === 'string') {
189
+ return value;
190
+ }
191
+
192
+ // Coerce number to string
193
+ if (typeof value === 'number') {
194
+ return String(value);
195
+ }
196
+
197
+ throw new Error(
198
+ `Flag "${flagName}" must be string, got ${typeof value}.`
199
+ );
200
+ }
201
+
202
+ export function parseNumber(value: unknown, flagName: string): number {
203
+ if (typeof value === 'number') {
204
+ if (!Number.isFinite(value)) {
205
+ throw new Error(`Flag "${flagName}" must be finite number, got ${value}.`);
206
+ }
207
+ return value;
208
+ }
209
+
210
+ if (typeof value === 'string') {
211
+ const trimmed = value.trim();
212
+ const parsed = Number(trimmed);
213
+ if (!Number.isFinite(parsed)) {
214
+ throw new Error(
215
+ `Flag "${flagName}" must be number, got invalid string "${value}".`
216
+ );
217
+ }
218
+ return parsed;
219
+ }
220
+
221
+ throw new Error(
222
+ `Flag "${flagName}" must be number, got ${typeof value}.`
223
+ );
224
+ }
225
+
226
+ // ============================================================================
227
+ // Legacy helper (keep for backward compatibility)
228
+ // ============================================================================
229
+
230
+ export function parseNumberFlag(value: unknown): number | undefined {
231
+ if (typeof value === 'number') {
232
+ return Number.isFinite(value) ? value : undefined;
233
+ }
234
+
235
+ if (typeof value === 'string') {
236
+ const trimmed = value.trim();
237
+ if (trimmed.length === 0) {
238
+ return undefined;
239
+ }
240
+
241
+ const parsed = Number(trimmed);
242
+ return Number.isFinite(parsed) ? parsed : undefined;
243
+ }
244
+
245
+ return undefined;
246
+ }
247
+
248
+ // ============================================================================
249
+ // Utility: Merge input.flags into input (for V3 compatibility)
250
+ // ============================================================================
251
+
252
+ /**
253
+ * Merge input.flags into input root (V3 compatibility helper)
254
+ *
255
+ * @example
256
+ * ```typescript
257
+ * const raw = { scope: 'old', flags: { scope: 'new', json: true } };
258
+ * const merged = mergeFlags(raw);
259
+ * // Result: { scope: 'new', json: true, flags: {...} }
260
+ * ```
261
+ */
262
+ export function mergeFlags<T extends Record<string, unknown>>(input: T): T {
263
+ if (!input.flags || typeof input.flags !== 'object') {
264
+ return input;
265
+ }
266
+
267
+ // Merge: root values first, then flags override
268
+ return { ...input, ...input.flags };
269
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Normalize filesystem paths to POSIX (forward-slash) form.
3
+ */
4
+ export function toPosixPath(input: string): string {
5
+ return input.replace(/\\/g, "/");
6
+ }
7
+
8
+
@@ -0,0 +1,15 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "baseUrl": ".",
6
+ "paths": {}
7
+ },
8
+ "include": [
9
+ "src/**/*"
10
+ ],
11
+ "exclude": [
12
+ "dist",
13
+ "node_modules"
14
+ ]
15
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "extends": "@kb-labs/devkit/tsconfig/node.json",
4
+ "compilerOptions": {
5
+ "rootDir": "src",
6
+ "outDir": "dist"
7
+ },
8
+ "include": ["src"]
9
+ }
@@ -0,0 +1,11 @@
1
+ import { defineConfig } from 'tsup';
2
+ import dualPreset from '@kb-labs/devkit/tsup/dual';
3
+
4
+ export default defineConfig({
5
+ ...dualPreset,
6
+ entry: {
7
+ index: "src/index.ts",
8
+ debug: "src/debug/index.ts",
9
+ },
10
+ tsconfig: "tsconfig.build.json", // Use build-specific tsconfig without paths
11
+ });
@@ -0,0 +1,15 @@
1
+ import preset from '@kb-labs/devkit/vitest/node'
2
+ import { defineConfig } from 'vitest/config'
3
+
4
+ export default defineConfig({
5
+ ...preset,
6
+ test: {
7
+ ...preset.test,
8
+ include: [
9
+ 'src/**/*.spec.ts',
10
+ 'src/**/*.test.ts',
11
+ 'src/**/__tests__/**/*.spec.ts',
12
+ 'src/**/__tests__/**/*.test.ts',
13
+ ],
14
+ },
15
+ })
@@ -0,0 +1,20 @@
1
+ ## [1.1.0] - 2026-03-24
2
+
3
+ **5 packages** bumped to v1.1.0
4
+
5
+ | Package | Previous | Bump |
6
+ |---------|----------|------|
7
+ | `@kb-labs/perm-presets` | 1.0.0 | minor |
8
+ | `@kb-labs/shared-command-kit` | 1.0.0 | minor |
9
+ | `@kb-labs/shared-tool-kit` | 1.0.0 | minor |
10
+ | `@kb-labs/shared-cli-ui` | 1.0.0 | minor |
11
+ | `@kb-labs/shared-testing` | 1.0.0 | minor |
12
+
13
+ ### ✨ New Features
14
+
15
+ - **config**: Introduces new configuration files for package management, allowing users to easily manage dependencies and ensure consistent environments across projects.
16
+ - **github**: Implements GitHub workflows for CI/CD, streamlining the development process and enabling quicker, more reliable software updates for users.
17
+
18
+ ### 🐛 Bug Fixes
19
+
20
+ - **tests**: Improves code clarity by using an object type instead of a placeholder, which helps prevent misunderstandings in the codebase and enhances maintainability. Additionally, it resolves a linting issue that could lead to confusion when no value is returned from certain functions.
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 KB Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+