@principal-ai/subsystems-core 0.52.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) 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 +9 -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 +13 -0
  123. package/dist/infra/index.d.ts.map +1 -0
  124. package/dist/infra/index.js +22 -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/terraform.d.ts +41 -0
  131. package/dist/infra/terraform.d.ts.map +1 -0
  132. package/dist/infra/terraform.js +208 -0
  133. package/dist/infra/terraform.js.map +1 -0
  134. package/dist/infra/types.d.ts +107 -0
  135. package/dist/infra/types.d.ts.map +1 -0
  136. package/dist/infra/types.js +47 -0
  137. package/dist/infra/types.js.map +1 -0
  138. package/dist/infra/wrangler.d.ts +32 -0
  139. package/dist/infra/wrangler.d.ts.map +1 -0
  140. package/dist/infra/wrangler.js +177 -0
  141. package/dist/infra/wrangler.js.map +1 -0
  142. package/dist/node.d.ts +3 -0
  143. package/dist/node.d.ts.map +1 -1
  144. package/dist/node.js +4 -1
  145. package/dist/node.js.map +1 -1
  146. package/dist/storage/topic-reference-links.d.ts +3 -3
  147. package/dist/storage/topic-reference-links.d.ts.map +1 -1
  148. package/dist/storage/topic-reference-links.js +23 -8
  149. package/dist/storage/topic-reference-links.js.map +1 -1
  150. package/dist/storage/topic-share.d.ts +69 -0
  151. package/dist/storage/topic-share.d.ts.map +1 -0
  152. package/dist/storage/topic-share.js +67 -0
  153. package/dist/storage/topic-share.js.map +1 -0
  154. package/dist/storage/topic-types.d.ts +5 -1
  155. package/dist/storage/topic-types.d.ts.map +1 -1
  156. package/dist/types/subsystem-model.d.ts +59 -0
  157. package/dist/types/subsystem-model.d.ts.map +1 -1
  158. package/dist/types/subsystem-model.js +50 -1
  159. package/dist/types/subsystem-model.js.map +1 -1
  160. package/dist/validation.d.ts.map +1 -1
  161. package/dist/validation.js +25 -2
  162. package/dist/validation.js.map +1 -1
  163. package/package.json +22 -2
  164. package/schemas/subsystem-model.schema.json +35 -19
  165. package/src/audit/boundary.ts +447 -0
  166. package/src/audit/c4.ts +70 -0
  167. package/src/audit/engine.ts +1099 -0
  168. package/src/audit/fixes.ts +192 -0
  169. package/src/audit/graphify-provider.test.ts +58 -0
  170. package/src/audit/graphify-provider.ts +77 -0
  171. package/src/audit/hash.ts +58 -0
  172. package/src/audit/index.ts +34 -0
  173. package/src/audit/local-graphify.test.ts +163 -0
  174. package/src/audit/local-graphify.ts +354 -0
  175. package/src/audit/paths.ts +25 -0
  176. package/src/audit/pure.ts +91 -0
  177. package/src/audit/report-logic.test.ts +145 -0
  178. package/src/audit/report-logic.ts +245 -0
  179. package/src/audit/report.ts +207 -0
  180. package/src/audit/trail.ts +77 -0
  181. package/src/audit/verification.ts +104 -0
  182. package/src/audit/verify/component.ts +760 -0
  183. package/src/audit/verify/declarations.ts +284 -0
  184. package/src/audit/verify/grammar.ts +57 -0
  185. package/src/audit/verify/index.ts +41 -0
  186. package/src/audit/verify/parser.ts +124 -0
  187. package/src/audit/verify/span.ts +478 -0
  188. package/src/graphify/anchor.ts +206 -0
  189. package/src/graphify/consolidated.ts +298 -0
  190. package/src/graphify/construct.ts +153 -0
  191. package/src/graphify/ids.ts +48 -0
  192. package/src/graphify/index.ts +16 -0
  193. package/src/graphify/resolve.ts +115 -0
  194. package/src/graphify/signature.ts +354 -0
  195. package/src/graphify/types.ts +164 -0
  196. package/src/index.ts +10 -0
  197. package/src/infra/c4.ts +146 -0
  198. package/src/infra/index.ts +21 -0
  199. package/src/infra/infra.test.ts +360 -0
  200. package/src/infra/jsonc.ts +70 -0
  201. package/src/infra/terraform.ts +251 -0
  202. package/src/infra/types.ts +136 -0
  203. package/src/infra/wrangler.ts +203 -0
  204. package/src/node.ts +3 -0
  205. package/src/storage/topic-reference-links.test.ts +7 -1
  206. package/src/storage/topic-reference-links.ts +24 -8
  207. package/src/storage/topic-share.test.ts +91 -0
  208. package/src/storage/topic-share.ts +118 -0
  209. package/src/storage/topic-types.ts +3 -1
  210. package/src/storage/topicStore.test.ts +1 -0
  211. package/src/types/subsystem-model.test.ts +52 -2
  212. package/src/types/subsystem-model.ts +104 -0
  213. package/src/validation.test.ts +71 -7
  214. package/src/validation.ts +27 -2
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Terraform → {@link InfraManifest}, read from `terraform show -json`.
3
+ *
4
+ * We read Terraform's own JSON rendering, never HCL: it is the documented
5
+ * machine-readable form, modules and variables are already resolved in it, and
6
+ * the same walk covers a plan (`planned_values`) and applied state (`values`).
7
+ *
8
+ * Cloudflare provider v5 resource shapes only. Attribute names follow the
9
+ * provider's published schema for `cloudflare_workers_script`,
10
+ * `cloudflare_worker` + `cloudflare_worker_version`, `cloudflare_r2_bucket`,
11
+ * `cloudflare_d1_database`, `cloudflare_workers_kv_namespace` and
12
+ * `cloudflare_queue`.
13
+ *
14
+ * Only type, name, id and declared URLs are ever read off a resource. State
15
+ * can hold secrets in other attributes; nothing here copies them out.
16
+ */
17
+
18
+ import {
19
+ infraResourceKey,
20
+ type InfraBinding,
21
+ type InfraDeploymentObservation,
22
+ type InfraManifest,
23
+ type InfraResource,
24
+ type InfraResourceSource,
25
+ } from './types';
26
+
27
+ const PROVIDER = 'cloudflare';
28
+
29
+ type Json = Record<string, unknown>;
30
+
31
+ function isObject(value: unknown): value is Json {
32
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
33
+ }
34
+
35
+ function str(value: unknown): string | undefined {
36
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
37
+ }
38
+
39
+ interface TfResource {
40
+ address: string;
41
+ type: string;
42
+ values: Json;
43
+ }
44
+
45
+ /** Managed resources of a module and every child module, depth-first. */
46
+ function collectResources(module: unknown, out: TfResource[] = []): TfResource[] {
47
+ if (!isObject(module)) return out;
48
+ if (Array.isArray(module.resources)) {
49
+ for (const resource of module.resources) {
50
+ if (!isObject(resource) || resource.mode !== 'managed') continue;
51
+ const address = str(resource.address);
52
+ const type = str(resource.type);
53
+ if (!address || !type) continue;
54
+ out.push({ address, type, values: isObject(resource.values) ? resource.values : {} });
55
+ }
56
+ }
57
+ if (Array.isArray(module.child_modules)) {
58
+ for (const child of module.child_modules) collectResources(child, out);
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /** State (`values`) when present, else a plan's `planned_values`. */
64
+ function rootModule(showJson: unknown): { module: unknown; applied: boolean } {
65
+ if (!isObject(showJson)) return { module: undefined, applied: false };
66
+ if (isObject(showJson.values)) return { module: showJson.values.root_module, applied: true };
67
+ if (isObject(showJson.planned_values)) {
68
+ return { module: showJson.planned_values.root_module, applied: false };
69
+ }
70
+ return { module: undefined, applied: false };
71
+ }
72
+
73
+ /** How each store type names itself and what its key is built from. */
74
+ interface StoreType {
75
+ resourceType: string;
76
+ /** The human name field. */
77
+ nameField: string;
78
+ /**
79
+ * Whether the key is the provider id rather than the name. True for KV,
80
+ * because a wrangler config knows a namespace by id only and the two tools
81
+ * must agree on the key.
82
+ */
83
+ keyById: boolean;
84
+ }
85
+
86
+ const STORE_TYPES: Record<string, StoreType> = {
87
+ cloudflare_r2_bucket: { resourceType: 'r2_bucket', nameField: 'name', keyById: false },
88
+ cloudflare_d1_database: { resourceType: 'd1_database', nameField: 'name', keyById: false },
89
+ cloudflare_workers_kv_namespace: { resourceType: 'kv_namespace', nameField: 'title', keyById: true },
90
+ cloudflare_queue: { resourceType: 'queue', nameField: 'queue_name', keyById: false },
91
+ };
92
+
93
+ /** Binding `type` → the resource type it reaches and the field that names the target. */
94
+ const BINDING_TYPES: Record<string, { resourceType: string; refFields: readonly string[] }> = {
95
+ kv_namespace: { resourceType: 'kv_namespace', refFields: ['namespace_id'] },
96
+ r2_bucket: { resourceType: 'r2_bucket', refFields: ['bucket_name'] },
97
+ d1: { resourceType: 'd1_database', refFields: ['id', 'database_id'] },
98
+ queue: { resourceType: 'queue', refFields: ['queue_name'] },
99
+ service: { resourceType: 'worker', refFields: ['service'] },
100
+ };
101
+
102
+ export interface ExtractTerraformOptions {
103
+ /**
104
+ * Repo-root-relative path recorded on every source — the directory or file
105
+ * the JSON was rendered from (e.g. `infra/` or `infra/main.tf`).
106
+ */
107
+ file: string;
108
+ }
109
+
110
+ interface Extracted {
111
+ manifest: InfraManifest;
112
+ /** Whether the JSON was applied state rather than a plan. */
113
+ applied: boolean;
114
+ /** Per resource key: the fields an observation is allowed to carry. */
115
+ observed: Map<string, { resourceId?: string; liveUrls?: string[] }>;
116
+ }
117
+
118
+ function extract(showJson: unknown, options: ExtractTerraformOptions): Extracted {
119
+ const { module, applied } = rootModule(showJson);
120
+ const tfResources = collectResources(module);
121
+ const source = (pointer: string): InfraResourceSource => ({
122
+ tool: 'terraform',
123
+ file: options.file,
124
+ pointer,
125
+ });
126
+
127
+ const resources: InfraResource[] = [];
128
+ const observed: Extracted['observed'] = new Map();
129
+ /** `<resourceType>\0<id or name>` → key, so a binding can find its target either way. */
130
+ const lookup = new Map<string, string>();
131
+ const index = (resourceType: string, ref: string | undefined, key: string) => {
132
+ if (ref) lookup.set(`${resourceType}\u0000${ref}`, key);
133
+ };
134
+
135
+ // Stores first, so Worker bindings can resolve against them.
136
+ for (const tf of tfResources) {
137
+ const store = STORE_TYPES[tf.type];
138
+ if (!store) continue;
139
+ const name = str(tf.values[store.nameField]);
140
+ const id = str(tf.values.id);
141
+ const identifier = store.keyById ? id ?? name : name;
142
+ if (!identifier) continue;
143
+ const key = infraResourceKey(PROVIDER, store.resourceType, identifier);
144
+ resources.push({
145
+ key,
146
+ provider: PROVIDER,
147
+ resourceType: store.resourceType,
148
+ name: identifier,
149
+ label: name ?? identifier,
150
+ source: source(tf.address),
151
+ ...(id ? { attributes: { id } } : {}),
152
+ });
153
+ index(store.resourceType, id, key);
154
+ index(store.resourceType, name, key);
155
+ observed.set(key, { ...(id ? { resourceId: id } : {}) });
156
+ }
157
+
158
+ // Workers: the classic single-resource script, and the split worker + version.
159
+ /** Worker id or name → key, for `cloudflare_worker_version.worker_id`. */
160
+ const workerKeys = new Map<string, string>();
161
+ for (const tf of tfResources) {
162
+ const isScript = tf.type === 'cloudflare_workers_script';
163
+ if (!isScript && tf.type !== 'cloudflare_worker') continue;
164
+ const name = str(isScript ? tf.values.script_name : tf.values.name);
165
+ if (!name) continue;
166
+ const key = infraResourceKey(PROVIDER, 'worker', name);
167
+ const id = str(tf.values.id);
168
+ resources.push({
169
+ key,
170
+ provider: PROVIDER,
171
+ resourceType: 'worker',
172
+ name,
173
+ label: name,
174
+ source: source(tf.address),
175
+ });
176
+ workerKeys.set(name, key);
177
+ if (id) workerKeys.set(id, key);
178
+ index('worker', name, key);
179
+ // `subdomain.url` is present whenever the account owns a workers.dev
180
+ // subdomain, so it is only a live URL when the subdomain is enabled.
181
+ const subdomain = isObject(tf.values.subdomain) ? tf.values.subdomain : undefined;
182
+ const url = subdomain?.enabled === true ? str(subdomain.url) : undefined;
183
+ observed.set(key, {
184
+ ...(id ? { resourceId: id } : {}),
185
+ ...(url ? { liveUrls: [url] } : {}),
186
+ });
187
+ }
188
+
189
+ const bindings: InfraBinding[] = [];
190
+ for (const tf of tfResources) {
191
+ let from: string | undefined;
192
+ if (tf.type === 'cloudflare_workers_script') {
193
+ const name = str(tf.values.script_name);
194
+ from = name ? workerKeys.get(name) : undefined;
195
+ } else if (tf.type === 'cloudflare_worker_version') {
196
+ const workerId = str(tf.values.worker_id);
197
+ from = workerId ? workerKeys.get(workerId) : undefined;
198
+ }
199
+ if (!from || !Array.isArray(tf.values.bindings)) continue;
200
+ tf.values.bindings.forEach((entry, i) => {
201
+ if (!isObject(entry)) return;
202
+ const family = BINDING_TYPES[str(entry.type) ?? ''];
203
+ const binding = str(entry.name);
204
+ if (!family || !binding) return;
205
+ const ref = family.refFields.map((field) => str(entry[field])).find(Boolean);
206
+ if (!ref) return;
207
+ // Resolve through a declared resource when there is one, so a D1 binding
208
+ // by id lands on the database's name-based key. Otherwise key by the ref.
209
+ const to =
210
+ lookup.get(`${family.resourceType}\u0000${ref}`) ??
211
+ infraResourceKey(PROVIDER, family.resourceType, ref);
212
+ bindings.push({ from: from!, to, binding, source: source(`${tf.address}.bindings[${i}]`) });
213
+ });
214
+ }
215
+
216
+ return { manifest: { resources, bindings }, applied, observed };
217
+ }
218
+
219
+ /**
220
+ * Read the declared resources out of `terraform show -json` output — applied
221
+ * state or a saved plan. Unknown resource types are ignored.
222
+ */
223
+ export function extractTerraformManifest(
224
+ showJson: unknown,
225
+ options: ExtractTerraformOptions,
226
+ ): InfraManifest {
227
+ return extract(showJson, options).manifest;
228
+ }
229
+
230
+ /**
231
+ * Turn applied state into deployment observations.
232
+ *
233
+ * State is a record of the last apply, not a live check: a resource deleted
234
+ * out of band still appears. The observation says so through its `source`
235
+ * (`terraform-state`), and `observedAt` should be when the state was read.
236
+ * A plan yields no observations.
237
+ */
238
+ export function terraformStateObservations(
239
+ showJson: unknown,
240
+ options: ExtractTerraformOptions & { observedAt: string },
241
+ ): InfraDeploymentObservation[] {
242
+ const { manifest, applied, observed } = extract(showJson, options);
243
+ if (!applied) return [];
244
+ return manifest.resources.map((resource) => ({
245
+ resourceKey: resource.key,
246
+ status: 'deployed' as const,
247
+ ...observed.get(resource.key),
248
+ observedAt: options.observedAt,
249
+ source: 'terraform-state',
250
+ }));
251
+ }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Infrastructure-as-code read side — what a config file *declares* and what a
3
+ * live account was *observed* to be running.
4
+ *
5
+ * Two facts, kept apart on purpose:
6
+ *
7
+ * - **Configured** ({@link InfraManifest}) is a static parse of a file at a
8
+ * commit. No credentials, always available, verifiable like source.
9
+ * - **Deployed** ({@link InfraDeploymentObservation}) is an observation of
10
+ * the live account. It needs credentials, carries a timestamp, and goes
11
+ * stale. Nothing here fetches one; the tooling that does is separate and
12
+ * only has to produce this shape.
13
+ *
14
+ * Everything in this folder is pure and browser-safe: extractors take text or
15
+ * parsed JSON, never a path.
16
+ */
17
+
18
+ /** The tool whose file declared a resource. */
19
+ export type InfraTool = 'wrangler' | 'terraform';
20
+
21
+ /** Where a declaration lives — the infra analogue of `file` + `symbol`. */
22
+ export interface InfraResourceSource {
23
+ tool: InfraTool;
24
+ /** Repo-root-relative path of the file the caller parsed. */
25
+ file: string;
26
+ /**
27
+ * Location inside that file. A JSON pointer for wrangler
28
+ * (`/r2_buckets/0`), a resource address for terraform
29
+ * (`cloudflare_r2_bucket.blobs`).
30
+ */
31
+ pointer: string;
32
+ }
33
+
34
+ /** One declared piece of infrastructure. */
35
+ export interface InfraResource {
36
+ /**
37
+ * Stable identity, `<provider>:<resourceType>:<identifier>` — e.g.
38
+ * `cloudflare:worker:topic-share`. Chosen so the same resource declared by
39
+ * two tools yields the same key; observations join on it.
40
+ */
41
+ key: string;
42
+ /** Hosting provider, lowercase: `cloudflare`. */
43
+ provider: string;
44
+ /** Provider-neutral-ish type: `worker`, `r2_bucket`, `d1_database`, `kv_namespace`, `queue`. */
45
+ resourceType: string;
46
+ /** The provider's own name or id for the resource. */
47
+ name: string;
48
+ /** What to show a reader. Falls back to the binding name when the provider name is an opaque id. */
49
+ label: string;
50
+ source: InfraResourceSource;
51
+ /** Small declared facts worth showing (`crons`, `assets`, `id`). Never secrets or env values. */
52
+ attributes?: Record<string, string>;
53
+ }
54
+
55
+ /** A declared access path from one resource to another — a Worker's binding. */
56
+ export interface InfraBinding {
57
+ /** Key of the resource that holds the binding (the Worker). */
58
+ from: string;
59
+ /** Key of the resource it reaches. May name a resource no parsed file declares. */
60
+ to: string;
61
+ /** The name code uses, e.g. `TOPIC_BLOBS` for `env.TOPIC_BLOBS`. */
62
+ binding: string;
63
+ source: InfraResourceSource;
64
+ }
65
+
66
+ /** Everything one or more config files declare. */
67
+ export interface InfraManifest {
68
+ resources: InfraResource[];
69
+ bindings: InfraBinding[];
70
+ }
71
+
72
+ /**
73
+ * Whether a resource was found live.
74
+ *
75
+ * `unknown` means the check could not be made (no permission, network
76
+ * failure). It is deliberately not `not-found`: a failed check must never read
77
+ * as "not deployed".
78
+ */
79
+ export type InfraDeploymentStatus = 'deployed' | 'not-found' | 'unknown';
80
+
81
+ /**
82
+ * One observation of one resource in a live account.
83
+ *
84
+ * Produced by credentialed tooling outside this package. Carries no
85
+ * credential, token, or environment value.
86
+ */
87
+ export interface InfraDeploymentObservation {
88
+ /** Joins to {@link InfraResource.key}. */
89
+ resourceKey: string;
90
+ status: InfraDeploymentStatus;
91
+ /** Provider id, e.g. a D1 database id. */
92
+ resourceId?: string;
93
+ /** Where the running thing answers — workers.dev, routes, custom domains. */
94
+ liveUrls?: string[];
95
+ /** The provider dashboard page for this resource. */
96
+ consoleUrl?: string;
97
+ /** Deployed version or deployment id, when the provider exposes one. */
98
+ version?: string;
99
+ /** When that version went live (ISO). */
100
+ deployedAt?: string;
101
+ /** When we looked (ISO). Required so a view can show staleness. */
102
+ observedAt: string;
103
+ /** Who said so: `cloudflare-api`, `terraform-state`, `authored`. */
104
+ source: string;
105
+ }
106
+
107
+ /** Build a resource key. Exported so observers produce the same string. */
108
+ export function infraResourceKey(
109
+ provider: string,
110
+ resourceType: string,
111
+ identifier: string,
112
+ ): string {
113
+ return `${provider}:${resourceType}:${identifier}`;
114
+ }
115
+
116
+ /**
117
+ * Merge manifests from several files. The first declaration of a key wins, so
118
+ * pass the more authoritative file first; bindings are de-duplicated on
119
+ * `from` + `to` + `binding`.
120
+ */
121
+ export function mergeInfraManifests(
122
+ manifests: readonly InfraManifest[],
123
+ ): InfraManifest {
124
+ const resources = new Map<string, InfraResource>();
125
+ const bindings = new Map<string, InfraBinding>();
126
+ for (const manifest of manifests) {
127
+ for (const resource of manifest.resources) {
128
+ if (!resources.has(resource.key)) resources.set(resource.key, resource);
129
+ }
130
+ for (const binding of manifest.bindings) {
131
+ const id = `${binding.from}\u0000${binding.to}\u0000${binding.binding}`;
132
+ if (!bindings.has(id)) bindings.set(id, binding);
133
+ }
134
+ }
135
+ return { resources: [...resources.values()], bindings: [...bindings.values()] };
136
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Wrangler config → {@link InfraManifest}.
3
+ *
4
+ * A `wrangler.jsonc` declares one Worker and the resources it binds. That maps
5
+ * cleanly: the Worker is a resource, each bound store is a resource, and each
6
+ * binding is the access path between them — named exactly as code names it
7
+ * (`env.TOPIC_BLOBS`), which is what makes the binding a join to trail steps.
8
+ *
9
+ * A `containers` entry is a second deployable unit: a Cloudflare Container the
10
+ * Worker starts and routes to through a Durable Object. The access path is the
11
+ * Durable Object binding of the same class, so that is the edge.
12
+ *
13
+ * Secrets are not in a wrangler config, so anything reached through one (an
14
+ * external Postgres behind `DATABASE_URL`, say) is not declared here and cannot
15
+ * be read from it.
16
+ *
17
+ * Top-level config only. Named environments (`env.staging`) are not read yet.
18
+ */
19
+
20
+ import { parseJsonc } from './jsonc';
21
+ import {
22
+ infraResourceKey,
23
+ type InfraBinding,
24
+ type InfraManifest,
25
+ type InfraResource,
26
+ type InfraResourceSource,
27
+ } from './types';
28
+
29
+ const PROVIDER = 'cloudflare';
30
+
31
+ type Json = Record<string, unknown>;
32
+
33
+ function isObject(value: unknown): value is Json {
34
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
35
+ }
36
+
37
+ function str(value: unknown): string | undefined {
38
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
39
+ }
40
+
41
+ /**
42
+ * One row per binding family. `identifier` is what the resource key is built
43
+ * from, so it must be the field another tool would also know the resource by.
44
+ */
45
+ interface BindingFamily {
46
+ /** Path to the array in the config, e.g. `['queues', 'producers']`. */
47
+ path: readonly string[];
48
+ resourceType: string;
49
+ /** Field holding the code-side binding name. */
50
+ bindingField: string;
51
+ /** Field holding the provider name/id the key is built from. */
52
+ identifierField: string;
53
+ /** Extra identifier worth keeping as an attribute (e.g. the D1 id). */
54
+ idField?: string;
55
+ }
56
+
57
+ const BINDING_FAMILIES: readonly BindingFamily[] = [
58
+ { path: ['kv_namespaces'], resourceType: 'kv_namespace', bindingField: 'binding', identifierField: 'id' },
59
+ { path: ['r2_buckets'], resourceType: 'r2_bucket', bindingField: 'binding', identifierField: 'bucket_name' },
60
+ {
61
+ path: ['d1_databases'],
62
+ resourceType: 'd1_database',
63
+ bindingField: 'binding',
64
+ identifierField: 'database_name',
65
+ idField: 'database_id',
66
+ },
67
+ { path: ['queues', 'producers'], resourceType: 'queue', bindingField: 'binding', identifierField: 'queue' },
68
+ { path: ['services'], resourceType: 'worker', bindingField: 'binding', identifierField: 'service' },
69
+ ];
70
+
71
+ /** A KV namespace is declared by opaque id only, so the binding names it. */
72
+ const OPAQUE_IDENTIFIER = new Set(['kv_namespace']);
73
+
74
+ export interface ExtractWranglerOptions {
75
+ /** Repo-root-relative path of the config, recorded on every source. */
76
+ file: string;
77
+ }
78
+
79
+ /**
80
+ * Read a wrangler config. Accepts JSONC text or an already-parsed object, so a
81
+ * caller holding a `wrangler.toml` can parse it and pass the result.
82
+ *
83
+ * Returns an empty manifest when the config names no Worker. Malformed JSONC
84
+ * text throws `SyntaxError`.
85
+ */
86
+ export function extractWranglerManifest(
87
+ config: string | unknown,
88
+ options: ExtractWranglerOptions,
89
+ ): InfraManifest {
90
+ const root = typeof config === 'string' ? parseJsonc(config) : config;
91
+ if (!isObject(root)) return { resources: [], bindings: [] };
92
+ const workerName = str(root.name);
93
+ if (!workerName) return { resources: [], bindings: [] };
94
+
95
+ const source = (pointer: string): InfraResourceSource => ({
96
+ tool: 'wrangler',
97
+ file: options.file,
98
+ pointer,
99
+ });
100
+
101
+ const workerKey = infraResourceKey(PROVIDER, 'worker', workerName);
102
+ const workerAttributes: Record<string, string> = {};
103
+ const main = str(root.main);
104
+ if (main) workerAttributes.main = main;
105
+ if (isObject(root.assets)) workerAttributes.assets = 'true';
106
+ const crons = isObject(root.triggers) ? root.triggers.crons : undefined;
107
+ if (Array.isArray(crons) && crons.length > 0) {
108
+ workerAttributes.crons = crons.filter((c) => typeof c === 'string').join(', ');
109
+ }
110
+
111
+ const resources: InfraResource[] = [
112
+ {
113
+ key: workerKey,
114
+ provider: PROVIDER,
115
+ resourceType: 'worker',
116
+ name: workerName,
117
+ label: workerName,
118
+ source: source(''),
119
+ ...(Object.keys(workerAttributes).length > 0 ? { attributes: workerAttributes } : {}),
120
+ },
121
+ ];
122
+ const bindings: InfraBinding[] = [];
123
+
124
+ for (const family of BINDING_FAMILIES) {
125
+ let entries: unknown = root;
126
+ for (const segment of family.path) {
127
+ entries = isObject(entries) ? entries[segment] : undefined;
128
+ }
129
+ if (!Array.isArray(entries)) continue;
130
+ entries.forEach((entry, index) => {
131
+ if (!isObject(entry)) return;
132
+ const binding = str(entry[family.bindingField]);
133
+ const identifier = str(entry[family.identifierField]);
134
+ if (!binding || !identifier) return;
135
+ const pointer = `/${family.path.join('/')}/${index}`;
136
+ const key = infraResourceKey(PROVIDER, family.resourceType, identifier);
137
+ const id = family.idField ? str(entry[family.idField]) : undefined;
138
+ // A service binding points at another Worker, which its own config
139
+ // declares; emit the access path but not a second declaration of it.
140
+ if (family.resourceType !== 'worker') {
141
+ resources.push({
142
+ key,
143
+ provider: PROVIDER,
144
+ resourceType: family.resourceType,
145
+ name: identifier,
146
+ label: OPAQUE_IDENTIFIER.has(family.resourceType) ? binding : identifier,
147
+ source: source(pointer),
148
+ ...(id ? { attributes: { id } } : {}),
149
+ });
150
+ }
151
+ bindings.push({ from: workerKey, to: key, binding, source: source(pointer) });
152
+ });
153
+ }
154
+
155
+ // Containers. Wrangler names the application `<worker>-<class_name>`,
156
+ // lowercased with spaces dashed, unless the entry names it.
157
+ const durableBindings = isObject(root.durable_objects) ? root.durable_objects.bindings : undefined;
158
+ const containers = Array.isArray(root.containers) ? root.containers : [];
159
+ containers.forEach((entry, index) => {
160
+ if (!isObject(entry)) return;
161
+ const className = str(entry.class_name);
162
+ const name =
163
+ str(entry.name) ??
164
+ (className ? `${workerName}-${className}`.toLowerCase().replace(/ /g, '-') : undefined);
165
+ if (!name) return;
166
+ const pointer = `/containers/${index}`;
167
+ const key = infraResourceKey(PROVIDER, 'container', name);
168
+ const attributes: Record<string, string> = {};
169
+ const image = str(entry.image);
170
+ if (image) attributes.image = image;
171
+ const instanceType = str(entry.instance_type);
172
+ if (instanceType) attributes.instanceType = instanceType;
173
+ if (typeof entry.max_instances === 'number') {
174
+ attributes.maxInstances = String(entry.max_instances);
175
+ }
176
+ resources.push({
177
+ key,
178
+ provider: PROVIDER,
179
+ resourceType: 'container',
180
+ name,
181
+ label: className ?? name,
182
+ source: source(pointer),
183
+ ...(Object.keys(attributes).length > 0 ? { attributes } : {}),
184
+ });
185
+ if (!className || !Array.isArray(durableBindings)) return;
186
+ durableBindings.forEach((durable, durableIndex) => {
187
+ if (!isObject(durable) || str(durable.class_name) !== className) return;
188
+ // A binding with `script_name` reaches a class another Worker defines.
189
+ const script = str(durable.script_name);
190
+ if (script && script !== workerName) return;
191
+ const binding = str(durable.name);
192
+ if (!binding) return;
193
+ bindings.push({
194
+ from: workerKey,
195
+ to: key,
196
+ binding,
197
+ source: source(`/durable_objects/bindings/${durableIndex}`),
198
+ });
199
+ });
200
+ });
201
+
202
+ return { resources, bindings };
203
+ }
package/src/node.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  export * from './types';
11
+ export * from './audit';
11
12
 
12
13
  // File-per-topic store (~/.principal/topics) — node:fs only
13
14
  export {
@@ -30,6 +31,8 @@ export type {
30
31
  TopicReference,
31
32
  } from './storage/topic-types';
32
33
  export { formatTopicReferenceLink, parseTopicReferenceLink } from './storage/topic-reference-links';
34
+ export { toSharedTopic } from './storage/topic-share';
35
+ export type { SharedTopic, SharedTopicAsset, SharedTopicProjection, SharedTopicReference } from './storage/topic-share';
33
36
 
34
37
  // OpenCode event retrieval (Node.js only - SQLite)
35
38
  export { OpenCodeEventStore, defaultOpenCodeDBPath } from './opencode/OpenCodeEventStore';
@@ -3,17 +3,20 @@ import { formatTopicReferenceLink, parseTopicReferenceLink } from './topic-refer
3
3
  import type { TopicReference } from './topic-types';
4
4
 
5
5
  describe('topic reference links', () => {
6
- test('formats topic and C4 sketch links', () => {
6
+ test('formats topic, C4 sketch, and drawing links', () => {
7
7
  expect(formatTopicReferenceLink({ kind: 'topic', topicId: 'topic-123-abc' }))
8
8
  .toBe('principal://topic/topic-123-abc');
9
9
  expect(formatTopicReferenceLink({ kind: 'c4-sketch', sketchId: 'c4s-123-abc' }))
10
10
  .toBe('principal://c4-sketch/c4s-123-abc');
11
+ expect(formatTopicReferenceLink({ kind: 'drawing', drawingId: '0b6f7c1e-2a4d-4e8f-9c3b-1d2e3f4a5b6c' }))
12
+ .toBe('principal://drawing/0b6f7c1e-2a4d-4e8f-9c3b-1d2e3f4a5b6c');
11
13
  });
12
14
 
13
15
  test('round-trips opaque ids and escapes Markdown delimiters', () => {
14
16
  const references: TopicReference[] = [
15
17
  { kind: 'topic', topicId: 'topic-123-abc' },
16
18
  { kind: 'c4-sketch', sketchId: 'c4s-123-abc' },
19
+ { kind: 'drawing', drawingId: 'drawing-123' },
17
20
  { kind: 'topic', topicId: "topic-é(1)!'?#%" },
18
21
  { kind: 'topic', topicId: 'topic-%2F' },
19
22
  ];
@@ -28,6 +31,7 @@ describe('topic reference links', () => {
28
31
  for (const topicId of ['', '.', '..', 'a/b', 'a\\b', ' a', 'a b', 'a\n', 'a\u0000']) {
29
32
  expect(() => formatTopicReferenceLink({ kind: 'topic', topicId })).toThrow();
30
33
  }
34
+ expect(() => formatTopicReferenceLink({ kind: 'drawing', drawingId: '../d1' })).toThrow();
31
35
  });
32
36
 
33
37
  test('returns null for unsupported or malformed hrefs', () => {
@@ -40,6 +44,8 @@ describe('topic reference links', () => {
40
44
  'principal://topic/%20', 'principal://topic/a\n', 'principal://topic/%',
41
45
  'principal://topic/%GG', 'principal://topic/%FF',
42
46
  ' principal://topic/a', 'principal://topic@host/a',
47
+ 'principal://drawing/', 'principal://drawing/a/b', 'principal://drawing/..',
48
+ 'principal://drawings/a',
43
49
  ]) {
44
50
  expect(parseTopicReferenceLink(href)).toBeNull();
45
51
  }