AI-native design editor. Open-source Figma alternative.
import { existsSync, watch } from 'node:fs'
import { glob, lstat, mkdir, mkdtemp, rename, rm, rmdir, writeFile } from 'node:fs/promises'
import {
basename,
dirname,
extname,
isAbsolute,
join,
posix,
relative,
resolve,
sep
} from 'node:path'
import { uniq } from 'es-toolkit'
import { BUILTIN_IO_FORMATS, IORegistry, vectorElement } from '@open-pencil/core/io'
import {
exportStorybook,
STORYBOOK_FRAMEWORKS,
type StorybookFile,
type StorybookFramework
} from '@open-pencil/dom-css'
import { requireFile } from '#cli/app/client'
import { applyExportFontPolicy } from '#cli/commands/export/font-policy'
import { ok, printError } from '#cli/format'
import { loadDocument, populateWholeDocument, requirePage } from '#cli/headless'
import { documentFolder, storyFonts } from './fonts'
import { readManifest, writeManifest, type StoryManifest, type StoryOwner } from './manifest'
import { readStoryRules, storyPlan } from './rules'
interface StorybookArgs {
file?: string
/** Every positional argument: a shell-expanded glob arrives as several files. */
_?: string[]
output?: string
beside?: boolean
page?: string
node?: string
framework: string
/** `tailwind` styles Vue and React components with utilities rather than a stylesheet. */
css: string
'design-images': boolean
'font-policy': string
watch?: boolean
/** A rules file for which stories each component gets and its title. */
rules?: string
/** `none` ships no font files with the stories. */
fonts?: string
}
const io = new IORegistry(BUILTIN_IO_FORMATS)
function isStorybookFramework(value: string): value is StorybookFramework {
return STORYBOOK_FRAMEWORKS.some((framework) => framework === value)
}
function toPosix(path: string): string {
return path.split(sep).join(posix.sep)
}
/** Repository-relative path for `openpencil://` links, when the file sits under the cwd. */
function linkPath(file: string): string | undefined {
const path = toPosix(relative(process.cwd(), resolve(file)))
return path.startsWith('../') || isAbsolute(path) ? undefined : path
}
/** What an export replaces: every page of `source`, or only `page` for a one-page export. */
interface ExportScope {
source: string
page?: string
}
function owns(scope: ExportScope, owner: StoryOwner): boolean {
return owner.source === scope.source && (scope.page === undefined || owner.page === scope.page)
}
function conflict(outputDir: string, path: string, manifest: StoryManifest, scope: ExportScope) {
const target = join(outputDir, path)
const elsewhere = `; export ${scope.source} to another --output directory.`
if (!Object.hasOwn(manifest.files, path))
return new Error(`${target} was not generated by this export${elsewhere}`)
const owner = manifest.files[path]
if (owner.source === scope.source)
return new Error(
`${target} holds page ${owner.page} of ${scope.source}; export the whole document to renumber its stories.`
)
return new Error(`${target} was generated from ${owner.source}, page ${owner.page}${elsewhere}`)
}
function isErrorCode(error: unknown, ...codes: string[]): boolean {
return error instanceof Error && 'code' in error && codes.includes(String(error.code))
}
/**
* Refuses a path whose `.design` folder is a symbolic link: removing or writing an image
* through it would reach outside the output directory.
*/
async function refuseLinkedFolder(outputDir: string, path: string): Promise<void> {
const folder = dirname(path)
if (folder === '.') return
const stats = await lstat(join(outputDir, folder)).catch((error: unknown) => {
if (isErrorCode(error, 'ENOENT')) return null
throw error
})
if (stats && !stats.isDirectory())
throw new Error(`${join(outputDir, folder)} is not a folder; remove it and export again.`)
}
/**
* Removes the files the manifest says a previous export of this scope generated, so a
* component deleted or renamed in the document does not linger, and returns the manifest
* for the new files. Refuses before removing anything when the export would overwrite a
* file it did not generate: a hand-written story, another document's, or someone's image.
*/
async function replaceGeneratedFiles(
outputDir: string,
scope: ExportScope,
files: StorybookFile[]
): Promise<StoryManifest> {
const manifest = await readManifest(outputDir)
const owned = new Set(
Object.entries(manifest.files)
.filter(([, owner]) => owns(scope, owner))
.map(([path]) => path)
)
const paths = files.map((file) => file.path)
for (const path of new Set([...paths, ...owned])) await refuseLinkedFolder(outputDir, path)
for (const path of paths) {
if (owned.has(path) || !existsSync(join(outputDir, path))) continue
throw conflict(outputDir, path, manifest, scope)
}
for (const path of owned) await rm(join(outputDir, path), { force: true })
for (const folder of new Set([...owned].map(dirname))) {
if (folder === '.') continue
// Only a folder the removal emptied goes; anything else someone put there stays.
await rmdir(join(outputDir, folder)).catch((error: unknown) => {
if (!isErrorCode(error, 'ENOTEMPTY', 'ENOENT', 'EEXIST')) throw error
})
}
const kept = Object.entries(manifest.files).filter(([path]) => !owned.has(path))
const added = files.map((file) => [file.path, { source: scope.source, page: file.page }])
return { version: 1, files: Object.fromEntries([...kept, ...added]) }
}
async function writeStories(
args: StorybookArgs,
file: string,
framework: StorybookFramework,
outputDir: string
): Promise<number> {
const graph = await loadDocument(file)
const pageId = args.page ? requirePage(graph, args.page).id : undefined
populateWholeDocument(graph)
if (args['design-images']) {
const pageIds = pageId ? [pageId] : graph.getPages().map((page) => page.id)
await applyExportFontPolicy(graph, pageIds, 'PNG', args['font-policy'])
}
// Read on every export, so a watch picks up edited rules with the next save.
const rules = await readStoryRules(args.rules)
// Relative to the output, the document's path tells apart documents exported there together.
const source = toPosix(relative(outputDir, resolve(file)))
const files = await exportStorybook(graph, {
framework,
styling: args.css === 'tailwind' ? 'tailwind' : 'css',
pageId,
plan: rules ? storyPlan(rules) : undefined,
fonts: args.fonts === 'none' ? undefined : storyFonts,
folder: documentFolder(source, args.page),
// Titled by the document, so stories of documents exported together stay apart.
document: basename(file, extname(file)),
linkPath: linkPath(file),
vectorElement,
renderDesignImage: args['design-images']
? async (nodeId) => {
const result = await io.exportContent(
'png',
{ graph, target: { scope: 'node', nodeId } },
{ format: 'PNG', scale: 2 }
)
if (!(result.data instanceof Uint8Array)) throw new Error('PNG export returned text.')
return result.data
}
: undefined
})
if (files.length === 0)
throw new Error(`No components found in ${args.page ? `page "${args.page}"` : 'the document'}.`)
// Relative to the output, the document's path is the same on every machine and cwd.
const scope = { source, page: args.page }
await mkdir(outputDir, { recursive: true })
// Staged next to the output so a failed write leaves the previous export in place,
// and in a dot folder, which Storybook's story globs skip.
const staging = await mkdtemp(join(outputDir, '.openpencil-export-'))
try {
for (const story of files) {
await mkdir(dirname(join(staging, story.path)), { recursive: true })
await writeFile(join(staging, story.path), story.content)
}
const manifest = await replaceGeneratedFiles(outputDir, scope, files)
for (const { path } of files) {
await mkdir(dirname(join(outputDir, path)), { recursive: true })
await rename(join(staging, path), join(outputDir, path))
}
await writeManifest(outputDir, manifest)
} finally {
await rm(staging, { recursive: true, force: true })
}
return files.filter((story) => story.path.endsWith('.stories.ts')).length
}
/**
* Re-exports a document on every save. One folder watch covers all its documents, since
* editors that save by rename replace the file, and every export runs through one queue:
* documents in a folder share its manifest, so two exports must never overlap.
*/
function watchDocuments(files: string[], onChange: (file: string) => Promise<void>): void {
const timers = new Map<string, ReturnType<typeof setTimeout>>()
let running = Promise.resolve()
const enqueue = (file: string) => {
running = running.then(() => onChange(file))
}
const folders = new Map<string, string[]>()
for (const file of files) {
const folder = dirname(resolve(file))
folders.set(folder, [...(folders.get(folder) ?? []), file])
}
for (const [folder, documents] of folders) {
watch(folder, (_event, name) => {
const file = documents.find((document) => basename(document) === name)
if (!file) return
clearTimeout(timers.get(file))
timers.set(
file,
setTimeout(() => enqueue(file), 200)
)
})
}
}
/**
* The documents to export: each argument is a file, or a quoted glob pattern
* for many.
*
* An existing path is that file, so a name containing glob syntax still opens
* directly. Anything else goes to `glob()`, which matches a plain path to
* itself and expands every pattern it supports, including the extglobs and
* escapes that inspecting the string for glob characters gets wrong.
*/
async function resolveDocuments(args: StorybookArgs): Promise<string[]> {
const patterns = args._?.length ? args._ : [requireFile(args.file)]
const documents: string[] = []
for (const pattern of patterns) {
if (existsSync(pattern)) {
documents.push(pattern)
continue
}
if (typeof glob !== 'function') throw new Error('Glob patterns need Node.js 22 or later.')
const matches: string[] = []
for await (const match of glob(pattern)) matches.push(match)
if (matches.length === 0) throw new Error(`No documents match ${pattern}.`)
documents.push(...matches.sort())
}
return uniq(documents)
}
function outputFor(args: StorybookArgs, file: string): string {
if (args.beside) return dirname(resolve(file))
return resolve(args.output ?? `${basename(file, extname(file))}-stories`)
}
function message(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
export async function exportStorybookFromFile(args: StorybookArgs): Promise<void> {
if (args.node) {
printError('--node is not supported for Storybook export. Use --page to limit it to one page.')
process.exit(1)
}
if (args.beside && args.output) {
printError('--beside and --output cannot be used together.')
process.exit(1)
}
const framework = args.framework
if (!isStorybookFramework(framework)) {
printError(
`Invalid Storybook framework "${framework}". Use ${STORYBOOK_FRAMEWORKS.join(', ')}.`
)
process.exit(1)
}
if (args.css !== 'inline' && args.css !== 'tailwind') {
printError(`Invalid Storybook CSS output "${args.css}". Use inline or tailwind.`)
process.exit(1)
}
let documents: string[]
try {
documents = await resolveDocuments(args)
} catch (error) {
printError(message(error))
process.exit(1)
}
if (documents.length > 1 && !args.beside && !args.output) {
printError(
`${documents.length} documents need --beside, to write stories next to each, or --output.`
)
process.exit(1)
}
if (documents.length > 1 && args.page) {
printError('--page names a page of one document; export a single document with it.')
process.exit(1)
}
const run = async (file: string) => {
const outputDir = outputFor(args, file)
const count = await writeStories(args, file, framework, outputDir)
console.log(ok(`Exported ${count} story files from ${file} to ${outputDir}`))
}
// One after another: documents that share an output folder share its manifest.
const failed: string[] = []
for (const file of documents) {
try {
await run(file)
} catch (error) {
printError(`${file}: ${message(error)}`)
failed.push(file)
}
}
if (!args.watch) {
if (failed.length > 0) process.exit(1)
return
}
// A save can land mid-write or break the document; report it and keep watching.
watchDocuments(documents, (file) =>
run(file).catch((error: unknown) => printError(`${file}: ${message(error)}`))
)
console.log(
ok(
`Watching ${documents.length === 1 ? documents[0] : `${documents.length} documents`} for changes`
)
)
}