netherframe.generation 0.3.0__py3-none-any.whl

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 (68) hide show
  1. netherframe/generation/__init__.py +31 -0
  2. netherframe/generation/api.py +306 -0
  3. netherframe/generation/batch.py +65 -0
  4. netherframe/generation/convert/__init__.py +6 -0
  5. netherframe/generation/convert/bindings.py +180 -0
  6. netherframe/generation/convert/converter.py +365 -0
  7. netherframe/generation/convert/emitter.py +972 -0
  8. netherframe/generation/convert/expressions.py +701 -0
  9. netherframe/generation/convert/hcl_ast.py +721 -0
  10. netherframe/generation/convert/module_fetch.py +135 -0
  11. netherframe/generation/convert/module_source.py +200 -0
  12. netherframe/generation/convert/python_code.py +152 -0
  13. netherframe/generation/discovered_code.py +777 -0
  14. netherframe/generation/functions/__init__.py +8 -0
  15. netherframe/generation/functions/generator.py +369 -0
  16. netherframe/generation/import_specs.py +179 -0
  17. netherframe/generation/imports.py +169 -0
  18. netherframe/generation/nf_alias_shims.py +104 -0
  19. netherframe/generation/providers/__init__.py +1 -0
  20. netherframe/generation/providers/build_backend.py +90 -0
  21. netherframe/generation/providers/cli.py +274 -0
  22. netherframe/generation/providers/code_generator.py +2128 -0
  23. netherframe/generation/providers/codegen_support.py +542 -0
  24. netherframe/generation/providers/logging.py +22 -0
  25. netherframe/generation/providers/output_transaction.py +85 -0
  26. netherframe/generation/providers/package_output.py +440 -0
  27. netherframe/generation/providers/release.py +155 -0
  28. netherframe/generation/providers/schema_generation.py +220 -0
  29. netherframe/generation/providers/schema_loading.py +10 -0
  30. netherframe/generation/providers/schema_native.py +97 -0
  31. netherframe/generation/providers/schema_parser.py +563 -0
  32. netherframe/generation/py.typed +0 -0
  33. netherframe_generation-0.3.0.dist-info/METADATA +66 -0
  34. netherframe_generation-0.3.0.dist-info/RECORD +68 -0
  35. netherframe_generation-0.3.0.dist-info/WHEEL +4 -0
  36. netherframe_generation-0.3.0.dist-info/licenses/LICENSE +21 -0
  37. nf/generation/__init__.py +4 -0
  38. nf/generation/api.py +4 -0
  39. nf/generation/batch.py +4 -0
  40. nf/generation/convert/__init__.py +4 -0
  41. nf/generation/convert/bindings.py +4 -0
  42. nf/generation/convert/converter.py +4 -0
  43. nf/generation/convert/emitter.py +4 -0
  44. nf/generation/convert/expressions.py +4 -0
  45. nf/generation/convert/hcl_ast.py +4 -0
  46. nf/generation/convert/module_fetch.py +4 -0
  47. nf/generation/convert/module_source.py +4 -0
  48. nf/generation/convert/python_code.py +4 -0
  49. nf/generation/discovered_code.py +4 -0
  50. nf/generation/functions/__init__.py +4 -0
  51. nf/generation/functions/generator.py +4 -0
  52. nf/generation/import_specs.py +4 -0
  53. nf/generation/imports.py +4 -0
  54. nf/generation/nf_alias_shims.py +4 -0
  55. nf/generation/providers/__init__.py +4 -0
  56. nf/generation/providers/build_backend.py +4 -0
  57. nf/generation/providers/cli.py +4 -0
  58. nf/generation/providers/code_generator.py +4 -0
  59. nf/generation/providers/codegen_support.py +4 -0
  60. nf/generation/providers/logging.py +4 -0
  61. nf/generation/providers/output_transaction.py +4 -0
  62. nf/generation/providers/package_output.py +4 -0
  63. nf/generation/providers/release.py +4 -0
  64. nf/generation/providers/schema_generation.py +4 -0
  65. nf/generation/providers/schema_loading.py +4 -0
  66. nf/generation/providers/schema_native.py +4 -0
  67. nf/generation/providers/schema_parser.py +4 -0
  68. nf/generation/py.typed +0 -0
@@ -0,0 +1,8 @@
1
+ """Function generation utilities.
2
+
3
+ This package contains the function generator implementation. Generated
4
+ function catalogs are written into the dedicated legacy function packages
5
+ under the workspace `functions/` tree, not maintained here as source code.
6
+ """
7
+
8
+ __all__ = []
@@ -0,0 +1,369 @@
1
+ """Generate Terraform/OpenTofu functions for Netherframe.
2
+
3
+ This script generates Python functions for all Terraform/OpenTofu built-in functions.
4
+ It creates type-safe wrappers that return RuntimeValue[T] instances.
5
+ """
6
+
7
+ import builtins
8
+ import hashlib
9
+ import keyword
10
+ import re
11
+ import subprocess
12
+ from datetime import UTC, datetime
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import orjson
17
+
18
+ from netherframe.generation.providers.logging import get_logger
19
+
20
+ # Reserved names that can't be used as function names
21
+ UNALLOWED_NAMES = {"self"}.union(keyword.kwlist, builtins.__dict__.keys())
22
+ logger = get_logger(__name__)
23
+ _FUNCTION_JSON_CACHE: dict[str, dict[str, Any]] = {}
24
+ _BINARY_LAYOUT: dict[str, tuple[str, str]] = {
25
+ "terraform": ("hashicorp", "terraform"),
26
+ "tofu": ("opentofu", "tofu"),
27
+ }
28
+
29
+
30
+ def _normalize_binary_name(legacy_binary: str | None = None) -> str:
31
+ if not legacy_binary:
32
+ return "terraform"
33
+ normalized = Path(legacy_binary).name.lower().strip()
34
+ if normalized.endswith(".exe"):
35
+ normalized = normalized[:-4]
36
+ if normalized == "opentofu":
37
+ return "tofu"
38
+ return normalized or "terraform"
39
+
40
+
41
+ def _workspace_root_from(path: Path) -> Path | None:
42
+ for candidate in [path, *path.parents]:
43
+ pyproject = candidate / "pyproject.toml"
44
+ if not pyproject.exists():
45
+ continue
46
+ try:
47
+ content = pyproject.read_text()
48
+ except Exception:
49
+ continue
50
+ if "[tool.uv.workspace]" in content:
51
+ return candidate
52
+ return None
53
+
54
+
55
+ def _resolve_default_output_path(binary_name: str) -> Path:
56
+ script_dir = Path(__file__).parent
57
+ workspace_root = _workspace_root_from(script_dir.resolve())
58
+ if workspace_root is None:
59
+ logger.warning("Could not resolve workspace root, using local generated.py fallback")
60
+ return script_dir / "generated.py"
61
+
62
+ layout = _BINARY_LAYOUT.get(binary_name)
63
+ if layout is None:
64
+ raise ValueError(f"Unsupported legacy binary '{binary_name}'")
65
+
66
+ org, binary = layout
67
+ return workspace_root / "functions" / org / binary / "netherframe" / "legacy_functions" / org / binary / "functions_generated.py"
68
+
69
+
70
+ def _resolve_binary_command(binary_name: str) -> list[str]:
71
+ if binary_name == "terraform":
72
+ return ["terraform"]
73
+ if binary_name == "tofu":
74
+ # Prefer current executable name, allow fallback for older setups.
75
+ return ["tofu", "opentofu"]
76
+ return [binary_name]
77
+
78
+
79
+ def _detect_binary_version(binary_name: str) -> str | None:
80
+ candidates = _resolve_binary_command(binary_name)
81
+ version_pattern = re.compile(r"v?(\d+\.\d+\.\d+)")
82
+
83
+ for command in candidates:
84
+ try:
85
+ result = subprocess.run(
86
+ [command, "version"],
87
+ capture_output=True,
88
+ text=True,
89
+ check=True,
90
+ )
91
+ except Exception:
92
+ continue
93
+
94
+ lines = [line for line in result.stdout.splitlines() if line.strip()]
95
+ if not lines:
96
+ continue
97
+ match = version_pattern.search(lines[0])
98
+ if match:
99
+ return match.group(1)
100
+ return None
101
+
102
+
103
+ def _update_catalog_package_version(output_file: Path, binary_name: str) -> None:
104
+ if "functions_generated.py" not in output_file.name:
105
+ return
106
+
107
+ pyproject_path = output_file
108
+ for candidate in [output_file.parent, *output_file.parents]:
109
+ possible = candidate / "pyproject.toml"
110
+ if possible.exists():
111
+ pyproject_path = possible
112
+ break
113
+ else:
114
+ return
115
+
116
+ version = _detect_binary_version(binary_name)
117
+ if not version:
118
+ return
119
+
120
+ try:
121
+ text = pyproject_path.read_text()
122
+ except Exception:
123
+ return
124
+
125
+ updated = re.sub(
126
+ r'^version\s*=\s*"[^"]+"',
127
+ f'version = "{version}"',
128
+ text,
129
+ flags=re.MULTILINE,
130
+ count=1,
131
+ )
132
+ updated = re.sub(r'(?m)^generated-at\s*=\s*"[^"]+"', f'generated-at = "{datetime.now(UTC).date().isoformat()}"', updated)
133
+ schema = _FUNCTION_JSON_CACHE.get(binary_name)
134
+ if schema is not None:
135
+ digest = hashlib.sha256(orjson.dumps(schema, option=orjson.OPT_SORT_KEYS)).hexdigest()
136
+ updated = re.sub(r"(?m)^catalog-sha256\s*=.*\n?", "", updated).rstrip() + f'\ncatalog-sha256 = "{digest}"\n'
137
+ if updated != text:
138
+ pyproject_path.write_text(updated)
139
+
140
+
141
+ def safe_name(name: str) -> str:
142
+ """Ensure the name is not a Python keyword by adding underscore if needed."""
143
+ return f"{name}_" if name in UNALLOWED_NAMES else name
144
+
145
+
146
+ def generate_type_hint(type_spec: Any) -> tuple[str, str]:
147
+ """Generate type hint for parameters and return types.
148
+
149
+ Returns tuple of (param_type, return_type) where param_type includes Union with RuntimeValue.
150
+ """
151
+ if isinstance(type_spec, list):
152
+ if type_spec[0] == "list":
153
+ inner_param, inner_return = generate_type_hint(type_spec[1])
154
+ return (
155
+ f"list[{inner_param}] | RuntimeValue[list[{inner_return}]]",
156
+ f"list[{inner_return}]",
157
+ )
158
+ if type_spec[0] == "set":
159
+ inner_param, inner_return = generate_type_hint(type_spec[1])
160
+ return (
161
+ f"list[{inner_param}] | RuntimeValue[list[{inner_return}]]",
162
+ f"list[{inner_return}]",
163
+ )
164
+ if type_spec[0] == "map":
165
+ inner_param, inner_return = generate_type_hint(type_spec[1])
166
+ return (
167
+ f"dict[str, {inner_param}] | RuntimeValue[dict[str, {inner_return}]]",
168
+ f"dict[str, {inner_return}]",
169
+ )
170
+
171
+ type_mapping = {
172
+ "string": ("str | RuntimeValue[str]", "str"),
173
+ "number": ("float | RuntimeValue[float]", "float"),
174
+ "bool": ("bool | RuntimeValue[bool]", "bool"),
175
+ "dynamic": ("Any", "Any"),
176
+ }
177
+
178
+ # Handle non-string types (dict, None, etc)
179
+ if not isinstance(type_spec, str):
180
+ return ("Any", "Any")
181
+
182
+ return type_mapping.get(type_spec, ("Any", "Any"))
183
+
184
+
185
+ def generate_function_def(name: str, info: dict[str, Any]) -> str:
186
+ """Generate a single function definition."""
187
+ safe_func_name = safe_name(name)
188
+
189
+ # Special handling for functions with optional variadic parameters
190
+ # These functions accept 0 or 1 extra argument, not *args
191
+ optional_variadic_functions = {"bcrypt"}
192
+
193
+ # Build docstring
194
+ # Use raw string to avoid escape sequence issues
195
+ description = info["description"].replace("\\", "\\\\")
196
+ docs = [f' r"""{description}']
197
+
198
+ # Build parameters
199
+ params = []
200
+ param_list = []
201
+
202
+ if "parameters" in info:
203
+ for param in info["parameters"]:
204
+ param_type, _ = generate_type_hint(param["type"])
205
+ param_name = safe_name(param["name"])
206
+ docs.append(f" @param {param_name} {param.get('description', '')}")
207
+ params.append(f"{param_name}: {param_type}")
208
+ param_list.append(param_name)
209
+
210
+ if "variadic_parameter" in info:
211
+ var_param = info["variadic_parameter"]
212
+ param_type, _ = generate_type_hint(var_param["type"])
213
+ param_name = safe_name(var_param["name"])
214
+
215
+ if name in optional_variadic_functions:
216
+ # Generate as optional parameter with None default
217
+ docs.append(
218
+ f" @param {param_name} {var_param.get('description', '')}",
219
+ )
220
+ params.append(f"{param_name}: {param_type} | None = None")
221
+ # Special handling in function body will be needed
222
+ else:
223
+ # Regular variadic parameter
224
+ docs.append(
225
+ f" @param *{param_name} {var_param.get('description', '')}",
226
+ )
227
+ params.append(f"*{param_name}: {param_type}")
228
+ param_list.append(f"*{param_name}")
229
+
230
+ docs.append(' """')
231
+
232
+ # Get return type
233
+ _, return_type = generate_type_hint(info["return_type"])
234
+
235
+ # Build function body
236
+ if name in optional_variadic_functions and "variadic_parameter" in info:
237
+ # Special handling for optional variadic parameters
238
+ var_param_name = safe_name(info["variadic_parameter"]["name"])
239
+ function_body = f""" @staticmethod
240
+ def {safe_func_name}({", ".join(params)}) -> RuntimeValue[{return_type}]:
241
+ {chr(10).join(docs)}
242
+ args = [{", ".join(param_list)}]
243
+ if {var_param_name} is not None:
244
+ args.append({var_param_name})
245
+ return NetherframeFunction("{name}", args)
246
+
247
+ """
248
+ else:
249
+ # Regular function
250
+ function_def = f""" @staticmethod
251
+ def {safe_func_name}({", ".join(params)}) -> RuntimeValue[{return_type}]:
252
+ {chr(10).join(docs)}
253
+ return NetherframeFunction("{name}", [{", ".join(param_list)}])
254
+
255
+ """
256
+ function_body = function_def
257
+
258
+ return function_body
259
+
260
+
261
+ def generate_functions_class(json_data: dict[str, Any]) -> str:
262
+ """Generate the complete FnGenerated class."""
263
+ functions = json_data["function_signatures"]
264
+
265
+ # Generate imports
266
+ imports = '''"""Auto-generated Terraform/OpenTofu functions for Netherframe.
267
+
268
+ DO NOT EDIT THIS FILE MANUALLY. It is generated by generate_functions.py.
269
+ """
270
+
271
+ from typing import Any
272
+
273
+ from netherframe.core.functions.function_base import NetherframeFunction
274
+ from netherframe.core.values.runtime_value import RuntimeValue
275
+
276
+
277
+ '''
278
+
279
+ # Generate class definition
280
+ class_parts = [
281
+ '''class FnGenerated:
282
+ """Auto-generated Terraform/OpenTofu functions."""
283
+
284
+ ''',
285
+ ]
286
+
287
+ # Add all functions
288
+ for name, info in sorted(functions.items()):
289
+ # Skip core:: prefixed functions as they're duplicates
290
+ if name.startswith("core::"):
291
+ continue
292
+ class_parts.append(generate_function_def(name, info))
293
+
294
+ return "\n".join(line.rstrip() for line in (imports + "".join(class_parts)).splitlines()) + "\n"
295
+
296
+
297
+ def get_functions_json(legacy_binary: str = "terraform") -> dict[str, Any]:
298
+ """Get functions.json from terraform/opentofu metadata command."""
299
+ binary_name = _normalize_binary_name(legacy_binary)
300
+ commands = _resolve_binary_command(binary_name)
301
+ last_error: Exception | None = None
302
+
303
+ for command in commands:
304
+ cmd = [command, "metadata", "functions", "-json"]
305
+ try:
306
+ logger.info(f"Running: {' '.join(cmd)}")
307
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
308
+ return orjson.loads(result.stdout)
309
+ except FileNotFoundError as e:
310
+ last_error = e
311
+ logger.warning(f"{command} not found in PATH")
312
+ continue
313
+ except subprocess.CalledProcessError as e:
314
+ logger.error_with_fields(
315
+ "Failed to fetch function metadata",
316
+ command=command,
317
+ error=str(e),
318
+ stderr=e.stderr,
319
+ )
320
+ raise
321
+
322
+ if last_error:
323
+ tried = ", ".join(commands)
324
+ raise RuntimeError(f"No supported command found in PATH for '{binary_name}' (tried: {tried})") from last_error
325
+ raise RuntimeError(f"Failed to fetch function metadata for '{binary_name}'")
326
+
327
+
328
+ def generate_terraform_functions(
329
+ output_path: str | None = None,
330
+ legacy_binary: str = "terraform",
331
+ dry_run: bool = False,
332
+ ) -> str:
333
+ """Generate Terraform/OpenTofu functions and optionally write to file.
334
+
335
+ Args:
336
+ output_path: Output file path. If None, defaults to <package>/generated.py
337
+ legacy_binary: Legacy binary to introspect (for example: terraform or tofu)
338
+ dry_run: Return generated code without writing to file
339
+
340
+ Returns:
341
+ Generated Python code as a string
342
+
343
+ """
344
+ binary_name = _normalize_binary_name(legacy_binary)
345
+ output_file = Path(output_path) if output_path else _resolve_default_output_path(binary_name)
346
+
347
+ # Get functions from terraform/opentofu with a per-process cache.
348
+ if binary_name in _FUNCTION_JSON_CACHE:
349
+ json_data = _FUNCTION_JSON_CACHE[binary_name]
350
+ else:
351
+ json_data = get_functions_json(legacy_binary=binary_name)
352
+ _FUNCTION_JSON_CACHE[binary_name] = json_data
353
+
354
+ source = "OpenTofu" if binary_name == "tofu" else "Terraform"
355
+ logger.info(f"Generating functions from {source}...")
356
+
357
+ python_code = generate_functions_class(json_data)
358
+
359
+ if not dry_run:
360
+ logger.info(f"Writing functions to {output_file}")
361
+ output_file.parent.mkdir(parents=True, exist_ok=True)
362
+ output_file.write_text(python_code)
363
+ _update_catalog_package_version(output_file, binary_name)
364
+ logger.info_with_fields(
365
+ "Generated functions written successfully",
366
+ output_path=str(output_file),
367
+ )
368
+
369
+ return python_code
@@ -0,0 +1,179 @@
1
+ from __future__ import annotations
2
+
3
+ import subprocess
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ import orjson
9
+
10
+ from netherframe.core.exceptions import ValidationError
11
+
12
+ if TYPE_CHECKING:
13
+ from netherframe.core.constructs.app_stack import Stack
14
+ from netherframe.core.constructs.infrastructure_support import ImportList
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class ImportSpec:
19
+ to: str
20
+ import_id: str
21
+
22
+
23
+ def build_terraform_address(resource_type: str, resource_name: str, index_key: Any = None) -> str:
24
+ """Build the Terraform address for a state resource instance."""
25
+ if index_key is None:
26
+ return f"{resource_type}.{resource_name}"
27
+ if isinstance(index_key, str):
28
+ return f'{resource_type}.{resource_name}["{index_key}"]'
29
+ return f"{resource_type}.{resource_name}[{index_key}]"
30
+
31
+
32
+ def extract_import_specs_from_state(
33
+ state: dict[str, Any],
34
+ *,
35
+ resource_types: list[str] | None = None,
36
+ exclude_types: list[str] | None = None,
37
+ ) -> list[ImportSpec]:
38
+ """Extract import specs from parsed Terraform state."""
39
+ specs: list[ImportSpec] = []
40
+ resources = state.get("resources", [])
41
+ for resource in resources:
42
+ if resource.get("mode") != "managed":
43
+ continue
44
+
45
+ resource_type = resource.get("type")
46
+ resource_name = resource.get("name")
47
+ if not isinstance(resource_type, str) or not isinstance(resource_name, str):
48
+ continue
49
+
50
+ if resource_types and resource_type not in resource_types:
51
+ continue
52
+ if exclude_types and resource_type in exclude_types:
53
+ continue
54
+
55
+ instances = resource.get("instances", [])
56
+ for instance in instances:
57
+ resource_id = instance.get("attributes", {}).get("id")
58
+ if not resource_id:
59
+ continue
60
+ specs.append(
61
+ ImportSpec(
62
+ to=build_terraform_address(
63
+ resource_type,
64
+ resource_name,
65
+ instance.get("index_key"),
66
+ ),
67
+ import_id=resource_id,
68
+ ),
69
+ )
70
+ return specs
71
+
72
+
73
+ def extract_import_specs_from_state_file(
74
+ state_file: str | Path,
75
+ *,
76
+ resource_types: list[str] | None = None,
77
+ exclude_types: list[str] | None = None,
78
+ ) -> list[ImportSpec]:
79
+ """Extract import specs from a Terraform state file."""
80
+ state_path = Path(state_file)
81
+ if not state_path.exists():
82
+ raise ValidationError(f"State file not found: {state_file}")
83
+ state = orjson.loads(state_path.read_bytes())
84
+ return extract_import_specs_from_state(
85
+ state,
86
+ resource_types=resource_types,
87
+ exclude_types=exclude_types,
88
+ )
89
+
90
+
91
+ def extract_import_specs_from_terraform_state_list(working_dir: str | Path) -> list[ImportSpec]:
92
+ """Extract import specs by querying Terraform state directly."""
93
+ try:
94
+ result = subprocess.run(
95
+ ["terraform", "state", "list"],
96
+ cwd=working_dir,
97
+ capture_output=True,
98
+ text=True,
99
+ check=True,
100
+ )
101
+ except subprocess.CalledProcessError as exc:
102
+ raise ValidationError(f"Failed to run terraform state list: {exc.stderr}") from exc
103
+ except FileNotFoundError as exc:
104
+ raise ValidationError("Terraform not found. Please ensure terraform is installed.") from exc
105
+
106
+ specs: list[ImportSpec] = []
107
+ for resource_address in result.stdout.strip().split("\n"):
108
+ if not resource_address or resource_address.startswith("data."):
109
+ continue
110
+ try:
111
+ show_result = subprocess.run(
112
+ ["terraform", "state", "show", "-json", resource_address],
113
+ cwd=working_dir,
114
+ capture_output=True,
115
+ text=True,
116
+ check=True,
117
+ )
118
+ resource_data = orjson.loads(show_result.stdout)
119
+ resource_id = resource_data.get("values", {}).get("id")
120
+ if resource_id:
121
+ specs.append(ImportSpec(to=resource_address, import_id=resource_id))
122
+ except subprocess.CalledProcessError, orjson.JSONDecodeError:
123
+ continue
124
+ return specs
125
+
126
+
127
+ def import_specs_to_config(specs: list[ImportSpec], *, stack_name: str | None = None) -> dict[str, Any] | list[dict[str, str]]:
128
+ """Convert import specs to the public config shapes used by generation APIs."""
129
+ imports = [{"to": spec.to, "id": spec.import_id} for spec in specs]
130
+ if stack_name is None:
131
+ return imports
132
+ return {"stack_name": stack_name, "imports": imports}
133
+
134
+
135
+ def write_import_config_file(output_file: str | Path, specs: list[ImportSpec]) -> None:
136
+ """Write import specs to JSON or YAML config."""
137
+ output_path = Path(output_file)
138
+ output_path.parent.mkdir(parents=True, exist_ok=True)
139
+ config = import_specs_to_config(specs)
140
+ if str(output_file).endswith((".yaml", ".yml")):
141
+ try:
142
+ import yaml # type: ignore[import-untyped]
143
+ except ImportError as exc:
144
+ raise ValidationError(
145
+ "PyYAML is required to write YAML files. Install with: pip install pyyaml",
146
+ ) from exc
147
+ with output_path.open("w") as f:
148
+ yaml.dump(config, f, default_flow_style=False)
149
+ return
150
+ output_path.write_bytes(orjson.dumps(config, option=orjson.OPT_INDENT_2))
151
+
152
+
153
+ def build_import_list(
154
+ stack: Stack,
155
+ specs: list[ImportSpec],
156
+ *,
157
+ import_list_id: str,
158
+ ) -> ImportList:
159
+ """Materialize plain import specs into an netherframe.core ImportList."""
160
+ from netherframe.core.constructs.infrastructure_support import ImportList
161
+
162
+ import_list = ImportList(nf_scope=stack, nf_id=import_list_id)
163
+ for spec in specs:
164
+ import_list.add_import(to=spec.to, import_id=spec.import_id)
165
+ return import_list
166
+
167
+
168
+ def next_import_list_id(stack: Stack, prefix: str) -> str:
169
+ """Allocate a unique import-list id without reaching into stack internals."""
170
+ children = getattr(stack, "_children", None)
171
+ if not isinstance(children, dict):
172
+ return prefix
173
+
174
+ candidate = prefix
175
+ suffix = 0
176
+ while candidate in children:
177
+ suffix += 1
178
+ candidate = f"{prefix}_{suffix}"
179
+ return candidate