@pstdio/canvas 0.0.0-stage → 0.45.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.
- package/README.md +95 -2
- package/bin/pstdio-canvas.ts +4 -0
- package/package.json +30 -4
- package/src/compose.ts +83 -0
- package/src/index.ts +16 -0
- package/src/indexer.ts +64 -0
- package/src/native-preview-runtime.tsx +30 -0
- package/src/project/archive.ts +126 -0
- package/src/project/build.ts +113 -0
- package/src/project/bundle.ts +140 -0
- package/src/project/cli.ts +58 -0
- package/src/project/discover.ts +64 -0
- package/src/project/index-canvas-file.ts +130 -0
- package/src/project/inputs.ts +76 -0
- package/src/project/lock.ts +42 -0
- package/src/project/manifest.ts +45 -0
- package/src/project/watch.ts +71 -0
- package/src/runtime/frame-runtime.tsx +183 -0
- package/src/runtime/navigation.ts +135 -0
- package/src/runtime/protocol.ts +54 -0
package/README.md
CHANGED
|
@@ -1,3 +1,96 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pstdio/canvas
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Build a React project's `.canvas.tsx` files into previews that UI Canvas shows. The package finds the canvas files, builds them with the project's own dependencies, and rebuilds them when files change. UI Canvas only reads the result.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
bun add -d @pstdio/canvas
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The `pstdio-canvas` command runs on Bun.
|
|
12
|
+
|
|
13
|
+
## Commands
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
bun x pstdio-canvas watch # build, then rebuild whenever a canvas or a file it uses changes
|
|
17
|
+
bun x pstdio-canvas build # build once, for CI and checks; add --force to build even when nothing changed
|
|
18
|
+
bun x pstdio-canvas list # print the project's canvases as JSON
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
All commands accept `--root <dir>` (default: the current folder). `build` and `watch` accept `--out <dir>` (default: `.pstdio/extension-storage/pstdio.canvas/build`, the folder UI Canvas reads). The output folder gets a `.gitignore` containing `*`, so it is never committed.
|
|
22
|
+
|
|
23
|
+
A canvas that cannot be built, for example because it imports a missing package, is listed with its error. The other canvases still build, and `build` exits with code 0.
|
|
24
|
+
|
|
25
|
+
## Canvas files
|
|
26
|
+
|
|
27
|
+
A canvas file is any `*.canvas.tsx` or `*.canvas.jsx` file that Git does not ignore. Outside Git, `node_modules`, `dist` and `.pstdio` are skipped. One file is one canvas; its id is its path from the project root.
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
// src/components/card.canvas.tsx
|
|
31
|
+
import { Button } from "./button";
|
|
32
|
+
import { Card } from "./card";
|
|
33
|
+
|
|
34
|
+
export default {
|
|
35
|
+
title: "Components/Card",
|
|
36
|
+
component: Card,
|
|
37
|
+
args: { title: "Usage this month" },
|
|
38
|
+
description: "A bordered surface for one topic.",
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// An object frame renders `component` with the merged args.
|
|
42
|
+
export const Default = {};
|
|
43
|
+
export const Long = { args: { title: "A much longer heading that wraps" } };
|
|
44
|
+
|
|
45
|
+
// A function frame renders whatever it returns.
|
|
46
|
+
export const WithAction = () => (
|
|
47
|
+
<Card title="Invite people">
|
|
48
|
+
<Button>Invite</Button>
|
|
49
|
+
</Card>
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
// `render` receives the merged args.
|
|
53
|
+
export const Compact = {
|
|
54
|
+
name: "Compact layout",
|
|
55
|
+
args: { size: "sm" },
|
|
56
|
+
render: (args) => <Card {...args} />,
|
|
57
|
+
description: "Used in side panels.",
|
|
58
|
+
};
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The default export is optional. `title` is `"Group/Name"`; the part before the last `/` is the navigation group, and it defaults to the file name. It can also set `component`, `args`, `description`, `fullscreen` (frames get the full viewport height) and `decorators`.
|
|
62
|
+
|
|
63
|
+
Each named export whose value is a component or an object is one frame, in export order. Its name is `name`, or the export name in sentence case (`WithAction` becomes "With action"). Other exported values are ignored.
|
|
64
|
+
|
|
65
|
+
## Project setup
|
|
66
|
+
|
|
67
|
+
An optional `.canvas/preview.tsx` applies to every canvas file in its folder and below; the nearest one wins. Use it for global CSS and providers:
|
|
68
|
+
|
|
69
|
+
```tsx
|
|
70
|
+
// .canvas/preview.tsx
|
|
71
|
+
import "../src/styles.css";
|
|
72
|
+
import { ThemeProvider } from "../src/theme";
|
|
73
|
+
|
|
74
|
+
export default {
|
|
75
|
+
decorators: [
|
|
76
|
+
(Frame, { theme }) => (
|
|
77
|
+
<ThemeProvider mode={theme}>
|
|
78
|
+
<Frame />
|
|
79
|
+
</ThemeProvider>
|
|
80
|
+
),
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
A decorator is `(Frame, context) => element`, where `context` is `{ theme, args }` and `theme` is `"light"` or `"dark"` from the frame's theme switch. Decorators run from the outside in: `.canvas/preview.tsx`, then the file's default export, then the frame.
|
|
86
|
+
|
|
87
|
+
## Types
|
|
88
|
+
|
|
89
|
+
Optional. Canvas files work without importing anything from this package.
|
|
90
|
+
|
|
91
|
+
```tsx
|
|
92
|
+
import type { CanvasFrame, CanvasMeta } from "@pstdio/canvas";
|
|
93
|
+
|
|
94
|
+
export default { title: "Components/Card", component: Card } satisfies CanvasMeta<typeof Card>;
|
|
95
|
+
export const Long: CanvasFrame<typeof Card> = { args: { title: "A much longer heading" } };
|
|
96
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pstdio/canvas",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.45.0",
|
|
4
|
+
"description": "Build and watch a project's .canvas.tsx files for UI Canvas.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/pufflyai/prompt-studio",
|
|
8
|
+
"directory": "packages/canvas"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"bin": {
|
|
12
|
+
"pstdio-canvas": "./bin/pstdio-canvas.ts"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"bin",
|
|
16
|
+
"src"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/index.ts",
|
|
20
|
+
"./indexer": "./src/indexer.ts"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"typescript": "6.0.2"
|
|
24
|
+
},
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"react": "^19.2.4",
|
|
27
|
+
"react-dom": "^19.2.4"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
}
|
|
32
|
+
}
|
package/src/compose.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type ComponentType, createContext, createElement, type ReactNode, useContext } from "react";
|
|
2
|
+
|
|
3
|
+
type Props<T> =
|
|
4
|
+
T extends ComponentType<infer P>
|
|
5
|
+
? P
|
|
6
|
+
: T extends { component?: ComponentType<infer P> }
|
|
7
|
+
? P
|
|
8
|
+
: T extends { args: infer P }
|
|
9
|
+
? P
|
|
10
|
+
: T;
|
|
11
|
+
export type CanvasTheme = "light" | "dark";
|
|
12
|
+
export interface CanvasContext {
|
|
13
|
+
args: Record<string, any>;
|
|
14
|
+
/** The frame's theme switch. Decorators use it to set the project's own theme provider. */
|
|
15
|
+
theme: CanvasTheme;
|
|
16
|
+
}
|
|
17
|
+
/** Provided by the frame runtime; previews outside a frame render light. */
|
|
18
|
+
export const CanvasThemeContext = createContext<CanvasTheme>("light");
|
|
19
|
+
export type CanvasRender<T = any> = (args: Props<T>, context: CanvasContext) => ReactNode;
|
|
20
|
+
export type CanvasDecorator = (Preview: (props?: any) => ReactNode, context: CanvasContext) => ReactNode;
|
|
21
|
+
export interface CanvasVariant<T = any> {
|
|
22
|
+
id?: string;
|
|
23
|
+
name?: string;
|
|
24
|
+
args?: Partial<Props<T>>;
|
|
25
|
+
render?: CanvasRender<T>;
|
|
26
|
+
decorators?: CanvasDecorator[];
|
|
27
|
+
description?: string;
|
|
28
|
+
/** The frame is at least as tall as the Canvas viewport, for full-page previews. */
|
|
29
|
+
fullscreen?: boolean;
|
|
30
|
+
setup?: () =>
|
|
31
|
+
| { args?: Record<string, any>; dispose?: () => void }
|
|
32
|
+
| Promise<{ args?: Record<string, any>; dispose?: () => void }>;
|
|
33
|
+
}
|
|
34
|
+
export interface CanvasMeta<T = any> extends CanvasVariant<T> {
|
|
35
|
+
title?: string;
|
|
36
|
+
component?: ComponentType<Props<T>>;
|
|
37
|
+
}
|
|
38
|
+
export type CanvasProject = Omit<CanvasVariant, "render">;
|
|
39
|
+
/** One frame: a component with no props, or an object rendering `render(args)` or `component`. */
|
|
40
|
+
export type CanvasFrame<T = any> = CanvasVariant<T> | ComponentType;
|
|
41
|
+
/** The default export of `.canvas/preview.tsx`. */
|
|
42
|
+
export type CanvasPreview = CanvasProject;
|
|
43
|
+
|
|
44
|
+
export const composePreview = async (
|
|
45
|
+
variant: CanvasVariant | CanvasRender,
|
|
46
|
+
meta: CanvasMeta = {},
|
|
47
|
+
project: CanvasProject = {},
|
|
48
|
+
) => {
|
|
49
|
+
const example = typeof variant === "function" ? { render: variant } : variant;
|
|
50
|
+
const context = { args: { ...meta.args, ...example.args } };
|
|
51
|
+
const cleanups: (() => void)[] = [];
|
|
52
|
+
let disposed = false;
|
|
53
|
+
const dispose = () => {
|
|
54
|
+
if (disposed) return;
|
|
55
|
+
disposed = true;
|
|
56
|
+
for (const cleanup of cleanups.reverse()) cleanup();
|
|
57
|
+
};
|
|
58
|
+
try {
|
|
59
|
+
for (const source of [project, meta, example]) {
|
|
60
|
+
const setup = await source.setup?.();
|
|
61
|
+
if (setup?.dispose) cleanups.push(setup.dispose);
|
|
62
|
+
Object.assign(context.args, setup?.args);
|
|
63
|
+
}
|
|
64
|
+
} catch (error) {
|
|
65
|
+
dispose();
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
const render = example.render ?? meta.render;
|
|
69
|
+
const decorators = [...(project.decorators ?? []), ...(meta.decorators ?? []), ...(example.decorators ?? [])];
|
|
70
|
+
const Component = (args: Record<string, unknown>) => {
|
|
71
|
+
const current: CanvasContext = { args: { ...context.args, ...args }, theme: useContext(CanvasThemeContext) };
|
|
72
|
+
const body = () =>
|
|
73
|
+
render ? render(current.args, current) : createElement(meta.component ?? (() => null), current.args);
|
|
74
|
+
return decorators.reduceRight<() => ReactNode>((child, decorator) => () => decorator(child, current), body)();
|
|
75
|
+
};
|
|
76
|
+
return {
|
|
77
|
+
Component,
|
|
78
|
+
args: context.args,
|
|
79
|
+
description: example.description,
|
|
80
|
+
fullscreen: example.fullscreen ?? meta.fullscreen ?? project.fullscreen ?? false,
|
|
81
|
+
dispose,
|
|
82
|
+
};
|
|
83
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export * from "./compose";
|
|
2
|
+
export {
|
|
3
|
+
type CanvasBuildManifest,
|
|
4
|
+
type CanvasEntry,
|
|
5
|
+
type CanvasFrameEntry,
|
|
6
|
+
DEFAULT_OUT,
|
|
7
|
+
type FrameManifest,
|
|
8
|
+
MANIFEST_FORMAT,
|
|
9
|
+
} from "./project/manifest";
|
|
10
|
+
export {
|
|
11
|
+
type FrameItem,
|
|
12
|
+
type FrameMessage,
|
|
13
|
+
type FrameRequest,
|
|
14
|
+
type FrameTheme,
|
|
15
|
+
frameProtocol,
|
|
16
|
+
} from "./runtime/protocol";
|
package/src/indexer.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
|
|
3
|
+
const bindings = (file: ts.SourceFile) => {
|
|
4
|
+
const declarations = new Map<string, ts.Expression>();
|
|
5
|
+
const imports = new Map<string, string>();
|
|
6
|
+
for (const statement of file.statements) {
|
|
7
|
+
if (ts.isVariableStatement(statement))
|
|
8
|
+
for (const declaration of statement.declarationList.declarations)
|
|
9
|
+
if (ts.isIdentifier(declaration.name) && declaration.initializer)
|
|
10
|
+
declarations.set(declaration.name.text, declaration.initializer);
|
|
11
|
+
if (
|
|
12
|
+
ts.isImportDeclaration(statement) &&
|
|
13
|
+
statement.importClause?.namedBindings &&
|
|
14
|
+
ts.isNamedImports(statement.importClause.namedBindings)
|
|
15
|
+
)
|
|
16
|
+
for (const binding of statement.importClause.namedBindings.elements)
|
|
17
|
+
imports.set(binding.name.text, (statement.moduleSpecifier as ts.StringLiteral).text);
|
|
18
|
+
}
|
|
19
|
+
return { declarations, imports };
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const indexExamples = (path: string, source: string) => {
|
|
23
|
+
const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
24
|
+
const { declarations, imports } = bindings(file);
|
|
25
|
+
const object = (node?: ts.Expression): ts.ObjectLiteralExpression | undefined => {
|
|
26
|
+
if (!node) return;
|
|
27
|
+
if (ts.isObjectLiteralExpression(node)) return node;
|
|
28
|
+
if (ts.isSatisfiesExpression(node) || ts.isAsExpression(node) || ts.isParenthesizedExpression(node))
|
|
29
|
+
return object(node.expression);
|
|
30
|
+
if (ts.isIdentifier(node)) return object(declarations.get(node.text));
|
|
31
|
+
};
|
|
32
|
+
const property = (node: ts.ObjectLiteralExpression | undefined, key: string) => {
|
|
33
|
+
const value = node?.properties.find(
|
|
34
|
+
(property) => ts.isPropertyAssignment(property) && property.name.getText(file) === key,
|
|
35
|
+
);
|
|
36
|
+
return value && ts.isPropertyAssignment(value) ? value.initializer : undefined;
|
|
37
|
+
};
|
|
38
|
+
const text = (node?: ts.Expression) => (node && ts.isStringLiteral(node) ? node.text : undefined);
|
|
39
|
+
const defaults = file.statements.find(ts.isExportAssignment);
|
|
40
|
+
const meta = object(defaults?.expression);
|
|
41
|
+
const component = property(meta, "component")?.getText(file);
|
|
42
|
+
const stories: { exportName: string; id: string; name: string }[] = [];
|
|
43
|
+
for (const statement of file.statements) {
|
|
44
|
+
if (
|
|
45
|
+
!ts.isVariableStatement(statement) ||
|
|
46
|
+
!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
|
|
47
|
+
)
|
|
48
|
+
continue;
|
|
49
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
50
|
+
const value = object(declaration.initializer);
|
|
51
|
+
const id = text(property(value, "id"));
|
|
52
|
+
if (!id) continue;
|
|
53
|
+
const exportName = declaration.name.getText(file);
|
|
54
|
+
const name = text(property(value, "name")) ?? exportName.replace(/([a-z\d])([A-Z])/g, "$1 $2");
|
|
55
|
+
stories.push({ exportName, id, name });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
title: text(property(meta, "title")) ?? path.replace(/\.canvas\.tsx?$/, ""),
|
|
60
|
+
component,
|
|
61
|
+
componentImport: component ? imports.get(component) : undefined,
|
|
62
|
+
stories,
|
|
63
|
+
};
|
|
64
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type CanvasMeta, type CanvasProject, type CanvasVariant, composePreview } from "@pstdio/canvas";
|
|
2
|
+
|
|
3
|
+
interface PreviewInput {
|
|
4
|
+
kind: string;
|
|
5
|
+
suite: string;
|
|
6
|
+
source: string;
|
|
7
|
+
exportName?: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const createPreviewLoader =
|
|
11
|
+
(
|
|
12
|
+
modules: Record<string, () => Promise<Record<string, unknown>>>,
|
|
13
|
+
projects: Record<string, () => Promise<{ default: Record<string, unknown> }>>,
|
|
14
|
+
) =>
|
|
15
|
+
async (input: PreviewInput, imported: () => void) => {
|
|
16
|
+
const started = performance.now();
|
|
17
|
+
const module = await modules[input.source]?.();
|
|
18
|
+
if (!module) throw new Error(`Missing preview source: ${input.source}`);
|
|
19
|
+
const project = (await projects[input.suite]()).default;
|
|
20
|
+
const exportName = input.exportName!;
|
|
21
|
+
if (!module[exportName]) throw new Error(`Missing preview: ${input.source}#${exportName}`);
|
|
22
|
+
const importedAt = performance.now();
|
|
23
|
+
imported();
|
|
24
|
+
const preview = await composePreview(
|
|
25
|
+
module[exportName] as CanvasVariant,
|
|
26
|
+
module.default as CanvasMeta,
|
|
27
|
+
project as CanvasProject,
|
|
28
|
+
);
|
|
29
|
+
return { ...preview, timings: { importMs: importedAt - started, setupMs: performance.now() - importedAt } };
|
|
30
|
+
};
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
4
|
+
import { join, resolve, sep } from "node:path";
|
|
5
|
+
import { gzipSync } from "node:zlib";
|
|
6
|
+
import { ASSET_TYPES } from "./bundle";
|
|
7
|
+
import type { CanvasEntry, FrameManifest } from "./manifest";
|
|
8
|
+
|
|
9
|
+
type Metafile = NonNullable<Bun.BuildOutput["metafile"]>;
|
|
10
|
+
const toPosix = (path: string) => path.split(sep).join("/");
|
|
11
|
+
const outputName = (path: string) => path.replace(/^\.\//, "");
|
|
12
|
+
// Bun writes metafile paths with forward slashes, relative to the project root it built from.
|
|
13
|
+
const fromMetafile = (root: string, path: string) => toPosix(resolve(root, path));
|
|
14
|
+
const isFrameEntry = (root: string, path?: string) =>
|
|
15
|
+
Boolean(path && fromMetafile(root, path).endsWith("/entries/frame.tsx"));
|
|
16
|
+
|
|
17
|
+
/** The absolute paths of every file the build read. */
|
|
18
|
+
export const metafileInputs = (root: string, metafile: Metafile) =>
|
|
19
|
+
Object.keys(metafile.inputs).map((path) => resolve(root, path));
|
|
20
|
+
|
|
21
|
+
// Module files are named by content, so an existing file already holds these bytes. A new one
|
|
22
|
+
// appears whole, because readers may load modules while a build runs.
|
|
23
|
+
const writeModule = async (path: string, code: string) => {
|
|
24
|
+
if (existsSync(path)) return;
|
|
25
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
26
|
+
await writeFile(temporary, encode(code));
|
|
27
|
+
await rename(temporary, path);
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// Frames import modules by bare names that the frame maps to blob URLs, so relative chunk
|
|
31
|
+
// references become `canvas-preview:<name>`.
|
|
32
|
+
const rewriteImports = (code: string, names: Set<string>) =>
|
|
33
|
+
code.replace(/(["'`])\.\/([^"'`]+\.js)\1/g, (match, quote, file) =>
|
|
34
|
+
names.has(file) ? `${quote}canvas-preview:${file}${quote}` : match,
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
// Emitted images, fonts and media, as data URLs keyed by their output name.
|
|
38
|
+
const readAssets = async (staging: string) => {
|
|
39
|
+
const assets = new Map<string, string>();
|
|
40
|
+
for (const name of await readdir(staging)) {
|
|
41
|
+
const type = ASSET_TYPES[name.split(".").at(-1)!.toLowerCase()];
|
|
42
|
+
if (type) assets.set(name, `data:${type};base64,${(await readFile(join(staging, name))).toString("base64")}`);
|
|
43
|
+
}
|
|
44
|
+
return assets;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// JavaScript refers to an emitted asset as "./name" and CSS as url(./name) or url("./name").
|
|
48
|
+
const inlineAssets = (code: string, assets: Map<string, string>) =>
|
|
49
|
+
code.replace(/(["'(])\.\/([^"'()\s]+)/g, (match, before, name) => {
|
|
50
|
+
const url = assets.get(name);
|
|
51
|
+
return url ? `${before}${url}` : match;
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const encode = (code: string) => {
|
|
55
|
+
const bytes = gzipSync(code);
|
|
56
|
+
// The gzip OS byte describes the machine, not the content. Keep names stable across machines.
|
|
57
|
+
bytes[9] = 255;
|
|
58
|
+
return bytes.toString("base64");
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
type Output = Metafile["outputs"][string];
|
|
62
|
+
|
|
63
|
+
const moduleEntry = (root: string, output: Output, file: string, bytes: number) => {
|
|
64
|
+
const linked = (kind: string) =>
|
|
65
|
+
output.imports.filter((entry) => entry.kind === kind).map((entry) => outputName(entry.path));
|
|
66
|
+
// The frame entry's CSS bundle collects every canvas's styles; the runtime itself has none.
|
|
67
|
+
const css = output.cssBundle && !isFrameEntry(root, output.entryPoint) ? [outputName(output.cssBundle)] : undefined;
|
|
68
|
+
return {
|
|
69
|
+
file,
|
|
70
|
+
imports: linked("import-statement"),
|
|
71
|
+
dynamicImports: linked("dynamic-import"),
|
|
72
|
+
bytes,
|
|
73
|
+
...(css ? { css } : {}),
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const bindSources = (root: string, frames: FrameManifest, chunkFor: Map<string, string>, canvases: CanvasEntry[]) => {
|
|
78
|
+
for (const canvas of canvases) {
|
|
79
|
+
if (canvas.error) continue;
|
|
80
|
+
const script = chunkFor.get(toPosix(join(root, canvas.id)));
|
|
81
|
+
if (!script) throw new Error(`The canvas build produced no module for ${canvas.id}`);
|
|
82
|
+
const project = canvas.preview ? chunkFor.get(toPosix(join(root, canvas.preview))) : undefined;
|
|
83
|
+
frames.sources[canvas.id] = { script, ...(project ? { project } : {}) };
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Turns Bun's split output into the module graph frames load. Module files are named by their
|
|
89
|
+
* content, so a rebuild only writes the modules that changed.
|
|
90
|
+
*/
|
|
91
|
+
export const archiveBuild = async (input: {
|
|
92
|
+
root: string;
|
|
93
|
+
out: string;
|
|
94
|
+
staging: string;
|
|
95
|
+
metafile: Metafile;
|
|
96
|
+
canvases: CanvasEntry[];
|
|
97
|
+
}) => {
|
|
98
|
+
const { root, out, staging, metafile, canvases } = input;
|
|
99
|
+
const outputs = Object.entries(metafile.outputs);
|
|
100
|
+
const names = new Set(outputs.map(([path]) => outputName(path)));
|
|
101
|
+
const assets = await readAssets(staging);
|
|
102
|
+
const frames: FrameManifest = { entry: "", catalog: "", sources: {}, modules: {}, styles: [] };
|
|
103
|
+
const chunkFor = new Map<string, string>();
|
|
104
|
+
await mkdir(join(out, "modules"), { recursive: true });
|
|
105
|
+
for (const [path, output] of outputs) {
|
|
106
|
+
const name = outputName(path);
|
|
107
|
+
const raw = inlineAssets(await readFile(join(staging, name), "utf8"), assets);
|
|
108
|
+
const code = name.endsWith(".js") ? rewriteImports(raw, names) : raw;
|
|
109
|
+
const file = `modules/${createHash("sha256").update(code).digest("hex")}.txt`;
|
|
110
|
+
await writeModule(join(out, file), code);
|
|
111
|
+
const bytes = Buffer.byteLength(code);
|
|
112
|
+
if (name.endsWith(".css")) {
|
|
113
|
+
frames.styles.push(name);
|
|
114
|
+
frames.modules[name] = { file, imports: [], dynamicImports: [], bytes };
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
frames.modules[name] = moduleEntry(root, output, file, bytes);
|
|
118
|
+
if (isFrameEntry(root, output.entryPoint)) frames.entry = name;
|
|
119
|
+
else if (output.entryPoint) chunkFor.set(fromMetafile(root, output.entryPoint), name);
|
|
120
|
+
}
|
|
121
|
+
if (!frames.entry) throw new Error("The canvas build produced no frame entry");
|
|
122
|
+
// The entry holds the map of canvas loaders; frames follow only the dynamic imports they need.
|
|
123
|
+
frames.catalog = frames.entry;
|
|
124
|
+
bindSources(root, frames, chunkFor, canvases);
|
|
125
|
+
return frames;
|
|
126
|
+
};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { archiveBuild, metafileInputs } from "./archive";
|
|
6
|
+
import { bundleCanvases } from "./bundle";
|
|
7
|
+
import { createPreviewFinder, discoverCanvases, listCanvasFiles } from "./discover";
|
|
8
|
+
import { collectInputs, inputsUnchanged, readInputs } from "./inputs";
|
|
9
|
+
import { lockOutput } from "./lock";
|
|
10
|
+
import { type CanvasBuildManifest, DEFAULT_OUT, MANIFEST_FORMAT } from "./manifest";
|
|
11
|
+
|
|
12
|
+
export interface CanvasBuildOptions {
|
|
13
|
+
/** The project root. */
|
|
14
|
+
root: string;
|
|
15
|
+
/** The output folder, relative to the root or absolute. */
|
|
16
|
+
out?: string;
|
|
17
|
+
/** Build even when no input changed. */
|
|
18
|
+
force?: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Bun reports real paths, so a root reached through a symbolic link is resolved first. */
|
|
22
|
+
export const resolveRoot = (root: string) => realpathSync(resolve(root));
|
|
23
|
+
export const resolveOut = (root: string, out = DEFAULT_OUT) => resolve(root, out);
|
|
24
|
+
|
|
25
|
+
export const readManifest = async (out: string) => {
|
|
26
|
+
try {
|
|
27
|
+
const manifest = JSON.parse(await readFile(join(out, "manifest.json"), "utf8")) as CanvasBuildManifest;
|
|
28
|
+
return manifest.format === MANIFEST_FORMAT ? manifest : undefined;
|
|
29
|
+
} catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* True when the canvas files, their preview files and every input of the last build are unchanged.
|
|
36
|
+
* Cheap enough to poll: it lists files and reads modification times, but parses nothing.
|
|
37
|
+
*/
|
|
38
|
+
export const isCurrent = async (root: string, manifest: CanvasBuildManifest) => {
|
|
39
|
+
const findPreview = createPreviewFinder(root);
|
|
40
|
+
const files = await listCanvasFiles(root);
|
|
41
|
+
const built = manifest.canvases;
|
|
42
|
+
if (files.length !== built.length) return false;
|
|
43
|
+
for (const [index, file] of files.entries())
|
|
44
|
+
if (built[index]?.id !== file || built[index]?.preview !== findPreview(file)) return false;
|
|
45
|
+
return inputsUnchanged(root, manifest.inputs);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// Readers may still load modules of the manifest they read last, so keep that generation too.
|
|
49
|
+
const removeUnusedModules = async (out: string, manifests: (CanvasBuildManifest | undefined)[]) => {
|
|
50
|
+
const used = new Set(
|
|
51
|
+
manifests.flatMap((manifest) => Object.values(manifest?.frames.modules ?? {}).map((module) => module.file)),
|
|
52
|
+
);
|
|
53
|
+
for (const name of await readdir(join(out, "modules")))
|
|
54
|
+
if (!used.has(`modules/${name}`)) await rm(join(out, "modules", name), { force: true });
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// A build that was killed leaves its work folder behind.
|
|
58
|
+
const removeWorkFolders = async (out: string) => {
|
|
59
|
+
for (const name of await readdir(out))
|
|
60
|
+
if (name.startsWith(".work-")) await rm(join(out, name), { recursive: true, force: true });
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const writeManifest = async (out: string, manifest: CanvasBuildManifest) => {
|
|
64
|
+
// Readers see the old manifest or the new one, never a partly written file.
|
|
65
|
+
const temporary = join(out, `manifest.${randomUUID()}.json`);
|
|
66
|
+
await writeFile(temporary, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
67
|
+
await rename(temporary, join(out, "manifest.json"));
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const build = async (root: string, out: string, previous: CanvasBuildManifest | undefined) => {
|
|
71
|
+
// Files saved from now on may be read before or after the change; they are recorded as unknown.
|
|
72
|
+
// The pause puts every earlier write before the cutoff.
|
|
73
|
+
const startedAt = Date.now() + 1;
|
|
74
|
+
await Bun.sleep(2);
|
|
75
|
+
const discovered = await discoverCanvases(root);
|
|
76
|
+
const workdir = join(out, `.work-${randomUUID()}`);
|
|
77
|
+
try {
|
|
78
|
+
const { result, errors, failedFiles } = await bundleCanvases(root, workdir, join(workdir, "dist"), discovered);
|
|
79
|
+
const metafile = result.metafile!;
|
|
80
|
+
const canvases = discovered.map((canvas) =>
|
|
81
|
+
errors.has(canvas.id) ? { ...canvas, error: errors.get(canvas.id) } : canvas,
|
|
82
|
+
);
|
|
83
|
+
const read = metafileInputs(root, metafile).filter((file) => !file.startsWith(workdir));
|
|
84
|
+
const manifest: CanvasBuildManifest = {
|
|
85
|
+
format: MANIFEST_FORMAT,
|
|
86
|
+
builtAt: new Date().toISOString(),
|
|
87
|
+
canvases,
|
|
88
|
+
frames: await archiveBuild({ root, out, staging: join(workdir, "dist"), metafile, canvases }),
|
|
89
|
+
inputs: await readInputs(root, collectInputs(root, read, canvases, failedFiles), startedAt),
|
|
90
|
+
};
|
|
91
|
+
await writeManifest(out, manifest);
|
|
92
|
+
await removeUnusedModules(out, [manifest, previous]);
|
|
93
|
+
return manifest;
|
|
94
|
+
} finally {
|
|
95
|
+
await rm(workdir, { recursive: true, force: true });
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
export const buildCanvases = async (options: CanvasBuildOptions) => {
|
|
100
|
+
const root = resolveRoot(options.root);
|
|
101
|
+
const out = resolveOut(root, options.out);
|
|
102
|
+
await mkdir(out, { recursive: true });
|
|
103
|
+
await writeFile(join(out, ".gitignore"), "*\n");
|
|
104
|
+
const lock = await lockOutput(out);
|
|
105
|
+
try {
|
|
106
|
+
await removeWorkFolders(out);
|
|
107
|
+
const previous = await readManifest(out);
|
|
108
|
+
if (!options.force && previous && (await isCurrent(root, previous))) return { built: false, manifest: previous };
|
|
109
|
+
return { built: true, manifest: await build(root, out, previous) };
|
|
110
|
+
} finally {
|
|
111
|
+
await lock.release();
|
|
112
|
+
}
|
|
113
|
+
};
|