@milesroxas/design-hub 0.8.0 → 0.9.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 (64) hide show
  1. package/README.md +7 -2
  2. package/core/prototype.test.ts +83 -0
  3. package/core/prototype.ts +84 -0
  4. package/core/review/model.ts +20 -2
  5. package/core/review/policy.test.ts +4 -2
  6. package/core/review/policy.ts +4 -2
  7. package/core/review/service.test.ts +200 -16
  8. package/core/review/service.ts +91 -5
  9. package/core/review/store.ts +10 -1
  10. package/dist/core/prototype.d.ts +35 -0
  11. package/dist/core/prototype.js +84 -0
  12. package/dist/core/review/model.d.ts +13 -2
  13. package/dist/core/review/model.js +13 -0
  14. package/dist/core/review/policy.d.ts +1 -1
  15. package/dist/core/review/policy.js +1 -0
  16. package/dist/core/review/service.d.ts +24 -2
  17. package/dist/core/review/service.js +81 -6
  18. package/dist/core/review/store.d.ts +10 -1
  19. package/dist/core/review/store.js +10 -1
  20. package/dist/scripts/comments.js +4 -3
  21. package/dist/scripts/lib/cdp.js +6 -1
  22. package/dist/scripts/lib/export-smoke.d.ts +18 -0
  23. package/dist/scripts/lib/export-smoke.js +73 -0
  24. package/dist/scripts/new.js +5 -2
  25. package/dist/scripts/release-check.d.ts +5 -3
  26. package/dist/scripts/release-check.js +17 -4
  27. package/dist/scripts/share.d.ts +2 -2
  28. package/dist/server/api.js +8 -0
  29. package/dist/server/session.d.ts +5 -1
  30. package/dist/server/session.js +39 -21
  31. package/dist/vercel/proxy.js +44 -8
  32. package/dist/vite/boundary.d.ts +93 -0
  33. package/dist/vite/boundary.js +218 -0
  34. package/dist/vite/css-boundary.d.ts +39 -0
  35. package/dist/vite/css-boundary.js +167 -0
  36. package/dist/vite/kit.js +15 -6
  37. package/dist/vite/leaks.d.ts +37 -0
  38. package/dist/vite/leaks.js +331 -0
  39. package/dist/vite/plugin.js +2 -1
  40. package/dist/vite/registry.d.ts +15 -4
  41. package/dist/vite/registry.js +531 -27
  42. package/dist/vite/settle.d.ts +27 -0
  43. package/dist/vite/settle.js +185 -0
  44. package/package.json +4 -3
  45. package/shell/ClientViewNote.tsx +18 -0
  46. package/shell/Guide.tsx +17 -2
  47. package/shell/Index.tsx +257 -25
  48. package/shell/audience.test.ts +63 -0
  49. package/shell/audience.ts +47 -0
  50. package/shell/hub.ts +36 -0
  51. package/shell/main.tsx +39 -5
  52. package/shell/registry.ts +28 -7
  53. package/shell/registry.virtual.d.ts +12 -4
  54. package/shell/review/Pins.tsx +8 -6
  55. package/shell/review/Review.tsx +8 -4
  56. package/shell/review/ThreadCard.tsx +6 -14
  57. package/shell/review/client.ts +16 -4
  58. package/shell/review/review.css +37 -24
  59. package/shell/shell.css +50 -3
  60. package/shell/system.css +5 -0
  61. package/skills/miles-deploy/SKILL.md +17 -0
  62. package/skills/miles-new-feature/SKILL.md +1 -1
  63. package/skills/miles-prototype/SKILL.md +14 -1
  64. package/skills/miles-review/SKILL.md +1 -1
@@ -0,0 +1,218 @@
1
+ /// <reference types="node" />
2
+ // The prototype boundary as the build sees it. A built file is owned by where
3
+ // its content comes from, never by who reads it:
4
+ //
5
+ // - owned only by prototype `a` (its modules, or for a stylesheet the
6
+ // modules whose CSS it holds): it lives in `_p/a/`, and only `a`'s files read it;
7
+ // - owned by nothing under `prototypes/` (the hub, the kit, node_modules): it
8
+ // lives in `assets/` and is never copied into a prototype's folder;
9
+ // - the same bytes from several owners (Rolldown writes them once): one copy
10
+ // per owner, each owner's files pointed at its own.
11
+ //
12
+ // A file that reads what another prototype owns, or a hub file that reads
13
+ // what a prototype owns, fails the build. These are the pure rules;
14
+ // vite/registry.ts and vite/settle.ts apply them to the modules and bundle
15
+ // Rolldown hands them.
16
+ import { realpathSync } from 'node:fs';
17
+ import nodePath, { extname, posix, resolve } from 'node:path';
18
+ import { parseSync, Visitor } from 'vite';
19
+ import { ALL_FILE, PROTOTYPE_DIR } from '../core/prototype.js';
20
+ /** The virtual module Studio and a Client load a prototype through: its README and its loader. */
21
+ export const ENTRY_ID = 'virtual:design-hub/entry/';
22
+ const realCache = new Map();
23
+ /**
24
+ * A path with every symlink followed and in the letter case it has on disk,
25
+ * or the path itself when it is not a file on disk (a virtual module). The
26
+ * native call, because Node's own keeps the case as written: on a disk that
27
+ * folds case (macOS, Windows) `Prototypes/beta/x.css` is `prototypes/beta/x.css`,
28
+ * and an owner must be the same either way.
29
+ */
30
+ export const real = (path) => {
31
+ let found = realCache.get(path);
32
+ if (found === undefined) {
33
+ try {
34
+ found = realpathSync.native(path);
35
+ }
36
+ catch {
37
+ found = path;
38
+ }
39
+ realCache.set(path, found);
40
+ }
41
+ return found;
42
+ };
43
+ /** A module id as a file path: no leading `\0`, no `?query`. */
44
+ const fileOf = (id) => id.replace(/^\0/, '').replace(/\?.*$/, '');
45
+ /**
46
+ * Which prototype folder a module or file belongs to, on its real path (a
47
+ * symlink into another prototype's folder is that prototype's): the first
48
+ * segment under `prototypes/`, whatever its name (a file directly there is
49
+ * owned by its own name, so nothing under `prototypes/` is ever the hub's),
50
+ * or null for anything outside it. A prototype's virtual entry belongs to its
51
+ * slug. Whether that owner is a prototype at all is for the caller: a folder
52
+ * with no README, or a file directly in `prototypes/`, is refused (looseFile).
53
+ */
54
+ export function ownerOf(prototypes, paths = nodePath) {
55
+ const roots = [...new Set([prototypes, real(prototypes)])];
56
+ return (id) => {
57
+ const path = real(fileOf(id));
58
+ if (path.startsWith(ENTRY_ID))
59
+ return path.slice(ENTRY_ID.length) || null;
60
+ if (!paths.isAbsolute(path))
61
+ return null;
62
+ // By the platform's path rules, so a Windows path (backslashes from realpath, `/` from Vite) is judged as a POSIX one.
63
+ for (const root of roots) {
64
+ const rest = paths.relative(root, path);
65
+ if (rest === '..' || rest.startsWith(`..${paths.sep}`) || paths.isAbsolute(rest))
66
+ continue;
67
+ // A file directly in prototypes/ is owned by its own name: nothing there is the hub's.
68
+ return rest.split(paths.sep)[0] || null;
69
+ }
70
+ return null;
71
+ };
72
+ }
73
+ /** The owners of a set of modules or files, each once, sorted; none for shared code. */
74
+ export function ownersOf(owner, ids) {
75
+ return [...new Set(ids.map(owner).filter((o) => o !== null))].sort();
76
+ }
77
+ /** Where a built file goes: under `_p/<slug>/` when one prototype owns it, else the shared `assets/`. */
78
+ export function placed(owners, pattern, shared = false) {
79
+ return owners.length === 1 && !shared ? `${PROTOTYPE_DIR}/${owners[0]}/${pattern}` : `assets/${pattern}`;
80
+ }
81
+ /** A file resolved against the Vite root: Rolldown reports an asset's original files relative to it. */
82
+ export const fromRoot = (viteRoot) => (file) => resolve(viteRoot, file);
83
+ /** A path for an error message: from the project root, with no `\0` or query. */
84
+ export const relativeTo = (root, path) => fileOf(path)
85
+ .replace(`${real(root)}/`, '')
86
+ .replace(`${root}/`, '');
87
+ /** The error for a file reaching a prototype's file, naming both: another prototype's, or (from the kit or the hub) any prototype's. */
88
+ export function crossImport(root, importer, imported, fromPrototype = true) {
89
+ const whose = fromPrototype
90
+ ? "another prototype's file"
91
+ : "a prototype's file, which the kit and the hub never read";
92
+ return `${relativeTo(root, importer)} imports ${relativeTo(root, imported)}, ${whose}. A prototype imports only @kit/* and its own folder: copy the file into this prototype, or move it into kit/.`;
93
+ }
94
+ /** Files the build names on purpose: never moved, copied, renamed or read for references. */
95
+ export const isFixed = (fileName) => fileName === ALL_FILE ||
96
+ !fileName.includes('/') ||
97
+ fileName.startsWith('_gate/') ||
98
+ (fileName.startsWith(`${PROTOTYPE_DIR}/`) && fileName.endsWith('/entry.js'));
99
+ const folderOf = (owner) => (owner === null ? 'assets' : `${PROTOTYPE_DIR}/${owner}`);
100
+ const HASH_TAIL = /-[\w-]{8}$/;
101
+ /** A built name without its hash: `logo-Fji5aE1.png` is `logo`. */
102
+ const stemOf = (base) => posix.basename(base, extname(base)).replace(HASH_TAIL, '');
103
+ /** What Rolldown makes of a name: the characters a URL or a file system would trip on become `_`. */
104
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the control characters are what it replaces
105
+ const sanitize = (name) => name.replace(/[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g, '_');
106
+ /**
107
+ * The name one owner's copy takes. The built name, which Rolldown has
108
+ * already made safe, while every source of the file, and the chunk that
109
+ * wrote it, is that owner's; else from that owner's own source (file or CSS
110
+ * module), made safe the same way. So a copy never carries a name from
111
+ * another owner's file: not another prototype's, and in `assets/` never a
112
+ * prototype's at all.
113
+ */
114
+ function nameFor(base, owner, sources, slugs, hash) {
115
+ const ext = extname(base);
116
+ const elsewhere = sources.some((s) => s.owner !== owner || (s.writer !== undefined && s.writer !== owner));
117
+ const foreign = slugs.some((s) => s !== owner && stemOf(base).includes(s));
118
+ if (!elsewhere && !foreign)
119
+ return base;
120
+ const own = sources.find((s) => s.owner === owner);
121
+ const stem = own ? sanitize(posix.basename(own.file, extname(own.file))) : (owner ?? 'asset');
122
+ return stemOf(base) === stem ? base : `${stem}-${hash}${ext}`;
123
+ }
124
+ /**
125
+ * Where an asset must be, one file per owner of its content: `_p/<slug>/`
126
+ * for a prototype, `assets/` for the hub or the kit. Null when it is already
127
+ * there or nothing shows where its content comes from.
128
+ */
129
+ export function placementsOf(fileName, sources, slugs, hash) {
130
+ if (!sources?.length || isFixed(fileName))
131
+ return null;
132
+ const owners = [...new Set(sources.map((s) => s.owner))].sort((a, b) => String(a).localeCompare(String(b)));
133
+ const base = posix.basename(fileName);
134
+ const places = owners.map((owner) => ({
135
+ owner,
136
+ fileName: `${folderOf(owner)}/${nameFor(base, owner, sources, slugs, hash)}`,
137
+ }));
138
+ return places.length === 1 && places[0].fileName === fileName ? null : places;
139
+ }
140
+ /**
141
+ * What a reader gets for a file it reads: its own owner's copy, else the
142
+ * hub's (anyone may read the kit), else nothing, which the build refuses.
143
+ */
144
+ export function copyFor(places, reader) {
145
+ return places.find((p) => p.owner === reader) ?? places.find((p) => p.owner === null) ?? null;
146
+ }
147
+ /** The error for a file that reads what another prototype owns, naming reader and source. */
148
+ export const readsAcross = (reader, source) => `${reader} reads ${source.file}, which belongs to prototypes/${source.owner}/. A prototype's files are read only by that prototype: copy the file into the one that reads it, or move it into kit/.`;
149
+ /** The error for a reach into `prototypes/` outside any prototype's folder. */
150
+ export const looseFile = (root, importer, file) => `${relativeTo(root, importer)} imports ${relativeTo(root, file)}, which is in prototypes/ but in no prototype's folder. Nothing in prototypes/ is shared: shared code belongs in kit/.`;
151
+ /** A stylesheet language whose own `@import` and `@use` resolve inside its preprocessor. */
152
+ export const PREPROCESSED = /\.(scss|sass|less|styl|stylus)$/;
153
+ /** The error for a prototype or the project's kit/ importing Sass, Less or Stylus. */
154
+ export const preprocessed = (root, importer, file) => `${relativeTo(root, importer)} imports ${relativeTo(root, file)}. Sass, Less and Stylus are refused in prototypes and kit/: they resolve their own @import and @use inside the preprocessor, where the build cannot check them for reaches into a prototype's folder. Use plain CSS or .pcss.`;
155
+ /** The error for a stylesheet the build cannot read. */
156
+ export const unreadable = (root, file, line, column, reason) => `${relativeTo(root, file)}:${line}:${column}: this stylesheet does not parse (${reason}). Fix the stylesheet: the build reads every stylesheet for reaches into a prototype's folder and refuses one it cannot read.`;
157
+ /** The path a `new URL(…)` argument names, when it is a literal: a string, or a template with no `${…}`. */
158
+ function literalPath(arg) {
159
+ if (arg.type === 'Literal' && typeof arg.value === 'string')
160
+ return arg.value;
161
+ if (arg.type === 'TemplateLiteral' && !arg.expressions?.length)
162
+ return arg.quasis?.[0]?.value.cooked ?? null;
163
+ return null;
164
+ }
165
+ const isImportMetaUrl = (arg) => arg?.type === 'MemberExpression' && arg.object?.type === 'MetaProperty' && arg.property?.name === 'url';
166
+ /**
167
+ * The paths a module names with `new URL('…', import.meta.url)`, found with
168
+ * the parser Vite itself uses (oxc, through `parseSync`), on the code Vite's
169
+ * own `new URL` plugin sees: TypeScript and JSX already compiled. So a quote
170
+ * in a regex literal, in JSX text, in a string or in a comment never hides
171
+ * one or fakes one. A template with `${…}` becomes an import.meta.glob, which
172
+ * the resolver sees; a data URL and one marked `@vite-ignore` are skipped, as
173
+ * Vite skips them. The query stays: `?inline` is a reach too. Null when the
174
+ * code does not parse (Vite then reports the error itself).
175
+ */
176
+ export function newUrlTargets(code, file) {
177
+ const parsed = parseSync(`${file.replace(/\?.*$/, '')}.js`, code, { lang: 'js', sourceType: 'module' });
178
+ if (parsed.errors.length)
179
+ return null;
180
+ const found = [];
181
+ new Visitor({
182
+ NewExpression(node) {
183
+ const callee = node.callee;
184
+ const [url, base] = node.arguments;
185
+ if (callee.type !== 'Identifier' || callee.name !== 'URL' || !url || !isImportMetaUrl(base))
186
+ return;
187
+ const ignored = parsed.comments.some((c) => c.start >= node.start && c.end <= url.start && c.value.includes('@vite-ignore'));
188
+ const path = literalPath(url);
189
+ if (path !== null && !ignored && !path.startsWith('data:'))
190
+ found.push(path);
191
+ },
192
+ }).visit(parsed.program);
193
+ return found;
194
+ }
195
+ /** The error for a built file with no record of where its content comes from. */
196
+ export const unrecorded = (fileName) => `${fileName} was written with no record of where its content comes from, so the build cannot tell who may read it. Only the hub's fixed files and a worker built from the kit may be written that way.`;
197
+ /** The error for a worker that reaches a prototype's folder. */
198
+ export const workerRefused = (root, file) => `${relativeTo(root, file)} is in a web worker. A worker cannot use a prototype's files: Vite builds it as a file of its own that the build cannot place in the prototype's folder. Run the work on the main thread, or build the worker from kit/ files only.`;
199
+ /**
200
+ * A file's text with every reference to `from` pointed at `to`: the whole
201
+ * path, and the path relative to the referring file when that differs.
202
+ */
203
+ export function repointText(text, referrer, from, to) {
204
+ let out = text.split(from).join(to);
205
+ const rel = posix.relative(posix.dirname(referrer), from);
206
+ if (rel.includes('/') && rel !== from)
207
+ out = out.split(rel).join(posix.relative(posix.dirname(referrer), to));
208
+ return out;
209
+ }
210
+ /** A chunk where its modules say: `_p/<slug>/` for one prototype's, never two. */
211
+ export function chunkProblems(fileName, owners) {
212
+ if (owners.length > 1)
213
+ return [`${fileName} holds files of ${owners.map((o) => `prototypes/${o}/`).join(' and ')}`];
214
+ const [slug] = owners;
215
+ return slug && !fileName.startsWith(`${PROTOTYPE_DIR}/${slug}/`)
216
+ ? [`${fileName} holds files of prototypes/${slug}/ but is not under ${PROTOTYPE_DIR}/${slug}/`]
217
+ : [];
218
+ }
@@ -0,0 +1,39 @@
1
+ import { type ChildNode, type PluginCreator } from 'postcss';
2
+ type Owner = (id: string) => string | null;
3
+ /** The references in a declaration's value, unescaped: `url()` and the strings in `image-set()`. */
4
+ export declare function valueRefs(value: string): string[];
5
+ /**
6
+ * Vite's own resolvers, as its CSS plugin builds them from the resolved
7
+ * config (`config.createResolver`: `resolve.alias` and Vite's node
8
+ * resolution): `url` for `url()` and `image-set()`, `css` for `@import`,
9
+ * `composes`, `@value` and `:import`. Each gives a file, or undefined.
10
+ */
11
+ export type CssResolvers = {
12
+ url: (id: string, importer: string) => Promise<string | undefined>;
13
+ css: (id: string, importer: string) => Promise<string | undefined>;
14
+ };
15
+ /** The file `@import` names, quoted or as `url()`. */
16
+ export declare const importRef: (params: string) => string;
17
+ /**
18
+ * A reference as a file on disk, or null: relative to the file that makes
19
+ * it, or an absolute path that exists (a `/` path that does not is the
20
+ * public folder's).
21
+ */
22
+ export declare function fileOfRef(ref: string, from: string): string | null;
23
+ /** The file a CSS modules node names: `composes … from`, `@value … from`, or `:import("…")`. */
24
+ export declare function moduleRef(node: ChildNode): string | undefined;
25
+ /**
26
+ * Every file a CSS module's chain reaches, read from disk, each once:
27
+ * `composes … from`, `@value … from` and `:import("…")`, through every module
28
+ * they name. postcss-modules resolves these before any other plugin sees the
29
+ * sheet, so they are followed here.
30
+ */
31
+ export declare function modulesChain(file: string, resolve?: CssResolvers['css'], seen?: Set<string>): Promise<string[]>;
32
+ /**
33
+ * The postcss plugin: for the stylesheet being compiled (the root), a node
34
+ * inlined from another owner's file, or a reference into a prototype the
35
+ * root's owner is not, throws the error that names both files. The kit and
36
+ * the hub own no prototype, so they may reach none.
37
+ */
38
+ export declare function cssBoundary(project: string, owner: Owner, isPrototype: (owner: string) => boolean, resolvers: () => CssResolvers | null): PluginCreator<never>;
39
+ export {};
@@ -0,0 +1,167 @@
1
+ /// <reference types="node" />
2
+ // The prototype boundary inside a stylesheet. `@import` and `composes`
3
+ // inline another file's CSS, which leaves no built file behind for the
4
+ // end-of-build check (vite/settle.ts) to see, and Vite resolves `url()`
5
+ // itself. So the plugin adds this to Vite's own postcss run, where it sees
6
+ // every stylesheet whoever owns it (a prototype's, the kit's, the hub's), in
7
+ // dev and in a build, after `@import` is inlined: each node still carries the
8
+ // file it came from, at any depth. Owners are decided on real paths, so a
9
+ // symlink into another prototype's folder is that prototype's.
10
+ //
11
+ // Only values that are references count: `@import`, `url()`, the strings in
12
+ // `image-set()`, and in a CSS module `composes … from`, `@value … from` and `:import("…")`. A string in `content:` is text.
13
+ // Comments never count: postcss keeps them apart. Each reference is followed
14
+ // as a path and as Vite resolves it (vite/registry.ts hands over Vite's own
15
+ // resolvers), so an alias or a package path into a prototype's folder counts.
16
+ import { existsSync, readFileSync } from 'node:fs';
17
+ import { dirname, resolve } from 'node:path';
18
+ import postcss, {} from 'postcss';
19
+ import { crossImport, looseFile, real } from './boundary.js';
20
+ const URL_REF = /url\(\s*(["']?)([^"')]*?)\1\s*\)/g;
21
+ const IMAGE_SET = /(?:-webkit-)?image-set\(([^;]*)\)/g;
22
+ const STRING = /(["'])((?:\\.|(?!\1)[^\\])*)\1/g;
23
+ const FROM = /\bfrom\s+(["'])([^"']+)\1/;
24
+ const IMPORT_SELECTOR = /:import\(\s*(["']?)([^"')]+)\1\s*\)/;
25
+ /** Data, remote and fragment references name no file. */
26
+ const isRef = (ref) => ref !== '' && !/^(#|[a-z][\w+.-]*:)/i.test(ref);
27
+ /** Nor, read as a path, do aliases and package paths: those are the resolver's. */
28
+ const isFile = (ref) => isRef(ref) && !/^[~@]/.test(ref);
29
+ /**
30
+ * A reference unescaped as Vite unescapes it before resolving (`doUrlReplace`
31
+ * in `vite:css`, which Vite does not export): a backslash before any
32
+ * character that is not a letter, digit or `_` is dropped, so
33
+ * `..\/beta\/x.png` is `../beta/x.png`. A hex escape (`\2f`) Vite leaves as
34
+ * written, and so does this: Vite then names no such file.
35
+ */
36
+ const unescaped = (ref) => ref.replace(/\\(\W)/g, '$1');
37
+ /** The references in a declaration's value, unescaped: `url()` and the strings in `image-set()`. */
38
+ export function valueRefs(value) {
39
+ const urls = [...value.matchAll(URL_REF)].map((m) => m[2]);
40
+ const sets = [...value.matchAll(IMAGE_SET)].flatMap((m) => [...m[1].matchAll(STRING)].map((s) => s[2]));
41
+ return [...urls, ...sets].map(unescaped).filter(isRef);
42
+ }
43
+ /** A URL as Vite reads it before resolving: decoded when it decodes, without its fragment. */
44
+ const asVite = (ref) => {
45
+ let decoded = ref;
46
+ try {
47
+ decoded = decodeURI(ref);
48
+ }
49
+ catch { }
50
+ return decoded.split('#')[0];
51
+ };
52
+ /**
53
+ * Every file a reference may name: as a path beside its stylesheet (or an
54
+ * absolute path that exists), and as Vite resolves it, aliases and package
55
+ * paths included. Both count, so neither spelling gets round the other.
56
+ */
57
+ async function targetsOf(ref, from, resolve) {
58
+ const found = [];
59
+ const file = fileOfRef(ref, from);
60
+ if (file)
61
+ found.push(file);
62
+ const resolved = resolve && isRef(ref) ? await resolve(asVite(ref), from) : undefined;
63
+ if (resolved)
64
+ found.push(resolved.replace(/[?#].*$/, ''));
65
+ return found;
66
+ }
67
+ /** The file `@import` names, quoted or as `url()`. */
68
+ export const importRef = (params) => [...valueRefs(params), ...[...params.matchAll(STRING)].map((m) => m[2])][0];
69
+ /**
70
+ * A reference as a file on disk, or null: relative to the file that makes
71
+ * it, or an absolute path that exists (a `/` path that does not is the
72
+ * public folder's).
73
+ */
74
+ export function fileOfRef(ref, from) {
75
+ const path = ref.split(/[?#]/)[0];
76
+ if (!isFile(path))
77
+ return null;
78
+ if (path.startsWith('/'))
79
+ return existsSync(path) ? path : null;
80
+ return resolve(dirname(from), path);
81
+ }
82
+ /** The file a CSS modules node names: `composes … from`, `@value … from`, or `:import("…")`. */
83
+ export function moduleRef(node) {
84
+ if (node.type === 'decl' && node.prop === 'composes')
85
+ return node.value.match(FROM)?.[2];
86
+ if (node.type === 'atrule' && node.name === 'value')
87
+ return node.params.match(FROM)?.[2];
88
+ if (node.type === 'rule')
89
+ return node.selector.match(IMPORT_SELECTOR)?.[2];
90
+ return undefined;
91
+ }
92
+ /**
93
+ * Every file a CSS module's chain reaches, read from disk, each once:
94
+ * `composes … from`, `@value … from` and `:import("…")`, through every module
95
+ * they name. postcss-modules resolves these before any other plugin sees the
96
+ * sheet, so they are followed here.
97
+ */
98
+ export async function modulesChain(file, resolve, seen = new Set()) {
99
+ if (seen.has(file) || !existsSync(file))
100
+ return [];
101
+ seen.add(file);
102
+ const refs = [];
103
+ postcss.parse(readFileSync(file, 'utf8'), { from: file }).walk((node) => {
104
+ const ref = moduleRef(node);
105
+ if (ref)
106
+ refs.push(ref);
107
+ });
108
+ const found = [];
109
+ for (const ref of refs)
110
+ for (const target of await targetsOf(ref, file, resolve))
111
+ found.push(target, ...(await modulesChain(target, resolve, seen)));
112
+ return found;
113
+ }
114
+ /**
115
+ * The postcss plugin: for the stylesheet being compiled (the root), a node
116
+ * inlined from another owner's file, or a reference into a prototype the
117
+ * root's owner is not, throws the error that names both files. The kit and
118
+ * the hub own no prototype, so they may reach none.
119
+ */
120
+ export function cssBoundary(project, owner, isPrototype, resolvers) {
121
+ const ownerOf = (file) => owner(real(file));
122
+ const plugin = () => ({
123
+ postcssPlugin: 'design-hub-css-boundary',
124
+ async Once(root) {
125
+ const rootFile = root.source?.input.file;
126
+ if (!rootFile)
127
+ return;
128
+ // Fail closed: without Vite's resolvers an alias or a package path would go unread.
129
+ const resolve = resolvers();
130
+ if (!resolve)
131
+ throw new Error(`${rootFile}: the stylesheet check ran before Vite resolved its config.`);
132
+ const rootOwner = ownerOf(rootFile);
133
+ const refuse = (reader, target, node) => {
134
+ const to = ownerOf(target);
135
+ if (to === null || (to === rootOwner && isPrototype(to)))
136
+ return;
137
+ const message = isPrototype(to)
138
+ ? crossImport(project, real(reader), real(target), ownerOf(reader) !== null)
139
+ : looseFile(project, real(reader), real(target));
140
+ throw node ? node.error(message) : new Error(message);
141
+ };
142
+ const reads = [];
143
+ root.walk((node) => {
144
+ const file = node.source?.input.file ?? rootFile;
145
+ if (file !== rootFile)
146
+ refuse(rootFile, file, node);
147
+ if (node.type === 'decl')
148
+ for (const ref of valueRefs(node.value))
149
+ reads.push({ file, node, ref, by: resolve.url });
150
+ if (node.type === 'atrule' && node.name === 'import') {
151
+ const ref = importRef(node.params);
152
+ if (ref)
153
+ reads.push({ file, node, ref, by: resolve.css });
154
+ }
155
+ });
156
+ for (const { file, node, ref, by } of reads)
157
+ for (const target of await targetsOf(ref, file, by))
158
+ refuse(file, target, node);
159
+ // postcss-modules runs first and resolves composes, @value and :import, so the chain is read from the files.
160
+ if (/\.module\.\w+$/.test(rootFile))
161
+ for (const target of await modulesChain(rootFile, resolve.css))
162
+ refuse(rootFile, target);
163
+ },
164
+ });
165
+ plugin.postcss = true;
166
+ return plugin;
167
+ }
package/dist/vite/kit.js CHANGED
@@ -4,10 +4,12 @@
4
4
  // name and changing the copy: every import of it, the hub's included, then
5
5
  // takes the project's. `@milesroxas/design-hub/kit/<name>` always means the package's
6
6
  // copy, for a project file that extends it (kit/icons.ts adds glyphs to the base set).
7
- import { existsSync, statSync } from 'node:fs';
7
+ import { existsSync, realpathSync, statSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
  const KIT_PREFIX = '@kit/';
10
10
  const PACKAGE_PREFIX = '@milesroxas/design-hub/kit/';
11
+ /** Vite's own test for a `?url` import (`urlRE`). */
12
+ const URL_QUERY = /(\?|&)url(?:&|$)/;
11
13
  const CANDIDATES = ['', '.ts', '.tsx', '.css', '.json', '/index.ts', '/index.tsx'];
12
14
  const isFile = (path) => existsSync(path) && statSync(path).isFile();
13
15
  /** The file `@kit/<rest>` names in the first of `dirs` that has it, or null. */
@@ -25,11 +27,18 @@ export function kitResolver(projectKit, packageKit) {
25
27
  name: 'design-hub-kit',
26
28
  enforce: 'pre',
27
29
  resolveId(id) {
28
- if (id.startsWith(KIT_PREFIX))
29
- return findKitFile([projectKit, packageKit], id.slice(KIT_PREFIX.length));
30
- if (id.startsWith(PACKAGE_PREFIX))
31
- return findKitFile([packageKit], id.slice(PACKAGE_PREFIX.length));
32
- return null;
30
+ // A query (`?worker`, `?url`) rides along on the file it finds.
31
+ const [path, query] = id.split(/(?=\?)/);
32
+ const found = path.startsWith(KIT_PREFIX)
33
+ ? findKitFile([projectKit, packageKit], path.slice(KIT_PREFIX.length))
34
+ : path.startsWith(PACKAGE_PREFIX)
35
+ ? findKitFile([packageKit], path.slice(PACKAGE_PREFIX.length))
36
+ : null;
37
+ // `?url` on its real path: Vite turns it into `?transform-only` and resolves that itself, on the
38
+ // real path, so both must name one module. Anything else keeps the path in kit/, so a kit/ linked
39
+ // from outside the project still resolves the project's own dependencies (`motion/react`).
40
+ const file = found && (query && URL_QUERY.test(query) ? realpathSync(found) : found);
41
+ return file && query ? file + query : file;
33
42
  },
34
43
  };
35
44
  }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The smallest source that counts, in bytes: a shorter file (an empty
3
+ * `.gitkeep`, `{"a":1}`) is never looked for, as it matches a short string
4
+ * by chance.
5
+ */
6
+ export declare const MIN = 40;
7
+ type Owner = string | null;
8
+ type Form = 'bytes' | 'base64' | 'svg' | 'string';
9
+ /** One form of a built file: what it is, and the hash and size of the whole content it holds. */
10
+ type Found = {
11
+ form: Form;
12
+ hash: string;
13
+ size: number;
14
+ };
15
+ /** What Vite writes for an SVG it inlines as text (`svgToDataURL`), or null when it writes base64 instead. */
16
+ export declare function svgDataUrlPayload(text: string): string | null;
17
+ /** The whole content a `data:` URI holds: its decoded bytes, or the payload of Vite's URL-encoded SVG form. */
18
+ export declare function dataUriForms(uri: string): Found[];
19
+ /** Every `data:` URI in a text (a stylesheet, or one string of a script): up to its closing quote, or without one up to `)` or a space. */
20
+ export declare function dataUrisIn(text: string): string[];
21
+ export type Written = {
22
+ fileName: string;
23
+ source: string | Uint8Array;
24
+ };
25
+ /** The error for a built file that holds a prototype's file whole outside its folder. */
26
+ export declare const leaked: (fileName: string, file: string, slug: string, form: Form) => string;
27
+ /**
28
+ * Every built file that holds a whole file of a prototype other than its own
29
+ * owner (for a file outside `_p/`, any prototype's), as problems naming the
30
+ * built file and the source, unless its owner has a source with the same
31
+ * content. `inputs` is every file the bundle read (every prototype file
32
+ * the build loaded, every chunk's modules, every asset's original files),
33
+ * recorded before settle moved anything; a string is compared only with
34
+ * those. A built script that does not parse is a problem, never skipped.
35
+ */
36
+ export declare function leaks(root: string, prototypes: string, owner: (id: string) => Owner, inputs: readonly string[], written: readonly Written[]): string[];
37
+ export {};