@filipgutica/design-system 1.0.17 → 1.0.18

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.
package/README.md CHANGED
@@ -12,7 +12,8 @@ Filip's design language for any framework: the spec, the tokens, the component c
12
12
  | --- | --- |
13
13
  | `language/` | The payload: `DESIGN.md`, `components.md`, `decisions.md`, `visualizations.md`, `tokens.css`, the catalogue (`components.html`), example pages, visualization helpers, and the Graphite Indigo editor theme |
14
14
  | `tokens/core.json`, `tokens/themes/*.tokens.json` | The token values, the only place a value lives, and each token's role. Core holds every token; each theme file is a W3C Design Tokens file (2025.10) that holds only its name, a note, its hue pair, and optional fonts and neutrals |
15
- | `scripts/build-tokens.mjs` | The token generator: writes `language/tokens.css`, `dist/`, and the theme mapper's `core.js` and `.d.ts` files, typechecking its JSDoc |
15
+ | `scripts/build-tokens.mjs` | The token generator: writes `language/tokens.css`, `dist/`, and the theme mapper's `core.js`; generates and checks declarations from JSDoc for `theme-mapper/` and `open-vsx/` |
16
+ | `open-vsx/` | Experimental JSONC theme-file parser and Open VSX client, with resolved includes and unaltered colours and syntax rules |
16
17
  | `theme-mapper/` | The theme engine the token build shares, and the experimental theme mapper built on it |
17
18
  | `scripts/build-site.mjs` | The site build: writes `site/` for GitHub Pages from `components.html`, the tokens, and `package.json` |
18
19
  | `dist/` | Generated theme files, JSON, and JavaScript |
@@ -39,6 +40,7 @@ npm install @filipgutica/design-system
39
40
  | `@filipgutica/design-system/tokens.json` | The resolved values as JSON. |
40
41
  | `@filipgutica/design-system/language/*` | The spec, catalogue, and example pages. |
41
42
  | `@filipgutica/design-system/theme-mapper` | Experimental: the API may change until a component library uses it. `mapVsCodeTheme(theme)` maps a VS Code colour theme onto theme inputs for its one mode, by selecting the theme's own colours, keeps the syntax colours its `tokenColors` set, and lists each check it still fails as a `theme` or `core` problem. `themeVariables(mapped)` returns the CSS custom properties to set inline on `<html>`, with `data-theme` forced to the theme's mode. Typed, with no framework and no runtime dependencies. |
43
+ | `@filipgutica/design-system/open-vsx` | Experimental: the API may change in a minor release. `parseVsCodeTheme({ source, fileName })` parses a JSONC theme file and normalises its name. `createOpenVsxThemeService({ fetchImpl })` accepts an optional fetch implementation, searches Open VSX, and imports a verified package, resolving includes into `{ name, type?, colors, tokenColors? }` for `mapVsCodeTheme`. The parser throws `ThemeValidationError` with `malformed-json` or `invalid-shape`; the client returns success or error results. Uses native ZIP decompression and `jsonc-parser`; picker UI, persistence, and applying a theme belong to component libraries. |
42
44
 
43
45
  In a React app, import `tokens.css` and `fonts.css` once in the entry and write `var(--color-text)` in styles, or `cssVar('color-text')` in TypeScript. `tests/react-smoke/` is a working example.
44
46
 
@@ -23,6 +23,7 @@ Each entry records a choice this language made, the options it rejected, and why
23
23
  | Phone drawer trigger | Core | A page-level contents drawer opens from a soft secondary button with a three-line menu glyph and a label. The no-JavaScript fallback keeps a chevron, because it opens in place. The site shell uses the same trigger below its header (see Phone header). | A down chevron promised a dropdown, but the trigger opens a side drawer. | No test yet |
24
24
  | Shape follows role | Core | A pill acts, or sets a value in place with every option shown, on one line (`--radius-control`); a select, which opens a list, is a one-line non-action control. Small state marks are pills (`--radius-pill`). Places and picked rows are 6px (`--radius-inline`). Typed fields, controls whose label wraps, and one-line controls that are not actions are 10px (`--radius-field`). Containers are 16px (`--radius-panel`). A pill never holds text that can wrap, and nested rectangles are concentric. The token names predate the rule: they say inline, control, and field, where the uses are rows, pills, and typed fields. The names stay, because a rename breaks every page that uses them. | One shape for every control. All pills put wrapping labels in pills, which the toggle card, fields, and the raised pill row already rejected; all rectangles lose the shape that marks an action. A list of components for each token with no reason: a new component had no rule to pick from, and a reader took a 6px row beside a pill for an error. | rendered corners by role: `tests/catalogue/catalogue.spec.ts` "each component renders the corner radius of its role, and no other part has one", "the DESIGN.md shape table names each role token with its value"; slider track and thumb, and select picker: `tests/design-foundations.test.mjs` "the slider track, slider thumb, and select picker take their role’s corners"; no literal radius: `tests/design-foundations.test.mjs` "no page or the report stylesheet writes a literal corner radius" |
25
25
  | Themes | Core | A theme sets only its inputs: a hue for light and for dark, and optionally its two fonts, its neutrals (page, surfaces, hover, edges, and text, as a whole set for both modes), and, for a theme imported at runtime through the mapper, any of its 11 syntax colours (`--color-syntax-*`); theme files do not take syntax colours. Shape, spacing, states, and status colours stay core, so actions are pills in every theme. Neutrals are an input so an open palette keeps its own surfaces: Catppuccin and GitHub's Primer ship as themes, each mapped by its palette's own roles and unaltered. Where a hue cannot carry the text on a selected fill at 4.5:1, the build takes the first of the theme's text colour, black, and white that can, as the token roles say. Every theme passes the contrast guards in both modes. Theme files use the W3C Design Tokens format (2025.10) and ship beside the CSS, so design-token tools can read and write them: one file per theme, with a `light` and a `dark` group of sRGB colour tokens. Tools read the two groups as separate tokens (`light.color-bg`, `dark.color-bg`), not as one token with two modes; the Design Tokens Resolver module expresses modes, and it can replace the groups once tools support it. Graphite Indigo is the default. The family sites' own hues ship as themes named for their colour, so a site can load its theme file in place of an inline hue pair: Lagoon (annoterm), Copper (devps), Iris (filip-stack), Lapis (Workbench), and Fern (wtree). Each theme's note names its site. Where a site's light hue falls just short of 4.5:1 as selected-row text, its theme takes the smallest OKLCH lightness step that passes and keeps the hue and chroma, so the selection keeps the hue; the site can adopt the theme's value. A third-party palette is never altered. The theme mapper (`./theme-mapper`, experimental) turns a VS Code colour theme into these inputs for its one mode by selection: each input takes the first of its keys whose colour passes that input's contrast gate, and no colour is changed. What still fails is reported, as a `theme` problem in the theme's colours or a `core` problem in a core link, status, syntax, or command-plate colour on its fills. The checks are data: every ink on every fill the catalogue draws, hover and pressed states included, so a state axe never renders is still measured. The mapper keeps an imported theme's syntax colours too, from its `tokenColors`: each role takes the rule nearest its scope family. A role the theme leaves out takes its core colour; keyword, string, number, and comment have core colours, and the other 7 follow one of them or the code text. The owner chose this on 2026-11-14 to support open themes as their authors made them: the person who installs a theme owns its contrast, so a failing syntax colour is reported as a `theme` problem, never blocked or replaced. Most imports report one: comments in 5 of 8 popular themes measure 2.4–3.7:1 on their own background. The checks stay at 4.5:1, the WCAG AA minimum for text of this size; 3:1 would clear only 2 of those 5. The build and the mapper share one engine for applying a theme, resolving it, and checking it. | The action shape as a theme input (a pill, the 10px field corner, or the 6px row corner): each rounded choice gives actions another role's shape, a select's at 10px and a tab's or row's at 6px, so shape stops telling an action from a field. Radix Themes and shadcn scale every corner together, and Primer, Carbon, Polaris, and Spectrum keep shape core; revisit it as a whole radius scale when a theme needs one. Linear and OpenAI themes: neither publishes an open palette, and their colours are brand identity. Pine and Mauve, the earlier invented themes: no product used them, and they read as unrelated to the family's sites. A grey-blue quiet theme (Slate): it sat beside the muted text and the info blue, so its selection read as metadata and its primary button looked disabled. Adjusting an imported colour until it passes: the result is no longer the theme, and nothing tells the reader it changed. Syntax colours kept core for imports: an import lost its author's code colours to stay clear of reports. A looser bar for syntax, such as 3:1: it is below AA for code text, and it clears few imports. | Per-theme contrast guards (`tests/design-foundations.test.mjs`), the catalogue's rendered recipes in every theme, the Themes page tests, and the theme mapper's tests (`tests/theme-mapper.test.mjs`, the React smoke test with the mode locked opposite the system's, and the catalogue test that every axe contrast failure is a reported problem) |
26
+ | Open VSX theme imports | Core | `./open-vsx` is an experimental, framework-agnostic export for JSONC theme-file parsing and the Open VSX client. It returns VS Code theme data for `./theme-mapper`, with colours unchanged. Includes overlay colours child last and concatenate syntax rules base first, so later rules win. The client keeps the source client’s response, archive, path, checksum, include-depth, and timeout limits. The client reads ZIP headers and caps output from native `DecompressionStream('deflate-raw')`. `jsonc-parser` 3.3.1 reads comments and trailing commas and reports parse locations. It is the only runtime dependency and is pinned, used only by this export; `./theme-mapper` keeps no runtime dependencies. Component libraries own picker UI, persistence, and applying a theme. | Keeping parsing and fetching in a component library: each framework would need its own implementation and safety checks. JSZip at runtime: its synchronous inflation cannot enforce the output cap within a chunk. Handwritten JSONC parsing: more code to maintain for an established format. Making the mapper depend on the client: mapping an already parsed theme would load unused dependencies. | `tests/open-vsx.test.mjs`: offline client imports, JSONC validation, name normalisation, include merging and safety limits; generated declarations checked by `pnpm tokens:check`; package exports checked by `pnpm verify` |
26
27
  | Navigation row corners | Core | Navigation rows, header and strip rows, list-selection rows, collapsible group labels, and tabs take 6px corners (`--radius-inline`), except rows inside a floating menu (see Floating-menu rows). The owner chose the more rectangular rows from the Gate M mockup (2026-11-09). | 10px (`--radius-field`), the previous corners, shared with fields. | 6px corners: `tests/catalogue/catalogue.spec.ts` "each component renders the corner radius of its role, and no other part has one"; Foundations swatch: `tests/design-foundations.test.mjs` "the Foundations current-row swatch and radius list follow the navigation row radius" |
27
28
  | Floating-menu rows | Core | Rows inside a floating menu, such as the project menu, are concentric with the 16px menu: `calc(var(--radius-panel) - var(--space-1))`, 12px, as select picker rows are. The owner approved it from the DS-3b comparison. | 6px like rail rows: a 6px row inside a 16px panel looks pinched. | 12px corners: `tests/catalogue/catalogue.spec.ts` "each component renders the corner radius of its role, and no other part has one" |
28
29
  | One-line non-action controls | Core | A one-line control that is not an action takes the 10px field corner (`--radius-field`), as a select does: the select, the project-menu trigger, the labelled contents trigger and its no-JavaScript summary ("On this page"), and the skip link. The project trigger keeps the quiet-action tint. The owner chose it on 2026-11-10. | The pill (`--radius-control`): a pill means an action, and these controls open a menu or list, pick a value, or move focus. 16px (`--radius-panel`), like the menu and other floating layers: on a one-line control 40 to 44px tall it reads almost as a pill. | 10px corners: `tests/catalogue/catalogue.spec.ts` "each component renders the corner radius of its role, and no other part has one" |
@@ -0,0 +1,41 @@
1
+ export function createOpenVsxThemeService({ fetchImpl, }?: OpenVsxThemeServiceDependencies): OpenVsxThemeService;
2
+ export type ParseError = import("jsonc-parser").ParseError;
3
+ export type VsCodeTheme = import("./parse.js").VsCodeTheme;
4
+ export type OpenVsxThemeSummary = import("./index.js").OpenVsxThemeSummary;
5
+ export type OpenVsxThemeSearchResult = import("./index.js").OpenVsxThemeSearchResult;
6
+ export type ThemeImportErrorCode = import("./index.js").ThemeImportErrorCode;
7
+ export type ThemeImportResult = import("./index.js").ThemeImportResult;
8
+ export type OpenVsxThemeService = import("./index.js").OpenVsxThemeService;
9
+ export type OpenVsxThemeServiceDependencies = import("./index.js").OpenVsxThemeServiceDependencies;
10
+ export type PreferredAppearance = "light" | "dark";
11
+ export type ThemeContribution = {
12
+ label?: unknown;
13
+ uiTheme?: unknown;
14
+ path?: unknown;
15
+ };
16
+ export type Requester = ReturnType<typeof createRequester>;
17
+ export type ZipEntry = {
18
+ name: string;
19
+ uncompressed: number;
20
+ compressed: number;
21
+ compression: number;
22
+ data: Uint8Array;
23
+ nextOffset: number;
24
+ };
25
+ export type ReadZipText = (options: {
26
+ path: string;
27
+ description: string;
28
+ limit?: number;
29
+ }) => Promise<string>;
30
+ /**
31
+ * @param {typeof fetch} fetchImpl
32
+ * @returns {(options: {url: string | URL, limit: number, failureMessage: string, tooLargeMessage: string, allowResourceOrigin?: boolean}) => Promise<Uint8Array>}
33
+ */
34
+ declare function createRequester(fetchImpl: typeof fetch): (options: {
35
+ url: string | URL;
36
+ limit: number;
37
+ failureMessage: string;
38
+ tooLargeMessage: string;
39
+ allowResourceOrigin?: boolean;
40
+ }) => Promise<Uint8Array>;
41
+ export {};
@@ -0,0 +1,789 @@
1
+ import { parse } from 'jsonc-parser'
2
+
3
+ import { ThemeValidationError, parseVsCodeTheme, isRecord } from './parse.js'
4
+
5
+ /** @typedef {import('jsonc-parser').ParseError} ParseError */
6
+ /** @typedef {import('./parse.js').VsCodeTheme} VsCodeTheme */
7
+ /** @typedef {import('./index.js').OpenVsxThemeSummary} OpenVsxThemeSummary */
8
+ /** @typedef {import('./index.js').OpenVsxThemeSearchResult} OpenVsxThemeSearchResult */
9
+ /** @typedef {import('./index.js').ThemeImportErrorCode} ThemeImportErrorCode */
10
+ /** @typedef {import('./index.js').ThemeImportResult} ThemeImportResult */
11
+ /** @typedef {import('./index.js').OpenVsxThemeService} OpenVsxThemeService */
12
+ /** @typedef {import('./index.js').OpenVsxThemeServiceDependencies} OpenVsxThemeServiceDependencies */
13
+ /** @typedef {'light' | 'dark'} PreferredAppearance */
14
+ /** @typedef {{ label?: unknown, uiTheme?: unknown, path?: unknown }} ThemeContribution */
15
+ /** @typedef {ReturnType<typeof createRequester>} Requester */
16
+ /** @typedef {{ name: string; uncompressed: number; compressed: number; compression: number; data: Uint8Array; nextOffset: number; }} ZipEntry */
17
+ /** @typedef {(options: { path: string; description: string; limit?: number; }) => Promise<string>} ReadZipText */
18
+
19
+ const OPEN_VSX_ORIGIN = 'https://open-vsx.org'
20
+ const OPEN_VSX_RESOURCE_ORIGIN = 'https://openvsx.eclipsecontent.org'
21
+ const OPEN_VSX_SEARCH_URL = `${OPEN_VSX_ORIGIN}/api/-/search`
22
+ const MAX_SEARCH_BYTES = 512 * 1024
23
+ const MAX_DETAIL_BYTES = 256 * 1024
24
+ const MAX_MANIFEST_BYTES = 256 * 1024
25
+ const MAX_THEME_BYTES = 1024 * 1024
26
+ const MAX_VSIX_BYTES = 20 * 1024 * 1024
27
+ const MAX_ZIP_ENTRIES = 5_000
28
+ const MAX_UNCOMPRESSED_BYTES = 100 * 1024 * 1024
29
+ const MAX_COMPRESSION_RATIO = 200
30
+ const MAX_THEMES_PER_EXTENSION = 40
31
+ const MAX_INCLUDE_DEPTH = 8
32
+ const REQUEST_TIMEOUT_MS = 15_000
33
+
34
+ class OpenVsxThemeError extends Error {
35
+ /** @param {ThemeImportErrorCode} code @param {string} message */
36
+ constructor(code, message) {
37
+ super(message)
38
+ this.name = 'OpenVsxThemeError'
39
+ this.code = code
40
+ }
41
+ }
42
+
43
+ /**
44
+ * @param {string} source
45
+ * @param {string} description
46
+ * @returns {Record<string, unknown>}
47
+ */
48
+ const parseJsonObject = (source, description) => {
49
+ /** @type {ParseError[]} */
50
+ const errors = []
51
+ /** @type {unknown} */
52
+ const value = parse(source, errors, { allowTrailingComma: true })
53
+ if (errors.length > 0 || !isRecord(value)) {
54
+ throw new OpenVsxThemeError(
55
+ 'unsupported-extension',
56
+ `${description} is not valid JSON.`,
57
+ )
58
+ }
59
+ return value
60
+ }
61
+
62
+ /**
63
+ * @param {unknown} value
64
+ * @param {{ allowResourceOrigin?: boolean; }} options
65
+ * @returns {string | null}
66
+ */
67
+ const trustedOpenVsxUrl = (
68
+ value,
69
+ { allowResourceOrigin = false } = {},
70
+ ) => {
71
+ if (typeof value !== 'string') return null
72
+ try {
73
+ const url = new URL(value)
74
+ const origin = url.origin.toLowerCase()
75
+ return origin === OPEN_VSX_ORIGIN || (allowResourceOrigin && origin === OPEN_VSX_RESOURCE_ORIGIN)
76
+ ? url.toString()
77
+ : null
78
+ } catch {
79
+ return null
80
+ }
81
+ }
82
+
83
+ /**
84
+ * @param {string} value
85
+ * @returns {[ publisher: string, name: string ]}
86
+ */
87
+ const validateExtensionId = (value) => {
88
+ const match = /^([a-z0-9][a-z0-9_-]{0,99})\.([a-z0-9][a-z0-9_-]{0,99})$/i.exec(value)
89
+ if (!match?.[1] || !match[2]) {
90
+ throw new OpenVsxThemeError(
91
+ 'unsupported-extension',
92
+ 'The selected Open VSX extension identifier is invalid.',
93
+ )
94
+ }
95
+ return [match[1], match[2]]
96
+ }
97
+
98
+ /**
99
+ * @param {Record<string, unknown>} manifest
100
+ * @returns {ThemeContribution[]}
101
+ */
102
+ const themeContributions = (manifest) => {
103
+ const contributes = isRecord(manifest.contributes) ? manifest.contributes : null
104
+ return Array.isArray(contributes?.themes)
105
+ ? contributes.themes.filter(isRecord)
106
+ : []
107
+ }
108
+
109
+ /**
110
+ * @param {{ response: Response, limit: number, tooLargeMessage: string }} options
111
+ * @returns {Promise<Uint8Array>}
112
+ */
113
+ const readCappedResponse = async ({ response, limit, tooLargeMessage }) => {
114
+ const contentLength = Number(response.headers.get('content-length'))
115
+ if (Number.isFinite(contentLength) && contentLength > limit) {
116
+ throw new OpenVsxThemeError('file-too-large', tooLargeMessage)
117
+ }
118
+ if (!response.body) {
119
+ const bytes = new Uint8Array(await response.arrayBuffer())
120
+ if (bytes.byteLength > limit) throw new OpenVsxThemeError('file-too-large', tooLargeMessage)
121
+ return bytes
122
+ }
123
+
124
+ const reader = response.body.getReader()
125
+ /** @type {Uint8Array[]} */
126
+ const chunks = []
127
+ let byteLength = 0
128
+ try {
129
+ while (true) {
130
+ const { done, value } = await reader.read()
131
+ if (done) break
132
+ byteLength += value.byteLength
133
+ if (byteLength > limit) {
134
+ await reader.cancel()
135
+ throw new OpenVsxThemeError('file-too-large', tooLargeMessage)
136
+ }
137
+ chunks.push(value)
138
+ }
139
+ } finally {
140
+ reader.releaseLock()
141
+ }
142
+
143
+ const bytes = new Uint8Array(byteLength)
144
+ let offset = 0
145
+ for (const chunk of chunks) {
146
+ bytes.set(chunk, offset)
147
+ offset += chunk.byteLength
148
+ }
149
+ return bytes
150
+ }
151
+
152
+ /**
153
+ * @param {typeof fetch} fetchImpl
154
+ * @returns {(options: {url: string | URL, limit: number, failureMessage: string, tooLargeMessage: string, allowResourceOrigin?: boolean}) => Promise<Uint8Array>}
155
+ */
156
+ const createRequester = (fetchImpl) => async ({
157
+ url,
158
+ limit,
159
+ failureMessage,
160
+ tooLargeMessage,
161
+ allowResourceOrigin = false,
162
+ }) => {
163
+ const controller = new AbortController()
164
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
165
+ try {
166
+ const requestedUrl = trustedOpenVsxUrl(String(url), { allowResourceOrigin })
167
+ if (!requestedUrl) {
168
+ throw new OpenVsxThemeError('open-vsx-unavailable', failureMessage)
169
+ }
170
+ const response = await fetchImpl(requestedUrl, {
171
+ redirect: 'follow',
172
+ signal: controller.signal,
173
+ })
174
+ if (!trustedOpenVsxUrl(response.url || requestedUrl, { allowResourceOrigin })) {
175
+ throw new OpenVsxThemeError('open-vsx-unavailable', failureMessage)
176
+ }
177
+ if (!response.ok) {
178
+ throw new OpenVsxThemeError('open-vsx-unavailable', failureMessage)
179
+ }
180
+ return await readCappedResponse({ response, limit, tooLargeMessage })
181
+ } catch (error) {
182
+ if (error instanceof OpenVsxThemeError) throw error
183
+ throw new OpenVsxThemeError(
184
+ 'open-vsx-unavailable',
185
+ controller.signal.aborted ? 'Open VSX took too long to respond.' : failureMessage,
186
+ )
187
+ } finally {
188
+ clearTimeout(timeout)
189
+ }
190
+ }
191
+
192
+ /**
193
+ * @param {unknown} value
194
+ * @returns {OpenVsxThemeSummary | null}
195
+ */
196
+ const searchSummary = (value) => {
197
+ if (!isRecord(value)) return null
198
+ const publisher = typeof value.namespace === 'string' ? value.namespace.trim() : ''
199
+ const extensionName = typeof value.name === 'string' ? value.name.trim() : ''
200
+ if (!publisher || !extensionName) return null
201
+ const name = typeof value.displayName === 'string' && value.displayName.trim()
202
+ ? value.displayName.trim()
203
+ : extensionName
204
+ return {
205
+ id: `${publisher}.${extensionName}`,
206
+ name: name.slice(0, 100),
207
+ publisher: publisher.slice(0, 100),
208
+ description: typeof value.description === 'string' ? value.description.slice(0, 300) : '',
209
+ downloadCount: typeof value.downloadCount === 'number' && Number.isFinite(value.downloadCount)
210
+ ? Math.max(0, value.downloadCount)
211
+ : 0,
212
+ }
213
+ }
214
+
215
+ /**
216
+ * @param {string} path
217
+ * @returns {void}
218
+ */
219
+ const validateRelativePath = (path) => {
220
+ if (
221
+ path.length > 1_024
222
+ || path.includes('\0')
223
+ || path.startsWith('/')
224
+ || /^[a-z]:/i.test(path)
225
+ ) {
226
+ throw new OpenVsxThemeError('unsupported-extension', 'A theme path is not safe.')
227
+ }
228
+ }
229
+
230
+ /**
231
+ * @param {{ path: string; initialSegments: string[]; minimumDepth: number; }} options
232
+ * @returns {string}
233
+ */
234
+ const resolveSafePath = ({
235
+ path,
236
+ initialSegments,
237
+ minimumDepth,
238
+ }) => {
239
+ validateRelativePath(path)
240
+ const segments = [...initialSegments]
241
+ for (const segment of path.replaceAll('\\', '/').split('/')) {
242
+ if (!segment || segment === '.') continue
243
+ if (segment === '..') {
244
+ if (segments.length <= minimumDepth) {
245
+ throw new OpenVsxThemeError('unsupported-extension', 'A theme path escapes its package.')
246
+ }
247
+ segments.pop()
248
+ } else {
249
+ segments.push(segment)
250
+ }
251
+ }
252
+ return segments.join('/')
253
+ }
254
+
255
+ /**
256
+ * @param {string} path
257
+ * @returns {string}
258
+ */
259
+ const normalizePackagePath = (path, relativeTo = 'extension/') => {
260
+ const initialSegments = relativeTo.split('/').slice(0, -1)
261
+ if (initialSegments[0] !== 'extension') initialSegments.unshift('extension')
262
+ return resolveSafePath({ path, initialSegments, minimumDepth: 1 })
263
+ }
264
+
265
+ /**
266
+ * @param {string} path
267
+ * @returns {string}
268
+ */
269
+ const normalizeArchiveEntryPath = (path) => {
270
+ if (path.includes('\\')) {
271
+ throw new OpenVsxThemeError('unsupported-extension', 'An extension package file name contains a backslash.')
272
+ }
273
+ if (path.split('/').includes('..')) {
274
+ throw new OpenVsxThemeError('unsupported-extension', 'A theme path escapes its package.')
275
+ }
276
+ const normalized = resolveSafePath({ path, initialSegments: [], minimumDepth: 0 })
277
+ if (!normalized) {
278
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has an invalid file name.')
279
+ }
280
+ return normalized
281
+ }
282
+
283
+ /**
284
+ * @param {DataView} view
285
+ * @returns {number}
286
+ */
287
+ const findZipDirectoryEnd = (view) => {
288
+ const byteLength = view.byteLength
289
+ const minimumOffset = Math.max(0, byteLength - 65_557)
290
+ let endOffset = byteLength - 22
291
+ while (
292
+ endOffset >= minimumOffset
293
+ && (
294
+ view.getUint32(endOffset, true) !== 0x06054b50
295
+ || endOffset + 22 + view.getUint16(endOffset + 20, true) !== byteLength
296
+ )
297
+ ) endOffset -= 1
298
+ if (endOffset < minimumOffset) {
299
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package is not a valid ZIP file.')
300
+ }
301
+ return endOffset
302
+ }
303
+
304
+ /**
305
+ * @param {DataView} view
306
+ * @returns {{ start: number; end: number; }}
307
+ */
308
+ const zipDirectoryBounds = (view) => {
309
+ const endOffset = findZipDirectoryEnd(view)
310
+
311
+ const directorySize = view.getUint32(endOffset + 12, true)
312
+ const directoryOffset = view.getUint32(endOffset + 16, true)
313
+ const directoryEnd = directoryOffset + directorySize
314
+ if (directoryEnd !== endOffset || directoryEnd > view.byteLength) {
315
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has an invalid ZIP directory.')
316
+ }
317
+ return { start: directoryOffset, end: directoryEnd }
318
+ }
319
+
320
+ /**
321
+ * @param {{ bytes: Uint8Array; view: DataView; offset: number; directoryStart: number; directoryEnd: number; }} options
322
+ * @returns {ZipEntry}
323
+ */
324
+ const readZipEntry = ({
325
+ bytes,
326
+ view,
327
+ offset,
328
+ directoryStart,
329
+ directoryEnd,
330
+ }) => {
331
+ if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014b50) {
332
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has an invalid ZIP directory.')
333
+ }
334
+ const compressed = view.getUint32(offset + 20, true)
335
+ const uncompressed = view.getUint32(offset + 24, true)
336
+ const nameLength = view.getUint16(offset + 28, true)
337
+ const extraLength = view.getUint16(offset + 30, true)
338
+ const commentLength = view.getUint16(offset + 32, true)
339
+ const nextOffset = offset + 46 + nameLength + extraLength + commentLength
340
+ if (nextOffset > directoryEnd || compressed === 0xffffffff || uncompressed === 0xffffffff) {
341
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has unsafe ZIP metadata.')
342
+ }
343
+ if (uncompressed > 0 && (compressed === 0 || uncompressed / compressed > MAX_COMPRESSION_RATIO)) {
344
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has unsafe ZIP metadata.')
345
+ }
346
+ const localOffset = view.getUint32(offset + 42, true)
347
+ if (localOffset + 30 > directoryStart || view.getUint32(localOffset, true) !== 0x04034b50) {
348
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has an invalid local ZIP header.')
349
+ }
350
+ const localNameLength = view.getUint16(localOffset + 26, true)
351
+ const dataOffset = localOffset + 30 + localNameLength + view.getUint16(localOffset + 28, true)
352
+ const compression = view.getUint16(offset + 10, true)
353
+ if (dataOffset > directoryStart || (compression !== 0 && compression !== 8)) {
354
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has unsafe ZIP metadata.')
355
+ }
356
+ try {
357
+ const name = new TextDecoder('utf-8', { fatal: true }).decode(
358
+ bytes.subarray(offset + 46, offset + 46 + nameLength),
359
+ )
360
+ const localName = new TextDecoder('utf-8', { fatal: true }).decode(
361
+ bytes.subarray(localOffset + 30, localOffset + 30 + localNameLength),
362
+ )
363
+ normalizeArchiveEntryPath(localName)
364
+ if (localName !== name) throw new Error('Mismatched ZIP entry names')
365
+ return { name, uncompressed, compressed, compression, data: bytes.subarray(dataOffset, Math.min(dataOffset + compressed, directoryStart)), nextOffset }
366
+ } catch (error) {
367
+ if (error instanceof OpenVsxThemeError) throw error
368
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has an invalid file name.')
369
+ }
370
+ }
371
+
372
+ /**
373
+ * @param {Uint8Array} bytes
374
+ * @returns {Map<string, ZipEntry>}
375
+ */
376
+ const inspectZipDirectory = (bytes) => {
377
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
378
+ const directory = zipDirectoryBounds(view)
379
+
380
+ /** @type {Map<string, ZipEntry>} */
381
+ const entries = new Map()
382
+ let totalUncompressed = 0
383
+ let entryCount = 0
384
+ let offset = directory.start
385
+ while (offset < directory.end) {
386
+ entryCount += 1
387
+ if (entryCount > MAX_ZIP_ENTRIES) {
388
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has an invalid ZIP directory.')
389
+ }
390
+ const entry = readZipEntry({ bytes, view, offset, directoryStart: directory.start, directoryEnd: directory.end })
391
+ totalUncompressed += entry.uncompressed
392
+ if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) {
393
+ throw new OpenVsxThemeError('file-too-large', 'The extension package expands beyond the safe limit.')
394
+ }
395
+ const path = normalizeArchiveEntryPath(entry.name)
396
+ if (entries.has(path)) {
397
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has duplicate file names.')
398
+ }
399
+ entries.set(path, entry)
400
+ offset = entry.nextOffset
401
+ }
402
+ // Check lengths after the directory walk so file-too-large takes precedence.
403
+ for (const entry of entries.values()) {
404
+ if (entry.data.byteLength !== entry.compressed) {
405
+ throw new OpenVsxThemeError('unsupported-extension', 'The extension package has unsafe ZIP metadata.')
406
+ }
407
+ }
408
+ return entries
409
+ }
410
+
411
+ /**
412
+ * @param {{ entries: ReadonlyMap<string, ZipEntry>; budget: { remaining: number }; path: string; description: string; limit?: number; }} options
413
+ * @returns {Promise<string>}
414
+ */
415
+ const readZipText = async ({
416
+ entries,
417
+ budget,
418
+ path,
419
+ description,
420
+ limit = MAX_THEME_BYTES,
421
+ }) => {
422
+ const entry = entries.get(path)
423
+ if (!entry || entry.name.endsWith('/')) {
424
+ throw new OpenVsxThemeError('unsupported-extension', `${description} is missing.`)
425
+ }
426
+ if (entry.uncompressed > limit) {
427
+ throw new OpenVsxThemeError('file-too-large', `${description} is too large.`)
428
+ }
429
+ let offset = 0
430
+ const input = new ReadableStream({
431
+ pull(controller) {
432
+ if (offset === entry.data.byteLength) {
433
+ controller.close()
434
+ return
435
+ }
436
+ // Bound each native inflation step too: a small DEFLATE input can expand
437
+ // roughly 1,032-fold before output backpressure or cancellation takes effect.
438
+ const end = Math.min(offset + (entry.compression === 8 ? 64 : 16 * 1024), entry.data.byteLength)
439
+ controller.enqueue(entry.data.subarray(offset, end))
440
+ offset = end
441
+ },
442
+ }, { highWaterMark: 0 })
443
+ try {
444
+ const output = entry.compression === 8 ? input.pipeThrough(new DecompressionStream('deflate-raw')) : input
445
+ const bytes = await readCappedResponse({
446
+ response: new Response(output),
447
+ limit: Math.min(limit, budget.remaining),
448
+ tooLargeMessage: budget.remaining < limit
449
+ ? 'The extension package expands beyond the safe limit.'
450
+ : `${description} is too large.`,
451
+ })
452
+ budget.remaining -= bytes.byteLength
453
+ return new TextDecoder().decode(bytes)
454
+ } catch (error) {
455
+ if (error instanceof OpenVsxThemeError) throw error
456
+ throw new OpenVsxThemeError('unsupported-extension', `${description} could not be decompressed.`)
457
+ }
458
+ }
459
+
460
+ /**
461
+ * @param {{ readText: ReadZipText; path: string; ancestors?: ReadonlySet<string>; }} options
462
+ * @returns {Promise<Record<string, unknown>>}
463
+ */
464
+ const resolveThemeObject = async ({
465
+ readText,
466
+ path,
467
+ ancestors = new Set(),
468
+ }) => {
469
+ if (ancestors.size >= MAX_INCLUDE_DEPTH || ancestors.has(path)) {
470
+ throw new OpenVsxThemeError('unsupported-extension', 'Theme includes are cyclic or too deeply nested.')
471
+ }
472
+ const value = parseJsonObject(
473
+ await readText({ path, description: `Theme file ${path}` }),
474
+ `Theme file ${path}`,
475
+ )
476
+ if (typeof value.include !== 'string') return value
477
+ const nextAncestors = new Set(ancestors)
478
+ nextAncestors.add(path)
479
+ const parent = await resolveThemeObject({
480
+ readText,
481
+ path: normalizePackagePath(value.include, path),
482
+ ancestors: nextAncestors,
483
+ })
484
+ return {
485
+ ...parent,
486
+ ...value,
487
+ // Workbench keys overlay, but later syntax rules win within one ordered array.
488
+ tokenColors: Array.isArray(parent.tokenColors) || Array.isArray(value.tokenColors)
489
+ ? [...(Array.isArray(parent.tokenColors) ? parent.tokenColors : []), ...(Array.isArray(value.tokenColors) ? value.tokenColors : [])]
490
+ : value.tokenColors ?? parent.tokenColors,
491
+ colors: {
492
+ ...(isRecord(parent.colors) ? parent.colors : {}),
493
+ ...(isRecord(value.colors) ? value.colors : {}),
494
+ },
495
+ }
496
+ }
497
+
498
+ /**
499
+ * @param {unknown} value
500
+ * @returns {string | null}
501
+ */
502
+ const contributionType = (value) => {
503
+ if (value === 'vs') return 'light'
504
+ if (value === 'vs-dark') return 'dark'
505
+ if (value === 'hc-black') return 'hc'
506
+ if (value === 'hc-light') return 'hcLight'
507
+ return null
508
+ }
509
+
510
+ /**
511
+ * @param {VsCodeTheme[]} themes
512
+ * @param {PreferredAppearance} preferredAppearance
513
+ * @returns {VsCodeTheme}
514
+ */
515
+ const selectTheme = (
516
+ themes,
517
+ preferredAppearance,
518
+ ) => themes.find(theme =>
519
+ preferredAppearance === 'dark'
520
+ ? theme.type === 'dark' || theme.type === 'hc'
521
+ : theme.type === 'light' || theme.type === 'hcLight') ?? themes[0]
522
+
523
+ /**
524
+ * @param {{ request: Requester; extensionId: string; }} options
525
+ * @returns {Promise<{ extensionName: string; manifestUrl: string; packageUrl: string; checksumUrl: string; version: string; }>}
526
+ */
527
+ const getPackageLocation = async ({
528
+ request,
529
+ extensionId,
530
+ }) => {
531
+ const [publisher, extensionName] = validateExtensionId(extensionId)
532
+ const detailBytes = await request({
533
+ url: `${OPEN_VSX_ORIGIN}/api/${encodeURIComponent(publisher)}/${encodeURIComponent(extensionName)}`,
534
+ limit: MAX_DETAIL_BYTES,
535
+ failureMessage: 'Open VSX theme details are unavailable right now.',
536
+ tooLargeMessage: 'Open VSX returned unexpectedly large theme details.',
537
+ })
538
+ /** @type {unknown} */
539
+ const detail = JSON.parse(new TextDecoder().decode(detailBytes))
540
+ if (!isRecord(detail) || !isRecord(detail.files)) {
541
+ throw new OpenVsxThemeError('unsupported-extension', 'Open VSX returned malformed theme details.')
542
+ }
543
+ const resourceOrigin = { allowResourceOrigin: true }
544
+ const manifestUrl = trustedOpenVsxUrl(detail.files.manifest, resourceOrigin)
545
+ const packageUrl = trustedOpenVsxUrl(detail.files.download, resourceOrigin)
546
+ const checksumUrl = trustedOpenVsxUrl(detail.files.sha256, resourceOrigin)
547
+ const version = typeof detail.version === 'string' ? detail.version : ''
548
+ if (!manifestUrl || !packageUrl || !checksumUrl || !version) {
549
+ throw new OpenVsxThemeError('unsupported-extension', 'Open VSX returned malformed theme details.')
550
+ }
551
+ return { extensionName, manifestUrl, packageUrl, checksumUrl, version }
552
+ }
553
+
554
+ /**
555
+ * @param {{ request: Requester; manifestUrl: string; }} options
556
+ * @returns {Promise<void>}
557
+ */
558
+ const validateAdvertisedThemes = async ({
559
+ request,
560
+ manifestUrl,
561
+ }) => {
562
+ const manifestBytes = await request({
563
+ url: manifestUrl,
564
+ limit: MAX_MANIFEST_BYTES,
565
+ failureMessage: 'That extension has no readable manifest.',
566
+ tooLargeMessage: 'That extension manifest is too large.',
567
+ allowResourceOrigin: true,
568
+ })
569
+ const manifest = parseJsonObject(
570
+ new TextDecoder().decode(manifestBytes),
571
+ 'The extension manifest',
572
+ )
573
+ const themes = themeContributions(manifest)
574
+ if (themes.length === 0 || themes.length > MAX_THEMES_PER_EXTENSION) {
575
+ throw new OpenVsxThemeError(
576
+ 'unsupported-extension',
577
+ 'That extension does not contain a supported number of color themes.',
578
+ )
579
+ }
580
+ }
581
+
582
+ /**
583
+ * @param {{ request: Requester; packageUrl: string; checksumUrl: string; }} options
584
+ * @returns {Promise<Uint8Array>}
585
+ */
586
+ const downloadVerifiedPackage = async ({
587
+ request,
588
+ packageUrl,
589
+ checksumUrl,
590
+ }) => {
591
+ const [packageBytes, checksumBytes] = await Promise.all([
592
+ request({
593
+ url: packageUrl,
594
+ limit: MAX_VSIX_BYTES,
595
+ failureMessage: 'That Open VSX theme could not be downloaded.',
596
+ tooLargeMessage: 'That theme extension is too large to import safely.',
597
+ allowResourceOrigin: true,
598
+ }),
599
+ request({
600
+ url: checksumUrl,
601
+ limit: 256,
602
+ failureMessage: 'That Open VSX theme has no readable checksum.',
603
+ tooLargeMessage: 'That Open VSX checksum response is invalid.',
604
+ allowResourceOrigin: true,
605
+ }),
606
+ ])
607
+ const expectedChecksum = new TextDecoder().decode(checksumBytes).trim().split(/\s+/)[0]
608
+ const digest = await globalThis.crypto.subtle.digest('SHA-256', new Uint8Array(packageBytes))
609
+ const actualChecksum = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')
610
+ if (!expectedChecksum || !/^[a-f\d]{64}$/i.test(expectedChecksum)) {
611
+ throw new OpenVsxThemeError('integrity-failed', 'That Open VSX theme has an invalid checksum.')
612
+ }
613
+ if (expectedChecksum.toLowerCase() !== actualChecksum) {
614
+ throw new OpenVsxThemeError('integrity-failed', 'That Open VSX theme failed its integrity check.')
615
+ }
616
+ return packageBytes
617
+ }
618
+
619
+ /**
620
+ * @param {Uint8Array} packageBytes
621
+ * @returns {Promise<ReadZipText>}
622
+ */
623
+ const openPackage = async (packageBytes) => {
624
+ const entries = inspectZipDirectory(packageBytes)
625
+ const budget = { remaining: MAX_UNCOMPRESSED_BYTES }
626
+ return options => readZipText({ entries, budget, ...options })
627
+ }
628
+
629
+ /**
630
+ * @param {{ readText: ReadZipText; extensionId: string; version: string; }} options
631
+ * @returns {Promise<Record<string, unknown>>}
632
+ */
633
+ const readMatchingManifest = async ({
634
+ readText,
635
+ extensionId,
636
+ version,
637
+ }) => {
638
+ const manifest = parseJsonObject(
639
+ await readText({
640
+ limit: MAX_MANIFEST_BYTES,
641
+ path: 'extension/package.json',
642
+ description: 'The packaged extension manifest',
643
+ }),
644
+ 'The packaged extension manifest',
645
+ )
646
+ const packagedId = typeof manifest.publisher === 'string' && typeof manifest.name === 'string'
647
+ ? `${manifest.publisher}.${manifest.name}`
648
+ : ''
649
+ if (packagedId.toLowerCase() !== extensionId.toLowerCase() || manifest.version !== version) {
650
+ throw new OpenVsxThemeError(
651
+ 'integrity-failed',
652
+ 'The downloaded package does not match the selected Open VSX theme.',
653
+ )
654
+ }
655
+ return manifest
656
+ }
657
+
658
+ /**
659
+ * @param {{ readText: ReadZipText; manifest: Record<string, unknown>; fallbackName: string; }} options
660
+ * @returns {Promise<VsCodeTheme[]>}
661
+ */
662
+ const parseContributedThemes = async ({
663
+ readText,
664
+ manifest,
665
+ fallbackName,
666
+ }) => {
667
+ const contributions = themeContributions(manifest)
668
+ if (contributions.length === 0 || contributions.length > MAX_THEMES_PER_EXTENSION) {
669
+ throw new OpenVsxThemeError('unsupported-extension', 'That extension has no compatible color themes.')
670
+ }
671
+
672
+ /** @type {VsCodeTheme[]} */
673
+ const themes = []
674
+ for (const contribution of contributions) {
675
+ if (typeof contribution.path !== 'string') {
676
+ throw new OpenVsxThemeError('unsupported-extension', 'A contributed theme has no valid path.')
677
+ }
678
+ const path = normalizePackagePath(contribution.path)
679
+ const value = await resolveThemeObject({ readText, path })
680
+ const type = contributionType(contribution.uiTheme)
681
+ const label = typeof contribution.label === 'string' && contribution.label.trim()
682
+ ? contribution.label.trim()
683
+ : fallbackName
684
+ themes.push(parseVsCodeTheme({
685
+ source: JSON.stringify({ ...value, name: label, ...(value.type === undefined && type ? { type } : {}) }),
686
+ fileName: path,
687
+ }))
688
+ }
689
+ return themes
690
+ }
691
+
692
+ /**
693
+ * @param {OpenVsxThemeSummary} options
694
+ * @returns {boolean}
695
+ */
696
+ const isLikelyColorTheme = ({
697
+ description,
698
+ name,
699
+ }) => {
700
+ const summary = `${name} ${description}`
701
+ return /\b(?:color\s+scheme|theme)\b/i.test(summary)
702
+ && !/\b(?:file\s+icons?|product\s+icons?|icon\s+theme|icons?)\b/i.test(summary)
703
+ }
704
+
705
+ /**
706
+ * @param {OpenVsxThemeServiceDependencies} options
707
+ * @returns {OpenVsxThemeService}
708
+ */
709
+ export const createOpenVsxThemeService = ({
710
+ fetchImpl = fetch,
711
+ } = {}) => {
712
+ const request = createRequester(fetchImpl)
713
+
714
+ /**
715
+ * @param {string} query
716
+ * @returns {Promise<OpenVsxThemeSearchResult>}
717
+ */
718
+ const search = async (query) => {
719
+ const searchText = query.trim()
720
+ if (searchText.length > 100) {
721
+ return { status: 'error', message: 'Search terms must be 100 characters or fewer.' }
722
+ }
723
+ try {
724
+ const url = new URL(OPEN_VSX_SEARCH_URL)
725
+ if (searchText) url.searchParams.set('query', searchText)
726
+ url.searchParams.set('category', 'Themes')
727
+ url.searchParams.set('sortBy', 'downloadCount')
728
+ url.searchParams.set('sortOrder', 'desc')
729
+ url.searchParams.set('size', '12')
730
+ const bytes = await request({
731
+ url,
732
+ limit: MAX_SEARCH_BYTES,
733
+ failureMessage: 'Open VSX search is unavailable right now.',
734
+ tooLargeMessage: 'Open VSX returned an unexpectedly large search response.',
735
+ })
736
+ /** @type {unknown} */
737
+ const payload = JSON.parse(new TextDecoder().decode(bytes))
738
+ if (!isRecord(payload) || !Array.isArray(payload.extensions)) throw new Error('invalid response')
739
+ const candidates = payload.extensions.flatMap(candidate => {
740
+ const summary = searchSummary(candidate)
741
+ return summary && isLikelyColorTheme(summary) ? [summary] : []
742
+ }).slice(0, 12)
743
+ return { status: 'success', themes: candidates }
744
+ } catch {
745
+ return { status: 'error', message: 'Open VSX search is unavailable right now.' }
746
+ }
747
+ }
748
+
749
+ /**
750
+ * @param {string} extensionId
751
+ * @param {PreferredAppearance} preferredAppearance
752
+ * @returns {Promise<ThemeImportResult>}
753
+ */
754
+ const importTheme = async (
755
+ extensionId,
756
+ preferredAppearance,
757
+ ) => {
758
+ try {
759
+ const location = await getPackageLocation({ request, extensionId })
760
+ await validateAdvertisedThemes({ request, manifestUrl: location.manifestUrl })
761
+ const packageBytes = await downloadVerifiedPackage({ request, ...location })
762
+ const readText = await openPackage(packageBytes)
763
+ const manifest = await readMatchingManifest({
764
+ readText,
765
+ extensionId,
766
+ version: location.version,
767
+ })
768
+ const themes = await parseContributedThemes({
769
+ readText,
770
+ manifest,
771
+ fallbackName: location.extensionName,
772
+ })
773
+ return { status: 'success', theme: selectTheme(themes, preferredAppearance) }
774
+ } catch (error) {
775
+ if (error instanceof ThemeValidationError || error instanceof OpenVsxThemeError) {
776
+ return { status: 'error', error: { code: error.code, message: error.message } }
777
+ }
778
+ return {
779
+ status: 'error',
780
+ error: {
781
+ code: 'open-vsx-unavailable',
782
+ message: 'Could not import that Open VSX theme.',
783
+ },
784
+ }
785
+ }
786
+ }
787
+
788
+ return { search, importTheme }
789
+ }
@@ -0,0 +1,48 @@
1
+ export { createOpenVsxThemeService } from "./client.js";
2
+ export type VsCodeTheme = import("./parse.js").VsCodeTheme;
3
+ export type ThemeValidationErrorCode = import("./parse.js").ThemeValidationErrorCode;
4
+ export type ThemeImportErrorCode = ThemeValidationErrorCode | "file-too-large" | "integrity-failed" | "open-vsx-unavailable" | "unsupported-extension";
5
+ export type ThemeImportResult = {
6
+ status: "success";
7
+ theme: VsCodeTheme;
8
+ } | {
9
+ status: "error";
10
+ error: {
11
+ code: ThemeImportErrorCode;
12
+ message: string;
13
+ };
14
+ };
15
+ export type OpenVsxThemeSummary = {
16
+ /**
17
+ * Publisher and extension name, separated by a dot.
18
+ */
19
+ id: string;
20
+ name: string;
21
+ publisher: string;
22
+ description: string;
23
+ downloadCount: number;
24
+ };
25
+ export type OpenVsxThemeSearchResult = {
26
+ status: "success";
27
+ themes: OpenVsxThemeSummary[];
28
+ } | {
29
+ status: "error";
30
+ message: string;
31
+ };
32
+ export type OpenVsxThemeServiceDependencies = {
33
+ /**
34
+ * Defaults to global fetch; inject for other runtimes or offline tests.
35
+ */
36
+ fetchImpl?: typeof fetch | undefined;
37
+ };
38
+ export type OpenVsxThemeService = {
39
+ /**
40
+ * Blank queries list popular themes.
41
+ */
42
+ search: (query: string) => Promise<OpenVsxThemeSearchResult>;
43
+ /**
44
+ * Imports the first theme matching the preferred type, or the first contribution when no type matches.
45
+ */
46
+ importTheme: (extensionId: string, preferredAppearance: "light" | "dark") => Promise<ThemeImportResult>;
47
+ };
48
+ export { ThemeValidationError, parseVsCodeTheme } from "./parse.js";
@@ -0,0 +1,28 @@
1
+ // @filipgutica/design-system/open-vsx: resolved VS Code theme files and an Open VSX client.
2
+ // Experimental: the API may change in a minor release. No framework or colour mapping.
3
+ export { ThemeValidationError, parseVsCodeTheme } from './parse.js'
4
+ export { createOpenVsxThemeService } from './client.js'
5
+
6
+ /** @typedef {import('./parse.js').VsCodeTheme} VsCodeTheme */
7
+ /** @typedef {import('./parse.js').ThemeValidationErrorCode} ThemeValidationErrorCode */
8
+ /** @typedef {ThemeValidationErrorCode | 'file-too-large' | 'integrity-failed' | 'open-vsx-unavailable' | 'unsupported-extension'} ThemeImportErrorCode */
9
+ /** @typedef {{ status: 'success', theme: VsCodeTheme } | { status: 'error', error: { code: ThemeImportErrorCode, message: string } }} ThemeImportResult */
10
+ /**
11
+ * @typedef {object} OpenVsxThemeSummary
12
+ * @property {string} id Publisher and extension name, separated by a dot.
13
+ * @property {string} name
14
+ * @property {string} publisher
15
+ * @property {string} description
16
+ * @property {number} downloadCount
17
+ */
18
+ /** @typedef {{ status: 'success', themes: OpenVsxThemeSummary[] } | { status: 'error', message: string }} OpenVsxThemeSearchResult */
19
+ /**
20
+ * @typedef {object} OpenVsxThemeServiceDependencies
21
+ * @property {typeof fetch} [fetchImpl] Defaults to global fetch; inject for other runtimes or offline tests.
22
+ */
23
+ /**
24
+ * @typedef {object} OpenVsxThemeService
25
+ * @property {(query: string) => Promise<OpenVsxThemeSearchResult>} search Blank queries list popular themes.
26
+ * @property {(extensionId: string, preferredAppearance: 'light' | 'dark') => Promise<ThemeImportResult>} importTheme
27
+ * Imports the first theme matching the preferred type, or the first contribution when no type matches.
28
+ */
@@ -0,0 +1,45 @@
1
+ /** @typedef {'malformed-json' | 'invalid-shape'} ThemeValidationErrorCode */
2
+ /**
3
+ * A resolved VS Code theme, ready for `mapVsCodeTheme`. Colours and syntax rules are kept as supplied.
4
+ * @typedef {object} VsCodeTheme
5
+ * @property {string} name Normalised theme name, with the file name as a fallback.
6
+ * @property {string} [type] `light`, `dark`, `hc`, or `hcLight` when supplied by the file or manifest.
7
+ * @property {Record<string, unknown>} colors Workbench colours; validation and mapping belong to the mapper.
8
+ * @property {unknown} [tokenColors] Syntax rules as supplied; include arrays concatenate base first, child last.
9
+ */
10
+ /** A theme file that cannot be parsed, before any colour mapping. */
11
+ export class ThemeValidationError extends Error {
12
+ /**
13
+ * @param {ThemeValidationErrorCode} code
14
+ * @param {string} message
15
+ */
16
+ constructor(code: ThemeValidationErrorCode, message: string);
17
+ code: ThemeValidationErrorCode;
18
+ }
19
+ export function isRecord(value: unknown): value is Record<string, unknown>;
20
+ export function parseVsCodeTheme({ source, fileName }: {
21
+ source: string;
22
+ fileName: string;
23
+ }): VsCodeTheme;
24
+ export type ThemeValidationErrorCode = "malformed-json" | "invalid-shape";
25
+ /**
26
+ * A resolved VS Code theme, ready for `mapVsCodeTheme`. Colours and syntax rules are kept as supplied.
27
+ */
28
+ export type VsCodeTheme = {
29
+ /**
30
+ * Normalised theme name, with the file name as a fallback.
31
+ */
32
+ name: string;
33
+ /**
34
+ * `light`, `dark`, `hc`, or `hcLight` when supplied by the file or manifest.
35
+ */
36
+ type?: string | undefined;
37
+ /**
38
+ * Workbench colours; validation and mapping belong to the mapper.
39
+ */
40
+ colors: Record<string, unknown>;
41
+ /**
42
+ * Syntax rules as supplied; include arrays concatenate base first, child last.
43
+ */
44
+ tokenColors?: unknown;
45
+ };
@@ -0,0 +1,64 @@
1
+ import { parse, printParseErrorCode } from 'jsonc-parser'
2
+
3
+ /** @typedef {'malformed-json' | 'invalid-shape'} ThemeValidationErrorCode */
4
+ /**
5
+ * A resolved VS Code theme, ready for `mapVsCodeTheme`. Colours and syntax rules are kept as supplied.
6
+ * @typedef {object} VsCodeTheme
7
+ * @property {string} name Normalised theme name, with the file name as a fallback.
8
+ * @property {string} [type] `light`, `dark`, `hc`, or `hcLight` when supplied by the file or manifest.
9
+ * @property {Record<string, unknown>} colors Workbench colours; validation and mapping belong to the mapper.
10
+ * @property {unknown} [tokenColors] Syntax rules as supplied; include arrays concatenate base first, child last.
11
+ */
12
+
13
+ /** A theme file that cannot be parsed, before any colour mapping. */
14
+ export class ThemeValidationError extends Error {
15
+ /**
16
+ * @param {ThemeValidationErrorCode} code
17
+ * @param {string} message
18
+ */
19
+ constructor(code, message) {
20
+ super(message)
21
+ this.name = 'ThemeValidationError'
22
+ this.code = code
23
+ }
24
+ }
25
+
26
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
27
+ export const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value)
28
+
29
+ /** @param {string} fileName */
30
+ const themeNameFromFile = (fileName) => {
31
+ const baseName = fileName.split(/[\\/]/).at(-1) ?? 'Imported theme'
32
+ return (baseName.replace(/\.jsonc?$/i, '') || 'Imported theme').slice(0, 80)
33
+ }
34
+
35
+ /**
36
+ * Parses one JSONC theme file. Resolve package `include` chains with the Open VSX client first.
37
+ * @param {{ source: string, fileName: string }} options
38
+ * @returns {VsCodeTheme}
39
+ * @throws {ThemeValidationError} `malformed-json` includes a location; `invalid-shape` describes the field.
40
+ */
41
+ export const parseVsCodeTheme = ({ source, fileName }) => {
42
+ /** @type {import('jsonc-parser').ParseError[]} */
43
+ const errors = []
44
+ /** @type {unknown} */
45
+ const parsed = parse(source, errors, { allowTrailingComma: true })
46
+ const firstError = errors[0]
47
+ if (firstError) {
48
+ const lines = source.slice(0, firstError.offset).split('\n')
49
+ const line = lines.length
50
+ const column = (lines.at(-1)?.length ?? 0) + 1
51
+ throw new ThemeValidationError('malformed-json', `The theme could not be parsed (${printParseErrorCode(firstError.error)} at line ${line}, column ${column}).`)
52
+ }
53
+ if (!isRecord(parsed)) throw new ThemeValidationError('invalid-shape', 'The theme file must contain a JSON object.')
54
+ if (parsed.name !== undefined && typeof parsed.name !== 'string') {
55
+ throw new ThemeValidationError('invalid-shape', 'The theme name must be a string when provided.')
56
+ }
57
+ if (!isRecord(parsed.colors)) throw new ThemeValidationError('invalid-shape', 'The theme must contain a "colors" object.')
58
+ return {
59
+ name: parsed.name?.trim().replace(/\s+/g, ' ').slice(0, 80) || themeNameFromFile(fileName),
60
+ ...(typeof parsed.type === 'string' ? { type: parsed.type } : {}),
61
+ colors: parsed.colors,
62
+ ...(parsed.tokenColors !== undefined ? { tokenColors: parsed.tokenColors } : {}),
63
+ }
64
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@filipgutica/design-system",
3
- "version": "1.0.17",
3
+ "version": "1.0.18",
4
4
  "description": "Filip's design language, tokens, and component catalogue for any framework",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -19,6 +19,10 @@
19
19
  "types": "./theme-mapper/index.d.ts",
20
20
  "default": "./theme-mapper/index.js"
21
21
  },
22
+ "./open-vsx": {
23
+ "types": "./open-vsx/index.d.ts",
24
+ "default": "./open-vsx/index.js"
25
+ },
22
26
  "./fonts.css": "./fonts/fonts.css",
23
27
  "./fonts/*": "./fonts/*",
24
28
  "./language/*": "./language/*",
@@ -28,7 +32,8 @@
28
32
  "language/",
29
33
  "dist/",
30
34
  "fonts/",
31
- "theme-mapper/"
35
+ "theme-mapper/",
36
+ "open-vsx/"
32
37
  ],
33
38
  "scripts": {
34
39
  "prepublishOnly": "pnpm verify",
@@ -66,15 +71,20 @@
66
71
  "@commitlint/config-conventional": "^21.2.2",
67
72
  "@playwright/test": "^1.65.0",
68
73
  "@semantic-release/commit-analyzer": "13.0.1",
74
+ "@types/node": "^24.19.2",
69
75
  "@types/react": "^19.3.0",
70
76
  "@types/react-dom": "^19.3.0",
71
77
  "@vitejs/plugin-react": "^6.2.1",
72
78
  "conventional-changelog-conventionalcommits": "^9.3.1",
79
+ "jszip": "3.10.1",
73
80
  "publint": "^0.3.24",
74
81
  "react": "^19.3.1",
75
82
  "react-dom": "^19.3.1",
76
83
  "semantic-release": "^25.0.9",
77
84
  "typescript": "^5.9.3",
78
85
  "vite": "^8.3.6"
86
+ },
87
+ "dependencies": {
88
+ "jsonc-parser": "3.3.1"
79
89
  }
80
90
  }