@principal-ai/subsystems-core 0.51.6 → 0.51.8

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 (46) hide show
  1. package/dist/index.d.ts +2 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +3 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/infra/c4.d.ts +59 -0
  6. package/dist/infra/c4.d.ts.map +1 -0
  7. package/dist/infra/c4.js +101 -0
  8. package/dist/infra/c4.js.map +1 -0
  9. package/dist/infra/index.d.ts +13 -0
  10. package/dist/infra/index.d.ts.map +1 -0
  11. package/dist/infra/index.js +22 -0
  12. package/dist/infra/index.js.map +1 -0
  13. package/dist/infra/jsonc.d.ts +10 -0
  14. package/dist/infra/jsonc.d.ts.map +1 -0
  15. package/dist/infra/jsonc.js +77 -0
  16. package/dist/infra/jsonc.js.map +1 -0
  17. package/dist/infra/terraform.d.ts +41 -0
  18. package/dist/infra/terraform.d.ts.map +1 -0
  19. package/dist/infra/terraform.js +208 -0
  20. package/dist/infra/terraform.js.map +1 -0
  21. package/dist/infra/types.d.ts +107 -0
  22. package/dist/infra/types.d.ts.map +1 -0
  23. package/dist/infra/types.js +47 -0
  24. package/dist/infra/types.js.map +1 -0
  25. package/dist/infra/wrangler.d.ts +24 -0
  26. package/dist/infra/wrangler.d.ts.map +1 -0
  27. package/dist/infra/wrangler.js +116 -0
  28. package/dist/infra/wrangler.js.map +1 -0
  29. package/dist/node.d.ts +1 -1
  30. package/dist/node.d.ts.map +1 -1
  31. package/dist/storage/topic-share.d.ts +23 -11
  32. package/dist/storage/topic-share.d.ts.map +1 -1
  33. package/dist/storage/topic-share.js +19 -7
  34. package/dist/storage/topic-share.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/index.ts +5 -1
  37. package/src/infra/c4.ts +141 -0
  38. package/src/infra/index.ts +21 -0
  39. package/src/infra/infra.test.ts +300 -0
  40. package/src/infra/jsonc.ts +70 -0
  41. package/src/infra/terraform.ts +251 -0
  42. package/src/infra/types.ts +136 -0
  43. package/src/infra/wrangler.ts +148 -0
  44. package/src/node.ts +1 -1
  45. package/src/storage/topic-share.test.ts +23 -3
  46. package/src/storage/topic-share.ts +38 -11
@@ -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,148 @@
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
+ * Top-level config only. Named environments (`env.staging`) are not read yet.
10
+ */
11
+
12
+ import { parseJsonc } from './jsonc';
13
+ import {
14
+ infraResourceKey,
15
+ type InfraBinding,
16
+ type InfraManifest,
17
+ type InfraResource,
18
+ type InfraResourceSource,
19
+ } from './types';
20
+
21
+ const PROVIDER = 'cloudflare';
22
+
23
+ type Json = Record<string, unknown>;
24
+
25
+ function isObject(value: unknown): value is Json {
26
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
27
+ }
28
+
29
+ function str(value: unknown): string | undefined {
30
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
31
+ }
32
+
33
+ /**
34
+ * One row per binding family. `identifier` is what the resource key is built
35
+ * from, so it must be the field another tool would also know the resource by.
36
+ */
37
+ interface BindingFamily {
38
+ /** Path to the array in the config, e.g. `['queues', 'producers']`. */
39
+ path: readonly string[];
40
+ resourceType: string;
41
+ /** Field holding the code-side binding name. */
42
+ bindingField: string;
43
+ /** Field holding the provider name/id the key is built from. */
44
+ identifierField: string;
45
+ /** Extra identifier worth keeping as an attribute (e.g. the D1 id). */
46
+ idField?: string;
47
+ }
48
+
49
+ const BINDING_FAMILIES: readonly BindingFamily[] = [
50
+ { path: ['kv_namespaces'], resourceType: 'kv_namespace', bindingField: 'binding', identifierField: 'id' },
51
+ { path: ['r2_buckets'], resourceType: 'r2_bucket', bindingField: 'binding', identifierField: 'bucket_name' },
52
+ {
53
+ path: ['d1_databases'],
54
+ resourceType: 'd1_database',
55
+ bindingField: 'binding',
56
+ identifierField: 'database_name',
57
+ idField: 'database_id',
58
+ },
59
+ { path: ['queues', 'producers'], resourceType: 'queue', bindingField: 'binding', identifierField: 'queue' },
60
+ { path: ['services'], resourceType: 'worker', bindingField: 'binding', identifierField: 'service' },
61
+ ];
62
+
63
+ /** A KV namespace is declared by opaque id only, so the binding names it. */
64
+ const OPAQUE_IDENTIFIER = new Set(['kv_namespace']);
65
+
66
+ export interface ExtractWranglerOptions {
67
+ /** Repo-root-relative path of the config, recorded on every source. */
68
+ file: string;
69
+ }
70
+
71
+ /**
72
+ * Read a wrangler config. Accepts JSONC text or an already-parsed object, so a
73
+ * caller holding a `wrangler.toml` can parse it and pass the result.
74
+ *
75
+ * Returns an empty manifest when the config names no Worker. Malformed JSONC
76
+ * text throws `SyntaxError`.
77
+ */
78
+ export function extractWranglerManifest(
79
+ config: string | unknown,
80
+ options: ExtractWranglerOptions,
81
+ ): InfraManifest {
82
+ const root = typeof config === 'string' ? parseJsonc(config) : config;
83
+ if (!isObject(root)) return { resources: [], bindings: [] };
84
+ const workerName = str(root.name);
85
+ if (!workerName) return { resources: [], bindings: [] };
86
+
87
+ const source = (pointer: string): InfraResourceSource => ({
88
+ tool: 'wrangler',
89
+ file: options.file,
90
+ pointer,
91
+ });
92
+
93
+ const workerKey = infraResourceKey(PROVIDER, 'worker', workerName);
94
+ const workerAttributes: Record<string, string> = {};
95
+ const main = str(root.main);
96
+ if (main) workerAttributes.main = main;
97
+ if (isObject(root.assets)) workerAttributes.assets = 'true';
98
+ const crons = isObject(root.triggers) ? root.triggers.crons : undefined;
99
+ if (Array.isArray(crons) && crons.length > 0) {
100
+ workerAttributes.crons = crons.filter((c) => typeof c === 'string').join(', ');
101
+ }
102
+
103
+ const resources: InfraResource[] = [
104
+ {
105
+ key: workerKey,
106
+ provider: PROVIDER,
107
+ resourceType: 'worker',
108
+ name: workerName,
109
+ label: workerName,
110
+ source: source(''),
111
+ ...(Object.keys(workerAttributes).length > 0 ? { attributes: workerAttributes } : {}),
112
+ },
113
+ ];
114
+ const bindings: InfraBinding[] = [];
115
+
116
+ for (const family of BINDING_FAMILIES) {
117
+ let entries: unknown = root;
118
+ for (const segment of family.path) {
119
+ entries = isObject(entries) ? entries[segment] : undefined;
120
+ }
121
+ if (!Array.isArray(entries)) continue;
122
+ entries.forEach((entry, index) => {
123
+ if (!isObject(entry)) return;
124
+ const binding = str(entry[family.bindingField]);
125
+ const identifier = str(entry[family.identifierField]);
126
+ if (!binding || !identifier) return;
127
+ const pointer = `/${family.path.join('/')}/${index}`;
128
+ const key = infraResourceKey(PROVIDER, family.resourceType, identifier);
129
+ const id = family.idField ? str(entry[family.idField]) : undefined;
130
+ // A service binding points at another Worker, which its own config
131
+ // declares; emit the access path but not a second declaration of it.
132
+ if (family.resourceType !== 'worker') {
133
+ resources.push({
134
+ key,
135
+ provider: PROVIDER,
136
+ resourceType: family.resourceType,
137
+ name: identifier,
138
+ label: OPAQUE_IDENTIFIER.has(family.resourceType) ? binding : identifier,
139
+ source: source(pointer),
140
+ ...(id ? { attributes: { id } } : {}),
141
+ });
142
+ }
143
+ bindings.push({ from: workerKey, to: key, binding, source: source(pointer) });
144
+ });
145
+ }
146
+
147
+ return { resources, bindings };
148
+ }
package/src/node.ts CHANGED
@@ -32,7 +32,7 @@ export type {
32
32
  } from './storage/topic-types';
33
33
  export { formatTopicReferenceLink, parseTopicReferenceLink } from './storage/topic-reference-links';
34
34
  export { toSharedTopic } from './storage/topic-share';
35
- export type { SharedTopic, SharedTopicAsset, SharedTopicProjection } from './storage/topic-share';
35
+ export type { SharedTopic, SharedTopicAsset, SharedTopicProjection, SharedTopicReference } from './storage/topic-share';
36
36
 
37
37
  // OpenCode event retrieval (Node.js only - SQLite)
38
38
  export { OpenCodeEventStore, defaultOpenCodeDBPath } from './opencode/OpenCodeEventStore';
@@ -19,11 +19,31 @@ describe('toSharedTopic', () => {
19
19
  expect(uploads).toEqual([]);
20
20
  });
21
21
 
22
- test('drops local store ids and references', () => {
22
+ test('keeps model, sketch and topic references by id and drops drawings', () => {
23
23
  const { topic } = toSharedTopic({
24
24
  ...base,
25
- subsystemModels: [{ modelId: 'sg-1', trailIds: ['wt-a'] }],
26
- references: [{ kind: 'c4-sketch', sketchId: 'c4s-1' }, { kind: 'topic', topicId: 'topic-2' }],
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' }],
27
47
  });
28
48
  expect(topic).not.toHaveProperty('subsystemModels');
29
49
  expect(topic).not.toHaveProperty('references');
@@ -2,13 +2,27 @@
2
2
  * Portable projection of a topic for sharing outside the machine that authored
3
3
  * it. Browser-safe (no `node:*`).
4
4
  *
5
- * A {@link DraftTopic} carries fields that only mean something locally: store
6
- * ids of subsystem models, references to sketches/drawings/topics on disk, and
7
- * inline image bytes. {@link toSharedTopic} drops the local-only fields and
8
- * splits image bytes out so a host can upload each one separately.
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.
9
14
  */
10
15
 
11
- import type { DraftTopic, TopicAsset, TopicCreator } from './topic-types';
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' }>;
12
26
 
13
27
  /** An image a shared topic refers to. Bytes travel separately, keyed by `id`. */
14
28
  export interface SharedTopicAsset {
@@ -23,9 +37,8 @@ export interface SharedTopicAsset {
23
37
  }
24
38
 
25
39
  /**
26
- * A topic as it leaves the authoring machine. No local store ids and no inline
27
- * bytes; `description` is unchanged, so `asset://<id>` links still resolve
28
- * against `assets`.
40
+ * A topic as it leaves the authoring machine. No inline bytes; `description`
41
+ * is unchanged, so `asset://<id>` links still resolve against `assets`.
29
42
  */
30
43
  export interface SharedTopic {
31
44
  id: string;
@@ -39,6 +52,10 @@ export interface SharedTopic {
39
52
  updatedAt: string;
40
53
  createdBy?: TopicCreator;
41
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[];
42
59
  }
43
60
 
44
61
  export interface SharedTopicProjection {
@@ -50,9 +67,9 @@ export interface SharedTopicProjection {
50
67
  /**
51
68
  * Project a local topic into its shared form.
52
69
  *
53
- * Dropped: `subsystemModels` and `references` (local store ids), each asset's
54
- * `source` (local Storybook origin) and inline `data`. Assets with neither
55
- * `data` nor `url` cannot be resolved by a reader and are omitted.
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.
56
73
  */
57
74
  export function toSharedTopic(topic: DraftTopic): SharedTopicProjection {
58
75
  const assets: SharedTopicAsset[] = [];
@@ -71,6 +88,14 @@ export function toSharedTopic(topic: DraftTopic): SharedTopicProjection {
71
88
  if (asset.data) uploads.push({ id: asset.id, mime: asset.mime, data: asset.data });
72
89
  }
73
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
+
74
99
  return {
75
100
  topic: {
76
101
  id: topic.id,
@@ -81,6 +106,8 @@ export function toSharedTopic(topic: DraftTopic): SharedTopicProjection {
81
106
  updatedAt: topic.updatedAt,
82
107
  ...(topic.createdBy ? { createdBy: { ...topic.createdBy } } : {}),
83
108
  ...(assets.length ? { assets } : {}),
109
+ ...(subsystemModels.length ? { subsystemModels } : {}),
110
+ ...(references.length ? { references: references.map((ref) => ({ ...ref })) } : {}),
84
111
  },
85
112
  uploads,
86
113
  };