@principal-ai/subsystems-core 0.52.0 → 0.53.1

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 (220) hide show
  1. package/README.md +30 -2
  2. package/dist/audit/boundary.d.ts +104 -0
  3. package/dist/audit/boundary.d.ts.map +1 -0
  4. package/dist/audit/boundary.js +363 -0
  5. package/dist/audit/boundary.js.map +1 -0
  6. package/dist/audit/c4.d.ts +41 -0
  7. package/dist/audit/c4.d.ts.map +1 -0
  8. package/dist/audit/c4.js +41 -0
  9. package/dist/audit/c4.js.map +1 -0
  10. package/dist/audit/engine.d.ts +135 -0
  11. package/dist/audit/engine.d.ts.map +1 -0
  12. package/dist/audit/engine.js +865 -0
  13. package/dist/audit/engine.js.map +1 -0
  14. package/dist/audit/fixes.d.ts +80 -0
  15. package/dist/audit/fixes.d.ts.map +1 -0
  16. package/dist/audit/fixes.js +162 -0
  17. package/dist/audit/fixes.js.map +1 -0
  18. package/dist/audit/graphify-provider.d.ts +51 -0
  19. package/dist/audit/graphify-provider.d.ts.map +1 -0
  20. package/dist/audit/graphify-provider.js +36 -0
  21. package/dist/audit/graphify-provider.js.map +1 -0
  22. package/dist/audit/hash.d.ts +25 -0
  23. package/dist/audit/hash.d.ts.map +1 -0
  24. package/dist/audit/hash.js +53 -0
  25. package/dist/audit/hash.js.map +1 -0
  26. package/dist/audit/index.d.ts +12 -0
  27. package/dist/audit/index.d.ts.map +1 -0
  28. package/dist/audit/index.js +40 -0
  29. package/dist/audit/index.js.map +1 -0
  30. package/dist/audit/local-graphify.d.ts +75 -0
  31. package/dist/audit/local-graphify.d.ts.map +1 -0
  32. package/dist/audit/local-graphify.js +283 -0
  33. package/dist/audit/local-graphify.js.map +1 -0
  34. package/dist/audit/paths.d.ts +16 -0
  35. package/dist/audit/paths.d.ts.map +1 -0
  36. package/dist/audit/paths.js +31 -0
  37. package/dist/audit/paths.js.map +1 -0
  38. package/dist/audit/pure.d.ts +18 -0
  39. package/dist/audit/pure.d.ts.map +1 -0
  40. package/dist/audit/pure.js +50 -0
  41. package/dist/audit/pure.js.map +1 -0
  42. package/dist/audit/report-logic.d.ts +17 -0
  43. package/dist/audit/report-logic.d.ts.map +1 -0
  44. package/dist/audit/report-logic.js +206 -0
  45. package/dist/audit/report-logic.js.map +1 -0
  46. package/dist/audit/report.d.ts +140 -0
  47. package/dist/audit/report.d.ts.map +1 -0
  48. package/dist/audit/report.js +3 -0
  49. package/dist/audit/report.js.map +1 -0
  50. package/dist/audit/trail.d.ts +29 -0
  51. package/dist/audit/trail.d.ts.map +1 -0
  52. package/dist/audit/trail.js +59 -0
  53. package/dist/audit/trail.js.map +1 -0
  54. package/dist/audit/verification.d.ts +98 -0
  55. package/dist/audit/verification.d.ts.map +1 -0
  56. package/dist/audit/verification.js +11 -0
  57. package/dist/audit/verification.js.map +1 -0
  58. package/dist/audit/verify/component.d.ts +68 -0
  59. package/dist/audit/verify/component.d.ts.map +1 -0
  60. package/dist/audit/verify/component.js +500 -0
  61. package/dist/audit/verify/component.js.map +1 -0
  62. package/dist/audit/verify/declarations.d.ts +58 -0
  63. package/dist/audit/verify/declarations.d.ts.map +1 -0
  64. package/dist/audit/verify/declarations.js +227 -0
  65. package/dist/audit/verify/declarations.js.map +1 -0
  66. package/dist/audit/verify/grammar.d.ts +12 -0
  67. package/dist/audit/verify/grammar.d.ts.map +1 -0
  68. package/dist/audit/verify/grammar.js +57 -0
  69. package/dist/audit/verify/grammar.js.map +1 -0
  70. package/dist/audit/verify/index.d.ts +12 -0
  71. package/dist/audit/verify/index.d.ts.map +1 -0
  72. package/dist/audit/verify/index.js +31 -0
  73. package/dist/audit/verify/index.js.map +1 -0
  74. package/dist/audit/verify/parser.d.ts +19 -0
  75. package/dist/audit/verify/parser.d.ts.map +1 -0
  76. package/dist/audit/verify/parser.js +122 -0
  77. package/dist/audit/verify/parser.js.map +1 -0
  78. package/dist/audit/verify/span.d.ts +49 -0
  79. package/dist/audit/verify/span.d.ts.map +1 -0
  80. package/dist/audit/verify/span.js +377 -0
  81. package/dist/audit/verify/span.js.map +1 -0
  82. package/dist/graphify/anchor.d.ts +45 -0
  83. package/dist/graphify/anchor.d.ts.map +1 -0
  84. package/dist/graphify/anchor.js +179 -0
  85. package/dist/graphify/anchor.js.map +1 -0
  86. package/dist/graphify/consolidated.d.ts +259 -0
  87. package/dist/graphify/consolidated.d.ts.map +1 -0
  88. package/dist/graphify/consolidated.js +12 -0
  89. package/dist/graphify/consolidated.js.map +1 -0
  90. package/dist/graphify/construct.d.ts +41 -0
  91. package/dist/graphify/construct.d.ts.map +1 -0
  92. package/dist/graphify/construct.js +106 -0
  93. package/dist/graphify/construct.js.map +1 -0
  94. package/dist/graphify/ids.d.ts +19 -0
  95. package/dist/graphify/ids.d.ts.map +1 -0
  96. package/dist/graphify/ids.js +53 -0
  97. package/dist/graphify/ids.js.map +1 -0
  98. package/dist/graphify/index.d.ts +16 -0
  99. package/dist/graphify/index.d.ts.map +1 -0
  100. package/dist/graphify/index.js +32 -0
  101. package/dist/graphify/index.js.map +1 -0
  102. package/dist/graphify/resolve.d.ts +48 -0
  103. package/dist/graphify/resolve.d.ts.map +1 -0
  104. package/dist/graphify/resolve.js +89 -0
  105. package/dist/graphify/resolve.js.map +1 -0
  106. package/dist/graphify/signature.d.ts +87 -0
  107. package/dist/graphify/signature.d.ts.map +1 -0
  108. package/dist/graphify/signature.js +282 -0
  109. package/dist/graphify/signature.js.map +1 -0
  110. package/dist/graphify/types.d.ts +141 -0
  111. package/dist/graphify/types.d.ts.map +1 -0
  112. package/dist/graphify/types.js +9 -0
  113. package/dist/graphify/types.js.map +1 -0
  114. package/dist/index.d.ts +4 -0
  115. package/dist/index.d.ts.map +1 -1
  116. package/dist/index.js +10 -1
  117. package/dist/index.js.map +1 -1
  118. package/dist/infra/c4.d.ts +59 -0
  119. package/dist/infra/c4.d.ts.map +1 -0
  120. package/dist/infra/c4.js +106 -0
  121. package/dist/infra/c4.js.map +1 -0
  122. package/dist/infra/index.d.ts +17 -0
  123. package/dist/infra/index.d.ts.map +1 -0
  124. package/dist/infra/index.js +30 -0
  125. package/dist/infra/index.js.map +1 -0
  126. package/dist/infra/jsonc.d.ts +10 -0
  127. package/dist/infra/jsonc.d.ts.map +1 -0
  128. package/dist/infra/jsonc.js +77 -0
  129. package/dist/infra/jsonc.js.map +1 -0
  130. package/dist/infra/observe.d.ts +102 -0
  131. package/dist/infra/observe.d.ts.map +1 -0
  132. package/dist/infra/observe.js +347 -0
  133. package/dist/infra/observe.js.map +1 -0
  134. package/dist/infra/terraform.d.ts +41 -0
  135. package/dist/infra/terraform.d.ts.map +1 -0
  136. package/dist/infra/terraform.js +208 -0
  137. package/dist/infra/terraform.js.map +1 -0
  138. package/dist/infra/types.d.ts +107 -0
  139. package/dist/infra/types.d.ts.map +1 -0
  140. package/dist/infra/types.js +47 -0
  141. package/dist/infra/types.js.map +1 -0
  142. package/dist/infra/wrangler.d.ts +32 -0
  143. package/dist/infra/wrangler.d.ts.map +1 -0
  144. package/dist/infra/wrangler.js +177 -0
  145. package/dist/infra/wrangler.js.map +1 -0
  146. package/dist/node.d.ts +3 -0
  147. package/dist/node.d.ts.map +1 -1
  148. package/dist/node.js +4 -1
  149. package/dist/node.js.map +1 -1
  150. package/dist/storage/topic-reference-links.d.ts +3 -3
  151. package/dist/storage/topic-reference-links.d.ts.map +1 -1
  152. package/dist/storage/topic-reference-links.js +23 -8
  153. package/dist/storage/topic-reference-links.js.map +1 -1
  154. package/dist/storage/topic-share.d.ts +69 -0
  155. package/dist/storage/topic-share.d.ts.map +1 -0
  156. package/dist/storage/topic-share.js +67 -0
  157. package/dist/storage/topic-share.js.map +1 -0
  158. package/dist/storage/topic-types.d.ts +5 -1
  159. package/dist/storage/topic-types.d.ts.map +1 -1
  160. package/dist/types/subsystem-model.d.ts +59 -0
  161. package/dist/types/subsystem-model.d.ts.map +1 -1
  162. package/dist/types/subsystem-model.js +50 -1
  163. package/dist/types/subsystem-model.js.map +1 -1
  164. package/dist/validation.d.ts.map +1 -1
  165. package/dist/validation.js +25 -2
  166. package/dist/validation.js.map +1 -1
  167. package/package.json +22 -2
  168. package/schemas/subsystem-model.schema.json +35 -19
  169. package/src/audit/boundary.ts +447 -0
  170. package/src/audit/c4.ts +70 -0
  171. package/src/audit/engine.ts +1099 -0
  172. package/src/audit/fixes.ts +192 -0
  173. package/src/audit/graphify-provider.test.ts +58 -0
  174. package/src/audit/graphify-provider.ts +77 -0
  175. package/src/audit/hash.ts +58 -0
  176. package/src/audit/index.ts +34 -0
  177. package/src/audit/local-graphify.test.ts +163 -0
  178. package/src/audit/local-graphify.ts +354 -0
  179. package/src/audit/paths.ts +25 -0
  180. package/src/audit/pure.ts +91 -0
  181. package/src/audit/report-logic.test.ts +145 -0
  182. package/src/audit/report-logic.ts +245 -0
  183. package/src/audit/report.ts +207 -0
  184. package/src/audit/trail.ts +77 -0
  185. package/src/audit/verification.ts +104 -0
  186. package/src/audit/verify/component.ts +760 -0
  187. package/src/audit/verify/declarations.ts +284 -0
  188. package/src/audit/verify/grammar.ts +57 -0
  189. package/src/audit/verify/index.ts +41 -0
  190. package/src/audit/verify/parser.ts +124 -0
  191. package/src/audit/verify/span.ts +478 -0
  192. package/src/graphify/anchor.ts +206 -0
  193. package/src/graphify/consolidated.ts +298 -0
  194. package/src/graphify/construct.ts +153 -0
  195. package/src/graphify/ids.ts +48 -0
  196. package/src/graphify/index.ts +16 -0
  197. package/src/graphify/resolve.ts +115 -0
  198. package/src/graphify/signature.ts +354 -0
  199. package/src/graphify/types.ts +164 -0
  200. package/src/index.ts +11 -0
  201. package/src/infra/c4.ts +146 -0
  202. package/src/infra/index.ts +36 -0
  203. package/src/infra/infra.test.ts +360 -0
  204. package/src/infra/jsonc.ts +70 -0
  205. package/src/infra/observe.test.ts +202 -0
  206. package/src/infra/observe.ts +451 -0
  207. package/src/infra/terraform.ts +251 -0
  208. package/src/infra/types.ts +136 -0
  209. package/src/infra/wrangler.ts +203 -0
  210. package/src/node.ts +3 -0
  211. package/src/storage/topic-reference-links.test.ts +7 -1
  212. package/src/storage/topic-reference-links.ts +24 -8
  213. package/src/storage/topic-share.test.ts +91 -0
  214. package/src/storage/topic-share.ts +118 -0
  215. package/src/storage/topic-types.ts +3 -1
  216. package/src/storage/topicStore.test.ts +1 -0
  217. package/src/types/subsystem-model.test.ts +52 -2
  218. package/src/types/subsystem-model.ts +104 -0
  219. package/src/validation.test.ts +71 -7
  220. package/src/validation.ts +27 -2
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Infrastructure-as-code read side. Browser-safe. Everything is pure except
3
+ * `./observe`, which asks a provider's API what is running, with a credential
4
+ * the caller supplies.
5
+ */
6
+
7
+ export { infraResourceKey, mergeInfraManifests } from './types';
8
+ export type {
9
+ InfraBinding,
10
+ InfraDeploymentObservation,
11
+ InfraDeploymentStatus,
12
+ InfraManifest,
13
+ InfraResource,
14
+ InfraResourceSource,
15
+ InfraTool,
16
+ } from './types';
17
+ export { parseJsonc, stripJsonc } from './jsonc';
18
+ export { extractWranglerManifest } from './wrangler';
19
+ export type { ExtractWranglerOptions } from './wrangler';
20
+ export { extractTerraformManifest, terraformStateObservations } from './terraform';
21
+ export type { ExtractTerraformOptions } from './terraform';
22
+ export { infraContainerId, infraDeploymentRef, infraToC4 } from './c4';
23
+ export type { InfraC4Container, InfraC4Deployment, InfraC4Edge } from './c4';
24
+ export {
25
+ CLOUDFLARE_OBSERVED_TYPES,
26
+ observeCloudflare,
27
+ parseWranglerAuthToken,
28
+ resolveCloudflareAccount,
29
+ withoutUnknownOverwrites,
30
+ } from './observe';
31
+ export type {
32
+ CloudflareAccess,
33
+ CloudflareAccountResult,
34
+ InfraObserveDeps,
35
+ InfraObserveResult,
36
+ } from './observe';
@@ -0,0 +1,360 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import {
3
+ extractTerraformManifest,
4
+ extractWranglerManifest,
5
+ infraToC4,
6
+ mergeInfraManifests,
7
+ parseJsonc,
8
+ terraformStateObservations,
9
+ } from './index';
10
+
11
+ // The two real configs this was built against, verbatim.
12
+ const DEV_FEED = `{
13
+ "name": "dev-feed",
14
+ "main": "src/worker/index.ts",
15
+ "compatibility_date": "2025-11-01",
16
+ "vars": { "ALLOWED_ORGS": "pingdotgg,anomalyco,earendil-works" },
17
+ "ratelimits": [
18
+ { "name": "API_LIMITER", "namespace_id": "1001", "simple": { "limit": 120, "period": 60 } }
19
+ ],
20
+ "assets": { "not_found_handling": "single-page-application" },
21
+ "kv_namespaces": [{ "binding": "CACHE", "id": "347138f6fdef49d585fc898d6d9cf65d" }]
22
+ }`;
23
+
24
+ const TOPIC_SHARE = `{
25
+ "name": "topic-share",
26
+ "main": "src/worker/index.ts",
27
+ "compatibility_date": "2025-11-01",
28
+ // Days a shared topic lives after its last publish.
29
+ "vars": { "TTL_DAYS": "7", "MAX_PUBLISHES_PER_DAY": "200" },
30
+ "ratelimits": [
31
+ { "name": "API_LIMITER", "namespace_id": "1002", "simple": { "limit": 120, "period": 60 } }
32
+ ],
33
+ "assets": { "not_found_handling": "single-page-application", "binding": "ASSETS" },
34
+ "r2_buckets": [{ "binding": "TOPIC_BLOBS", "bucket_name": "topic-share" }],
35
+ // Replace database_id with the id from \`wrangler d1 create topic-share\` before the first deploy.
36
+ "d1_databases": [
37
+ {
38
+ "binding": "SHARE_INDEX",
39
+ "database_name": "topic-share",
40
+ "database_id": "62f4ec1e-1371-468d-9d13-eef5015c44ea",
41
+ "migrations_dir": "migrations"
42
+ }
43
+ ],
44
+ // Daily sweep of expired topics.
45
+ "triggers": { "crons": ["17 4 * * *"] }
46
+ }`;
47
+
48
+ describe('parseJsonc', () => {
49
+ test('drops comments and trailing commas but not string contents', () => {
50
+ const parsed = parseJsonc(`{
51
+ // line
52
+ "url": "https://example.com/a,]//b", /* block */
53
+ "list": [1, 2,],
54
+ }`);
55
+ expect(parsed).toEqual({ url: 'https://example.com/a,]//b', list: [1, 2] });
56
+ });
57
+
58
+ test('throws on malformed input', () => {
59
+ expect(() => parseJsonc('{ "a": ')).toThrow(SyntaxError);
60
+ });
61
+ });
62
+
63
+ describe('extractWranglerManifest', () => {
64
+ test('dev-feed: a Worker bound to one KV namespace', () => {
65
+ const manifest = extractWranglerManifest(DEV_FEED, { file: 'wrangler.jsonc' });
66
+ expect(manifest.resources.map((r) => r.key)).toEqual([
67
+ 'cloudflare:worker:dev-feed',
68
+ 'cloudflare:kv_namespace:347138f6fdef49d585fc898d6d9cf65d',
69
+ ]);
70
+ // A KV namespace is declared by opaque id, so the binding labels it.
71
+ expect(manifest.resources[1]).toMatchObject({
72
+ label: 'CACHE',
73
+ source: { tool: 'wrangler', file: 'wrangler.jsonc', pointer: '/kv_namespaces/0' },
74
+ });
75
+ expect(manifest.resources[0]!.attributes).toEqual({
76
+ main: 'src/worker/index.ts',
77
+ assets: 'true',
78
+ });
79
+ expect(manifest.bindings).toHaveLength(1);
80
+ expect(manifest.bindings[0]).toMatchObject({
81
+ from: 'cloudflare:worker:dev-feed',
82
+ to: 'cloudflare:kv_namespace:347138f6fdef49d585fc898d6d9cf65d',
83
+ binding: 'CACHE',
84
+ });
85
+ });
86
+
87
+ test('topic-share: R2 and D1 share a name but not a key; crons are kept', () => {
88
+ const manifest = extractWranglerManifest(TOPIC_SHARE, { file: 'wrangler.jsonc' });
89
+ expect(manifest.resources.map((r) => r.key)).toEqual([
90
+ 'cloudflare:worker:topic-share',
91
+ 'cloudflare:r2_bucket:topic-share',
92
+ 'cloudflare:d1_database:topic-share',
93
+ ]);
94
+ expect(manifest.resources[0]!.attributes?.crons).toBe('17 4 * * *');
95
+ expect(manifest.resources[2]!.attributes).toEqual({
96
+ id: '62f4ec1e-1371-468d-9d13-eef5015c44ea',
97
+ });
98
+ expect(manifest.bindings.map((b) => b.binding)).toEqual(['TOPIC_BLOBS', 'SHARE_INDEX']);
99
+ });
100
+
101
+ test('never copies vars into the manifest', () => {
102
+ const manifest = extractWranglerManifest(DEV_FEED, { file: 'wrangler.jsonc' });
103
+ expect(JSON.stringify(manifest)).not.toContain('pingdotgg');
104
+ });
105
+
106
+ test('a service binding is an access path, not a second Worker declaration', () => {
107
+ const manifest = extractWranglerManifest(
108
+ { name: 'web', services: [{ binding: 'API', service: 'api' }] },
109
+ { file: 'wrangler.jsonc' },
110
+ );
111
+ expect(manifest.resources.map((r) => r.key)).toEqual(['cloudflare:worker:web']);
112
+ expect(manifest.bindings[0]).toMatchObject({ to: 'cloudflare:worker:api', binding: 'API' });
113
+ });
114
+
115
+ test('OpenBot: a Worker fronting a Container, reached through its Durable Object', () => {
116
+ const manifest = extractWranglerManifest(
117
+ `{
118
+ "name": "openbot",
119
+ "main": "src/index.ts",
120
+ // Postgres is external (DATABASE_URL, a secret).
121
+ "containers": [
122
+ { "class_name": "OpenBot", "image": "../../Dockerfile", "instance_type": "standard-1", "max_instances": 1 }
123
+ ],
124
+ "durable_objects": { "bindings": [{ "name": "OPENBOT", "class_name": "OpenBot" }] },
125
+ "vars": { "EMBEDDED_POSTGRES": "off" }
126
+ }`,
127
+ { file: 'deploy/cloudflare/wrangler.jsonc' },
128
+ );
129
+ expect(manifest.resources.map((r) => r.key)).toEqual([
130
+ 'cloudflare:worker:openbot',
131
+ 'cloudflare:container:openbot-openbot',
132
+ ]);
133
+ expect(manifest.resources[1]).toMatchObject({
134
+ label: 'OpenBot',
135
+ attributes: { image: '../../Dockerfile', instanceType: 'standard-1', maxInstances: '1' },
136
+ source: { pointer: '/containers/0' },
137
+ });
138
+ expect(manifest.bindings).toEqual([
139
+ {
140
+ from: 'cloudflare:worker:openbot',
141
+ to: 'cloudflare:container:openbot-openbot',
142
+ binding: 'OPENBOT',
143
+ source: {
144
+ tool: 'wrangler',
145
+ file: 'deploy/cloudflare/wrangler.jsonc',
146
+ pointer: '/durable_objects/bindings/0',
147
+ },
148
+ },
149
+ ]);
150
+ // Same-named Worker and Container stay distinct containers in the sketch.
151
+ const { nodes, edges } = infraToC4(manifest);
152
+ expect(nodes.map((n) => [n.id, n.containerKind, n.technology])).toEqual([
153
+ ['container:openbot', 'application', 'Cloudflare Worker'],
154
+ ['container:openbot-container', 'application', 'Cloudflare Container'],
155
+ ]);
156
+ expect(edges.map((e) => e.label)).toEqual(['env.OPENBOT']);
157
+ });
158
+
159
+ test('a named container keeps its name; a Durable Object of another Worker is not its path', () => {
160
+ const manifest = extractWranglerManifest(
161
+ {
162
+ name: 'web',
163
+ containers: [{ name: 'runner', class_name: 'Runner' }],
164
+ durable_objects: { bindings: [{ name: 'RUNNER', class_name: 'Runner', script_name: 'other' }] },
165
+ },
166
+ { file: 'wrangler.jsonc' },
167
+ );
168
+ expect(manifest.resources.map((r) => r.key)).toEqual([
169
+ 'cloudflare:worker:web',
170
+ 'cloudflare:container:runner',
171
+ ]);
172
+ expect(manifest.bindings).toEqual([]);
173
+ });
174
+
175
+ test('a config with no Worker name declares nothing', () => {
176
+ expect(extractWranglerManifest('{}', { file: 'wrangler.jsonc' })).toEqual({
177
+ resources: [],
178
+ bindings: [],
179
+ });
180
+ });
181
+ });
182
+
183
+ // Hand-written to the Cloudflare provider v5 schema; not captured from a real
184
+ // `terraform show -json` run.
185
+ const TF_STATE = {
186
+ format_version: '1.0',
187
+ values: {
188
+ root_module: {
189
+ resources: [
190
+ {
191
+ address: 'cloudflare_workers_script.topic_share',
192
+ mode: 'managed',
193
+ type: 'cloudflare_workers_script',
194
+ name: 'topic_share',
195
+ values: {
196
+ id: 'topic-share',
197
+ script_name: 'topic-share',
198
+ content: 'SECRET_SOURCE',
199
+ bindings: [
200
+ { type: 'r2_bucket', name: 'TOPIC_BLOBS', bucket_name: 'topic-share' },
201
+ { type: 'd1', name: 'SHARE_INDEX', id: '62f4ec1e-1371-468d-9d13-eef5015c44ea' },
202
+ { type: 'secret_text', name: 'TOKEN', text: 'SECRET_VALUE' },
203
+ ],
204
+ },
205
+ },
206
+ { address: 'data.cloudflare_zone.z', mode: 'data', type: 'cloudflare_zone', values: {} },
207
+ ],
208
+ child_modules: [
209
+ {
210
+ address: 'module.storage',
211
+ resources: [
212
+ {
213
+ address: 'module.storage.cloudflare_r2_bucket.blobs',
214
+ mode: 'managed',
215
+ type: 'cloudflare_r2_bucket',
216
+ values: { id: 'topic-share', name: 'topic-share' },
217
+ },
218
+ {
219
+ address: 'module.storage.cloudflare_d1_database.index',
220
+ mode: 'managed',
221
+ type: 'cloudflare_d1_database',
222
+ values: { id: '62f4ec1e-1371-468d-9d13-eef5015c44ea', name: 'topic-share' },
223
+ },
224
+ ],
225
+ },
226
+ ],
227
+ },
228
+ },
229
+ };
230
+
231
+ describe('extractTerraformManifest', () => {
232
+ test('yields the same keys and bindings as the equivalent wrangler config', () => {
233
+ const tf = extractTerraformManifest(TF_STATE, { file: 'infra' });
234
+ const wrangler = extractWranglerManifest(TOPIC_SHARE, { file: 'wrangler.jsonc' });
235
+ expect(tf.resources.map((r) => r.key).sort()).toEqual(
236
+ wrangler.resources.map((r) => r.key).sort(),
237
+ );
238
+ // The D1 binding names the database by id; it resolves to the name-based key.
239
+ expect(tf.bindings.map((b) => [b.to, b.binding])).toEqual(
240
+ wrangler.bindings.map((b) => [b.to, b.binding]),
241
+ );
242
+ expect(tf.resources.find((r) => r.resourceType === 'r2_bucket')!.source).toEqual({
243
+ tool: 'terraform',
244
+ file: 'infra',
245
+ pointer: 'module.storage.cloudflare_r2_bucket.blobs',
246
+ });
247
+ });
248
+
249
+ test('copies no secret-bearing attribute out of state', () => {
250
+ const text = JSON.stringify([
251
+ extractTerraformManifest(TF_STATE, { file: 'infra' }),
252
+ terraformStateObservations(TF_STATE, { file: 'infra', observedAt: '2026-11-29T00:00:00.000Z' }),
253
+ ]);
254
+ expect(text).not.toContain('SECRET');
255
+ expect(text).not.toContain('TOKEN');
256
+ });
257
+
258
+ test('reads a plan, which declares but observes nothing', () => {
259
+ const plan = { planned_values: TF_STATE.values };
260
+ expect(extractTerraformManifest(plan, { file: 'infra' }).resources).toHaveLength(3);
261
+ expect(
262
+ terraformStateObservations(plan, { file: 'infra', observedAt: '2026-11-29T00:00:00.000Z' }),
263
+ ).toEqual([]);
264
+ });
265
+
266
+ test('split worker + version: bindings come from the version, live URL only when enabled', () => {
267
+ const state = (enabled: boolean) => ({
268
+ values: {
269
+ root_module: {
270
+ resources: [
271
+ {
272
+ address: 'cloudflare_worker.api',
273
+ mode: 'managed',
274
+ type: 'cloudflare_worker',
275
+ values: {
276
+ id: 'wid-1',
277
+ name: 'api',
278
+ subdomain: { enabled, url: 'https://api.acme.workers.dev' },
279
+ },
280
+ },
281
+ {
282
+ address: 'cloudflare_worker_version.api',
283
+ mode: 'managed',
284
+ type: 'cloudflare_worker_version',
285
+ values: {
286
+ worker_id: 'wid-1',
287
+ bindings: [{ type: 'kv_namespace', name: 'CACHE', namespace_id: 'ns-1' }],
288
+ },
289
+ },
290
+ ],
291
+ },
292
+ },
293
+ });
294
+ const options = { file: 'infra', observedAt: '2026-11-29T00:00:00.000Z' };
295
+ expect(extractTerraformManifest(state(true), options).bindings[0]).toMatchObject({
296
+ from: 'cloudflare:worker:api',
297
+ to: 'cloudflare:kv_namespace:ns-1',
298
+ binding: 'CACHE',
299
+ });
300
+ expect(terraformStateObservations(state(true), options)).toEqual([
301
+ {
302
+ resourceKey: 'cloudflare:worker:api',
303
+ status: 'deployed',
304
+ resourceId: 'wid-1',
305
+ liveUrls: ['https://api.acme.workers.dev'],
306
+ observedAt: options.observedAt,
307
+ source: 'terraform-state',
308
+ },
309
+ ]);
310
+ expect(terraformStateObservations(state(false), options)[0]!.liveUrls).toBeUndefined();
311
+ });
312
+ });
313
+
314
+ describe('infraToC4', () => {
315
+ test('one proposed container per resource, one draft edge per binding', () => {
316
+ const { nodes, edges } = infraToC4(
317
+ mergeInfraManifests([
318
+ extractWranglerManifest(DEV_FEED, { file: 'wrangler.jsonc' }),
319
+ extractWranglerManifest(TOPIC_SHARE, { file: 'wrangler.jsonc' }),
320
+ ]),
321
+ );
322
+ expect(nodes.map((n) => [n.id, n.containerKind, n.technology])).toEqual([
323
+ ['container:dev-feed', 'application', 'Cloudflare Worker'],
324
+ ['container:cache-kv', 'data-store', 'Cloudflare KV'],
325
+ ['container:topic-share', 'application', 'Cloudflare Worker'],
326
+ ['container:topic-share-r2', 'data-store', 'Cloudflare R2'],
327
+ ['container:topic-share-d1', 'data-store', 'Cloudflare D1'],
328
+ ]);
329
+ expect(nodes.every((n) => n.state === 'proposed')).toBe(true);
330
+ expect(nodes[0]!.deployment).toMatchObject({
331
+ resourceKey: 'cloudflare:worker:dev-feed',
332
+ provider: 'cloudflare',
333
+ });
334
+ expect(edges.map((e) => [e.source, e.target, e.label])).toEqual([
335
+ ['container:dev-feed', 'container:cache-kv', 'env.CACHE'],
336
+ ['container:topic-share', 'container:topic-share-r2', 'env.TOPIC_BLOBS'],
337
+ ['container:topic-share', 'container:topic-share-d1', 'env.SHARE_INDEX'],
338
+ ]);
339
+ });
340
+
341
+ test('drops a binding whose target no manifest declares', () => {
342
+ const { edges } = infraToC4(
343
+ extractWranglerManifest(
344
+ { name: 'web', services: [{ binding: 'API', service: 'api' }] },
345
+ { file: 'wrangler.jsonc' },
346
+ ),
347
+ );
348
+ expect(edges).toEqual([]);
349
+ });
350
+
351
+ test('merging two tools declaring one resource keeps a single container', () => {
352
+ const merged = mergeInfraManifests([
353
+ extractWranglerManifest(TOPIC_SHARE, { file: 'wrangler.jsonc' }),
354
+ extractTerraformManifest(TF_STATE, { file: 'infra' }),
355
+ ]);
356
+ expect(merged.resources).toHaveLength(3);
357
+ expect(merged.bindings).toHaveLength(2);
358
+ expect(merged.resources.every((r) => r.source.tool === 'wrangler')).toBe(true);
359
+ });
360
+ });
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Minimal JSONC reader — JSON with `//` and block comments and trailing
3
+ * commas, which is what `wrangler.jsonc` allows. Kept in-house so the
4
+ * browser-safe entry gains no dependency for a small job.
5
+ */
6
+
7
+ /** Index just past the string literal that opens at `start`. */
8
+ function skipString(text: string, start: number): number {
9
+ let i = start + 1;
10
+ while (i < text.length && text[i] !== '"') i += text[i] === '\\' ? 2 : 1;
11
+ return i + 1;
12
+ }
13
+
14
+ function stripComments(text: string): string {
15
+ let out = '';
16
+ let i = 0;
17
+ while (i < text.length) {
18
+ const ch = text[i]!;
19
+ const next = text[i + 1];
20
+ if (ch === '"') {
21
+ const end = skipString(text, i);
22
+ out += text.slice(i, end);
23
+ i = end;
24
+ } else if (ch === '/' && next === '/') {
25
+ while (i < text.length && text[i] !== '\n') i += 1;
26
+ } else if (ch === '/' && next === '*') {
27
+ const end = text.indexOf('*/', i + 2);
28
+ i = end === -1 ? text.length : end + 2;
29
+ } else {
30
+ out += ch;
31
+ i += 1;
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+
37
+ function stripTrailingCommas(text: string): string {
38
+ let out = '';
39
+ let i = 0;
40
+ while (i < text.length) {
41
+ const ch = text[i]!;
42
+ if (ch === '"') {
43
+ const end = skipString(text, i);
44
+ out += text.slice(i, end);
45
+ i = end;
46
+ continue;
47
+ }
48
+ if (ch === ',') {
49
+ let j = i + 1;
50
+ while (j < text.length && /\s/.test(text[j]!)) j += 1;
51
+ if (text[j] === '}' || text[j] === ']') {
52
+ i += 1;
53
+ continue;
54
+ }
55
+ }
56
+ out += ch;
57
+ i += 1;
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /** Remove comments and trailing commas, leaving string contents untouched. */
63
+ export function stripJsonc(text: string): string {
64
+ return stripTrailingCommas(stripComments(text));
65
+ }
66
+
67
+ /** Parse JSONC text. Throws `SyntaxError` like `JSON.parse` on malformed input. */
68
+ export function parseJsonc(text: string): unknown {
69
+ return JSON.parse(stripJsonc(text));
70
+ }
@@ -0,0 +1,202 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import {
3
+ observeCloudflare,
4
+ parseWranglerAuthToken,
5
+ resolveCloudflareAccount,
6
+ withoutUnknownOverwrites,
7
+ } from './observe';
8
+
9
+ const TOKEN = 'cf_test_token_0123456789abcdefghij';
10
+ const ACCOUNT = 'a'.repeat(32);
11
+ const NOW = () => new Date('2026-12-05T12:00:00.000Z');
12
+
13
+ type Route = { status?: number; result?: unknown; errors?: Array<{ code: number; message: string }> };
14
+
15
+ /** A Cloudflare API stand-in: path → answer. Records what it was asked. */
16
+ function fakeCloudflare(routes: Record<string, Route>) {
17
+ const seen: Array<{ method: string; path: string; authorization: string | null }> = [];
18
+ const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
19
+ const url = new URL(String(input));
20
+ const path = url.pathname.replace('/client/v4', '');
21
+ seen.push({
22
+ method: init?.method ?? 'GET',
23
+ path,
24
+ authorization: new Headers(init?.headers).get('authorization'),
25
+ });
26
+ const route = routes[`${path}${url.search}`] ?? routes[path];
27
+ if (!route) {
28
+ return Response.json(
29
+ { success: false, errors: [{ code: 10007, message: 'not found' }] },
30
+ { status: 404 },
31
+ );
32
+ }
33
+ const status = route.status ?? 200;
34
+ return Response.json(
35
+ { success: status < 400, result: route.result ?? null, errors: route.errors ?? [] },
36
+ { status },
37
+ );
38
+ }) as typeof fetch;
39
+ return { fetchImpl, seen };
40
+ }
41
+
42
+ describe('resolveCloudflareAccount', () => {
43
+ test('one visible account that can read Workers is accepted', async () => {
44
+ const { fetchImpl } = fakeCloudflare({
45
+ '/accounts': { result: [{ id: ACCOUNT, name: 'Acme' }] },
46
+ [`/accounts/${ACCOUNT}/workers/subdomain`]: { result: { subdomain: 'acme' } },
47
+ });
48
+ expect(await resolveCloudflareAccount({ token: TOKEN }, { fetch: fetchImpl })).toEqual({
49
+ ok: true,
50
+ accountId: ACCOUNT,
51
+ account: 'Acme',
52
+ });
53
+ });
54
+
55
+ test('several accounts: the caller has to choose', async () => {
56
+ const other = 'b'.repeat(32);
57
+ const { fetchImpl } = fakeCloudflare({
58
+ '/accounts': { result: [{ id: ACCOUNT, name: 'Acme' }, { id: other, name: 'Other' }] },
59
+ });
60
+ const result = await resolveCloudflareAccount({ token: TOKEN }, { fetch: fetchImpl });
61
+ expect(result).toMatchObject({ ok: false, accounts: [{ id: ACCOUNT }, { id: other }] });
62
+ });
63
+
64
+ test('a token that cannot read Workers is refused with the reason', async () => {
65
+ const { fetchImpl } = fakeCloudflare({
66
+ '/accounts': { result: [{ id: ACCOUNT, name: 'Acme' }] },
67
+ [`/accounts/${ACCOUNT}/workers/subdomain`]: {
68
+ status: 403,
69
+ errors: [{ code: 10000, message: 'Authentication error' }],
70
+ },
71
+ });
72
+ const result = await resolveCloudflareAccount({ token: TOKEN }, { fetch: fetchImpl });
73
+ expect(result).toEqual({
74
+ ok: false,
75
+ error: 'The token cannot read Workers on that account: Authentication error',
76
+ });
77
+ });
78
+
79
+ test('a malformed account id is refused before asking anyone', async () => {
80
+ const { fetchImpl, seen } = fakeCloudflare({});
81
+ const result = await resolveCloudflareAccount(
82
+ { token: TOKEN, accountId: 'nope' },
83
+ { fetch: fetchImpl },
84
+ );
85
+ expect(result.ok).toBe(false);
86
+ expect(seen).toEqual([]);
87
+ });
88
+ });
89
+
90
+ describe('observeCloudflare', () => {
91
+ const access = { token: TOKEN, accountId: ACCOUNT };
92
+
93
+ test('deployed, not-found, unknown and skipped are told apart, and nothing but reads is sent', async () => {
94
+ const { fetchImpl, seen } = fakeCloudflare({
95
+ [`/accounts/${ACCOUNT}/workers/scripts/api/subdomain`]: { result: { enabled: true } },
96
+ [`/accounts/${ACCOUNT}/workers/subdomain`]: { result: { subdomain: 'acme' } },
97
+ [`/accounts/${ACCOUNT}/workers/scripts/api/deployments`]: {
98
+ result: {
99
+ deployments: [{ created_on: '2026-12-01T08:00:00Z', versions: [{ version_id: 'v-123' }] }],
100
+ },
101
+ },
102
+ [`/accounts/${ACCOUNT}/r2/buckets/blobs`]: {
103
+ status: 403,
104
+ errors: [{ code: 10000, message: 'Authentication error' }],
105
+ },
106
+ });
107
+ const result = await observeCloudflare(
108
+ [
109
+ 'cloudflare:worker:api',
110
+ 'cloudflare:worker:gone',
111
+ 'cloudflare:r2_bucket:blobs',
112
+ 'cloudflare:hyperdrive:pg',
113
+ 'aws:lambda:ignored',
114
+ 'cloudflare:worker:api',
115
+ ],
116
+ access,
117
+ { fetch: fetchImpl, now: NOW },
118
+ );
119
+
120
+ expect(result.observations).toEqual([
121
+ {
122
+ resourceKey: 'cloudflare:worker:api',
123
+ status: 'deployed',
124
+ liveUrls: ['https://api.acme.workers.dev'],
125
+ consoleUrl: `https://dash.cloudflare.com/${ACCOUNT}/workers/services/view/api/production`,
126
+ version: 'v-123',
127
+ deployedAt: '2026-12-01T08:00:00.000Z',
128
+ observedAt: '2026-12-05T12:00:00.000Z',
129
+ source: 'cloudflare-api',
130
+ },
131
+ {
132
+ resourceKey: 'cloudflare:worker:gone',
133
+ status: 'not-found',
134
+ observedAt: '2026-12-05T12:00:00.000Z',
135
+ source: 'cloudflare-api',
136
+ },
137
+ {
138
+ resourceKey: 'cloudflare:r2_bucket:blobs',
139
+ status: 'unknown',
140
+ observedAt: '2026-12-05T12:00:00.000Z',
141
+ source: 'cloudflare-api',
142
+ },
143
+ ]);
144
+ expect(result.skipped).toEqual([
145
+ { resourceKey: 'cloudflare:hyperdrive:pg', reason: 'hyperdrive is not checked yet' },
146
+ ]);
147
+ expect(result.failure).toBe('r2 bucket: Authentication error');
148
+ expect(seen.every((call) => call.method === 'GET')).toBe(true);
149
+ expect(seen.every((call) => call.authorization === `Bearer ${TOKEN}`)).toBe(true);
150
+ expect(JSON.stringify(result)).not.toContain(TOKEN);
151
+ });
152
+
153
+ test('an unreachable API reads as unknown, never as not-found', async () => {
154
+ const failing = (async () => {
155
+ throw new Error('offline');
156
+ }) as unknown as typeof fetch;
157
+ const result = await observeCloudflare(['cloudflare:worker:api'], access, {
158
+ fetch: failing,
159
+ now: NOW,
160
+ });
161
+ expect(result.observations.map((o) => o.status)).toEqual(['unknown']);
162
+ expect(result.failure).toBe('worker: could not reach the Cloudflare API');
163
+ });
164
+ });
165
+
166
+ describe('withoutUnknownOverwrites', () => {
167
+ test('an unknown is kept only when nothing is known about the resource', () => {
168
+ const at = { observedAt: '2026-12-05T12:00:00.000Z', source: 'cloudflare-api' };
169
+ const kept = withoutUnknownOverwrites(
170
+ [
171
+ { resourceKey: 'a', status: 'unknown', ...at },
172
+ { resourceKey: 'b', status: 'unknown', ...at },
173
+ { resourceKey: 'c', status: 'not-found', ...at },
174
+ ],
175
+ new Set(['a', 'c']),
176
+ );
177
+ expect(kept.map((o) => o.resourceKey)).toEqual(['b', 'c']);
178
+ });
179
+ });
180
+
181
+ describe('parseWranglerAuthToken', () => {
182
+ test('an OAuth login and an API token are usable', () => {
183
+ const oauth = `${'x'.repeat(40)}.${'y'.repeat(40)}`;
184
+ expect(parseWranglerAuthToken(JSON.stringify({ type: 'oauth', token: oauth }))).toEqual({
185
+ type: 'oauth',
186
+ token: oauth,
187
+ });
188
+ expect(parseWranglerAuthToken(JSON.stringify({ type: 'api_token', token: TOKEN }))).toEqual({
189
+ type: 'api_token',
190
+ token: TOKEN,
191
+ });
192
+ });
193
+
194
+ test('a global API key, a logged-out answer and noise are not', () => {
195
+ expect(parseWranglerAuthToken(JSON.stringify({ type: 'api_key', key: 'k', email: 'e' }))).toBeNull();
196
+ expect(parseWranglerAuthToken('Not logged in.')).toBeNull();
197
+ expect(parseWranglerAuthToken(JSON.stringify({ type: 'oauth', token: 'short' }))).toBeNull();
198
+ expect(
199
+ parseWranglerAuthToken(JSON.stringify({ type: 'oauth', token: `${'x'.repeat(30)}\r\nX-Evil: 1` })),
200
+ ).toBeNull();
201
+ });
202
+ });