@canonical/design-system 0.1.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 (231) hide show
  1. package/.mcp.json +8 -0
  2. package/README.md +438 -0
  3. package/biome.json +6 -0
  4. package/bun.lock +349 -0
  5. package/data/apps/component/file_tree.ttl +8 -0
  6. package/data/apps/component/key_value_pair.ttl +8 -0
  7. package/data/apps/component/navigation.ttl +8 -0
  8. package/data/apps/component/skeleton_loading.ttl +8 -0
  9. package/data/apps/component/status_bar.ttl +8 -0
  10. package/data/apps/component/toolbar.ttl +8 -0
  11. package/data/apps/layout/application_layout.ttl +8 -0
  12. package/data/apps/layout/empty_layout.ttl +8 -0
  13. package/data/apps/layout/list_page_layout.ttl +8 -0
  14. package/data/apps/layout/settings_page_layout.ttl +8 -0
  15. package/data/apps/pattern/code_diff.ttl +8 -0
  16. package/data/apps/pattern/data_table.ttl +8 -0
  17. package/data/apps/pattern/destructive_modal.ttl +8 -0
  18. package/data/apps/pattern/key_value_summary.ttl +8 -0
  19. package/data/apps/pattern/keyboard_shortcuts.ttl +8 -0
  20. package/data/apps/pattern/notification_center.ttl +8 -0
  21. package/data/apps/pattern/side_panel.ttl +8 -0
  22. package/data/apps/pattern/sidepanel_stacked.ttl +8 -0
  23. package/data/apps.ttl +5 -0
  24. package/data/apps_wpe.ttl +5 -0
  25. package/data/documentation/layout/documentation_layout.ttl +8 -0
  26. package/data/documentation.ttl +5 -0
  27. package/data/global/component/accordion.ttl +14 -0
  28. package/data/global/component/announcement.ttl +8 -0
  29. package/data/global/component/badge.ttl +9 -0
  30. package/data/global/component/button.ttl +20 -0
  31. package/data/global/component/card.ttl +8 -0
  32. package/data/global/component/chip.ttl +8 -0
  33. package/data/global/component/code_snippet.ttl +8 -0
  34. package/data/global/component/contextual_menu.ttl +8 -0
  35. package/data/global/component/heading.ttl +14 -0
  36. package/data/global/component/icon.ttl +14 -0
  37. package/data/global/component/icon_in_container.ttl +8 -0
  38. package/data/global/component/keyboard_key.ttl +8 -0
  39. package/data/global/component/label.ttl +15 -0
  40. package/data/global/component/link.ttl +8 -0
  41. package/data/global/component/notification_inline.ttl +8 -0
  42. package/data/global/component/notification_toast.ttl +8 -0
  43. package/data/global/component/pagination.ttl +8 -0
  44. package/data/global/component/popover.ttl +8 -0
  45. package/data/global/component/rich_text_editor.ttl +8 -0
  46. package/data/global/component/search_bar.ttl +8 -0
  47. package/data/global/component/table.ttl +8 -0
  48. package/data/global/component/tabs.ttl +8 -0
  49. package/data/global/component/theme_switcher.ttl +8 -0
  50. package/data/global/component/tile.ttl +14 -0
  51. package/data/global/component/tooltip.ttl +8 -0
  52. package/data/global/group/buttons.ttl +8 -0
  53. package/data/global/group/cards.ttl +8 -0
  54. package/data/global/group/tiles.ttl +8 -0
  55. package/data/global/layout/error_layout.ttl +8 -0
  56. package/data/global/layout/form_layout.ttl +8 -0
  57. package/data/global/layout/identity_page_form.ttl +8 -0
  58. package/data/global/modifier/alpha.ttl +6 -0
  59. package/data/global/modifier/beta.ttl +6 -0
  60. package/data/global/modifier/caution.ttl +6 -0
  61. package/data/global/modifier/comfortable.ttl +6 -0
  62. package/data/global/modifier/completed.ttl +6 -0
  63. package/data/global/modifier/constructive.ttl +6 -0
  64. package/data/global/modifier/dark.ttl +6 -0
  65. package/data/global/modifier/dense.ttl +6 -0
  66. package/data/global/modifier/destructive.ttl +6 -0
  67. package/data/global/modifier/editable.ttl +6 -0
  68. package/data/global/modifier/elevated.ttl +6 -0
  69. package/data/global/modifier/error.ttl +6 -0
  70. package/data/global/modifier/experimental.ttl +6 -0
  71. package/data/global/modifier/failed.ttl +6 -0
  72. package/data/global/modifier/focused.ttl +6 -0
  73. package/data/global/modifier/highlighted.ttl +6 -0
  74. package/data/global/modifier/in_progress.ttl +6 -0
  75. package/data/global/modifier/information.ttl +6 -0
  76. package/data/global/modifier/light.ttl +6 -0
  77. package/data/global/modifier/loading.ttl +6 -0
  78. package/data/global/modifier/muted.ttl +6 -0
  79. package/data/global/modifier/paper.ttl +6 -0
  80. package/data/global/modifier/planned.ttl +6 -0
  81. package/data/global/modifier/primary.ttl +6 -0
  82. package/data/global/modifier/secondary.ttl +6 -0
  83. package/data/global/modifier/stable.ttl +6 -0
  84. package/data/global/modifier/success.ttl +6 -0
  85. package/data/global/modifier/tertiary.ttl +6 -0
  86. package/data/global/modifier/warning.ttl +6 -0
  87. package/data/global/modifier/wireframe.ttl +6 -0
  88. package/data/global/modifier_family/_color_luminosity.ttl +7 -0
  89. package/data/global/modifier_family/_emphasis.ttl +7 -0
  90. package/data/global/modifier_family/_other.ttl +7 -0
  91. package/data/global/modifier_family/anticipation.ttl +7 -0
  92. package/data/global/modifier_family/criticality.ttl +7 -0
  93. package/data/global/modifier_family/density.ttl +7 -0
  94. package/data/global/modifier_family/importance.ttl +7 -0
  95. package/data/global/modifier_family/lifecycle.ttl +7 -0
  96. package/data/global/modifier_family/release.ttl +7 -0
  97. package/data/global/pattern/breadcrumbs.ttl +14 -0
  98. package/data/global/pattern/info_table.ttl +8 -0
  99. package/data/global/pattern/modal.ttl +8 -0
  100. package/data/global/pattern/navigation.ttl +8 -0
  101. package/data/global/pattern/select_button.ttl +8 -0
  102. package/data/global/pattern/stepper.ttl +8 -0
  103. package/data/global/pattern/table_of_contents.ttl +8 -0
  104. package/data/global/pattern/timeline.ttl +14 -0
  105. package/data/global/subcomponent/accordion-item.ttl +19 -0
  106. package/data/global/subcomponent/breadcrumbs-item.ttl +19 -0
  107. package/data/global/subcomponent/card-content.ttl +14 -0
  108. package/data/global/subcomponent/card-header.ttl +14 -0
  109. package/data/global/subcomponent/card-image.ttl +20 -0
  110. package/data/global/subcomponent/divider.ttl +8 -0
  111. package/data/global/subcomponent/modal-content.ttl +8 -0
  112. package/data/global/subcomponent/modal-footer.ttl +8 -0
  113. package/data/global/subcomponent/modal-header.ttl +8 -0
  114. package/data/global/subcomponent/spinner.ttl +8 -0
  115. package/data/global/subcomponent/table-cell.ttl +8 -0
  116. package/data/global/subcomponent/table-row.ttl +8 -0
  117. package/data/global/subcomponent/tile-content.ttl +14 -0
  118. package/data/global/subcomponent/tile-header.ttl +14 -0
  119. package/data/global/subcomponent/timeline-content.ttl +14 -0
  120. package/data/global/subcomponent/timeline-event.ttl +31 -0
  121. package/data/global/subcomponent/timeline-footer.ttl +8 -0
  122. package/data/global/subcomponent/timeline-header.ttl +8 -0
  123. package/data/global.ttl +5 -0
  124. package/data/global_form/component/checkbox_input.ttl +8 -0
  125. package/data/global_form/component/choices_input.ttl +8 -0
  126. package/data/global_form/component/combobox_input.ttl +8 -0
  127. package/data/global_form/component/custom_choices_input.ttl +8 -0
  128. package/data/global_form/component/datepicker_input.ttl +8 -0
  129. package/data/global_form/component/rating_input.ttl +8 -0
  130. package/data/global_form/component/segmented_control_input.ttl +8 -0
  131. package/data/global_form/component/slider_input.ttl +8 -0
  132. package/data/global_form/component/switch_input.ttl +8 -0
  133. package/data/global_form/component/text_input.ttl +8 -0
  134. package/data/global_form/component/textarea_input.ttl +8 -0
  135. package/data/global_form/component/wysiwginput.ttl +8 -0
  136. package/data/global_form/pattern/field.ttl +8 -0
  137. package/data/global_form/pattern/form.ttl +8 -0
  138. package/data/global_form/subcomponent/field-description.ttl +8 -0
  139. package/data/global_form/subcomponent/field-label.ttl +8 -0
  140. package/data/global_form.ttl +5 -0
  141. package/data/site/component/quote.ttl +8 -0
  142. package/data/site/component/rule.ttl +8 -0
  143. package/data/site/component/section.ttl +8 -0
  144. package/data/site/layout/site_layout.ttl +8 -0
  145. package/data/site/pattern/hero-github.ttl +8 -0
  146. package/data/site/pattern/hero.ttl +8 -0
  147. package/data/site/pattern/info_table.ttl +8 -0
  148. package/data/site/pattern/skip_link.ttl +8 -0
  149. package/data/site.ttl +5 -0
  150. package/data/stores.ttl +5 -0
  151. package/definitions/ontology.ttl +498 -0
  152. package/package.json +42 -0
  153. package/session/A.DSL.md +429 -0
  154. package/session/B.NOTES.md +84 -0
  155. package/session/global.component.accordion.yaml +13 -0
  156. package/session/global.component.button.yaml +26 -0
  157. package/session/global.component.card.yaml +24 -0
  158. package/session/global.component.icon.yaml +7 -0
  159. package/session/global.component.label.yaml +7 -0
  160. package/session/global.component.tile.yaml +21 -0
  161. package/session/global.component.timeline.yaml +20 -0
  162. package/session/global.pattern.breadcrumbs.yaml +13 -0
  163. package/session/global.subcomponent.accordion-item.yaml +37 -0
  164. package/session/global.subcomponent.breadcrumbs-item.yaml +21 -0
  165. package/session/global.subcomponent.card-content.yaml +7 -0
  166. package/session/global.subcomponent.card-header.yaml +22 -0
  167. package/session/global.subcomponent.card-image.yaml +7 -0
  168. package/session/global.subcomponent.tile-content.yaml +7 -0
  169. package/session/global.subcomponent.tile-header.yaml +8 -0
  170. package/session/global.subcomponent.timeline-content.yaml +13 -0
  171. package/session/global.subcomponent.timeline-event.yaml +20 -0
  172. package/session/global.subcomponent.timeline-footer.yaml +9 -0
  173. package/session/global.subcomponent.timeline-header.yaml +18 -0
  174. package/skills/anatomy-author/ANATOMY_DSL_SPEC.md +423 -0
  175. package/skills/anatomy-author/SKILL.md +911 -0
  176. package/skills/component-specifier/SKILL.md +413 -0
  177. package/skills/design-auditor/SKILL.md +428 -0
  178. package/source.json +101 -0
  179. package/src/cli.ts +45 -0
  180. package/src/collect/generateTurtle.tests.ts +200 -0
  181. package/src/collect/generateTurtle.ts +187 -0
  182. package/src/collect/index.ts +4 -0
  183. package/src/collect/scanAnnotations.tests.ts +138 -0
  184. package/src/collect/scanAnnotations.ts +78 -0
  185. package/src/collect/types.ts +57 -0
  186. package/src/collect/validateCollectConfig.tests.ts +116 -0
  187. package/src/collect/validateCollectConfig.ts +74 -0
  188. package/src/collect-implementations.ts +99 -0
  189. package/src/commands/extract.tests.ts +41 -0
  190. package/src/commands/extract.ts +48 -0
  191. package/src/commands/index.ts +3 -0
  192. package/src/commands/list.tests.ts +26 -0
  193. package/src/commands/list.ts +26 -0
  194. package/src/commands/transform.tests.ts +28 -0
  195. package/src/commands/transform.ts +133 -0
  196. package/src/config/index.ts +2 -0
  197. package/src/config/source.schema.json +110 -0
  198. package/src/config/types.ts +97 -0
  199. package/src/config/validateConfig.tests.ts +46 -0
  200. package/src/config/validateConfig.ts +21 -0
  201. package/src/constants.ts +20 -0
  202. package/src/graph/GraphStore.tests.ts +157 -0
  203. package/src/graph/GraphStore.ts +200 -0
  204. package/src/graph/PrefixMap.tests.ts +129 -0
  205. package/src/graph/PrefixMap.ts +95 -0
  206. package/src/graph/buildUri.tests.ts +158 -0
  207. package/src/graph/buildUri.ts +69 -0
  208. package/src/graph/index.ts +4 -0
  209. package/src/graph/types.ts +20 -0
  210. package/src/providers/CodaProvider.tests.ts +241 -0
  211. package/src/providers/CodaProvider.ts +174 -0
  212. package/src/providers/CodaProvider.types.generated.ts +12236 -0
  213. package/src/providers/index.ts +18 -0
  214. package/src/serializers/JSONSerializer.tests.ts +79 -0
  215. package/src/serializers/JSONSerializer.ts +87 -0
  216. package/src/serializers/TTLSerializer.tests.ts +75 -0
  217. package/src/serializers/TTLSerializer.ts +99 -0
  218. package/src/serializers/index.ts +3 -0
  219. package/src/serializers/types.ts +16 -0
  220. package/src/transform/resolveReferences.tests.ts +63 -0
  221. package/src/transform/resolveReferences.ts +36 -0
  222. package/src/transform/resolveValue.tests.ts +76 -0
  223. package/src/transform/resolveValue.ts +87 -0
  224. package/src/transform/transform.tests.ts +99 -0
  225. package/src/transform/transform.ts +109 -0
  226. package/src/transform/transformRow.tests.ts +269 -0
  227. package/src/transform/transformRow.ts +220 -0
  228. package/src/transform/types.ts +26 -0
  229. package/tsconfig.json +8 -0
  230. package/vite.config.ts +11 -0
  231. package/vitest.config.ts +21 -0
@@ -0,0 +1,116 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import validateCollectConfig from "./validateCollectConfig.js";
3
+
4
+ describe("validateCollectConfig", () => {
5
+ const validConfig = {
6
+ name: "Pragma React",
7
+ platform: "react",
8
+ link: "https://github.com/canonical/pragma",
9
+ prefix: {
10
+ short: "ds",
11
+ namespace: "https://ds.canonical.com/data/",
12
+ },
13
+ pattern: "src/**/*.tsx",
14
+ };
15
+
16
+ it("should validate a minimal valid config", () => {
17
+ const result = validateCollectConfig(validConfig);
18
+ expect(result.name).toBe("Pragma React");
19
+ expect(result.platform).toBe("react");
20
+ expect(result.link).toBe("https://github.com/canonical/pragma");
21
+ expect(result.prefix.short).toBe("ds");
22
+ expect(result.prefix.namespace).toBe("https://ds.canonical.com/data/");
23
+ expect(result.pattern).toBe("src/**/*.tsx");
24
+ });
25
+
26
+ it("should validate a config with all optional fields", () => {
27
+ const fullConfig = {
28
+ ...validConfig,
29
+ description: "React implementation",
30
+ documentation: "https://docs.example.com",
31
+ tier: "ds:global",
32
+ outputDir: "output",
33
+ };
34
+ const result = validateCollectConfig(fullConfig);
35
+ expect(result.description).toBe("React implementation");
36
+ expect(result.documentation).toBe("https://docs.example.com");
37
+ expect(result.tier).toBe("ds:global");
38
+ expect(result.outputDir).toBe("output");
39
+ });
40
+
41
+ it("should throw if config is not an object", () => {
42
+ expect(() => validateCollectConfig(null)).toThrow("Config must be an object");
43
+ expect(() => validateCollectConfig("string")).toThrow("Config must be an object");
44
+ expect(() => validateCollectConfig(123)).toThrow("Config must be an object");
45
+ });
46
+
47
+ it("should throw if name is missing", () => {
48
+ const config = { ...validConfig, name: undefined };
49
+ expect(() => validateCollectConfig(config)).toThrow("Config must have a 'name' string");
50
+ });
51
+
52
+ it("should throw if name is empty", () => {
53
+ const config = { ...validConfig, name: "" };
54
+ expect(() => validateCollectConfig(config)).toThrow("Config must have a 'name' string");
55
+ });
56
+
57
+ it("should throw if platform is missing", () => {
58
+ const config = { ...validConfig, platform: undefined };
59
+ expect(() => validateCollectConfig(config)).toThrow("Config must have a 'platform' string");
60
+ });
61
+
62
+ it("should throw if link is missing", () => {
63
+ const config = { ...validConfig, link: undefined };
64
+ expect(() => validateCollectConfig(config)).toThrow("Config must have a 'link' string");
65
+ });
66
+
67
+ it("should throw if prefix is missing", () => {
68
+ const config = { ...validConfig, prefix: undefined };
69
+ expect(() => validateCollectConfig(config)).toThrow("Config must have a 'prefix' object");
70
+ });
71
+
72
+ it("should throw if prefix.short is missing", () => {
73
+ const config = { ...validConfig, prefix: { namespace: "https://example.com/" } };
74
+ expect(() => validateCollectConfig(config)).toThrow("Config prefix must have a 'short' string");
75
+ });
76
+
77
+ it("should throw if prefix.namespace is missing", () => {
78
+ const config = { ...validConfig, prefix: { short: "ds" } };
79
+ expect(() => validateCollectConfig(config)).toThrow(
80
+ "Config prefix must have a 'namespace' string",
81
+ );
82
+ });
83
+
84
+ it("should throw if pattern is missing", () => {
85
+ const config = { ...validConfig, pattern: undefined };
86
+ expect(() => validateCollectConfig(config)).toThrow("Config must have a 'pattern' string");
87
+ });
88
+
89
+ it("should throw if description is not a string", () => {
90
+ const config = { ...validConfig, description: 123 };
91
+ expect(() => validateCollectConfig(config)).toThrow(
92
+ "Config 'description' must be a string if provided",
93
+ );
94
+ });
95
+
96
+ it("should throw if documentation is not a string", () => {
97
+ const config = { ...validConfig, documentation: 123 };
98
+ expect(() => validateCollectConfig(config)).toThrow(
99
+ "Config 'documentation' must be a string if provided",
100
+ );
101
+ });
102
+
103
+ it("should throw if tier is not a string", () => {
104
+ const config = { ...validConfig, tier: 123 };
105
+ expect(() => validateCollectConfig(config)).toThrow(
106
+ "Config 'tier' must be a string if provided",
107
+ );
108
+ });
109
+
110
+ it("should throw if outputDir is not a string", () => {
111
+ const config = { ...validConfig, outputDir: 123 };
112
+ expect(() => validateCollectConfig(config)).toThrow(
113
+ "Config 'outputDir' must be a string if provided",
114
+ );
115
+ });
116
+ });
@@ -0,0 +1,74 @@
1
+ import type { CollectConfig } from "./types.js";
2
+
3
+ /**
4
+ * Validate and parse a design-system.json configuration
5
+ */
6
+ export default function validateCollectConfig(data: unknown): CollectConfig {
7
+ if (!data || typeof data !== "object") {
8
+ throw new Error("Config must be an object");
9
+ }
10
+
11
+ const config = data as Record<string, unknown>;
12
+
13
+ // Required fields
14
+ if (typeof config.name !== "string" || !config.name) {
15
+ throw new Error("Config must have a 'name' string");
16
+ }
17
+
18
+ if (typeof config.platform !== "string" || !config.platform) {
19
+ throw new Error("Config must have a 'platform' string");
20
+ }
21
+
22
+ if (typeof config.link !== "string" || !config.link) {
23
+ throw new Error("Config must have a 'link' string");
24
+ }
25
+
26
+ if (!config.prefix || typeof config.prefix !== "object") {
27
+ throw new Error("Config must have a 'prefix' object");
28
+ }
29
+
30
+ const prefix = config.prefix as Record<string, unknown>;
31
+ if (typeof prefix.short !== "string" || !prefix.short) {
32
+ throw new Error("Config prefix must have a 'short' string");
33
+ }
34
+
35
+ if (typeof prefix.namespace !== "string" || !prefix.namespace) {
36
+ throw new Error("Config prefix must have a 'namespace' string");
37
+ }
38
+
39
+ if (typeof config.pattern !== "string" || !config.pattern) {
40
+ throw new Error("Config must have a 'pattern' string");
41
+ }
42
+
43
+ // Optional fields validation
44
+ if (config.description !== undefined && typeof config.description !== "string") {
45
+ throw new Error("Config 'description' must be a string if provided");
46
+ }
47
+
48
+ if (config.documentation !== undefined && typeof config.documentation !== "string") {
49
+ throw new Error("Config 'documentation' must be a string if provided");
50
+ }
51
+
52
+ if (config.tier !== undefined && typeof config.tier !== "string") {
53
+ throw new Error("Config 'tier' must be a string if provided");
54
+ }
55
+
56
+ if (config.outputDir !== undefined && typeof config.outputDir !== "string") {
57
+ throw new Error("Config 'outputDir' must be a string if provided");
58
+ }
59
+
60
+ return {
61
+ name: config.name,
62
+ platform: config.platform,
63
+ description: config.description as string | undefined,
64
+ link: config.link,
65
+ documentation: config.documentation as string | undefined,
66
+ tier: config.tier as string | undefined,
67
+ prefix: {
68
+ short: prefix.short,
69
+ namespace: prefix.namespace,
70
+ },
71
+ pattern: config.pattern,
72
+ outputDir: config.outputDir as string | undefined,
73
+ };
74
+ }
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env bun
2
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
3
+ import { join, dirname } from "node:path";
4
+ import {
5
+ validateCollectConfig,
6
+ scanAnnotations,
7
+ generateLibraryTurtle,
8
+ generateObjectsTurtle,
9
+ } from "./collect/index.js";
10
+
11
+ const CONFIG_FILENAME = "design-system.json";
12
+
13
+ async function main(): Promise<void> {
14
+ const cwd = process.cwd();
15
+ const configPath = join(cwd, CONFIG_FILENAME);
16
+
17
+ // Load and validate config
18
+ let configContent: string;
19
+ try {
20
+ configContent = await readFile(configPath, "utf-8");
21
+ } catch {
22
+ console.error(`Error: ${CONFIG_FILENAME} not found in current directory`);
23
+ console.error(`Expected location: ${configPath}`);
24
+ process.exit(1);
25
+ }
26
+
27
+ let config;
28
+ try {
29
+ config = validateCollectConfig(JSON.parse(configContent));
30
+ } catch (err) {
31
+ console.error(`Error: Invalid ${CONFIG_FILENAME}`);
32
+ console.error((err as Error).message);
33
+ process.exit(1);
34
+ }
35
+
36
+ console.log(`Scanning ${config.pattern} for @implements annotations...`);
37
+
38
+ // Scan for annotations
39
+ const annotations = await scanAnnotations(config.pattern, cwd);
40
+
41
+ if (annotations.length === 0) {
42
+ console.log("No @implements annotations found.");
43
+ console.log("");
44
+ console.log("Add annotations to your component files like:");
45
+ console.log(" // @implements ds:global.component.button");
46
+ console.log(" // @implements ds:global.component.button@1.0.0");
47
+ console.log(" // @implements ds:global.component.button [draft]");
48
+ process.exit(0);
49
+ }
50
+
51
+ // Separate valid annotations from those with illegal prefixes
52
+ const validAnnotations = annotations.filter(ann => ann.prefix === config.prefix.short);
53
+ const illegalAnnotations = annotations.filter(ann => ann.prefix !== config.prefix.short);
54
+
55
+ // Warn about illegal prefixes
56
+ if (illegalAnnotations.length > 0) {
57
+ console.warn(`\nWarning: Found ${illegalAnnotations.length} annotation(s) with illegal prefix (expected "${config.prefix.short}"):`);
58
+ for (const ann of illegalAnnotations) {
59
+ const relativePath = ann.filePath.replace(cwd + "/", "");
60
+ console.warn(` - ${relativePath}: ${ann.blockUri}`);
61
+ }
62
+ console.warn("These annotations will be skipped. Please update them to use the correct prefix.\n");
63
+ }
64
+
65
+ console.log(`Found ${validAnnotations.length} valid implementation(s):`);
66
+ for (const ann of validAnnotations) {
67
+ const status = ann.isDraft ? " [draft]" : "";
68
+ const version = ann.version ? `@${ann.version}` : "";
69
+ console.log(` - ${ann.blockUri}${version}${status}`);
70
+ }
71
+
72
+ // Use only valid annotations for generation
73
+ const annotations_to_use = validAnnotations;
74
+
75
+ // Generate Turtle files
76
+ const outputDir = join(cwd, config.outputDir || "data");
77
+ await mkdir(outputDir, { recursive: true });
78
+
79
+ // Generate library TTL
80
+ const libraryTtl = await generateLibraryTurtle(config);
81
+ const libraryPath = join(outputDir, "implementationLibrary.ttl");
82
+ await writeFile(libraryPath, libraryTtl, "utf-8");
83
+ console.log(`Written: ${libraryPath}`);
84
+
85
+ // Generate objects TTL
86
+ const objectsTtl = await generateObjectsTurtle(config, annotations_to_use, cwd);
87
+ if (objectsTtl) {
88
+ const objectsPath = join(outputDir, "implementationObjects.ttl");
89
+ await writeFile(objectsPath, objectsTtl, "utf-8");
90
+ console.log(`Written: ${objectsPath}`);
91
+ }
92
+
93
+ console.log("\nDone!");
94
+ }
95
+
96
+ main().catch((err) => {
97
+ console.error("Error:", err.message);
98
+ process.exit(1);
99
+ });
@@ -0,0 +1,41 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const mockFetchTable = vi.fn();
4
+
5
+ vi.mock("../providers", () => ({
6
+ CodaProvider: class MockCodaProvider {
7
+ constructor() {}
8
+ fetchTable = mockFetchTable;
9
+ },
10
+ }));
11
+
12
+ describe("extract", () => {
13
+ beforeEach(() => {
14
+ vi.clearAllMocks();
15
+ });
16
+
17
+ it("should throw if extract config is missing", async () => {
18
+ const extract = (await import("./extract.js")).default;
19
+
20
+ await expect(
21
+ extract({ document: "doc", provider: "coda" }),
22
+ ).rejects.toThrow("Extract config section is required");
23
+ });
24
+
25
+ it("should propagate provider errors", async () => {
26
+ mockFetchTable.mockRejectedValueOnce(new Error("API Error"));
27
+
28
+ const extract = (await import("./extract.js")).default;
29
+
30
+ await expect(
31
+ extract({
32
+ document: "doc",
33
+ provider: "coda",
34
+ extract: {
35
+ tables: { test: "table-123" },
36
+ output: "/tmp/test-output.json",
37
+ },
38
+ }),
39
+ ).rejects.toThrow("API Error");
40
+ });
41
+ });
@@ -0,0 +1,48 @@
1
+ import { writeFile, mkdir } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import type { Config } from "../config/types.js";
4
+ import { CodaProvider } from "../providers/index.js";
5
+
6
+ /**
7
+ * Extract output structure
8
+ */
9
+ export interface ExtractOutput {
10
+ document: string;
11
+ extractedAt: string;
12
+ tables: Record<string, Array<Record<string, unknown>>>;
13
+ }
14
+
15
+ /**
16
+ * Ensure directory exists for a file path
17
+ */
18
+ async function ensureDir(filePath: string): Promise<void> {
19
+ await mkdir(dirname(filePath), { recursive: true });
20
+ }
21
+
22
+ /**
23
+ * Extracts table data from the configured document
24
+ */
25
+ export default async function extract(config: Config): Promise<void> {
26
+ if (!config.extract) {
27
+ throw new Error("Extract config section is required");
28
+ }
29
+
30
+ const provider = new CodaProvider();
31
+
32
+ const tables: Record<string, Array<Record<string, unknown>>> = {};
33
+
34
+ for (const [tableName, tableId] of Object.entries(config.extract.tables)) {
35
+ const rows = await provider.fetchTable(config.document, tableId);
36
+ tables[tableName] = rows;
37
+ }
38
+
39
+ const result: ExtractOutput = {
40
+ document: config.document,
41
+ extractedAt: new Date().toISOString(),
42
+ tables,
43
+ };
44
+
45
+ await ensureDir(config.extract.output);
46
+ await writeFile(config.extract.output, JSON.stringify(result, null, 2));
47
+ console.log(`Extracted ${Object.keys(result.tables).length} tables to ${config.extract.output}`);
48
+ }
@@ -0,0 +1,3 @@
1
+ export { default as list, type ListOutput } from "./list.js";
2
+ export { default as extract, type ExtractOutput } from "./extract.js";
3
+ export { default as transform } from "./transform.js";
@@ -0,0 +1,26 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const mockListTables = vi.fn();
4
+
5
+ vi.mock("../providers", () => ({
6
+ CodaProvider: class MockCodaProvider {
7
+ constructor() {}
8
+ listTables = mockListTables;
9
+ },
10
+ }));
11
+
12
+ describe("list", () => {
13
+ beforeEach(() => {
14
+ vi.clearAllMocks();
15
+ });
16
+
17
+ it("should propagate provider errors", async () => {
18
+ mockListTables.mockRejectedValueOnce(new Error("API Error"));
19
+
20
+ const list = (await import("./list.js")).default;
21
+
22
+ await expect(
23
+ list({ document: "doc", provider: "coda" }),
24
+ ).rejects.toThrow("API Error");
25
+ });
26
+ });
@@ -0,0 +1,26 @@
1
+ import type { Config } from "../config/types.js";
2
+ import { CodaProvider } from "../providers/index.js";
3
+
4
+ /**
5
+ * List tables output structure
6
+ */
7
+ export interface ListOutput {
8
+ document: string;
9
+ tables: Array<{ id: string; name: string }>;
10
+ }
11
+
12
+ /**
13
+ * Lists all tables in the configured document
14
+ */
15
+ export default async function list(config: Config): Promise<void> {
16
+ const provider = new CodaProvider();
17
+
18
+ const tables = await provider.listTables(config.document);
19
+
20
+ const result: ListOutput = {
21
+ document: config.document,
22
+ tables,
23
+ };
24
+
25
+ console.log(JSON.stringify(result, null, 2));
26
+ }
@@ -0,0 +1,28 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ describe("transform command", () => {
4
+ it("should throw if transform config is missing", async () => {
5
+ const transform = (await import("./transform.js")).default;
6
+
7
+ await expect(
8
+ transform({ document: "doc", provider: "coda" }),
9
+ ).rejects.toThrow("Transform config section is required");
10
+ });
11
+
12
+ it("should throw if extract output path is missing", async () => {
13
+ const transform = (await import("./transform.js")).default;
14
+
15
+ await expect(
16
+ transform({
17
+ document: "doc",
18
+ provider: "coda",
19
+ transform: {
20
+ format: "json-ld",
21
+ outputDir: "instances/",
22
+ atomicity: "instance",
23
+ tables: {},
24
+ },
25
+ }),
26
+ ).rejects.toThrow("Extract output path is required for transform");
27
+ });
28
+ });
@@ -0,0 +1,133 @@
1
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import type { Config } from "../config/types.js";
4
+ import transformData from "../transform/transform.js";
5
+ import { serializeToTurtle, serializeToJsonLd } from "../serializers/index.js";
6
+
7
+ /**
8
+ * Extracted data structure from the extract command
9
+ */
10
+ interface ExtractedData {
11
+ document: string;
12
+ extractedAt: string;
13
+ tables: Record<string, Array<Record<string, unknown>>>;
14
+ }
15
+
16
+ /**
17
+ * Load extracted data from file
18
+ */
19
+ async function loadExtractedData(inputPath: string): Promise<ExtractedData> {
20
+ const content = await readFile(inputPath, "utf-8");
21
+ return JSON.parse(content);
22
+ }
23
+
24
+ /**
25
+ * Parse URI into path components for file organization
26
+ *
27
+ * Splits dot-separated URI path into folder structure:
28
+ * "https://ds.canonical.com/data/global.component.button" -> ["global", "component", "button"]
29
+ *
30
+ * Returns array of path parts, or null if URI doesn't match expected format
31
+ */
32
+ function parseUri(uri: string): string[] | null {
33
+ const dsNamespace = "https://ds.canonical.com/data/";
34
+
35
+ if (!uri.startsWith(dsNamespace)) {
36
+ return null;
37
+ }
38
+
39
+ const path = uri.slice(dsNamespace.length);
40
+ const parts = path.split(".");
41
+
42
+ return parts.length > 0 ? parts : null;
43
+ }
44
+
45
+ /**
46
+ * Transforms extracted data into RDF and serializes to files
47
+ */
48
+ export default async function transform(config: Config): Promise<void> {
49
+ if (!config.transform) {
50
+ throw new Error("Transform config section is required");
51
+ }
52
+
53
+ const inputPath = config.extract?.output;
54
+ if (!inputPath) {
55
+ throw new Error("Extract output path is required for transform");
56
+ }
57
+
58
+ const extractedData = await loadExtractedData(inputPath);
59
+ const { store, prefixes, subjects } = transformData(config.transform, extractedData);
60
+
61
+ const isTurtle = config.transform.format === "ttl";
62
+ const ext = isTurtle ? "ttl" : "jsonld";
63
+
64
+ await mkdir(config.transform.outputDir, { recursive: true });
65
+
66
+ if (config.transform.atomicity === "class") {
67
+ // One file per table - serialize all subjects together
68
+ const content = isTurtle
69
+ ? await serializeToTurtle(store, { prefixes })
70
+ : JSON.stringify(
71
+ await serializeToJsonLd(store, { prefixes }),
72
+ null,
73
+ 2,
74
+ );
75
+
76
+ const outputPath = join(config.transform.outputDir, `all.${ext}`);
77
+ await writeFile(outputPath, content);
78
+ console.log(`Wrote ${subjects.length} subjects to ${outputPath}`);
79
+ } else {
80
+ // One file per instance, organized by URI structure
81
+ for (const subjectUri of subjects) {
82
+ const parts = parseUri(subjectUri);
83
+
84
+ let outputDir: string;
85
+ let filename: string;
86
+
87
+ if (parts && parts.length > 1) {
88
+ // Use all parts except the last as directory path, last part as filename
89
+ const dirParts = parts.slice(0, -1);
90
+ filename = parts[parts.length - 1];
91
+ outputDir = join(config.transform.outputDir, ...dirParts);
92
+ } else if (parts && parts.length === 1) {
93
+ // Single part - put in root output dir
94
+ outputDir = config.transform.outputDir;
95
+ filename = parts[0];
96
+ } else {
97
+ // Fallback for URIs that don't match expected format
98
+ outputDir = config.transform.outputDir;
99
+ const lastSlash = subjectUri.lastIndexOf("/");
100
+ const path = lastSlash !== -1 ? subjectUri.slice(lastSlash + 1) : subjectUri;
101
+ const colonIdx = path.indexOf(":");
102
+ filename = colonIdx !== -1 ? path.slice(colonIdx + 1) : path;
103
+ filename = filename.replace(/[^a-z0-9.\-_]/gi, "_");
104
+ }
105
+
106
+ await mkdir(outputDir, { recursive: true });
107
+ const outputPath = join(outputDir, `${filename}.${ext}`);
108
+
109
+ // Create a new store with just this subject's quads
110
+ const subjectQuads = store.getQuadsForSubject(subjectUri);
111
+ const { GraphStore } = await import("../graph/index.js");
112
+ const subjectStore = new GraphStore();
113
+ for (const quad of subjectQuads) {
114
+ // Re-add using full URIs since we extracted them from the original store
115
+ subjectStore.getN3Store().addQuad(quad);
116
+ }
117
+
118
+ const content = isTurtle
119
+ ? await serializeToTurtle(subjectStore, { prefixes })
120
+ : JSON.stringify(
121
+ await serializeToJsonLd(subjectStore, {
122
+ prefixes,
123
+ subject: subjectUri,
124
+ }),
125
+ null,
126
+ 2,
127
+ );
128
+
129
+ await writeFile(outputPath, content);
130
+ }
131
+ console.log(`Wrote ${subjects.length} files`);
132
+ }
133
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./types.js";
2
+ export { default as validateConfig } from "./validateConfig.js";