dsh-artifact-studio 0.0.0-stage → 0.2.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.
@@ -0,0 +1,10 @@
1
+ - insert:
2
+ - id: dsh-artifact-studio
3
+ name: 'dsh-artifact-studio'
4
+ config: {}
5
+ - id: dsh-artifact-studio-tools
6
+ name: 'dsh-artifact-studio/tools'
7
+ config: {}
8
+ - id: dsh-artifact-studio-skill
9
+ name: 'dsh-artifact-studio/skill'
10
+ config: {}
@@ -0,0 +1,178 @@
1
+ /** Wire shapes shared by the host route, the tools, and the browser client. */
2
+ export const ARTIFACT_TYPES = ['page', 'doc'];
3
+ /**
4
+ * Tell an artifact type from an unknown string without widening to string[].
5
+ * @param value a candidate type.
6
+ * @returns whether it is a supported type.
7
+ */
8
+ export function isArtifactType(value) {
9
+ return ARTIFACT_TYPES.some((type) => type === value);
10
+ }
11
+ export const SCOPES = ['workspace', 'library'];
12
+ export const EXPORT_FORMATS = ['html', 'md', 'docx'];
13
+ /** Which exporters each type supports. */
14
+ export const FORMATS_BY_TYPE = {
15
+ page: ['html'],
16
+ doc: ['md', 'docx', 'html'],
17
+ };
18
+ /** Content file name inside `content/`, by type. */
19
+ export const CONTENT_FILE = {
20
+ page: 'index.html',
21
+ doc: 'document.md',
22
+ };
23
+ export const ID_PATTERN = /^art_(ws|lib)_[a-z0-9]{10,32}$/;
24
+ export const MAX_TITLE = 120;
25
+ export const MAX_LIST_LIMIT = 50;
26
+ export const COLOR_ROLES = ['primary', 'accent', 'surface', 'text', 'muted'];
27
+ /**
28
+ * Narrow a version source read from disk or the wire.
29
+ * @param value the parsed value.
30
+ * @returns whether it is a version source.
31
+ */
32
+ export function isVersionSource(value) {
33
+ if (value === null || typeof value !== 'object')
34
+ return false;
35
+ const origin = 'origin' in value ? value.origin : undefined;
36
+ const action = 'action' in value ? value.action : undefined;
37
+ return ((origin === 'agent' || origin === 'user') &&
38
+ (action === 'create' || action === 'update' || action === 'restore'));
39
+ }
40
+ /**
41
+ * Narrow a manifest read from disk or the wire.
42
+ * @param value the parsed value.
43
+ * @returns whether it is a manifest.
44
+ */
45
+ export function isManifest(value) {
46
+ if (value === null || typeof value !== 'object')
47
+ return false;
48
+ const record = { ...value };
49
+ return (record.schemaVersion === 1 &&
50
+ typeof record.id === 'string' &&
51
+ ID_PATTERN.test(record.id) &&
52
+ (record.scope === 'workspace' || record.scope === 'library') &&
53
+ typeof record.type === 'string' &&
54
+ isArtifactType(record.type) &&
55
+ typeof record.title === 'string' &&
56
+ typeof record.createdAt === 'string' &&
57
+ typeof record.updatedAt === 'string' &&
58
+ typeof record.version === 'number' &&
59
+ Number.isInteger(record.version) &&
60
+ record.version >= 1 &&
61
+ typeof record.contentFile === 'string' &&
62
+ typeof record.contentBytes === 'number' &&
63
+ typeof record.contentHash === 'string' &&
64
+ isVersionSource(record.source));
65
+ }
66
+ const ADDRESS_PREFIX = 'dsh-resource://artifact/';
67
+ /** The root attribute that selects the dark token colors. */
68
+ export const THEME_ATTRIBUTE = 'data-artifact-theme';
69
+ /**
70
+ * Build the tab address of an artifact.
71
+ * @param address the scope, workspace, and id.
72
+ * @returns the `dsh-resource://artifact/...` address.
73
+ */
74
+ export function formatArtifactAddress(address) {
75
+ return address.scope === 'workspace'
76
+ ? `${ADDRESS_PREFIX}workspace/${encodeURIComponent(address.workspaceId)}/${address.id}`
77
+ : `${ADDRESS_PREFIX}library/${address.id}`;
78
+ }
79
+ /**
80
+ * Read an artifact address.
81
+ * @param value a candidate address.
82
+ * @returns the parts, or undefined when the value is not an artifact address.
83
+ */
84
+ export function parseArtifactAddress(value) {
85
+ if (typeof value !== 'string' || !value.startsWith(ADDRESS_PREFIX))
86
+ return undefined;
87
+ const parts = value.slice(ADDRESS_PREFIX.length).split('/');
88
+ if (parts[0] === 'library' && parts.length === 2) {
89
+ const id = parts[1] ?? '';
90
+ return ID_PATTERN.test(id) && id.startsWith('art_lib_') ? { scope: 'library', id } : undefined;
91
+ }
92
+ if (parts[0] === 'workspace' && parts.length === 3) {
93
+ const id = parts[2] ?? '';
94
+ let workspaceId;
95
+ try {
96
+ workspaceId = decodeURIComponent(parts[1] ?? '');
97
+ }
98
+ catch {
99
+ return undefined;
100
+ }
101
+ if (workspaceId === '' || !ID_PATTERN.test(id) || !id.startsWith('art_ws_'))
102
+ return undefined;
103
+ return { scope: 'workspace', workspaceId, id };
104
+ }
105
+ return undefined;
106
+ }
107
+ /**
108
+ * The scope an id belongs to, read from its prefix.
109
+ * @param id an artifact id.
110
+ * @returns the scope, or undefined for a malformed id.
111
+ */
112
+ export function scopeOfId(id) {
113
+ if (!ID_PATTERN.test(id))
114
+ return undefined;
115
+ return id.startsWith('art_ws_') ? 'workspace' : 'library';
116
+ }
117
+ /** The default design system: neutral, readable, and offline (system font stacks only). */
118
+ export const DEFAULT_TOKENS = {
119
+ schemaVersion: 1,
120
+ name: 'Default',
121
+ colors: { primary: '#2856c7', accent: '#0f8a72', surface: '#ffffff', text: '#16181d', muted: '#5b6170' },
122
+ colorsDark: { primary: '#86a8ff', accent: '#45c9a8', surface: '#15171b', text: '#e8e9ec', muted: '#a0a6b2' },
123
+ typography: {
124
+ fontFamily: 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
125
+ displayFamily: 'ui-serif, "Iowan Old Style", Charter, Georgia, serif',
126
+ monoFamily: 'ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace',
127
+ scale: [12, 14, 16, 20, 24, 32, 40],
128
+ },
129
+ spacing: { unit: 4, scale: [4, 8, 12, 16, 24, 32, 48] },
130
+ radius: { sm: 4, md: 8, lg: 12 },
131
+ notes: '',
132
+ };
133
+ /**
134
+ * Turn tokens into CSS custom properties on `:root`.
135
+ * @param tokens the design tokens.
136
+ * @returns a CSS rule.
137
+ */
138
+ export function tokensToCss(tokens) {
139
+ const lines = [];
140
+ for (const role of COLOR_ROLES)
141
+ lines.push(`--artifact-color-${role}: ${tokens.colors[role]};`);
142
+ lines.push(`--artifact-font-family: ${tokens.typography.fontFamily};`);
143
+ lines.push(`--artifact-font-display: ${tokens.typography.displayFamily};`);
144
+ lines.push(`--artifact-font-mono: ${tokens.typography.monoFamily};`);
145
+ tokens.typography.scale.forEach((size, index) => lines.push(`--artifact-font-size-${index}: ${size}px;`));
146
+ lines.push(`--artifact-space-unit: ${tokens.spacing.unit}px;`);
147
+ tokens.spacing.scale.forEach((size, index) => lines.push(`--artifact-space-${index}: ${size}px;`));
148
+ for (const [key, value] of Object.entries(tokens.radius))
149
+ lines.push(`--artifact-radius-${key}: ${value}px;`);
150
+ const dark = COLOR_ROLES.map((role) => `--artifact-color-${role}: ${tokens.colorsDark[role]};`).join('\n ');
151
+ return [
152
+ `:root {\n ${lines.join('\n ')}\n}`,
153
+ `:root[${THEME_ATTRIBUTE}="dark"] {\n color-scheme: dark;\n ${dark}\n}`,
154
+ `@media (prefers-color-scheme: dark) {\n :root[${THEME_ATTRIBUTE}="auto"] {\n color-scheme: dark;\n ${dark.replace(/\n /g, '\n ')}\n }\n}`,
155
+ ].join('\n');
156
+ }
157
+ /**
158
+ * The token variables as a style object for one theme, for surfaces the plugin
159
+ * draws itself instead of a frame.
160
+ * @param tokens the design tokens.
161
+ * @param dark whether to use the dark colors.
162
+ * @returns custom property names and values.
163
+ */
164
+ export function tokenVariables(tokens, dark) {
165
+ const colors = dark ? tokens.colorsDark : tokens.colors;
166
+ const vars = {
167
+ '--artifact-font-family': tokens.typography.fontFamily,
168
+ '--artifact-font-display': tokens.typography.displayFamily,
169
+ '--artifact-font-mono': tokens.typography.monoFamily,
170
+ };
171
+ for (const role of COLOR_ROLES)
172
+ vars[`--artifact-color-${role}`] = colors[role];
173
+ tokens.typography.scale.forEach((size, index) => { vars[`--artifact-font-size-${index}`] = `${size}px`; });
174
+ tokens.spacing.scale.forEach((size, index) => { vars[`--artifact-space-${index}`] = `${size}px`; });
175
+ for (const [key, value] of Object.entries(tokens.radius))
176
+ vars[`--artifact-radius-${key}`] = `${value}px`;
177
+ return vars;
178
+ }
@@ -0,0 +1,14 @@
1
+ import { registerArtifactsRoute } from './lib/http.js';
2
+ import { createHandler } from './lib/rpc.js';
3
+ import { createService } from './lib/setup.js';
4
+ export const name = 'dsh-artifact-studio';
5
+ export const inject = ['workspaceRegistry', 'connection', 'webServer'];
6
+ /**
7
+ * Expose the authenticated artifact channel. The browser reads and writes
8
+ * artifacts only through this route.
9
+ * @param ctx the plugin context.
10
+ */
11
+ export function apply(ctx) {
12
+ const handler = createHandler(createService(ctx.workspaceRegistry));
13
+ ctx.effect(() => registerArtifactsRoute(ctx, handler), 'dsh-artifact-studio: authenticated artifact channel');
14
+ }
@@ -0,0 +1,52 @@
1
+ /** Static checks for page content. They warn and never block a write. */
2
+ const REMOTE = '\\s*["\']?\\s*(?:https?:)?\\/\\/';
3
+ const ATTRIBUTE_URL = new RegExp('\\b(?:src|href|action|poster|data)\\s*=' + REMOTE, 'i');
4
+ const CSS_URL = new RegExp('url\\(' + REMOTE + '|@import\\s+(?:url\\()?' + REMOTE, 'i');
5
+ const SCRIPT_NETWORK = /\b(?:fetch|EventSource|WebSocket|XMLHttpRequest|sendBeacon)\s*\(/;
6
+ const STORAGE = /\b(?:localStorage|sessionStorage|indexedDB)\b/;
7
+ /** The widest fixed width that still fits the full-width view without sideways scrolling. */
8
+ const MAX_FIXED_WIDTH = 960;
9
+ /**
10
+ * Split a page into what the browser executes or fetches. A tutorial that
11
+ * shows fetch() in a code sample, or prose that names localStorage, must not
12
+ * read as a page that calls them.
13
+ * @param content the page HTML.
14
+ * @returns script text, style text, and opening tags.
15
+ */
16
+ function partsOf(content) {
17
+ const html = content.replace(/<!--[\s\S]*?-->/g, '');
18
+ const blocks = (tag) => [...html.matchAll(new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*?)<\\/${tag}\\s*>`, 'gi'))].map((match) => match[1] ?? '').join('\n');
19
+ const markup = html
20
+ .replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi, '')
21
+ .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/gi, '')
22
+ .replace(/<(pre|code|textarea)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, '');
23
+ const tags = [...markup.matchAll(/<[a-z][^>]*>/gi)].map((match) => match[0]).join('\n');
24
+ return { scripts: blocks('script'), styles: blocks('style'), tags };
25
+ }
26
+ /**
27
+ * Find page problems the sandbox or the side panel will expose.
28
+ * @param content the page HTML.
29
+ * @returns one message per problem, each starting with its code.
30
+ */
31
+ export function checkPage(content) {
32
+ const warnings = [];
33
+ const { scripts, styles, tags } = partsOf(content);
34
+ if (ATTRIBUTE_URL.test(tags) || CSS_URL.test(styles) || CSS_URL.test(tags) || SCRIPT_NETWORK.test(scripts)) {
35
+ warnings.push('network: the page loads or calls a network URL. The sandbox blocks every request, so inline the asset or use a data: URI.');
36
+ }
37
+ if (STORAGE.test(scripts) || STORAGE.test(tags)) {
38
+ warnings.push('storage: browser storage throws in the sandbox. Keep state in memory.');
39
+ }
40
+ const widths = styles + '\n' + tags;
41
+ const fixed = [...widths.matchAll(/(?<![-\w])(?:min-)?width\s*:\s*(\d+)px/gi)].some((match) => Number(match[1]) > MAX_FIXED_WIDTH);
42
+ if (fixed) {
43
+ warnings.push(`fixed-width: a fixed width over ${MAX_FIXED_WIDTH}px scrolls sideways in the side panel. Use max-width and a fluid layout.`);
44
+ }
45
+ if (!/<meta\b[^>]*name\s*=\s*["']?viewport/i.test(tags)) {
46
+ warnings.push('viewport: the page has no viewport meta, so an exported copy renders zoomed out on a phone. Add <meta name="viewport" content="width=device-width, initial-scale=1">.');
47
+ }
48
+ if (!content.includes('--artifact-')) {
49
+ warnings.push('no-tokens: the page uses no --artifact-* variables, so it ignores the design system.');
50
+ }
51
+ return warnings;
52
+ }
@@ -0,0 +1,180 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { COLOR_ROLES, DEFAULT_TOKENS, tokensToCss } from '../../contract.js';
4
+ import { ArtifactError } from './errors.js';
5
+ import { assertWithin, withLock, writeAtomic } from './fsutil.js';
6
+ import { assertPlainFile } from './paths.js';
7
+ const FILE = 'design-system.json';
8
+ /**
9
+ * Values reach a `<style>` block, so only characters that cannot close a
10
+ * declaration, a rule, or the element are accepted.
11
+ */
12
+ const SAFE_VALUE = /^[#\w\s,.'"()%+-]{1,200}$/;
13
+ /**
14
+ * Whether a value is a plain object.
15
+ * @param value the value.
16
+ * @returns whether it is an object.
17
+ */
18
+ function isObject(value) {
19
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
20
+ }
21
+ /**
22
+ * Read a CSS-safe string.
23
+ * @param value the value.
24
+ * @param field the field name for the error.
25
+ * @returns the string.
26
+ */
27
+ function cssString(value, field) {
28
+ if (typeof value !== 'string' || !SAFE_VALUE.test(value)) {
29
+ throw new ArtifactError('artifact/invalid-tokens', `${field} must be a short CSS value without ; { } < or >.`, {
30
+ field,
31
+ });
32
+ }
33
+ return value.trim();
34
+ }
35
+ /**
36
+ * Read a list of pixel sizes.
37
+ * @param value the value.
38
+ * @param field the field name for the error.
39
+ * @returns the sizes.
40
+ */
41
+ function sizes(value, field) {
42
+ if (!Array.isArray(value) || value.length === 0 || value.length > 12) {
43
+ throw new ArtifactError('artifact/invalid-tokens', `${field} must be a list of 1 to 12 numbers.`, { field });
44
+ }
45
+ return value.map((item) => size(item, field));
46
+ }
47
+ /**
48
+ * Read one pixel size.
49
+ * @param value the value.
50
+ * @param field the field name for the error.
51
+ * @returns the size.
52
+ */
53
+ function size(value, field) {
54
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 512) {
55
+ throw new ArtifactError('artifact/invalid-tokens', `${field} must be a number from 0 to 512.`, { field });
56
+ }
57
+ return value;
58
+ }
59
+ /**
60
+ * Merge one color set.
61
+ * @param base the colors to start from.
62
+ * @param patch the patch value for this set.
63
+ * @param field the field name for errors.
64
+ * @returns valid colors.
65
+ */
66
+ function mergeColors(base, patch, field) {
67
+ const source = isObject(patch) ? patch : {};
68
+ const colors = { ...base };
69
+ for (const role of COLOR_ROLES)
70
+ colors[role] = cssString(source[role] ?? base[role], `${field}.${role}`);
71
+ return colors;
72
+ }
73
+ /**
74
+ * Merge a partial token patch onto a base and validate the result.
75
+ * @param base the tokens to start from.
76
+ * @param patch a partial or full token object.
77
+ * @returns valid tokens.
78
+ */
79
+ export function mergeTokens(base, patch) {
80
+ if (!isObject(patch))
81
+ throw new ArtifactError('artifact/invalid-tokens', 'Tokens must be an object.');
82
+ const typography = isObject(patch.typography) ? patch.typography : {};
83
+ const spacing = isObject(patch.spacing) ? patch.spacing : {};
84
+ const radius = isObject(patch.radius) ? patch.radius : {};
85
+ const name = patch.name ?? base.name;
86
+ const notes = patch.notes ?? base.notes;
87
+ if (typeof name !== 'string' || name.trim() === '' || name.length > 80) {
88
+ throw new ArtifactError('artifact/invalid-tokens', 'name must be 1 to 80 characters.');
89
+ }
90
+ if (typeof notes !== 'string' || notes.length > 4000) {
91
+ throw new ArtifactError('artifact/invalid-tokens', 'notes must be text up to 4000 characters.');
92
+ }
93
+ return {
94
+ schemaVersion: 1,
95
+ name: name.trim(),
96
+ colors: mergeColors(base.colors, patch.colors, 'colors'),
97
+ colorsDark: mergeColors(base.colorsDark, patch.colorsDark, 'colorsDark'),
98
+ typography: {
99
+ fontFamily: cssString(typography.fontFamily ?? base.typography.fontFamily, 'typography.fontFamily'),
100
+ displayFamily: cssString(typography.displayFamily ?? base.typography.displayFamily, 'typography.displayFamily'),
101
+ monoFamily: cssString(typography.monoFamily ?? base.typography.monoFamily, 'typography.monoFamily'),
102
+ scale: sizes(typography.scale ?? base.typography.scale, 'typography.scale'),
103
+ },
104
+ spacing: {
105
+ unit: size(spacing.unit ?? base.spacing.unit, 'spacing.unit'),
106
+ scale: sizes(spacing.scale ?? base.spacing.scale, 'spacing.scale'),
107
+ },
108
+ radius: {
109
+ sm: size(radius.sm ?? base.radius.sm, 'radius.sm'),
110
+ md: size(radius.md ?? base.radius.md, 'radius.md'),
111
+ lg: size(radius.lg ?? base.radius.lg, 'radius.lg'),
112
+ },
113
+ notes,
114
+ };
115
+ }
116
+ /**
117
+ * Read the token file of one scope root.
118
+ * @param root the scope root.
119
+ * @returns the tokens, or undefined when the scope has none or the file is invalid.
120
+ */
121
+ async function readScopeTokens(root) {
122
+ const file = path.join(root.root, FILE);
123
+ if (!(await assertPlainFile(file)))
124
+ return undefined;
125
+ try {
126
+ return mergeTokens(DEFAULT_TOKENS, JSON.parse(await fs.readFile(file, 'utf8')));
127
+ }
128
+ catch (error) {
129
+ if (error instanceof SyntaxError || error instanceof ArtifactError)
130
+ return undefined;
131
+ throw error;
132
+ }
133
+ }
134
+ /**
135
+ * Resolve tokens workspace first, then library, then the built-in default.
136
+ * @param workspace the workspace root, when the caller has one.
137
+ * @param library the library root.
138
+ * @returns the tokens, their source, and the CSS rule.
139
+ */
140
+ export async function resolveDesignSystem(workspace, library) {
141
+ const own = workspace === undefined ? undefined : await readScopeTokens(workspace);
142
+ if (own !== undefined)
143
+ return { tokens: own, source: 'workspace', css: tokensToCss(own) };
144
+ const shared = await readScopeTokens(library);
145
+ if (shared !== undefined)
146
+ return { tokens: shared, source: 'library', css: tokensToCss(shared) };
147
+ return { tokens: DEFAULT_TOKENS, source: 'default', css: tokensToCss(DEFAULT_TOKENS) };
148
+ }
149
+ /**
150
+ * Save tokens at one scope, merging a partial patch onto what that scope
151
+ * currently resolves to.
152
+ * @param target the scope root to write.
153
+ * @param library the library root, for the base of a new workspace override.
154
+ * @param patch partial or full tokens.
155
+ * @returns the saved tokens and their scope.
156
+ */
157
+ export async function saveDesignSystem(target, library, patch) {
158
+ const file = path.join(target.root, FILE);
159
+ return withLock(file, async () => {
160
+ // Read inside the lock, so a UI save and a tool save cannot interleave.
161
+ const base = (await resolveDesignSystem(target.scope === 'workspace' ? target : undefined, library)).tokens;
162
+ const tokens = mergeTokens(base, patch);
163
+ await assertWithin(target.root, file);
164
+ await assertPlainFile(file);
165
+ await writeAtomic(file, `${JSON.stringify(tokens, null, 2)}\n`);
166
+ return { tokens, scope: target.scope };
167
+ });
168
+ }
169
+ /**
170
+ * Remove a workspace override so the workspace inherits the library again.
171
+ * @param workspace the workspace root.
172
+ */
173
+ export async function clearWorkspaceDesignSystem(workspace) {
174
+ const file = path.join(workspace.root, FILE);
175
+ await withLock(file, async () => {
176
+ await assertWithin(workspace.root, file);
177
+ if (await assertPlainFile(file))
178
+ await fs.rm(file);
179
+ });
180
+ }
@@ -0,0 +1,27 @@
1
+ /** One failure with a stable `artifact/*` code that the route and tools report. */
2
+ export class ArtifactError extends Error {
3
+ code;
4
+ details;
5
+ /**
6
+ * @param code stable error code, for example `artifact/stale-version`.
7
+ * @param message message safe to show to the user and the model.
8
+ * @param details optional structured details.
9
+ */
10
+ constructor(code, message, details = {}) {
11
+ super(message);
12
+ this.name = 'ArtifactError';
13
+ this.code = code;
14
+ this.details = details;
15
+ }
16
+ }
17
+ /**
18
+ * Read the errno name of a filesystem failure.
19
+ * @param error the thrown value.
20
+ * @returns the errno name, or undefined when it is not an errno failure.
21
+ */
22
+ export function errnoCode(error) {
23
+ if (!(error instanceof Error) || !('code' in error))
24
+ return undefined;
25
+ const { code } = error;
26
+ return typeof code === 'string' ? code : undefined;
27
+ }