@skillstech/thunderlang 0.5.10 → 0.5.12

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 (66) hide show
  1. package/CHANGELOG.md +450 -0
  2. package/dist/core.cjs +30434 -7577
  3. package/dist/index.cjs +28576 -5328
  4. package/dist/learn.cjs +24201 -5367
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +49 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +65 -14
  34. package/src/model.mjs +496 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1017 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
@@ -0,0 +1,348 @@
1
+ // Words for cloud infrastructure, shared by the Terraform and Bicep readers (spec section 12): resource types in
2
+ // words ("azurerm_storage_account" -> "storage account", "Microsoft.Web/sites" -> "web app"), values in words
3
+ // ("worked out when it is applied"), well-known Azure roles by name and id, which permissions are wide, and the facts
4
+ // both formats can state (public ingress, public storage, secrets written in plain config, encryption turned off).
5
+ // Deterministic and browser-safe; no regex here can backtrack.
6
+ import { isLiteral, refsIn } from './infra-expr.mjs';
7
+ import { listWords, cap } from './infra-words.mjs';
8
+
9
+ export const APPLIED = 'worked out when it is applied';
10
+
11
+ const UPPER = new Set(['iam', 'vpc', 's3', 'ec2', 'ecs', 'eks', 'rds', 'sql', 'dns', 'ip', 'nat', 'acm', 'kms', 'sns', 'sqs', 'ssm', 'api', 'cdn', 'aks', 'acr', 'nsg', 'vm', 'lb', 'alb', 'elb', 'waf', 'ssl', 'tls', 'url', 'id', 'arn', 'http', 'https', 'tcp', 'udp', 'cidr', 'ebs', 'efs', 'ecr', 'gke', 'vnet', 'ad', 'ipv4', 'ipv6', 'acl', 'tags', 'ddos', 'oidc', 'saml', 'mssql', 'vpn', 'gcs', 'pubsub', 'ttl', 'cpu', 'gpu', 'dynamodb', 'msk', 'sso']);
12
+ const KEEP = { tags: 'tags', dynamodb: 'DynamoDB', pubsub: 'Pub/Sub', mssql: 'SQL Server', ipv4: 'IPv4', ipv6: 'IPv6', vnet: 'virtual network' };
13
+ /** snake_case or camelCase in plain words, with well-known short names kept upper case: "vpc_id" -> "VPC id". */
14
+ export function words(s) {
15
+ return String(s ?? '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_\-.]+/g, ' ').trim().split(/\s+/)
16
+ .map((w) => { const l = w.toLowerCase(); return KEEP[l] ?? (UPPER.has(l) && l !== 'id' ? l.toUpperCase() : l); }).join(' ');
17
+ }
18
+
19
+ const PROVIDERS = { azurerm: 'Azure', azuread: 'Microsoft Entra ID', azapi: 'Azure', aws: 'AWS', google: 'Google Cloud', 'google-beta': 'Google Cloud', kubernetes: 'Kubernetes', helm: 'Helm', github: 'GitHub', cloudflare: 'Cloudflare', datadog: 'Datadog', random: 'Terraform (random values)', null: 'Terraform', local: 'this computer', tls: 'Terraform (keys and certificates)', time: 'Terraform (time)', vault: 'HashiCorp Vault', docker: 'Docker', archive: 'Terraform (archives)', http: 'the web' };
20
+ /** A Terraform provider name in words ("azurerm" -> "Azure"). */
21
+ export const providerWords = (p) => PROVIDERS[p] ?? p;
22
+
23
+ // Terraform types that read better with their own words than with the type name.
24
+ const TF_TYPES = {
25
+ azurerm_linux_web_app: 'web app (Linux)', azurerm_windows_web_app: 'web app (Windows)', azurerm_service_plan: 'app service plan',
26
+ azurerm_app_service_plan: 'app service plan', azurerm_linux_function_app: 'function app (Linux)', azurerm_windows_function_app: 'function app (Windows)',
27
+ azurerm_kubernetes_cluster: 'Kubernetes cluster (AKS)', azurerm_mssql_server: 'SQL server', azurerm_mssql_database: 'SQL database',
28
+ azurerm_cosmosdb_account: 'Cosmos DB account', azurerm_application_insights: 'Application Insights', azurerm_log_analytics_workspace: 'Log Analytics workspace',
29
+ azurerm_user_assigned_identity: 'managed identity', azurerm_container_app_environment: 'container apps environment', azurerm_public_ip: 'public IP address',
30
+ aws_instance: 'virtual machine (EC2 instance)', aws_db_instance: 'database (RDS instance)', aws_lb: 'load balancer', aws_alb: 'load balancer',
31
+ aws_iam_role_policy_attachment: 'IAM policy attachment', aws_s3_bucket: 'S3 bucket', aws_eip: 'public IP address (Elastic IP)', aws_vpc: 'VPC',
32
+ google_compute_instance: 'virtual machine (Compute Engine)', google_container_cluster: 'Kubernetes cluster (GKE)', google_sql_database_instance: 'SQL instance',
33
+ };
34
+ const AZ_TYPES = {
35
+ 'microsoft.web/sites': 'web app', 'microsoft.web/serverfarms': 'app service plan', 'microsoft.web/sites/config': 'web app setting',
36
+ 'microsoft.resources/resourcegroups': 'resource group', 'microsoft.keyvault/vaults': 'key vault', 'microsoft.keyvault/vaults/secrets': 'key vault secret',
37
+ 'microsoft.insights/components': 'Application Insights', 'microsoft.operationalinsights/workspaces': 'Log Analytics workspace',
38
+ 'microsoft.containerregistry/registries': 'container registry', 'microsoft.app/containerapps': 'container app', 'microsoft.app/managedenvironments': 'container apps environment',
39
+ 'microsoft.documentdb/databaseaccounts': 'Cosmos DB account', 'microsoft.sql/servers': 'SQL server', 'microsoft.sql/servers/databases': 'SQL database',
40
+ 'microsoft.network/virtualnetworks': 'virtual network', 'microsoft.network/virtualnetworks/subnets': 'subnet', 'microsoft.network/networksecuritygroups': 'network security group',
41
+ 'microsoft.network/publicipaddresses': 'public IP address', 'microsoft.managedidentity/userassignedidentities': 'managed identity',
42
+ 'microsoft.authorization/roleassignments': 'role assignment', 'microsoft.authorization/roledefinitions': 'role definition', 'microsoft.storage/storageaccounts': 'storage account',
43
+ 'microsoft.storage/storageaccounts/blobservices': 'blob service', 'microsoft.storage/storageaccounts/blobservices/containers': 'blob container',
44
+ 'microsoft.cognitiveservices/accounts': 'Azure AI services account', 'microsoft.cognitiveservices/accounts/deployments': 'AI model deployment',
45
+ 'microsoft.search/searchservices': 'search service', 'microsoft.containerservice/managedclusters': 'Kubernetes cluster (AKS)',
46
+ 'microsoft.dbforpostgresql/flexibleservers': 'PostgreSQL server', 'microsoft.cache/redis': 'Redis cache', 'microsoft.servicebus/namespaces': 'Service Bus namespace',
47
+ 'microsoft.eventhub/namespaces': 'Event Hubs namespace', 'microsoft.compute/virtualmachines': 'virtual machine', 'microsoft.network/privateendpoints': 'private endpoint',
48
+ 'microsoft.insights/diagnosticsettings': 'diagnostic setting', 'microsoft.web/staticsites': 'static web app', 'microsoft.apimanagement/service': 'API Management service',
49
+ };
50
+ const singular = (w) => (/ies$/.test(w) ? `${w.slice(0, -3)}y` : /(ss|us)$/.test(w) ? w : /sses$/.test(w) ? w.slice(0, -2) : /s$/.test(w) ? w.slice(0, -1) : w);
51
+
52
+ /** A resource type in words: Terraform ("aws_s3_bucket" -> "S3 bucket") or Azure ("Microsoft.Web/sites" -> "web app"). */
53
+ export function typeWords(type) {
54
+ const t = String(type ?? '');
55
+ if (!t) return 'resource';
56
+ if (t === 'module') return 'module';
57
+ if (/\//.test(t) || /^Microsoft\./i.test(t)) {
58
+ const k = t.toLowerCase();
59
+ if (AZ_TYPES[k]) return AZ_TYPES[k];
60
+ const segs = t.split('/');
61
+ return words(singular(segs.at(-1))).toLowerCase().replace(/\b(ip|sql|dns|vm|api|aks)\b/g, (m) => m.toUpperCase());
62
+ }
63
+ if (TF_TYPES[t]) return TF_TYPES[t];
64
+ const us = t.indexOf('_');
65
+ return words(us > 0 ? t.slice(us + 1) : t);
66
+ }
67
+
68
+ /** "Storage account main", or just "Storage account" when the name only repeats the type. */
69
+ export function resourceLabel(type, name) {
70
+ const tw = typeWords(type);
71
+ const nw = words(name).toLowerCase();
72
+ const twl = tw.toLowerCase();
73
+ if (!nw || nw === 'this') return cap(tw);
74
+ if (nw === twl || twl.split(/\s+/).includes(nw) || twl.endsWith(nw)) return cap(tw);
75
+ if (nw.endsWith(twl)) return cap(nw);
76
+ return `${cap(tw)} ${name}`;
77
+ }
78
+
79
+ // ── Roles: well-known Azure roles by id, what they let someone do, and which are wide ──────────────────────────
80
+
81
+ /** Built-in Azure role ids (checked against the Azure Verified Modules' own tables). */
82
+ export const AZURE_ROLES = {
83
+ '8e3af657-a8ff-443c-a75c-2fe8c4bcb635': 'Owner', 'b24988ac-6180-42a0-ab88-20f7382dd24c': 'Contributor', 'acdd72a7-3385-48ef-bd42-f606fba81ae7': 'Reader',
84
+ '18d7d88d-d35e-4fb5-a5c3-7773c20a72d9': 'User Access Administrator', 'f58310d9-a9f6-439a-9e8d-f62e7b41a168': 'Role Based Access Control Administrator',
85
+ '2a2b9908-6ea1-4ae2-8e65-a410df84e7d1': 'Storage Blob Data Reader', 'ba92f5b4-2d11-453d-a403-e96b0029c9fe': 'Storage Blob Data Contributor',
86
+ 'b7e6dc6d-f1e8-4753-8033-0f276bb0955b': 'Storage Blob Data Owner', 'db58b8e5-c6ad-4a2a-8342-4190687cbf4a': 'Storage Blob Delegator',
87
+ '974c5e8b-45b9-4653-ba55-5f855dd0fb88': 'Storage Queue Data Contributor', '19e7f393-937e-4f77-808e-94535e297925': 'Storage Queue Data Reader',
88
+ 'c6a89b2d-59bc-44d0-9896-0f6e12d7b80a': 'Storage Queue Data Message Sender', '0a9a7e1f-b9d0-4cc4-a60d-0319b160aaa3': 'Storage Table Data Contributor',
89
+ '76199698-9eea-4c19-bc75-cec21354c6b6': 'Storage Table Data Reader', '0c867c2a-1d8c-454a-a3db-ab2ea1bdc8bb': 'Storage File Data SMB Share Contributor',
90
+ '17d1049b-9a84-46fb-8f53-869881c3d3ab': 'Storage Account Contributor',
91
+ '4633458b-17de-408a-b874-0445c86b69e6': 'Key Vault Secrets User', 'b86a8fe4-44ce-4948-aee5-eccb2c155cd7': 'Key Vault Secrets Officer',
92
+ '00482a5a-887f-4fb3-b363-3b7fe8e74483': 'Key Vault Administrator', '12338af0-0e69-4776-bea7-57ae8d297424': 'Key Vault Crypto User',
93
+ '21090545-7ca7-4776-b22c-e363652d74d2': 'Key Vault Reader', 'e147488a-f6f5-4113-8e2d-b22465e65bf6': 'Key Vault Crypto Service Encryption User',
94
+ 'a4417e6f-fecd-4de8-b567-7b0420556985': 'Key Vault Certificates Officer',
95
+ '7f951dda-4ed3-4680-a7ca-43fe172d538d': 'AcrPull', '8311e382-0749-4cb8-b61a-304f252e45ec': 'AcrPush',
96
+ '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd': 'Cognitive Services OpenAI User', 'a001fd3d-188f-4b5d-821b-7da978bf7442': 'Cognitive Services OpenAI Contributor',
97
+ 'a97b65f3-24c7-4388-baec-2e87135dc908': 'Cognitive Services User', '3913510d-42f4-4e42-8a64-420c390055eb': 'Monitoring Metrics Publisher',
98
+ '749f88d5-cbae-40b8-bcfc-e573ddc772fa': 'Monitoring Contributor', '92aaf0da-9dab-42b6-94a3-d43ce8d16293': 'Log Analytics Contributor',
99
+ '73c42c96-874c-492b-b04d-ab87d138a893': 'Log Analytics Reader',
100
+ '69a216fc-b8fb-44d8-bc22-1f3c2cd27a39': 'Azure Service Bus Data Sender', '4f6d3b9b-027b-4f4c-9142-0e5a2a2247e0': 'Azure Service Bus Data Receiver',
101
+ '2b629674-e913-4c01-ae53-ef4638d8f975': 'Azure Event Hubs Data Sender', 'a638d3c7-ab3a-418d-83e6-5f17a39d4fde': 'Azure Event Hubs Data Receiver',
102
+ 'de139f84-1756-47ae-9be6-808fbbe84772': 'Website Contributor', '4d97b98b-1d4f-4787-a291-c67834d212e7': 'Network Contributor',
103
+ '9980e02c-c2be-4d73-94e8-173b1dc7cf3c': 'Virtual Machine Contributor', '6d8ee4ec-f05a-4a1d-8b00-a9b17e38b437': 'SQL Server Contributor',
104
+ '5bd9cd88-fe45-4216-938b-f97437e15450': 'DocumentDB Account Contributor',
105
+ '1407120a-92aa-4202-b7e9-c0e197c71c8f': 'Search Index Data Reader', '8ebe5a00-799e-43f5-93ac-243d3dce84a7': 'Search Index Data Contributor',
106
+ '7ca78c08-252a-4471-8644-bb5ff32d4ba0': 'Search Service Contributor', 'f1a07417-d97a-45cb-824c-7a7467783830': 'Managed Identity Operator',
107
+ 'b1ff04bb-8a4e-4dc4-8eb5-8693973ce19b': 'Azure Kubernetes Service RBAC Cluster Admin',
108
+ '516239f1-63e1-4d78-a4de-a74fb236a071': 'App Configuration Data Reader', '5ae67dd6-50cb-40e7-96ff-dc2bfa4b606b': 'App Configuration Data Owner',
109
+ };
110
+
111
+ const ROLE_CAN = {
112
+ Owner: 'do anything, including give others access', Contributor: 'change anything except who has access', Reader: 'read everything',
113
+ 'User Access Administrator': 'give anyone access', 'Role Based Access Control Administrator': 'give others access',
114
+ };
115
+ /** What a role lets someone do, in words: "read blobs (Storage Blob Data Reader)". */
116
+ export function roleCan(role) {
117
+ const r = String(role);
118
+ if (ROLE_CAN[r]) return `${ROLE_CAN[r]} (${r})`;
119
+ let m;
120
+ if ((m = /^Storage (Blob|Queue|Table|File) Data (Reader|Contributor|Owner)/.exec(r))) return `${m[2] === 'Reader' ? 'read' : m[2] === 'Owner' ? 'fully control' : 'read and change'} ${m[1].toLowerCase()}s (${r})`;
121
+ if ((m = /^Key Vault (Secrets|Certificates|Crypto|Keys)? ?(User|Officer|Reader|Administrator)/.exec(r))) return `${m[2] === 'User' ? 'use' : m[2] === 'Reader' ? 'read the list of' : 'manage'} ${m[1] ? m[1].toLowerCase() : 'everything'} in the key vault (${r})`;
122
+ if (r === 'AcrPull') return 'pull images (AcrPull)';
123
+ if (r === 'AcrPush') return 'push and pull images (AcrPush)';
124
+ if (/Reader$/.test(r)) return `read (${r})`;
125
+ if (/Sender$/.test(r)) return `send messages (${r})`;
126
+ if (/Receiver$/.test(r)) return `receive messages (${r})`;
127
+ if (/ User$/.test(r)) return `use it (${r})`;
128
+ return `act as ${r}`;
129
+ }
130
+
131
+ /** Roles that can change everything (or give anyone access) where they apply. */
132
+ export const WIDE_ROLES = new Set(['Owner', 'Contributor', 'User Access Administrator', 'Role Based Access Control Administrator', 'roles/owner', 'roles/editor', 'roles/resourcemanager.projectIamAdmin', 'roles/iam.securityAdmin']);
133
+
134
+ /** The role named by an id or name anywhere in a text ("…/roleDefinitions/b24988ac-…" -> "Contributor"). */
135
+ export function roleIn(text) {
136
+ const s = String(text ?? '').toLowerCase();
137
+ for (let i = 0; i + 36 <= s.length; i++) {
138
+ if (s[i + 8] !== '-' || s[i + 13] !== '-') continue;
139
+ const g = s.slice(i, i + 36);
140
+ if (AZURE_ROLES[g]) return AZURE_ROLES[g];
141
+ }
142
+ return null;
143
+ }
144
+
145
+ // ── Keys: how a resource names another, and what it says about it ──────────────────────────────────────────────
146
+
147
+ /** A key with case and separators removed: "allow_blob_public_access" and "allowBlobPublicAccess" are one key. */
148
+ export const normKey = (k) => String(k ?? '').toLowerCase().replace(/[_\-.]/g, '');
149
+
150
+ const RUNS_IN = new Set(['resourcegroupname', 'resourcegroup', 'resourcegroupid', 'serviceplanid', 'appserviceplanid', 'serverfarmid', 'serverid', 'clusterid', 'vpcid', 'subnetid', 'subnetids', 'subnets', 'virtualnetworkname', 'virtualnetworkid', 'parent', 'parentid', 'managedenvironmentid', 'environmentid', 'containerappenvironmentid', 'namespacename', 'namespaceid', 'hostingplanid', 'clustername', 'instanceid', 'dbsubnetgroupname', 'subnet']);
151
+ const SENDS_TO = new Set(['loganalyticsworkspaceid', 'workspaceid', 'workspaceresourceid', 'applicationinsightsid', 'appinsightsid', 'topicarn', 'snstopicarn', 'queueurl', 'queuearn', 'destinationarn', 'eventhubname', 'eventhubauthorizationruleid', 'targetarn', 'deadlettertargetarn']);
152
+ const CHILD_STORAGE = /(container|share|queue|table|blob|file_system|filesystem)/i;
153
+ /** The kind of link a reference makes, from the key it sits under and what it points to. */
154
+ export function linkKind(key, { toLookup = false, fromType = '', secretValue = false } = {}) {
155
+ const k = normKey(key);
156
+ if (toLookup || secretValue) return 'reads-from';
157
+ if (RUNS_IN.has(k)) return 'runs-in';
158
+ if ((k === 'storageaccountname' || k === 'storageaccountid' || k === 'keyvaultid' || k === 'servername') && /(container|share|queue|table|blob|secret|key|certificate|database|filesystem|file_system)/i.test(fromType) && CHILD_STORAGE.test(fromType + (k === 'keyvaultid' ? 'container' : ''))) return 'runs-in';
159
+ if (k === 'keyvaultid' && /secret|key|certificate|access_policy/i.test(fromType)) return 'runs-in';
160
+ if (SENDS_TO.has(k) || /endpoint$/.test(k)) return 'sends-to';
161
+ return 'uses';
162
+ }
163
+
164
+ // ── Values in words ──────────────────────────────────────────────────────────────────────────────────────
165
+
166
+ const short = (s, n = 70) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
167
+ const lit = (n) => {
168
+ if (n.t === 'str' && !n.template) return short(n.v.replace(/\s+/g, ' ').trim() || '(empty)');
169
+ if (n.t === 'num') return String(n.v);
170
+ if (n.t === 'bool') return n.v ? 'yes' : 'no';
171
+ if (n.t === 'null') return 'nothing (left to its default)';
172
+ if (n.t === 'unary') return `-${n.x.v}`;
173
+ return null;
174
+ };
175
+
176
+ /**
177
+ * A value in words: { text, computed? }. Literals are shown as written; anything else is "worked out when it is
178
+ * applied", naming what it comes from when that is one or a few references. `refWords(ref)` names one reference.
179
+ */
180
+ export function valueText(n, refWords, depth = 0) {
181
+ if (!n) return { text: 'nothing' };
182
+ const l = lit(n);
183
+ if (l != null) return { text: l };
184
+ if (n.t === 'list' && isLiteral(n) && n.items.length && n.items.every((x) => x.t === 'obj')) return { text: `${n.items.length} entr${n.items.length === 1 ? 'y' : 'ies'}` };
185
+ if (n.t === 'list' && isLiteral(n)) return { text: n.items.length ? short(listWords(n.items.map((x) => valueText(x, refWords, depth + 1).text)), 120) : 'none' };
186
+ if (n.t === 'obj' && isLiteral(n) && depth >= 2) return { text: n.entries.length ? `${n.entries.length} setting${n.entries.length === 1 ? '' : 's'}` : 'none' };
187
+ if (n.t === 'obj' && isLiteral(n)) {
188
+ if (!n.entries.length) return { text: 'none' };
189
+ const shown = n.entries.slice(0, 4).map((e) => `${words(e.key)}: ${valueText(e.value, refWords, depth + 1).text}`);
190
+ return { text: `${shown.join('; ')}${n.entries.length > 4 ? `; and ${n.entries.length - 4} more` : ''}` };
191
+ }
192
+ if (n.t === 'call' && /^(jsonencode|tolist|toset|tomap)$/.test(n.name) && n.args.length === 1 && isLiteral(n.args[0])) return valueText(n.args[0], refWords, depth);
193
+ if (n.t === 'ref' || (n.t === 'get' && n.obj.t === 'call')) { const w = refWords(n); return { text: w ? `${w} (${APPLIED})` : APPLIED, computed: true, ...(w ? { from: [w] } : {}) }; }
194
+ const from = [...new Set(refsIn(n).map(refWords).filter(Boolean))];
195
+ if (n.t === 'str' && n.template && from.length && from.length <= 3) return { text: `${APPLIED}, from ${listWords(from)}`, computed: true, from };
196
+ if (n.t === 'cond') return { text: `one of two values, ${APPLIED}${from.length && from.length <= 2 ? `, from ${listWords(from)}` : ''}`, computed: true, from };
197
+ if (from.length && from.length <= 2) return { text: `${APPLIED}, from ${listWords(from)}`, computed: true, from };
198
+ return { text: APPLIED, computed: true, from };
199
+ }
200
+
201
+ /** A condition in words, as a question: "Is the setting enabled on?", "Is the setting env prod?". */
202
+ export function conditionWords(n, refWords) {
203
+ const say = (x) => { const v = valueText(x, refWords); return v.computed ? (v.from?.length === 1 && x.t === 'ref' ? v.from[0] : v.text) : v.text; };
204
+ const inner = (x) => {
205
+ if (!x) return 'it applies';
206
+ if (x.paren) x = { ...x, paren: false };
207
+ if (x.t === 'ref') return `${say(x)} is on`;
208
+ if (x.t === 'unary' && x.op === '!') return x.x.t === 'ref' ? `${say(x.x)} is off` : `not (${inner(x.x)})`;
209
+ if (x.t === 'bin' && (x.op === '==' || x.op === '=~')) return x.b.t === 'null' ? `${say(x.a)} is not set` : `${say(x.a)} is ${say(x.b)}`;
210
+ if (x.t === 'bin' && (x.op === '!=' || x.op === '!~')) return x.b.t === 'null' ? `${say(x.a)} is set` : `${say(x.a)} is not ${say(x.b)}`;
211
+ if (x.t === 'bin' && x.op === '&&') return `${inner(x.a)} and ${inner(x.b)}`;
212
+ if (x.t === 'bin' && x.op === '||') return `${inner(x.a)} or ${inner(x.b)}`;
213
+ if (x.t === 'bin' && /^[<>]=?$/.test(x.op)) return `${say(x.a)} is ${{ '<': 'less than', '>': 'more than', '<=': 'at most', '>=': 'at least' }[x.op]} ${say(x.b)}`;
214
+ if (x.t === 'call' && x.name === 'length' && x.args.length === 1) return `${say(x.args[0])} has items`;
215
+ if (x.t === 'call' && x.name === 'contains' && x.args.length === 2) return `${say(x.args[0])} includes ${say(x.args[1])}`;
216
+ if (x.t === 'call' && /^(can|try)$/.test(x.name)) return `${say(x.args[0])} can be worked out`;
217
+ if (x.t === 'call' && x.name === 'empty' && x.args.length === 1) return `${say(x.args[0])} is empty`;
218
+ if (x.t === 'bool') return x.v ? 'always' : 'never';
219
+ return `${say(x)} is true`;
220
+ };
221
+ return inner(n);
222
+ }
223
+
224
+ // ── Facts both formats can state ─────────────────────────────────────────────────────────────────────────────
225
+
226
+ const ANYWHERE = new Set(['0.0.0.0/0', '::/0', '*', 'internet', 'any']);
227
+ /** True when a source address list lets anyone on the internet in. */
228
+ export const fromAnywhere = (xs) => xs.some((x) => ANYWHERE.has(String(x).trim().toLowerCase()));
229
+
230
+ /** Ports a rule opens, in words, and whether it opens more than web ports (80 and 443). */
231
+ export function portsOpen(from, to, protocol) {
232
+ const proto = String(protocol ?? '').toLowerCase();
233
+ if (proto === '-1' || proto === 'all' || (proto === '*' && from == null)) return { says: 'every port', beyondWeb: true };
234
+ if (proto === 'icmp' || proto === 'icmpv6' || proto === '1') return { says: 'it with ping (ICMP)', beyondWeb: true };
235
+ const f = from == null || from === '*' ? null : Number(String(from).split('-')[0]);
236
+ const t = to == null ? (String(from ?? '').includes('-') ? Number(String(from).split('-')[1]) : f) : Number(to);
237
+ if (f == null || Number.isNaN(f)) return { says: 'every port', beyondWeb: true };
238
+ if ((f === 0 && (t === 0 || t === 65535)) || (f === 1 && t === 65535)) return { says: 'every port', beyondWeb: true };
239
+ const range = f === t ? `port ${f}` : `ports ${f} to ${t}`;
240
+ return { says: range, beyondWeb: !(f === t && (f === 80 || f === 443)) };
241
+ }
242
+
243
+ const PUBLIC_TRUE = new Set(['allowblobpublicaccess', 'allownesteditemstobepublic']);
244
+ const PUBLIC_FALSE = new Set(['blockpublicacls', 'blockpublicpolicy', 'ignorepublicacls', 'restrictpublicbuckets']);
245
+ const ENCRYPT_FALSE = new Set(['encrypted', 'storageencrypted', 'encryptionenabled', 'enableencryption', 'httpsonly', 'enablehttpstrafficonly', 'httpstrafficonlyenabled', 'supportshttpstrafficonly', 'sslenforcementenabled', 'enforcessl', 'requiressl', 'encryptionatrest', 'kmsencrypted', 'atrestencryptionenabled', 'transitencryptionenabled']);
246
+ const ENCRYPT_TRUE = new Set(['enablenonsslport', 'nonsslportenabled', 'allowhttp']);
247
+ const PUBLIC_ACL = new Set(['public-read', 'public-read-write', 'authenticated-read', 'website']);
248
+
249
+ /**
250
+ * Facts from one key and its literal value, wherever it is written: public storage, encryption turned off, a secret
251
+ * written in the file. `say(kind, says)` records one. Returns true when the key was a secret written in the file.
252
+ */
253
+ export function keyFacts(key, value, say, where) {
254
+ const k = normKey(key);
255
+ const v = value?.t === 'bool' ? value.v : value?.t === 'str' && !value.template ? value.v : undefined;
256
+ if (v === undefined) return false;
257
+ if (PUBLIC_TRUE.has(k) && v === true) say('storage-public', `${where} allows public, anonymous access to its files (${key} = true).`);
258
+ else if (PUBLIC_FALSE.has(k) && v === false) say('storage-public', `${where} does not block public access (${key} = false).`);
259
+ else if ((k === 'containeraccesstype' || k === 'publicaccess') && typeof v === 'string' && /^(blob|container)$/i.test(v)) say('storage-public', `${where} lets anyone read its ${/^container$/i.test(v) ? 'files and list them' : 'files'} without signing in (${key} = ${v}).`);
260
+ else if (k === 'acl' && typeof v === 'string' && PUBLIC_ACL.has(v.toLowerCase())) say('storage-public', `${where} is readable by ${v.toLowerCase() === 'authenticated-read' ? 'any AWS account' : 'anyone'} (acl = ${v}).`);
261
+ else if (ENCRYPT_FALSE.has(k) && v === false) say('encryption-off', `${where} turns off ${/https|ssl/.test(k) ? 'encrypted connections (HTTPS)' : 'encryption'} (${key} = false).`);
262
+ else if (ENCRYPT_TRUE.has(k) && v === true) say('encryption-off', `${where} allows connections that are not encrypted (${key} = true).`);
263
+ else if ((k === 'mintlsversion' || k === 'minimumtlsversion') && typeof v === 'string' && /1[._]?[01]$/.test(v)) say('encryption-off', `${where} accepts old, weak encryption (${key} = ${v}).`);
264
+ else if (isSecretKey(key) && typeof v === 'string' && v.length > 0 && !/^(true|false|\d+|enabled|disabled|none|null)$/i.test(v)) {
265
+ say('secret-in-plain-config', `${where} has ${key} written in the file, where anyone who can read it sees the value.`);
266
+ return true;
267
+ }
268
+ return false;
269
+ }
270
+
271
+ /** Keys that hold a secret value, by their last word ("admin_password", "clientSecret", "access_key"), not ones that
272
+ * only mention one ("password_enabled", "secret_name", "bypass", "passwordAuth"). */
273
+ const SECRET_LAST = new Set(['password', 'passwd', 'pwd', 'secret', 'token', 'credential', 'credentials', 'passphrase', 'sas']);
274
+ const KEY_KINDS = new Set(['api', 'access', 'private', 'secret', 'account', 'shared', 'primary', 'secondary', 'master', 'admin', 'signing', 'subscription', 'storage', 'client', 'auth', 'instrumentation']);
275
+ export function isSecretKey(key) {
276
+ const w = String(key ?? '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
277
+ const last = w.at(-1), prev = w.at(-2);
278
+ if (!last) return false;
279
+ if (SECRET_LAST.has(last)) return true;
280
+ if (last === 'key' && KEY_KINDS.has(prev)) return true;
281
+ if (last === 'apikey' || last === 'accesskey' || last === 'secretkey' || last === 'privatekey') return true;
282
+ return last === 'string' && prev === 'connection';
283
+ }
284
+
285
+ /** Every literal key/value under an object node, with its line (nested objects and lists included). */
286
+ export function literalEntries(n, path = [], out = []) {
287
+ if (!n) return out;
288
+ if (n.t === 'obj') for (const e of n.entries) { if (e.nested) continue; out.push({ key: e.key, value: e.value, line: e.line, path }); literalEntries(e.value, [...path, e.key], out); }
289
+ else if (n.t === 'list') for (const x of n.items) literalEntries(x, path, out);
290
+ else if (n.t === 'if') literalEntries(n.body, path, out);
291
+ else if (n.t === 'for') literalEntries(n.value, path, out);
292
+ return out;
293
+ }
294
+
295
+ // ── Order of creation ────────────────────────────────────────────────────────────────────────────────────
296
+
297
+ /** Nodes in an order where each comes after what it relies on; ties and cycles keep the file's order. */
298
+ export function topoOrder(allIds, edges) {
299
+ const ids = [...new Set(allIds)];
300
+ const pos = new Map(ids.map((id, i) => [id, i]));
301
+ const indeg = new Map(ids.map((id) => [id, 0]));
302
+ const out = new Map(ids.map((id) => [id, []]));
303
+ const seen = new Set();
304
+ for (const [from, to] of edges) {
305
+ // from relies on to: to comes first.
306
+ if (!pos.has(from) || !pos.has(to) || from === to || seen.has(`${to}>${from}`)) continue;
307
+ seen.add(`${to}>${from}`);
308
+ out.get(to).push(from);
309
+ indeg.set(from, indeg.get(from) + 1);
310
+ }
311
+ const ready = ids.filter((id) => indeg.get(id) === 0);
312
+ const order = [];
313
+ const done = new Set();
314
+ while (order.length < ids.length) {
315
+ if (!ready.length) { const next = ids.find((id) => !done.has(id)); ready.push(next); indeg.set(next, 0); }
316
+ ready.sort((a, b) => pos.get(a) - pos.get(b));
317
+ const id = ready.shift();
318
+ if (done.has(id)) continue;
319
+ done.add(id); order.push(id);
320
+ for (const n of out.get(id)) { indeg.set(n, indeg.get(n) - 1); if (indeg.get(n) === 0 && !done.has(n)) ready.push(n); }
321
+ }
322
+ return order;
323
+ }
324
+
325
+ /** Add a link once per pair: a more exact kind (runs in, reads from, sends to) replaces a plain "uses". */
326
+ export function addLink(links, file, from, to, kind, line) {
327
+ if (from === to) return;
328
+ const same = links.find((l) => l.from === from && l.to === to);
329
+ if (!same) { links.push({ from, to, kind, file, line }); return; }
330
+ if (same.kind === 'uses' && kind !== 'uses') { same.kind = kind; same.line = line; }
331
+ }
332
+
333
+ /** "the setting enabled is on" -> "Is the setting enabled on?" */
334
+ export function question(c) {
335
+ const s = String(c);
336
+ const i = s.indexOf(' is ');
337
+ if (i > 0 && !/ (and|or) /.test(s.slice(0, i))) return `Is ${s.slice(0, i)} ${s.slice(i + 4)}?`;
338
+ return `Only when ${s}?`;
339
+ }
340
+
341
+ /** The values under a node with the nearest key and line each sits under (objects and lists opened up). */
342
+ export function leaves(n, key, line, out = []) {
343
+ if (!n) return out;
344
+ if (n.t === 'obj') { for (const e of n.entries) if (!e.nested) leaves(e.value, e.spread ? key : e.key, e.line, out); }
345
+ else if (n.t === 'list') for (const x of n.items) leaves(x, key, x.line ?? line, out);
346
+ else out.push({ key, value: n, line: n.t === 'str' || n.t === 'ref' ? line : line });
347
+ return out;
348
+ }