@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,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. `./observe` produces them from a credential its caller supplies;
12
+ * any other tooling only has to produce this shape.
13
+ *
14
+ * Everything in this folder is browser-safe: extractors take text or parsed
15
+ * JSON, never a path, and the checks reach the network only through `fetch`.
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
  }
@@ -6,9 +6,20 @@ function isReferenceId(id: string): boolean {
6
6
  return id.length > 0 && id !== '.' && id !== '..' && !/[/\\\s\u0000-\u001f\u007f]/.test(id);
7
7
  }
8
8
 
9
+ function referenceId(reference: TopicReference): string {
10
+ switch (reference.kind) {
11
+ case 'topic':
12
+ return reference.topicId;
13
+ case 'c4-sketch':
14
+ return reference.sketchId;
15
+ case 'drawing':
16
+ return reference.drawingId;
17
+ }
18
+ }
19
+
9
20
  /** Format a Markdown-safe href. Does not attach or resolve the target. */
10
21
  export function formatTopicReferenceLink(reference: TopicReference): string {
11
- const id = reference.kind === 'topic' ? reference.topicId : reference.sketchId;
22
+ const id = referenceId(reference);
12
23
  if (!isReferenceId(id)) throw new Error('Invalid topic reference id');
13
24
  const encoded = encodeURIComponent(id).replace(
14
25
  /[!'()*]/g,
@@ -18,12 +29,12 @@ export function formatTopicReferenceLink(reference: TopicReference): string {
18
29
  }
19
30
 
20
31
  /**
21
- * Parse a local topic/sketch href without I/O. Unknown kinds, malformed escapes,
22
- * extra path segments, queries, and fragments return null. Target existence and
23
- * navigation belong to the host. Parsing never creates an attachment.
32
+ * Parse a local topic/sketch/drawing href without I/O. Unknown kinds, malformed
33
+ * escapes, extra path segments, queries, and fragments return null. Target
34
+ * existence and navigation belong to the host. Parsing never creates an attachment.
24
35
  */
25
36
  export function parseTopicReferenceLink(href: string): TopicReference | null {
26
- const match = /^principal:\/\/(topic|c4-sketch)\/([^/?#]+)$/.exec(href);
37
+ const match = /^principal:\/\/(topic|c4-sketch|drawing)\/([^/?#]+)$/.exec(href);
27
38
  if (!match) return null;
28
39
  let id: string;
29
40
  try {
@@ -32,7 +43,12 @@ export function parseTopicReferenceLink(href: string): TopicReference | null {
32
43
  return null;
33
44
  }
34
45
  if (!isReferenceId(id)) return null;
35
- return match[1] === 'topic'
36
- ? { kind: 'topic', topicId: id }
37
- : { kind: 'c4-sketch', sketchId: id };
46
+ switch (match[1]) {
47
+ case 'topic':
48
+ return { kind: 'topic', topicId: id };
49
+ case 'c4-sketch':
50
+ return { kind: 'c4-sketch', sketchId: id };
51
+ default:
52
+ return { kind: 'drawing', drawingId: id };
53
+ }
38
54
  }
@@ -0,0 +1,91 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { toSharedTopic } from './topic-share';
3
+ import type { DraftTopic } from './topic-types';
4
+
5
+ const base: DraftTopic = {
6
+ id: 'topic-1-abc',
7
+ title: 'Sharing',
8
+ description: 'Brief with ![shot](asset://hash-a)',
9
+ repos: ['pkg:github/principal-ai/subsystem-modeling'],
10
+ createdAt: '2026-11-01T00:00:00.000Z',
11
+ updatedAt: '2026-11-02T00:00:00.000Z',
12
+ createdBy: { githubId: 1, githubLogin: 'octocat' },
13
+ };
14
+
15
+ describe('toSharedTopic', () => {
16
+ test('keeps the portable fields unchanged', () => {
17
+ const { topic, uploads } = toSharedTopic(base);
18
+ expect(topic).toEqual(base);
19
+ expect(uploads).toEqual([]);
20
+ });
21
+
22
+ test('keeps model, sketch and topic references by id and drops drawings', () => {
23
+ const { topic } = toSharedTopic({
24
+ ...base,
25
+ subsystemModels: [{ modelId: 'sg-1', trailIds: ['wt-a'] }, { modelId: 'sg-2', trailIds: [] }],
26
+ references: [
27
+ { kind: 'c4-sketch', sketchId: 'c4s-1' },
28
+ { kind: 'drawing', drawingId: 'd-1' },
29
+ { kind: 'topic', topicId: 'topic-2' },
30
+ ],
31
+ });
32
+ expect(topic.subsystemModels).toEqual([
33
+ { modelId: 'sg-1', trailIds: ['wt-a'] },
34
+ { modelId: 'sg-2' },
35
+ ]);
36
+ expect(topic.references).toEqual([
37
+ { kind: 'c4-sketch', sketchId: 'c4s-1' },
38
+ { kind: 'topic', topicId: 'topic-2' },
39
+ ]);
40
+ });
41
+
42
+ test('omits empty reference lists', () => {
43
+ const { topic } = toSharedTopic({
44
+ ...base,
45
+ subsystemModels: [],
46
+ references: [{ kind: 'drawing', drawingId: 'd-1' }],
47
+ });
48
+ expect(topic).not.toHaveProperty('subsystemModels');
49
+ expect(topic).not.toHaveProperty('references');
50
+ });
51
+
52
+ test('splits inline bytes into uploads and strips local asset origin', () => {
53
+ const { topic, uploads } = toSharedTopic({
54
+ ...base,
55
+ assets: [
56
+ {
57
+ id: 'hash-a',
58
+ mime: 'image/png',
59
+ data: 'AAAA',
60
+ alt: 'shot',
61
+ source: { storyId: 's', storybookUrl: 'http://localhost:6006' },
62
+ },
63
+ { id: 'hash-b', mime: 'image/jpeg', url: 'https://example.com/b.jpg' },
64
+ ],
65
+ });
66
+ expect(topic.assets).toEqual([
67
+ { id: 'hash-a', mime: 'image/png', alt: 'shot' },
68
+ { id: 'hash-b', mime: 'image/jpeg', url: 'https://example.com/b.jpg' },
69
+ ]);
70
+ expect(uploads).toEqual([{ id: 'hash-a', mime: 'image/png', data: 'AAAA' }]);
71
+ });
72
+
73
+ test('omits unresolvable and duplicate assets', () => {
74
+ const { topic, uploads } = toSharedTopic({
75
+ ...base,
76
+ assets: [
77
+ { id: 'hash-a', mime: 'image/png', data: 'AAAA' },
78
+ { id: 'hash-a', mime: 'image/png', data: 'AAAA' },
79
+ { id: 'hash-c', mime: 'image/png' },
80
+ ],
81
+ });
82
+ expect(topic.assets).toEqual([{ id: 'hash-a', mime: 'image/png' }]);
83
+ expect(uploads).toHaveLength(1);
84
+ });
85
+
86
+ test('does not alias the source arrays', () => {
87
+ const { topic } = toSharedTopic(base);
88
+ expect(topic.repos).not.toBe(base.repos);
89
+ expect(topic.createdBy).not.toBe(base.createdBy);
90
+ });
91
+ });
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Portable projection of a topic for sharing outside the machine that authored
3
+ * it. Browser-safe (no `node:*`).
4
+ *
5
+ * A {@link DraftTopic} carries fields that only mean something locally: inline
6
+ * image bytes, local asset origins and drawing references. {@link toSharedTopic}
7
+ * drops those and splits image bytes out so a host can upload each one
8
+ * separately.
9
+ *
10
+ * References to subsystem models, C4 sketches and other topics are kept as ids.
11
+ * A share is published under its local id, so a reader resolves the same id
12
+ * against the sharing service instead of the local store. A reference whose
13
+ * target was not shared (or not with the reader) is simply unavailable.
14
+ */
15
+
16
+ import type {
17
+ DraftTopic,
18
+ TopicAsset,
19
+ TopicCreator,
20
+ TopicReference,
21
+ TopicSubsystemModelRef,
22
+ } from './topic-types';
23
+
24
+ /** A reference a shared topic can carry. Drawings have no shared form yet. */
25
+ export type SharedTopicReference = Exclude<TopicReference, { kind: 'drawing' }>;
26
+
27
+ /** An image a shared topic refers to. Bytes travel separately, keyed by `id`. */
28
+ export interface SharedTopicAsset {
29
+ /** Content hash; the `asset://<id>` target in the description. */
30
+ id: string;
31
+ /** MIME type, e.g. "image/png". */
32
+ mime: string;
33
+ /** Resolvable URL, when the bytes already live somewhere public. */
34
+ url?: string;
35
+ /** Markdown alt text. */
36
+ alt?: string;
37
+ }
38
+
39
+ /**
40
+ * A topic as it leaves the authoring machine. No inline bytes; `description`
41
+ * is unchanged, so `asset://<id>` links still resolve against `assets`.
42
+ */
43
+ export interface SharedTopic {
44
+ id: string;
45
+ title: string;
46
+ description?: string;
47
+ /** Repositories as PURL strings. */
48
+ repos?: string[];
49
+ /** ISO 8601. */
50
+ createdAt: string;
51
+ /** ISO 8601. */
52
+ updatedAt: string;
53
+ createdBy?: TopicCreator;
54
+ assets?: SharedTopicAsset[];
55
+ /** Subsystem models the topic concerns, by share id (same as the local id). */
56
+ subsystemModels?: TopicSubsystemModelRef[];
57
+ /** Attached C4 sketches and related topics, by share id. */
58
+ references?: SharedTopicReference[];
59
+ }
60
+
61
+ export interface SharedTopicProjection {
62
+ topic: SharedTopic;
63
+ /** Assets whose bytes must be uploaded alongside the topic (those with `data`). */
64
+ uploads: Array<{ id: string; mime: string; data: string }>;
65
+ }
66
+
67
+ /**
68
+ * Project a local topic into its shared form.
69
+ *
70
+ * Dropped: drawing references (no shared form), each asset's `source` (local
71
+ * Storybook origin) and inline `data`. Assets with neither `data` nor `url`
72
+ * cannot be resolved by a reader and are omitted.
73
+ */
74
+ export function toSharedTopic(topic: DraftTopic): SharedTopicProjection {
75
+ const assets: SharedTopicAsset[] = [];
76
+ const uploads: SharedTopicProjection['uploads'] = [];
77
+ const seen = new Set<string>();
78
+
79
+ for (const asset of topic.assets ?? []) {
80
+ if (seen.has(asset.id) || !isResolvable(asset)) continue;
81
+ seen.add(asset.id);
82
+ assets.push({
83
+ id: asset.id,
84
+ mime: asset.mime,
85
+ ...(asset.url ? { url: asset.url } : {}),
86
+ ...(asset.alt ? { alt: asset.alt } : {}),
87
+ });
88
+ if (asset.data) uploads.push({ id: asset.id, mime: asset.mime, data: asset.data });
89
+ }
90
+
91
+ const subsystemModels = (topic.subsystemModels ?? []).map((ref) => ({
92
+ modelId: ref.modelId,
93
+ ...(ref.trailIds?.length ? { trailIds: [...ref.trailIds] } : {}),
94
+ }));
95
+ const references = (topic.references ?? []).filter(
96
+ (ref): ref is SharedTopicReference => ref.kind !== 'drawing',
97
+ );
98
+
99
+ return {
100
+ topic: {
101
+ id: topic.id,
102
+ title: topic.title,
103
+ ...(topic.description !== undefined ? { description: topic.description } : {}),
104
+ ...(topic.repos?.length ? { repos: [...topic.repos] } : {}),
105
+ createdAt: topic.createdAt,
106
+ updatedAt: topic.updatedAt,
107
+ ...(topic.createdBy ? { createdBy: { ...topic.createdBy } } : {}),
108
+ ...(assets.length ? { assets } : {}),
109
+ ...(subsystemModels.length ? { subsystemModels } : {}),
110
+ ...(references.length ? { references: references.map((ref) => ({ ...ref })) } : {}),
111
+ },
112
+ uploads,
113
+ };
114
+ }
115
+
116
+ function isResolvable(asset: TopicAsset): boolean {
117
+ return Boolean(asset.data || asset.url);
118
+ }
@@ -60,9 +60,11 @@ export interface TopicSubsystemModelRef {
60
60
  * A directional, local-only reference owned by a topic. Targets remain separate
61
61
  * artifacts; their contents and titles are resolved by the host, not copied here.
62
62
  * Referencing a C4 sketch does not make its authored hypothesis evidence.
63
+ * A drawing ID is the `.excalidraw` file stem under the host's drawings folder.
63
64
  */
64
65
  export type TopicReference =
65
66
  | { kind: 'c4-sketch'; sketchId: string }
67
+ | { kind: 'drawing'; drawingId: string }
66
68
  | { kind: 'topic'; topicId: string };
67
69
 
68
70
  /**
@@ -102,7 +104,7 @@ export interface DraftTopic {
102
104
  */
103
105
  subsystemModels?: TopicSubsystemModelRef[];
104
106
  /**
105
- * Attached topics and C4 sketches. Whole-array replacement on update; `[]`
107
+ * Attached topics, C4 sketches, and drawings. Whole-array replacement on update; `[]`
106
108
  * clears attachments. Independent of links in `description`: neither edits
107
109
  * the other. Hosts validate target existence and reject self-references.
108
110
  */