@secondlayer/cli 0.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,380 @@
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/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ PluginManager: () => PluginManager,
34
+ defineConfig: () => defineConfig
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+
38
+ // src/utils/config.ts
39
+ var import_esbuild = require("esbuild");
40
+
41
+ // src/core/plugin-manager.ts
42
+ var import_prettier = require("prettier");
43
+ var import_fs = require("fs");
44
+ var import_path = __toESM(require("path"), 1);
45
+ var import_transactions = require("@stacks/transactions");
46
+ var PluginManager = class {
47
+ constructor() {
48
+ this.plugins = [];
49
+ this.logger = this.createLogger();
50
+ this.utils = this.createUtils();
51
+ this.executionContext = {
52
+ phase: "config",
53
+ startTime: Date.now(),
54
+ results: /* @__PURE__ */ new Map()
55
+ };
56
+ }
57
+ /**
58
+ * Register a plugin
59
+ */
60
+ register(plugin) {
61
+ if (!plugin.name || !plugin.version) {
62
+ throw new Error("Plugin must have a name and version");
63
+ }
64
+ const existing = this.plugins.find((p) => p.name === plugin.name);
65
+ if (existing) {
66
+ throw new Error(
67
+ `Plugin "${plugin.name}" is already registered (version ${existing.version})`
68
+ );
69
+ }
70
+ this.plugins.push(plugin);
71
+ this.logger.debug(`Registered plugin: ${plugin.name}@${plugin.version}`);
72
+ }
73
+ /**
74
+ * Get all registered plugins
75
+ */
76
+ getPlugins() {
77
+ return [...this.plugins];
78
+ }
79
+ /**
80
+ * Transform user config through all plugins
81
+ */
82
+ async transformConfig(config) {
83
+ this.executionContext.phase = "config";
84
+ let transformedConfig = { ...config };
85
+ for (const plugin of this.plugins) {
86
+ if (plugin.transformConfig) {
87
+ this.executionContext.currentPlugin = plugin;
88
+ try {
89
+ const result = await plugin.transformConfig(transformedConfig);
90
+ transformedConfig = result;
91
+ this.recordHookResult(plugin.name, "transformConfig", {
92
+ success: true
93
+ });
94
+ } catch (error) {
95
+ const err = error;
96
+ this.recordHookResult(plugin.name, "transformConfig", {
97
+ success: false,
98
+ error: err
99
+ });
100
+ throw new Error(
101
+ `Plugin "${plugin.name}" failed during config transformation: ${err.message}`
102
+ );
103
+ }
104
+ }
105
+ }
106
+ const resolvedConfig = {
107
+ ...transformedConfig,
108
+ plugins: this.plugins
109
+ };
110
+ return resolvedConfig;
111
+ }
112
+ /**
113
+ * Transform contracts through all plugins
114
+ */
115
+ async transformContracts(contracts, _config) {
116
+ const processedContracts = [];
117
+ for (let contract of contracts) {
118
+ if (contract._clarinetSource && contract.abi) {
119
+ const address = typeof contract.address === "string" ? contract.address : "";
120
+ const [contractAddress, contractName] = address.split(".");
121
+ const processed = {
122
+ name: contract.name || contractName,
123
+ address: contractAddress,
124
+ contractName,
125
+ abi: contract.abi,
126
+ source: "local",
127
+ metadata: { source: "clarinet" }
128
+ };
129
+ processedContracts.push(processed);
130
+ continue;
131
+ }
132
+ for (const plugin of this.plugins) {
133
+ if (plugin.transformContract) {
134
+ this.executionContext.currentPlugin = plugin;
135
+ try {
136
+ contract = await plugin.transformContract(contract);
137
+ this.recordHookResult(plugin.name, "transformContract", {
138
+ success: true
139
+ });
140
+ } catch (error) {
141
+ const err = error;
142
+ this.recordHookResult(plugin.name, "transformContract", {
143
+ success: false,
144
+ error: err
145
+ });
146
+ this.logger.warn(
147
+ `Plugin "${plugin.name}" failed to transform contract: ${err.message}`
148
+ );
149
+ }
150
+ }
151
+ }
152
+ if (contract.abi) {
153
+ const processed = {
154
+ name: contract.name || "unknown",
155
+ address: typeof contract.address === "string" ? contract.address.split(".")[0] : "unknown",
156
+ contractName: contract.name || "unknown",
157
+ abi: contract.abi,
158
+ source: "api",
159
+ // Use "api" as default for plugin-processed contracts
160
+ metadata: contract.metadata
161
+ };
162
+ processedContracts.push(processed);
163
+ }
164
+ }
165
+ return processedContracts;
166
+ }
167
+ /**
168
+ * Execute lifecycle hooks
169
+ */
170
+ async executeHook(hookName, context) {
171
+ for (const plugin of this.plugins) {
172
+ const hook = plugin[hookName];
173
+ if (typeof hook === "function") {
174
+ this.executionContext.currentPlugin = plugin;
175
+ try {
176
+ await hook.call(plugin, context);
177
+ this.recordHookResult(plugin.name, hookName, {
178
+ success: true
179
+ });
180
+ } catch (error) {
181
+ const err = error;
182
+ this.recordHookResult(plugin.name, hookName, {
183
+ success: false,
184
+ error: err
185
+ });
186
+ this.logger.error(
187
+ `Plugin "${plugin.name}" failed during ${hookName}: ${err.message}`
188
+ );
189
+ }
190
+ }
191
+ }
192
+ }
193
+ /**
194
+ * Execute generation phase with full context
195
+ */
196
+ async executeGeneration(contracts, config) {
197
+ this.executionContext.phase = "generate";
198
+ const outputs = /* @__PURE__ */ new Map();
199
+ const context = {
200
+ config,
201
+ logger: this.logger,
202
+ utils: this.utils,
203
+ contracts,
204
+ outputs,
205
+ augment: (outputKey, contractName, content) => {
206
+ this.augmentOutput(outputs, outputKey, contractName, content);
207
+ },
208
+ addOutput: (key, output) => {
209
+ outputs.set(key, output);
210
+ }
211
+ };
212
+ await this.executeHook("beforeGenerate", context);
213
+ await this.executeHook("generate", context);
214
+ await this.executeHook("afterGenerate", context);
215
+ return outputs;
216
+ }
217
+ /**
218
+ * Transform outputs through plugins
219
+ */
220
+ async transformOutputs(outputs) {
221
+ this.executionContext.phase = "output";
222
+ const transformedOutputs = /* @__PURE__ */ new Map();
223
+ for (const [key, output] of outputs) {
224
+ let transformedContent = output.content;
225
+ for (const plugin of this.plugins) {
226
+ if (plugin.transformOutput) {
227
+ this.executionContext.currentPlugin = plugin;
228
+ try {
229
+ transformedContent = await plugin.transformOutput(
230
+ transformedContent,
231
+ output.type || "other"
232
+ );
233
+ this.recordHookResult(plugin.name, "transformOutput", {
234
+ success: true
235
+ });
236
+ } catch (error) {
237
+ const err = error;
238
+ this.recordHookResult(plugin.name, "transformOutput", {
239
+ success: false,
240
+ error: err
241
+ });
242
+ this.logger.warn(
243
+ `Plugin "${plugin.name}" failed to transform output: ${err.message}`
244
+ );
245
+ }
246
+ }
247
+ }
248
+ transformedOutputs.set(key, {
249
+ ...output,
250
+ content: transformedContent
251
+ });
252
+ }
253
+ return transformedOutputs;
254
+ }
255
+ /**
256
+ * Write outputs to disk
257
+ */
258
+ async writeOutputs(outputs) {
259
+ for (const [, output] of outputs) {
260
+ try {
261
+ const resolvedPath = import_path.default.resolve(process.cwd(), output.path);
262
+ await this.utils.ensureDir(import_path.default.dirname(resolvedPath));
263
+ await this.utils.writeFile(resolvedPath, output.content);
264
+ } catch (error) {
265
+ const err = error;
266
+ this.logger.error(`Failed to write ${output.path}: ${err.message}`);
267
+ throw err;
268
+ }
269
+ }
270
+ }
271
+ /**
272
+ * Get execution results for debugging
273
+ */
274
+ getExecutionResults() {
275
+ return new Map(this.executionContext.results);
276
+ }
277
+ /**
278
+ * Augment existing output with additional content
279
+ */
280
+ augmentOutput(outputs, outputKey, contractName, content) {
281
+ const existing = outputs.get(outputKey);
282
+ if (!existing) {
283
+ this.logger.warn(`Cannot augment non-existent output: ${outputKey}`);
284
+ return;
285
+ }
286
+ const augmentedContent = `${existing.content}
287
+
288
+ // Augmented by plugin for ${contractName}
289
+ ${JSON.stringify(content, null, 2)}`;
290
+ outputs.set(outputKey, {
291
+ ...existing,
292
+ content: augmentedContent
293
+ });
294
+ }
295
+ /**
296
+ * Record hook execution result
297
+ */
298
+ recordHookResult(pluginName, hookName, result) {
299
+ const key = `${pluginName}:${hookName}`;
300
+ const existing = this.executionContext.results.get(key) || [];
301
+ existing.push({ ...result, plugin: pluginName });
302
+ this.executionContext.results.set(key, existing);
303
+ }
304
+ /**
305
+ * Create logger instance
306
+ */
307
+ createLogger() {
308
+ return {
309
+ info: (message) => console.log(`\u2139\uFE0F ${message}`),
310
+ warn: (message) => console.warn(`\u26A0\uFE0F ${message}`),
311
+ error: (message) => console.error(`\u274C ${message}`),
312
+ debug: (message) => {
313
+ if (process.env.DEBUG) {
314
+ console.log(`\u{1F41B} ${message}`);
315
+ }
316
+ },
317
+ success: (message) => console.log(`\u2705 ${message}`)
318
+ };
319
+ }
320
+ /**
321
+ * Create utils instance
322
+ */
323
+ createUtils() {
324
+ return {
325
+ toCamelCase: (str) => {
326
+ return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
327
+ },
328
+ toKebabCase: (str) => {
329
+ return str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
330
+ },
331
+ validateAddress: (address) => {
332
+ return (0, import_transactions.validateStacksAddress)(address.split(".")[0]);
333
+ },
334
+ parseContractId: (contractId) => {
335
+ const [address, contractName] = contractId.split(".");
336
+ return { address, contractName };
337
+ },
338
+ formatCode: async (code) => {
339
+ return (0, import_prettier.format)(code, {
340
+ parser: "typescript",
341
+ singleQuote: true,
342
+ semi: true,
343
+ printWidth: 100,
344
+ trailingComma: "es5"
345
+ });
346
+ },
347
+ resolvePath: (relativePath) => {
348
+ return import_path.default.resolve(process.cwd(), relativePath);
349
+ },
350
+ fileExists: async (filePath) => {
351
+ try {
352
+ await import_fs.promises.access(filePath);
353
+ return true;
354
+ } catch {
355
+ return false;
356
+ }
357
+ },
358
+ readFile: async (filePath) => {
359
+ return import_fs.promises.readFile(filePath, "utf-8");
360
+ },
361
+ writeFile: async (filePath, content) => {
362
+ await import_fs.promises.writeFile(filePath, content, "utf-8");
363
+ },
364
+ ensureDir: async (dirPath) => {
365
+ await import_fs.promises.mkdir(dirPath, { recursive: true });
366
+ }
367
+ };
368
+ }
369
+ };
370
+
371
+ // src/utils/config.ts
372
+ function defineConfig(configOrDefiner) {
373
+ return configOrDefiner;
374
+ }
375
+ // Annotate the CommonJS export names for ESM import in node:
376
+ 0 && (module.exports = {
377
+ PluginManager,
378
+ defineConfig
379
+ });
380
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/utils/config.ts","../src/core/plugin-manager.ts"],"sourcesContent":["/**\n * @stacks/codegen\n * CLI tool for generating type-safe Stacks contract interfaces\n */\n\nexport { defineConfig } from \"./utils/config.js\";\nexport type {\n StacksConfig,\n ContractSource,\n NetworkName,\n} from \"./types/config.js\";\n\nexport type {\n ClarityContract,\n ClarityFunction,\n ClarityType,\n ContractCallParams,\n ReadOnlyCallParams,\n} from \"@secondlayer/clarity-types\";\n\n// Plugin system exports\nexport type {\n StacksCodegenPlugin,\n PluginFactory,\n PluginOptions,\n UserConfig,\n ResolvedConfig,\n GenerateContext,\n PluginContext,\n Logger,\n PluginUtils,\n GeneratedOutput,\n ProcessedContract,\n ContractConfig,\n OutputType,\n} from \"./types/plugin.js\";\n\nexport { PluginManager } from \"./core/plugin-manager.js\";\n","import { promises as fs } from \"fs\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { createRequire } from \"module\";\nimport { transformSync } from \"esbuild\";\nimport type { StacksConfig, ConfigDefiner } from \"../types/config.js\";\nimport type { ResolvedConfig } from \"../types/plugin.js\";\nimport { PluginManager } from \"../core/plugin-manager.js\";\n\n/**\n * Config file utilities\n */\n\nconst CONFIG_FILE_NAMES = [\n \"stacks.config.ts\",\n \"stacks.config.js\",\n \"stacks.config.mjs\",\n];\n\nexport async function findConfigFile(cwd: string): Promise<string | null> {\n for (const fileName of CONFIG_FILE_NAMES) {\n const filePath = path.join(cwd, fileName);\n try {\n await fs.access(filePath);\n return filePath;\n } catch {\n // File doesn't exist, continue\n }\n }\n return null;\n}\n\nexport async function loadConfig(configPath?: string): Promise<ResolvedConfig> {\n const cwd = process.cwd();\n\n const resolvedPath = configPath\n ? path.resolve(cwd, configPath)\n : await findConfigFile(cwd);\n\n if (!resolvedPath) {\n throw new Error(\n \"No config file found. Create a stacks.config.ts file or specify a path with --config\"\n );\n }\n\n let config: any;\n\n if (resolvedPath.endsWith(\".ts\")) {\n const code = await fs.readFile(resolvedPath, \"utf-8\");\n\n // Transform TypeScript to JavaScript, replacing the @stacks/codegen import\n // For development/linked packages, we need to resolve to the actual package location\n // This will work both for published packages and local development\n let replacementPath: string;\n\n try {\n // Try to resolve @stacks/codegen as if it were a normal package\n const require = createRequire(import.meta.url);\n const packagePath = require.resolve(\"@stacks/codegen\");\n replacementPath = pathToFileURL(packagePath).href;\n } catch {\n // Fallback: resolve relative to current module (for development)\n const currentModuleDir = path.dirname(new URL(import.meta.url).pathname);\n const indexPath = path.resolve(currentModuleDir, \"../index.js\");\n replacementPath = pathToFileURL(indexPath).href;\n }\n\n const transformedCode = code.replace(\n /from\\s+[\"']@stacks\\/cli[\"']/g,\n `from '${replacementPath}'`\n );\n\n const result = transformSync(transformedCode, {\n format: \"esm\",\n target: \"node18\",\n loader: \"ts\",\n });\n\n const tempPath = resolvedPath.replace(/\\.ts$/, \".mjs\");\n await fs.writeFile(tempPath, result.code);\n\n try {\n const fileUrl = pathToFileURL(tempPath).href;\n const module = await import(fileUrl);\n config = module.default;\n } finally {\n await fs.unlink(tempPath).catch(() => {});\n }\n } else {\n const fileUrl = pathToFileURL(resolvedPath).href;\n const module = await import(fileUrl);\n config = module.default;\n }\n\n if (!config) {\n throw new Error(\"Config file must export a default configuration\");\n }\n\n if (typeof config === \"function\") {\n config = config({} as StacksConfig);\n }\n\n validateConfig(config);\n\n // Process plugins if they exist\n const pluginManager = new PluginManager();\n\n if (config.plugins && Array.isArray(config.plugins)) {\n for (const plugin of config.plugins) {\n pluginManager.register(plugin);\n }\n }\n\n // Transform config through plugins\n const resolvedConfig = await pluginManager.transformConfig(config);\n\n return resolvedConfig;\n}\n\nexport function validateConfig(\n config: unknown\n): asserts config is StacksConfig {\n if (!config || typeof config !== \"object\") {\n throw new Error(\"Config must be an object\");\n }\n\n const c = config as any;\n\n // Contracts are optional now since plugins can provide them\n if (c.contracts && !Array.isArray(c.contracts)) {\n throw new Error(\"Config contracts must be an array\");\n }\n\n if (!c.out || typeof c.out !== \"string\") {\n throw new Error(\"Config out must be a string path\");\n }\n\n // Validate contracts if they exist\n if (c.contracts) {\n for (const contract of c.contracts) {\n if (!contract.address && !contract.source) {\n throw new Error(\"Each contract must have either an address or source\");\n }\n }\n }\n\n // Validate plugins if they exist\n if (c.plugins && !Array.isArray(c.plugins)) {\n throw new Error(\"Config plugins must be an array\");\n }\n}\n\nexport function defineConfig(config: StacksConfig): StacksConfig;\nexport function defineConfig(definer: ConfigDefiner): ConfigDefiner;\nexport function defineConfig(configOrDefiner: StacksConfig | ConfigDefiner) {\n return configOrDefiner;\n}\n","/**\n * Plugin Manager for @stacks/codegen\n * Handles plugin registration, lifecycle execution, and output management\n */\n\nimport { format } from \"prettier\";\nimport { promises as fs } from \"fs\";\nimport path from \"path\";\nimport { validateStacksAddress } from \"@stacks/transactions\";\nimport type {\n StacksCodegenPlugin,\n UserConfig,\n ResolvedConfig,\n GenerateContext,\n Logger,\n PluginUtils,\n GeneratedOutput,\n ProcessedContract,\n ContractConfig,\n HookResult,\n PluginExecutionContext,\n} from \"../types/plugin.js\";\n\n/**\n * Core plugin manager that orchestrates plugin execution\n */\nexport class PluginManager {\n private plugins: StacksCodegenPlugin[] = [];\n private logger: Logger;\n private utils: PluginUtils;\n private executionContext: PluginExecutionContext;\n\n constructor() {\n this.logger = this.createLogger();\n this.utils = this.createUtils();\n this.executionContext = {\n phase: \"config\",\n startTime: Date.now(),\n results: new Map(),\n };\n }\n\n /**\n * Register a plugin\n */\n register(plugin: StacksCodegenPlugin): void {\n // Validate plugin\n if (!plugin.name || !plugin.version) {\n throw new Error(\"Plugin must have a name and version\");\n }\n\n // Check for duplicate plugin names\n const existing = this.plugins.find((p) => p.name === plugin.name);\n if (existing) {\n throw new Error(\n `Plugin \"${plugin.name}\" is already registered (version ${existing.version})`\n );\n }\n\n this.plugins.push(plugin);\n this.logger.debug(`Registered plugin: ${plugin.name}@${plugin.version}`);\n }\n\n /**\n * Get all registered plugins\n */\n getPlugins(): StacksCodegenPlugin[] {\n return [...this.plugins];\n }\n\n /**\n * Transform user config through all plugins\n */\n async transformConfig(config: UserConfig): Promise<ResolvedConfig> {\n this.executionContext.phase = \"config\";\n let transformedConfig = { ...config };\n\n for (const plugin of this.plugins) {\n if (plugin.transformConfig) {\n this.executionContext.currentPlugin = plugin;\n try {\n const result = await plugin.transformConfig(transformedConfig);\n transformedConfig = result;\n this.recordHookResult(plugin.name, \"transformConfig\", {\n success: true,\n });\n } catch (error) {\n const err = error as Error;\n this.recordHookResult(plugin.name, \"transformConfig\", {\n success: false,\n error: err,\n });\n throw new Error(\n `Plugin \"${plugin.name}\" failed during config transformation: ${err.message}`\n );\n }\n }\n }\n\n // Add plugins array to resolved config\n const resolvedConfig: ResolvedConfig = {\n ...transformedConfig,\n plugins: this.plugins,\n };\n\n return resolvedConfig;\n }\n\n /**\n * Transform contracts through all plugins\n */\n async transformContracts(\n contracts: ContractConfig[],\n _config: ResolvedConfig\n ): Promise<ProcessedContract[]> {\n const processedContracts: ProcessedContract[] = [];\n\n for (let contract of contracts) {\n // Handle special case for Clarinet plugin contracts\n if ((contract as any)._clarinetSource && contract.abi) {\n // Convert Clarinet contracts directly to ProcessedContract format\n const address =\n typeof contract.address === \"string\" ? contract.address : \"\";\n const [contractAddress, contractName] = address.split(\".\");\n const processed: ProcessedContract = {\n name: contract.name || contractName,\n address: contractAddress,\n contractName: contractName,\n abi: contract.abi,\n source: \"local\" as const,\n metadata: { source: \"clarinet\" },\n };\n processedContracts.push(processed);\n continue;\n }\n\n // Transform through each plugin\n for (const plugin of this.plugins) {\n if (plugin.transformContract) {\n this.executionContext.currentPlugin = plugin;\n try {\n contract = await plugin.transformContract(contract);\n this.recordHookResult(plugin.name, \"transformContract\", {\n success: true,\n });\n } catch (error) {\n const err = error as Error;\n this.recordHookResult(plugin.name, \"transformContract\", {\n success: false,\n error: err,\n });\n this.logger.warn(\n `Plugin \"${plugin.name}\" failed to transform contract: ${err.message}`\n );\n }\n }\n }\n\n // Convert to ProcessedContract\n if (contract.abi) {\n const processed: ProcessedContract = {\n name: contract.name || \"unknown\",\n address:\n typeof contract.address === \"string\"\n ? contract.address.split(\".\")[0]\n : \"unknown\",\n contractName: contract.name || \"unknown\",\n abi: contract.abi,\n source: \"api\" as const, // Use \"api\" as default for plugin-processed contracts\n metadata: contract.metadata,\n };\n processedContracts.push(processed);\n }\n }\n\n return processedContracts;\n }\n\n /**\n * Execute lifecycle hooks\n */\n async executeHook(\n hookName: keyof StacksCodegenPlugin,\n context: any\n ): Promise<void> {\n for (const plugin of this.plugins) {\n const hook = plugin[hookName];\n if (typeof hook === \"function\") {\n this.executionContext.currentPlugin = plugin;\n try {\n await (hook as any).call(plugin, context);\n this.recordHookResult(plugin.name, hookName as string, {\n success: true,\n });\n } catch (error) {\n const err = error as Error;\n this.recordHookResult(plugin.name, hookName as string, {\n success: false,\n error: err,\n });\n this.logger.error(\n `Plugin \"${plugin.name}\" failed during ${hookName as string}: ${err.message}`\n );\n // Don't throw - allow other plugins to continue\n }\n }\n }\n }\n\n /**\n * Execute generation phase with full context\n */\n async executeGeneration(\n contracts: ProcessedContract[],\n config: ResolvedConfig\n ): Promise<Map<string, GeneratedOutput>> {\n this.executionContext.phase = \"generate\";\n const outputs = new Map<string, GeneratedOutput>();\n\n // Create generation context\n const context: GenerateContext = {\n config,\n logger: this.logger,\n utils: this.utils,\n contracts,\n outputs,\n augment: (outputKey: string, contractName: string, content: any) => {\n this.augmentOutput(outputs, outputKey, contractName, content);\n },\n addOutput: (key: string, output: GeneratedOutput) => {\n outputs.set(key, output);\n },\n };\n\n // Execute beforeGenerate hooks\n await this.executeHook(\"beforeGenerate\", context);\n\n // Execute generate hooks\n await this.executeHook(\"generate\", context);\n\n // Execute afterGenerate hooks\n await this.executeHook(\"afterGenerate\", context);\n\n return outputs;\n }\n\n /**\n * Transform outputs through plugins\n */\n async transformOutputs(\n outputs: Map<string, GeneratedOutput>\n ): Promise<Map<string, GeneratedOutput>> {\n this.executionContext.phase = \"output\";\n const transformedOutputs = new Map<string, GeneratedOutput>();\n\n for (const [key, output] of outputs) {\n let transformedContent = output.content;\n\n for (const plugin of this.plugins) {\n if (plugin.transformOutput) {\n this.executionContext.currentPlugin = plugin;\n try {\n transformedContent = await plugin.transformOutput(\n transformedContent,\n output.type || \"other\"\n );\n this.recordHookResult(plugin.name, \"transformOutput\", {\n success: true,\n });\n } catch (error) {\n const err = error as Error;\n this.recordHookResult(plugin.name, \"transformOutput\", {\n success: false,\n error: err,\n });\n this.logger.warn(\n `Plugin \"${plugin.name}\" failed to transform output: ${err.message}`\n );\n }\n }\n }\n\n transformedOutputs.set(key, {\n ...output,\n content: transformedContent,\n });\n }\n\n return transformedOutputs;\n }\n\n /**\n * Write outputs to disk\n */\n async writeOutputs(outputs: Map<string, GeneratedOutput>): Promise<void> {\n for (const [, output] of outputs) {\n try {\n const resolvedPath = path.resolve(process.cwd(), output.path);\n await this.utils.ensureDir(path.dirname(resolvedPath));\n await this.utils.writeFile(resolvedPath, output.content);\n // Don't log here - let the main command handle success messaging\n } catch (error) {\n const err = error as Error;\n this.logger.error(`Failed to write ${output.path}: ${err.message}`);\n throw err;\n }\n }\n }\n\n /**\n * Get execution results for debugging\n */\n getExecutionResults(): Map<string, HookResult[]> {\n return new Map(this.executionContext.results);\n }\n\n /**\n * Augment existing output with additional content\n */\n private augmentOutput(\n outputs: Map<string, GeneratedOutput>,\n outputKey: string,\n contractName: string,\n content: any\n ): void {\n const existing = outputs.get(outputKey);\n if (!existing) {\n this.logger.warn(`Cannot augment non-existent output: ${outputKey}`);\n return;\n }\n\n // Simple augmentation - append content\n // In a real implementation, this would be more sophisticated\n const augmentedContent = `${existing.content}\\n\\n// Augmented by plugin for ${contractName}\\n${JSON.stringify(content, null, 2)}`;\n\n outputs.set(outputKey, {\n ...existing,\n content: augmentedContent,\n });\n }\n\n /**\n * Record hook execution result\n */\n private recordHookResult(\n pluginName: string,\n hookName: string,\n result: Omit<HookResult, \"plugin\">\n ): void {\n const key = `${pluginName}:${hookName}`;\n const existing = this.executionContext.results.get(key) || [];\n existing.push({ ...result, plugin: pluginName });\n this.executionContext.results.set(key, existing);\n }\n\n /**\n * Create logger instance\n */\n private createLogger(): Logger {\n return {\n info: (message: string) => console.log(`ℹ️ ${message}`),\n warn: (message: string) => console.warn(`⚠️ ${message}`),\n error: (message: string) => console.error(`❌ ${message}`),\n debug: (message: string) => {\n if (process.env.DEBUG) {\n console.log(`🐛 ${message}`);\n }\n },\n success: (message: string) => console.log(`✅ ${message}`),\n };\n }\n\n /**\n * Create utils instance\n */\n private createUtils(): PluginUtils {\n return {\n toCamelCase: (str: string) => {\n return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());\n },\n\n toKebabCase: (str: string) => {\n return str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n },\n\n validateAddress: (address: string) => {\n return validateStacksAddress(address.split(\".\")[0]);\n },\n\n parseContractId: (contractId: string) => {\n const [address, contractName] = contractId.split(\".\");\n return { address, contractName };\n },\n\n formatCode: async (code: string) => {\n return format(code, {\n parser: \"typescript\",\n singleQuote: true,\n semi: true,\n printWidth: 100,\n trailingComma: \"es5\",\n });\n },\n\n resolvePath: (relativePath: string) => {\n return path.resolve(process.cwd(), relativePath);\n },\n\n fileExists: async (filePath: string) => {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n },\n\n readFile: async (filePath: string) => {\n return fs.readFile(filePath, \"utf-8\");\n },\n\n writeFile: async (filePath: string, content: string) => {\n await fs.writeFile(filePath, content, \"utf-8\");\n },\n\n ensureDir: async (dirPath: string) => {\n await fs.mkdir(dirPath, { recursive: true });\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIA,qBAA8B;;;ACC9B,sBAAuB;AACvB,gBAA+B;AAC/B,kBAAiB;AACjB,0BAAsC;AAkB/B,IAAM,gBAAN,MAAoB;AAAA,EAMzB,cAAc;AALd,SAAQ,UAAiC,CAAC;AAMxC,SAAK,SAAS,KAAK,aAAa;AAChC,SAAK,QAAQ,KAAK,YAAY;AAC9B,SAAK,mBAAmB;AAAA,MACtB,OAAO;AAAA,MACP,WAAW,KAAK,IAAI;AAAA,MACpB,SAAS,oBAAI,IAAI;AAAA,IACnB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,SAAS,QAAmC;AAE1C,QAAI,CAAC,OAAO,QAAQ,CAAC,OAAO,SAAS;AACnC,YAAM,IAAI,MAAM,qCAAqC;AAAA,IACvD;AAGA,UAAM,WAAW,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,OAAO,IAAI;AAChE,QAAI,UAAU;AACZ,YAAM,IAAI;AAAA,QACR,WAAW,OAAO,IAAI,oCAAoC,SAAS,OA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B,CAAC,eAAuB;AACvC,cAAM,CAAC,SAAS,YAAY,IAAI,WAAW,MAAM,GAAG;AACpD,eAAO,EAAE,SAAS,aAAa;AAAA,MACjC;AAAA,MAEA,YAAY,OAAO,SAAiB;AAClC,mBAAO,wBAAO,MAAM;AAAA,UAClB,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,MAAM;AAAA,UACN,YAAY;AAAA,UACZ,eAAe;AAAA,QACjB,CAAC;AAAA,MACH;AAAA,MAEA,aAAa,CAAC,iBAAyB;AACrC,eAAO,YAAAA,QAAK,QAAQ,QAAQ,IAAI,GAAG,YAAY;AAAA,MACjD;AAAA,MAEA,YAAY,OAAO,aAAqB;AACtC,YAAI;AACF,gBAAM,UAAAC,SAAG,OAAO,QAAQ;AACxB,iBAAO;AAAA,QACT,QAAQ;AACN,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,MAEA,UAAU,OAAO,aAAqB;AACpC,eAAO,UAAAA,SAAG,SAAS,UAAU,OAAO;AAAA,MACtC;AAAA,MAEA,WAAW,OAAO,UAAkB,YAAoB;AACtD,cAAM,UAAAA,SAAG,UAAU,UAAU,SAAS,OAAO;AAAA,MAC/C;AAAA,MAEA,WAAW,OAAO,YAAoB;AACpC,cAAM,UAAAA,SAAG,MAAM,SAAS,EAAE,WAAW,KAAK,CAAC;AAAA,MAC7C;AAAA,IACF;AAAA,EACF;AACF;;;ADpRO,SAAS,aAAa,iBAA+C;AAC1E,SAAO;AACT;","names":["path","fs"]}
@@ -0,0 +1,8 @@
1
+ import { S as StacksConfig, C as ConfigDefiner } from './plugin-manager-DBXFfyFZ.cjs';
2
+ export { h as ContractConfig, a as ContractSource, G as GenerateContext, f as GeneratedOutput, L as Logger, N as NetworkName, O as OutputType, d as PluginContext, P as PluginFactory, i as PluginManager, c as PluginOptions, e as PluginUtils, g as ProcessedContract, R as ResolvedConfig, b as StacksCodegenPlugin, U as UserConfig } from './plugin-manager-DBXFfyFZ.cjs';
3
+ export { ClarityContract, ClarityFunction, ClarityType, ContractCallParams, ReadOnlyCallParams } from '@secondlayer/clarity-types';
4
+
5
+ declare function defineConfig(config: StacksConfig): StacksConfig;
6
+ declare function defineConfig(definer: ConfigDefiner): ConfigDefiner;
7
+
8
+ export { StacksConfig, defineConfig };
@@ -0,0 +1,8 @@
1
+ import { S as StacksConfig, C as ConfigDefiner } from './plugin-manager-DBXFfyFZ.js';
2
+ export { h as ContractConfig, a as ContractSource, G as GenerateContext, f as GeneratedOutput, L as Logger, N as NetworkName, O as OutputType, d as PluginContext, P as PluginFactory, i as PluginManager, c as PluginOptions, e as PluginUtils, g as ProcessedContract, R as ResolvedConfig, b as StacksCodegenPlugin, U as UserConfig } from './plugin-manager-DBXFfyFZ.js';
3
+ export { ClarityContract, ClarityFunction, ClarityType, ContractCallParams, ReadOnlyCallParams } from '@secondlayer/clarity-types';
4
+
5
+ declare function defineConfig(config: StacksConfig): StacksConfig;
6
+ declare function defineConfig(definer: ConfigDefiner): ConfigDefiner;
7
+
8
+ export { StacksConfig, defineConfig };