@sashaangelm/designkit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +22 -2
  3. package/THIRD_PARTY_NOTICES.md +33 -0
  4. package/dist/browser.d.ts +17 -0
  5. package/dist/browser.js +108 -0
  6. package/dist/catalog.d.ts +22 -0
  7. package/dist/catalog.js +33 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +222 -0
  10. package/dist/definitions.d.ts +37 -0
  11. package/dist/definitions.js +39 -0
  12. package/dist/exporter.d.ts +24 -0
  13. package/dist/exporter.js +342 -0
  14. package/dist/index.d.ts +7 -0
  15. package/dist/index.js +3 -0
  16. package/dist/nested.d.ts +2 -0
  17. package/dist/nested.js +60 -0
  18. package/dist/output.d.ts +3 -0
  19. package/dist/output.js +52 -0
  20. package/dist/primitives.d.ts +34 -0
  21. package/dist/primitives.js +60 -0
  22. package/dist/project.d.ts +27 -0
  23. package/dist/project.js +60 -0
  24. package/dist/render-types.d.ts +51 -0
  25. package/dist/render-types.js +1 -0
  26. package/dist/render.d.ts +1 -0
  27. package/dist/render.js +129 -0
  28. package/dist/scaffold.d.ts +8 -0
  29. package/dist/scaffold.js +71 -0
  30. package/dist/selection.d.ts +16 -0
  31. package/dist/selection.js +39 -0
  32. package/dist/server.d.ts +26 -0
  33. package/dist/server.js +123 -0
  34. package/dist/studio-server.d.ts +22 -0
  35. package/dist/studio-server.js +170 -0
  36. package/dist/studio.css +470 -0
  37. package/dist/studio.d.ts +1 -0
  38. package/dist/studio.js +396 -0
  39. package/package.json +56 -3
  40. package/template/AGENTS.md +6 -0
  41. package/template/README.md +21 -0
  42. package/template/assets/README.md +5 -0
  43. package/template/assets/designkit-starter-MIT.txt +21 -0
  44. package/template/assets/orbit.svg +33 -0
  45. package/template/assets/space-grotesk-OFL.txt +93 -0
  46. package/template/assets/space-grotesk-latin-700-normal.woff2 +0 -0
  47. package/template/designkit.config.ts +7 -0
  48. package/template/designkit.root.tsx +30 -0
  49. package/template/designs/assets.d.ts +6 -0
  50. package/template/designs/social.design.tsx +46 -0
  51. package/template/gitignore.txt +3 -0
  52. package/template/package.json +27 -0
  53. package/template/styles/social.css +53 -0
  54. package/template/tsconfig.json +19 -0
@@ -0,0 +1,51 @@
1
+ import type { ExportPreset } from "./definitions.js";
2
+ export interface FrameInfo {
3
+ id: string;
4
+ name: string;
5
+ width: number;
6
+ height: number;
7
+ exports?: ExportPreset[];
8
+ }
9
+ export interface NestedInfo extends FrameInfo {
10
+ x: number;
11
+ y: number;
12
+ exportError?: string;
13
+ }
14
+ export interface RootInfo extends FrameInfo {
15
+ x?: number;
16
+ y?: number;
17
+ nested?: NestedInfo[];
18
+ }
19
+ export interface PageInfo {
20
+ projectId: string;
21
+ id: string;
22
+ name: string;
23
+ source: string;
24
+ frames: RootInfo[];
25
+ }
26
+ export interface ProjectInfo {
27
+ id: string;
28
+ name: string;
29
+ pages: PageInfo[];
30
+ }
31
+ export interface Diagnostic {
32
+ code: string;
33
+ message: string;
34
+ source?: string;
35
+ selector?: string;
36
+ }
37
+ export interface RegistryReport {
38
+ projects: ProjectInfo[];
39
+ errors: Diagnostic[];
40
+ }
41
+ export interface RenderState {
42
+ status: "loading" | "ready" | "error";
43
+ error?: string;
44
+ registry?: RegistryReport;
45
+ nested?: NestedInfo[];
46
+ }
47
+ declare global {
48
+ interface Window {
49
+ designkitRender?: RenderState;
50
+ }
51
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
package/dist/render.js ADDED
@@ -0,0 +1,129 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useLayoutEffect } from "react";
3
+ import { createRoot } from "react-dom/client";
4
+ import loadEntry, { source } from "virtual:designkit-registry";
5
+ import { CatalogContext } from "./catalog.js";
6
+ import { idSchema } from "./definitions.js";
7
+ import { inspectNested } from "./nested.js";
8
+ const app = document.querySelector("#app");
9
+ window.designkitRender = { status: "loading" };
10
+ const discovering = location.pathname === "/registry";
11
+ function fail(error) {
12
+ const message = error instanceof Error ? error.message : String(error);
13
+ window.designkitRender = discovering
14
+ ? {
15
+ status: "ready",
16
+ registry: {
17
+ projects: [],
18
+ errors: [{ code: "INVALID_DESIGN", source, message }],
19
+ },
20
+ }
21
+ : { status: "error", error: message };
22
+ }
23
+ const nextPaint = () => new Promise((resolve) => requestAnimationFrame(() => resolve()));
24
+ function Readiness({ selector }) {
25
+ useLayoutEffect(() => {
26
+ async function ready() {
27
+ const roots = app.querySelectorAll("[data-designkit-root]");
28
+ if (roots.length !== 1) {
29
+ throw new Error(roots.length
30
+ ? `Multiple artboards match: ${selector}`
31
+ : `Unknown frame: ${selector}`);
32
+ }
33
+ await nextPaint();
34
+ await document.fonts.ready;
35
+ for (const font of document.fonts) {
36
+ if (font.status === "error")
37
+ throw new Error(`Could not load font ${font.family}`);
38
+ }
39
+ await Promise.all(Array.from(document.images, async (image) => {
40
+ if (!image.getAttribute("src") && !image.getAttribute("srcset"))
41
+ return;
42
+ image.loading = "eager";
43
+ try {
44
+ await image.decode();
45
+ }
46
+ catch {
47
+ throw new Error(`Could not decode image ${image.currentSrc || image.src}`);
48
+ }
49
+ }));
50
+ await nextPaint();
51
+ if (window.designkitRender?.status === "loading") {
52
+ const nested = inspectNested(roots[0]);
53
+ window.designkitRender = { status: "ready", nested };
54
+ }
55
+ }
56
+ void ready().catch(fail);
57
+ }, [selector]);
58
+ return null;
59
+ }
60
+ function readCatalog() {
61
+ const roots = app.querySelectorAll("[data-designkit-catalog]");
62
+ if (roots.length !== 1) {
63
+ throw new Error("The entry component must render exactly one <Root>.");
64
+ }
65
+ const errors = [];
66
+ function collect(parent, attribute, kind, prefix) {
67
+ const items = new Map();
68
+ const duplicates = new Set();
69
+ for (const element of parent.querySelectorAll(`[${attribute}]`)) {
70
+ const metadata = JSON.parse(element.getAttribute(attribute));
71
+ if (items.has(metadata.id)) {
72
+ if (!duplicates.has(metadata.id)) {
73
+ const selector = prefix + metadata.id;
74
+ errors.push({
75
+ code: `DUPLICATE_${kind.toUpperCase()}`,
76
+ message: `Duplicate ${kind} ID "${metadata.id}" at "${selector}"`,
77
+ selector,
78
+ source,
79
+ });
80
+ }
81
+ duplicates.add(metadata.id);
82
+ }
83
+ items.set(metadata.id, { metadata, element });
84
+ }
85
+ return Array.from(items.values()).filter(({ metadata }) => !duplicates.has(metadata.id));
86
+ }
87
+ const projects = collect(roots[0], "data-designkit-project", "project", "").map(({ metadata: project, element }) => ({
88
+ ...project,
89
+ pages: collect(element, "data-designkit-page", "page", project.id + "/").map(({ metadata: page, element }) => ({
90
+ ...page,
91
+ projectId: project.id,
92
+ source,
93
+ frames: collect(element, "data-designkit-artboard", "frame", `${project.id}/${page.id}/`).map(({ metadata }) => metadata),
94
+ })),
95
+ }));
96
+ return { projects, errors };
97
+ }
98
+ function Discovery() {
99
+ useLayoutEffect(() => {
100
+ window.designkitRender = { status: "ready", registry: readCatalog() };
101
+ }, []);
102
+ return null;
103
+ }
104
+ async function main() {
105
+ if (!discovering)
106
+ await import("virtual:designkit-css");
107
+ const { default: Entry } = await loadEntry();
108
+ if (!Entry)
109
+ throw new Error(`${source} must default-export an app component.`);
110
+ const root = createRoot(app, { onUncaughtError: fail });
111
+ if (discovering) {
112
+ root.render(_jsxs(CatalogContext.Provider, { value: { scope: "entry" }, children: [_jsx(Entry, {}), _jsx(Discovery, {})] }));
113
+ return;
114
+ }
115
+ const [, , project, page, frame, ...extra] = location.pathname.split("/");
116
+ const selector = [project, page, frame].join("/");
117
+ if (extra.length ||
118
+ [project, page, frame].some((id) => !idSchema.safeParse(id).success)) {
119
+ throw new Error(`Unknown frame: ${selector}`);
120
+ }
121
+ if (new URLSearchParams(location.search).has("static")) {
122
+ const style = document.createElement("style");
123
+ style.textContent =
124
+ "*,*::before,*::after{animation:none!important;transition:none!important;scroll-behavior:auto!important}";
125
+ document.head.append(style);
126
+ }
127
+ root.render(_jsxs(CatalogContext.Provider, { value: { scope: "entry", selection: { project, page, frame } }, children: [_jsx(Entry, {}), _jsx(Readiness, { selector: selector })] }));
128
+ }
129
+ void main().catch(fail);
@@ -0,0 +1,8 @@
1
+ export interface ScaffoldResult {
2
+ root: string;
3
+ created: string[];
4
+ skipped: string[];
5
+ }
6
+ export declare function scaffoldProject(target: string, { mode }: {
7
+ mode: "create" | "init";
8
+ }): Promise<ScaffoldResult>;
@@ -0,0 +1,71 @@
1
+ import { constants } from "node:fs";
2
+ import { copyFile, lstat, mkdir, readdir, realpath } from "node:fs/promises";
3
+ import { dirname, join, relative, resolve, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ const template = fileURLToPath(new URL("../template", import.meta.url));
6
+ async function entry(path) {
7
+ return lstat(path).catch((error) => {
8
+ if (error.code !== "ENOENT")
9
+ throw error;
10
+ return undefined;
11
+ });
12
+ }
13
+ async function ensureParent(root, destination) {
14
+ let directory = root;
15
+ for (const segment of relative(root, dirname(destination))
16
+ .split(sep)
17
+ .filter(Boolean)) {
18
+ directory = join(directory, segment);
19
+ await mkdir(directory).catch((error) => {
20
+ if (error.code !== "EEXIST")
21
+ throw error;
22
+ });
23
+ if (!(await lstat(directory)).isDirectory())
24
+ return false;
25
+ }
26
+ return true;
27
+ }
28
+ export async function scaffoldProject(target, { mode }) {
29
+ const destination = resolve(target);
30
+ const existing = await entry(destination);
31
+ if (existing && !existing.isDirectory()) {
32
+ throw new Error(`Expected a project directory: ${destination}`);
33
+ }
34
+ if (mode === "create" && existing && (await readdir(destination)).length) {
35
+ throw new Error(`Project directory is not empty: ${destination}. Run designkit init inside it to add missing starter files.`);
36
+ }
37
+ await mkdir(destination, { recursive: true });
38
+ if (!(await lstat(destination)).isDirectory()) {
39
+ throw new Error(`Expected a project directory: ${destination}`);
40
+ }
41
+ const root = await realpath(destination);
42
+ const result = { root, created: [], skipped: [] };
43
+ const entries = await readdir(template, {
44
+ withFileTypes: true,
45
+ recursive: true,
46
+ });
47
+ const sources = entries
48
+ .filter((item) => item.isFile())
49
+ .map((item) => relative(template, join(item.parentPath, item.name)).split(sep).join("/"))
50
+ .sort();
51
+ for (const source of sources) {
52
+ const name = source === "gitignore.txt" ? ".gitignore" : source;
53
+ const path = join(root, name);
54
+ if (!(await ensureParent(root, path)) || (await entry(path))) {
55
+ result.skipped.push(name);
56
+ continue;
57
+ }
58
+ try {
59
+ await copyFile(join(template, source), path, constants.COPYFILE_EXCL);
60
+ result.created.push(name);
61
+ }
62
+ catch (error) {
63
+ if (error.code !== "EEXIST")
64
+ throw error;
65
+ result.skipped.push(name);
66
+ }
67
+ }
68
+ result.created.sort();
69
+ result.skipped.sort();
70
+ return result;
71
+ }
@@ -0,0 +1,16 @@
1
+ import type { ExportPreset } from "./definitions.js";
2
+ export interface Selection {
3
+ all?: boolean;
4
+ project?: string;
5
+ page?: string;
6
+ frame?: string[];
7
+ }
8
+ export interface ExportOptions extends Selection {
9
+ format?: ExportPreset["format"];
10
+ scale?: number;
11
+ quality?: number;
12
+ transparent?: boolean;
13
+ overwrite?: boolean;
14
+ }
15
+ export declare function validateSelection({ all, project, page, frame }: Selection): void;
16
+ export declare function resolvePreset(options: ExportOptions, fallback: ExportPreset): ExportPreset | undefined;
@@ -0,0 +1,39 @@
1
+ import { exportPresetSchema, idSchema } from "./definitions.js";
2
+ export function validateSelection({ all, project, page, frame }) {
3
+ if ([all, project, page, frame?.length].filter(Boolean).length > 1) {
4
+ throw new Error("Choose one selection mode: --all, --project, --page, or --frame.");
5
+ }
6
+ if (project !== undefined && !idSchema.safeParse(project).success)
7
+ throw new Error("Invalid project ID.");
8
+ if (page !== undefined && !validSelector(page, 2, 2))
9
+ throw new Error("Invalid page selector. Use project/page.");
10
+ for (const selector of frame ?? []) {
11
+ if (!validSelector(selector, 3, 4)) {
12
+ throw new Error(`Invalid selector "${selector}". Use project/page/frame or project/page/frame/nested.`);
13
+ }
14
+ }
15
+ if (new Set(frame).size !== (frame?.length ?? 0))
16
+ throw new Error("Frame selectors must be unique.");
17
+ }
18
+ function validSelector(selector, min, max) {
19
+ const ids = selector.split("/");
20
+ return (ids.length >= min &&
21
+ ids.length <= max &&
22
+ ids.every((id) => idSchema.safeParse(id).success));
23
+ }
24
+ export function resolvePreset(options, fallback) {
25
+ const { format, scale, quality, transparent } = options;
26
+ if (format === undefined &&
27
+ scale === undefined &&
28
+ quality === undefined &&
29
+ transparent === undefined)
30
+ return;
31
+ const outputFormat = format ?? fallback.format;
32
+ return exportPresetSchema.parse({
33
+ format: outputFormat,
34
+ scale: scale ?? fallback.scale,
35
+ quality: quality ?? (outputFormat === "png" ? undefined : fallback.quality),
36
+ transparent: transparent ??
37
+ (outputFormat === "jpeg" ? undefined : fallback.transparent),
38
+ });
39
+ }
@@ -0,0 +1,26 @@
1
+ import type { Plugin, ViteDevServer } from "vite";
2
+ import { loadProject } from "./project.js";
3
+ export declare function startServer(project: string, config?: Awaited<ReturnType<typeof loadProject>>, studio?: {
4
+ port?: number;
5
+ plugin: Plugin;
6
+ }): Promise<{
7
+ server: ViteDevServer;
8
+ config: {
9
+ entry: string;
10
+ output: string;
11
+ studio: {
12
+ port?: number | undefined;
13
+ };
14
+ export: {
15
+ format: "png" | "jpeg" | "webp";
16
+ scale: number;
17
+ quality?: number | undefined;
18
+ transparent?: boolean | undefined;
19
+ };
20
+ concurrency: number;
21
+ globalCss?: string | undefined;
22
+ } & {
23
+ root: string;
24
+ };
25
+ origin: string;
26
+ }>;
package/dist/server.js ADDED
@@ -0,0 +1,123 @@
1
+ import { mkdtemp, rm } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { createServer, normalizePath, searchForWorkspaceRoot } from "vite";
6
+ import { loadProject, projectFile } from "./project.js";
7
+ const registryId = "virtual:designkit-registry";
8
+ const renderEntry = normalizePath(fileURLToPath(new URL("./render.js", import.meta.url)));
9
+ const cssId = "virtual:designkit-css";
10
+ export async function startServer(project, config, studio) {
11
+ config ??= await loadProject(project);
12
+ const { root, globalCss, entry } = config;
13
+ const registry = {
14
+ name: "designkit-registry",
15
+ resolveId(id) {
16
+ if (id === registryId || id === cssId)
17
+ return "\0" + id;
18
+ },
19
+ async load(id) {
20
+ if (id === "\0" + cssId) {
21
+ return globalCss
22
+ ? `import ${JSON.stringify("/@fs/" + normalizePath(globalCss))}`
23
+ : "";
24
+ }
25
+ if (id !== "\0" + registryId)
26
+ return;
27
+ try {
28
+ const path = normalizePath(await projectFile(root, entry));
29
+ return `export const source = ${JSON.stringify(entry)};
30
+ export default () => import(${JSON.stringify("/@fs/" + path)});`;
31
+ }
32
+ catch (error) {
33
+ return `export const source = ${JSON.stringify(entry)};
34
+ export default () => { throw new Error(${JSON.stringify(String(error))}); };`;
35
+ }
36
+ },
37
+ configureServer(server) {
38
+ server.middlewares.use(async (request, response, next) => {
39
+ const pathname = request.url?.split("?")[0];
40
+ if (pathname !== "/registry" && !pathname?.startsWith("/render/"))
41
+ return next();
42
+ if (request.method !== "GET" && request.method !== "HEAD") {
43
+ response.writeHead(405).end();
44
+ return;
45
+ }
46
+ try {
47
+ const html = await server.transformIndexHtml(pathname, `<!doctype html>
48
+ <html lang="en"><head><meta charset="utf-8">
49
+ <meta name="viewport" content="width=device-width, initial-scale=1">
50
+ <title>Designkit render</title>
51
+ <style>html,body{margin:0;padding:0}#app{width:max-content;height:max-content}</style>
52
+ </head><body><div id="app"></div>
53
+ <script type="module" src="/@fs/${renderEntry}"></script></body></html>`);
54
+ response
55
+ .writeHead(200, { "Content-Type": "text/html; charset=utf-8" })
56
+ .end(html);
57
+ }
58
+ catch (error) {
59
+ next(error);
60
+ }
61
+ });
62
+ },
63
+ };
64
+ const cacheDir = await mkdtemp(join(tmpdir(), "designkit-vite-"));
65
+ let server;
66
+ try {
67
+ server = await createServer({
68
+ root,
69
+ cacheDir,
70
+ configFile: false,
71
+ appType: "custom",
72
+ logLevel: "silent",
73
+ clearScreen: false,
74
+ plugins: [registry, ...(studio ? [studio.plugin] : [])],
75
+ resolve: { dedupe: ["react", "react-dom"] },
76
+ optimizeDeps: {
77
+ noDiscovery: true,
78
+ include: [
79
+ "react",
80
+ "react/jsx-runtime",
81
+ "react/jsx-dev-runtime",
82
+ "react-dom/client",
83
+ ],
84
+ },
85
+ server: {
86
+ host: "127.0.0.1",
87
+ port: studio?.port ?? 0,
88
+ watch: studio
89
+ ? { ignored: [normalizePath(resolve(root, config.output)) + "/**"] }
90
+ : null,
91
+ ws: studio ? {} : false,
92
+ strictPort: Boolean(studio?.port),
93
+ cors: false,
94
+ fs: {
95
+ allow: [searchForWorkspaceRoot(root), dirname(renderEntry), cacheDir],
96
+ },
97
+ },
98
+ });
99
+ await server.listen();
100
+ const address = server.httpServer?.address();
101
+ if (!address || typeof address === "string")
102
+ throw new Error("No local render port available");
103
+ const stop = server.close.bind(server);
104
+ server.close = async () => {
105
+ try {
106
+ await stop();
107
+ }
108
+ finally {
109
+ await rm(cacheDir, { recursive: true, force: true });
110
+ }
111
+ };
112
+ return { server, config, origin: `http://127.0.0.1:${address.port}` };
113
+ }
114
+ catch (error) {
115
+ try {
116
+ await server?.close();
117
+ }
118
+ finally {
119
+ await rm(cacheDir, { recursive: true, force: true });
120
+ }
121
+ throw error;
122
+ }
123
+ }
@@ -0,0 +1,22 @@
1
+ export declare function startStudio(project: string, port?: number): Promise<{
2
+ server: import("vite").ViteDevServer;
3
+ config: {
4
+ entry: string;
5
+ output: string;
6
+ studio: {
7
+ port?: number | undefined;
8
+ };
9
+ export: {
10
+ format: "png" | "jpeg" | "webp";
11
+ scale: number;
12
+ quality?: number | undefined;
13
+ transparent?: boolean | undefined;
14
+ };
15
+ concurrency: number;
16
+ globalCss?: string | undefined;
17
+ } & {
18
+ root: string;
19
+ };
20
+ origin: string;
21
+ }>;
22
+ export declare function openBrowser(url: string): void;
@@ -0,0 +1,170 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { fileURLToPath } from "node:url";
4
+ import { normalizePath } from "vite";
5
+ import { z } from "zod";
6
+ import { exportProject } from "./exporter.js";
7
+ import { loadProject } from "./project.js";
8
+ import { resolvePreset, validateSelection } from "./selection.js";
9
+ import { startServer } from "./server.js";
10
+ const entry = normalizePath(fileURLToPath(new URL("./studio.js", import.meta.url)));
11
+ const exportInput = z.strictObject({
12
+ selector: z.string().min(3).max(512),
13
+ format: z.enum(["png", "jpeg", "webp"]).optional(),
14
+ scale: z.number().positive().max(8).optional(),
15
+ quality: z.number().int().min(1).max(100).optional(),
16
+ transparent: z.boolean().optional(),
17
+ overwrite: z.boolean().optional(),
18
+ });
19
+ function json(response, status, data) {
20
+ response.writeHead(status, {
21
+ "Content-Type": "application/json; charset=utf-8",
22
+ "Cache-Control": "no-store",
23
+ });
24
+ response.end(JSON.stringify(data));
25
+ }
26
+ function reject(response, status, code, message) {
27
+ json(response, status, { files: [], errors: [{ code, message }] });
28
+ }
29
+ const byteLimit = 8192;
30
+ async function readBody(request) {
31
+ const chunks = [];
32
+ let length = 0;
33
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
34
+ length += chunk.length;
35
+ if (length > byteLimit) {
36
+ request.resume();
37
+ return;
38
+ }
39
+ chunks.push(chunk);
40
+ }
41
+ return Buffer.concat(chunks).toString("utf8");
42
+ }
43
+ export async function startStudio(project, port) {
44
+ const config = await loadProject(project);
45
+ const token = randomBytes(32).toString("hex");
46
+ let session = undefined;
47
+ let exporting = false;
48
+ const plugin = {
49
+ name: "designkit-studio",
50
+ configureServer(server) {
51
+ server.middlewares.use(async (request, response, next) => {
52
+ const path = request.url?.split("?")[0];
53
+ if (path !== "/" && path !== "/api/export")
54
+ return next();
55
+ if (!session || request.headers.host !== new URL(session.origin).host) {
56
+ reject(response, 403, "FORBIDDEN", "Use the Studio loopback address.");
57
+ return;
58
+ }
59
+ if (path === "/") {
60
+ if (request.method !== "GET" && request.method !== "HEAD") {
61
+ response.setHeader("Allow", "GET, HEAD");
62
+ response.writeHead(405).end();
63
+ return;
64
+ }
65
+ try {
66
+ const html = await server.transformIndexHtml("/", `<!doctype html>
67
+ <html lang="en"><head><meta charset="utf-8">
68
+ <meta name="viewport" content="width=device-width, initial-scale=1">
69
+ <meta name="designkit-token" content="${token}">
70
+ <title>Designkit Studio</title></head><body><div id="app"></div>
71
+ <script type="module" src="/@fs/${entry}"></script></body></html>`);
72
+ response
73
+ .writeHead(200, {
74
+ "Content-Type": "text/html; charset=utf-8",
75
+ "Cache-Control": "no-store",
76
+ "X-Frame-Options": "DENY",
77
+ "Referrer-Policy": "no-referrer",
78
+ })
79
+ .end(html);
80
+ }
81
+ catch (error) {
82
+ next(error);
83
+ }
84
+ return;
85
+ }
86
+ if (request.method !== "POST") {
87
+ response.setHeader("Allow", "POST");
88
+ reject(response, 405, "METHOD_NOT_ALLOWED", "Use POST for exports.");
89
+ return;
90
+ }
91
+ if (request.headers.origin !== session.origin ||
92
+ request.headers["x-designkit-token"] !== token) {
93
+ reject(response, 403, "FORBIDDEN", "The export request must come from this Studio session.");
94
+ return;
95
+ }
96
+ const contentType = request.headers["content-type"]
97
+ ?.split(";")[0]
98
+ .trim()
99
+ .toLowerCase();
100
+ if (contentType !== "application/json") {
101
+ reject(response, 415, "INVALID_REQUEST", "Expected application/json.");
102
+ return;
103
+ }
104
+ if (Number(request.headers["content-length"]) > byteLimit) {
105
+ reject(response, 413, "REQUEST_TOO_LARGE", "The export request is too large.");
106
+ return;
107
+ }
108
+ let options;
109
+ try {
110
+ const body = await readBody(request);
111
+ if (body === undefined) {
112
+ reject(response, 413, "REQUEST_TOO_LARGE", "The export request is too large.");
113
+ return;
114
+ }
115
+ const { selector, ...settings } = exportInput.parse(JSON.parse(body));
116
+ options = { ...settings, frame: [selector] };
117
+ validateSelection(options);
118
+ resolvePreset(options, config.export);
119
+ }
120
+ catch (error) {
121
+ reject(response, 400, "INVALID_REQUEST", error instanceof Error ? error.message : String(error));
122
+ return;
123
+ }
124
+ if (exporting) {
125
+ reject(response, 409, "EXPORT_BUSY", "An export is already running.");
126
+ return;
127
+ }
128
+ exporting = true;
129
+ try {
130
+ const result = await exportProject(project, options, session);
131
+ json(response, result.errors.length ? 422 : 200, result);
132
+ }
133
+ catch (error) {
134
+ reject(response, 500, "EXPORT_FAILED", error instanceof Error ? error.message : String(error));
135
+ }
136
+ finally {
137
+ exporting = false;
138
+ }
139
+ });
140
+ let reload;
141
+ server.watcher.on("all", (event) => {
142
+ if (!["add", "unlink", "change"].includes(event))
143
+ return;
144
+ clearTimeout(reload);
145
+ reload = setTimeout(() => {
146
+ const registry = server.moduleGraph.getModuleById("\0virtual:designkit-registry");
147
+ if (registry)
148
+ server.moduleGraph.invalidateModule(registry);
149
+ server.ws.send({ type: "full-reload", path: "*" });
150
+ }, 100);
151
+ });
152
+ server.httpServer?.once("close", () => clearTimeout(reload));
153
+ },
154
+ };
155
+ session = await startServer(project, config, {
156
+ port: port ?? config.studio.port,
157
+ plugin,
158
+ });
159
+ return session;
160
+ }
161
+ export function openBrowser(url) {
162
+ const [command, ...args] = process.platform === "darwin"
163
+ ? ["open", url]
164
+ : process.platform === "win32"
165
+ ? ["rundll32.exe", "url.dll,FileProtocolHandler", url]
166
+ : ["xdg-open", url];
167
+ const child = spawn(command, args, { detached: true, stdio: "ignore" });
168
+ child.once("error", () => console.error(`Open ${url} in your browser.`));
169
+ child.unref();
170
+ }