@shware/workflow-ui 2.1.3 → 2.1.4
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/dist/cli.mjs +4 -8
- package/dist/cli.mjs.map +1 -1
- package/dist/config.d.mts +0 -2
- package/dist/config.d.mts.map +1 -1
- package/dist/config.mjs +1 -2
- package/dist/index.d.mts +0 -28
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +26 -52
- package/dist/index.mjs.map +1 -1
- package/dist/postgres.d.mts +0 -2
- package/dist/postgres.d.mts.map +1 -1
- package/dist/postgres.mjs +1 -2
- package/package.json +10 -10
package/dist/cli.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url";
|
|
|
8
8
|
import tailwindcss from "@tailwindcss/vite";
|
|
9
9
|
import react from "@vitejs/plugin-react";
|
|
10
10
|
import svgr from "vite-plugin-svgr";
|
|
11
|
-
|
|
11
|
+
// src/server/project.ts
|
|
12
12
|
/** The modules a Vite server has evaluated for SSR — where registries are located by identity. */
|
|
13
13
|
function ssrModulesOf(server) {
|
|
14
14
|
return function* () {
|
|
@@ -199,8 +199,7 @@ ${registries.join("\n")}${stats === void 0 ? "" : `\n stats: ${stats},`}
|
|
|
199
199
|
};
|
|
200
200
|
`;
|
|
201
201
|
}
|
|
202
|
-
|
|
203
|
-
//#region src/server.ts
|
|
202
|
+
// src/server.ts
|
|
204
203
|
/**
|
|
205
204
|
* The studio dev server.
|
|
206
205
|
*
|
|
@@ -605,8 +604,7 @@ async function startStudio(options = {}) {
|
|
|
605
604
|
await server.listen();
|
|
606
605
|
return server;
|
|
607
606
|
}
|
|
608
|
-
|
|
609
|
-
//#region src/generate.ts
|
|
607
|
+
// src/generate.ts
|
|
610
608
|
/** The host's formatter may rewrap the file, change quotes or trailing commas: not a difference. */
|
|
611
609
|
function normalize(source) {
|
|
612
610
|
return source.replace(/"/g, "'").replace(/\s+/g, " ").replace(/ ?([{}()[\],;:=<>.]) ?/g, "$1").replace(/,([}\])])/g, "$1").trim();
|
|
@@ -626,8 +624,7 @@ async function generateSchema(options) {
|
|
|
626
624
|
writeFileSync(out, file);
|
|
627
625
|
return "written";
|
|
628
626
|
}
|
|
629
|
-
|
|
630
|
-
//#region src/cli.ts
|
|
627
|
+
// src/cli.ts
|
|
631
628
|
function parseArgs(argv) {
|
|
632
629
|
const args = {
|
|
633
630
|
open: false,
|
|
@@ -706,7 +703,6 @@ async function main() {
|
|
|
706
703
|
}
|
|
707
704
|
}
|
|
708
705
|
main();
|
|
709
|
-
//#endregion
|
|
710
706
|
export {};
|
|
711
707
|
|
|
712
708
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":[],"sources":["../src/server/project.ts","../src/server.ts","../src/generate.ts","../src/cli.ts"],"sourcesContent":["import {\n ConfigCompileError,\n type JourneyConfig,\n compileConfig,\n isConfig,\n isDiscordTemplate,\n isEmailTemplate,\n isPushTemplate,\n isSlackTemplate,\n} from '@shware/workflow';\nimport type { ViteDevServer } from 'vite';\nimport type { ResolvedStudioConfig, StudioError } from '../config';\n\n/**\n * Reading the project — on the dev server, never in the browser.\n *\n * workflow.config.ts default-exports `defineConfig({...})` from\n * `@shware/workflow`, and the studio reads exactly that: its workflows,\n * segments, actions, template registries, title and what the email templates share. It is\n * compiled with `compileConfig`, the same compile the Worker deploys, so the\n * studio lists exactly what would ship.\n *\n * What crosses to the browser is decided here too. The config is a source\n * object — schemas, components, the contract, runtime settings, whatever the\n * host imports — so it stays on the server. The browser receives the compiled\n * IR as JSON, and imports the two template registries (the code a preview has\n * to run) straight from the modules that export them, located by identity in\n * Vite's SSR module graph. It never imports workflow.config.ts.\n */\n\n/** How the server evaluates a project module (Vite's ssrLoadModule in the studio). */\nexport type ModuleLoader = (file: string) => Promise<Record<string, unknown>>;\n\n/** Every module the loader has evaluated so far, with its exports. */\nexport type LoadedModules = () => Iterable<[file: string, exports: Record<string, unknown>]>;\n\n/** The modules a Vite server has evaluated for SSR — where registries are located by identity. */\nexport function ssrModulesOf(server: ViteDevServer): LoadedModules {\n return function* () {\n for (const mod of server.moduleGraph.idToModuleMap.values()) {\n const exports = mod.ssrModule as Record<string, unknown> | null;\n if (mod.file !== null && exports !== null) yield [mod.file, exports];\n }\n };\n}\n\ntype Channel = 'email' | 'push' | 'discord' | 'slack';\n\n/** One named export the browser imports — or one channel of it, for an exported `{ email, push }`. */\nexport interface ModuleRef {\n file: string;\n name: string;\n property?: Channel;\n}\n\n/** Per channel: how to recognise its entries, the factory to name, the virtual module's field. */\nconst CHANNELS: Record<\n Channel,\n { is: (value: unknown) => boolean; factory: string; field: string }\n> = {\n email: { is: isEmailTemplate, factory: 'emailTemplate', field: 'emails' },\n push: { is: isPushTemplate, factory: 'pushTemplate', field: 'pushes' },\n discord: { is: isDiscordTemplate, factory: 'discordTemplate', field: 'discords' },\n slack: { is: isSlackTemplate, factory: 'slackTemplate', field: 'slacks' },\n};\n\nexport interface StudioSnapshot {\n /** The JSON half of the virtual module: compiled output and labels only. */\n payload: Omit<ResolvedStudioConfig, 'emails' | 'pushes' | 'discords' | 'slacks' | 'stats'>;\n /** The import half: where each registry comes from. */\n registries: Record<Channel, ModuleRef | undefined>;\n}\n\n/** A project the studio cannot read: the message says what to change. */\nclass StudioLoadError extends Error {}\n\n/* --------------------------------- Imports --------------------------------- */\n\n/**\n * The module that exports `registry`, by identity: the registry itself, or\n * else an exported `{ email, push }` holding it (`export const templates =\n * { email, push }`).\n * workflow.config.ts itself is never a candidate: importing it would bring the\n * whole config (and everything it imports) into the browser. Sorted by path,\n * so the answer does not depend on load order.\n */\nfunction locate(\n channel: Channel,\n registry: Record<string, unknown> | undefined,\n modules: LoadedModules,\n configPath: string\n): ModuleRef | undefined {\n if (registry === undefined) return undefined;\n const { is: isTemplate, factory } = CHANNELS[channel];\n for (const [key, entry] of Object.entries(registry)) {\n if (!isTemplate(entry)) {\n throw new StudioLoadError(\n `templates.${channel}['${key}'] is not a ${factory}({...}) definition — every entry of the ${channel} registry must be one.`\n );\n }\n }\n /* An empty registry has nothing for the browser to import. */\n if (Object.keys(registry).length === 0) return undefined;\n const sorted = [...modules()]\n .filter(([file]) => file !== configPath)\n .sort(([a], [b]) => a.localeCompare(b));\n for (const [file, exports] of sorted) {\n for (const [name, exported] of Object.entries(exports)) {\n if (exported === registry) return { file, name };\n }\n }\n for (const [file, exports] of sorted) {\n for (const [name, exported] of Object.entries(exports)) {\n if (\n typeof exported === 'object' &&\n exported !== null &&\n (exported as Partial<Record<Channel, unknown>>)[channel] === registry\n ) {\n return { file, name, property: channel };\n }\n }\n }\n throw new StudioLoadError(\n `templates.${channel} is not exported from a module of its own. Export the registry ` +\n `(e.g. \\`export const ${channel} = {...}\\` in src/${channel}/index.ts, or ` +\n '`export const templates = { email, push }` in src/templates.ts) ' +\n 'and import it into workflow.config.ts — the studio loads that module, never the config, into the browser.'\n );\n}\n\n/* --------------------------------- Snapshot -------------------------------- */\n\nfunction errorOf(error: unknown): StudioError {\n return {\n kind: error instanceof ConfigCompileError ? 'compile' : 'load',\n message: error instanceof Error ? error.message : String(error),\n };\n}\n\nfunction failed(error: unknown, title?: string): StudioSnapshot {\n return {\n payload: {\n ...(title !== undefined ? { title } : {}),\n workflows: {},\n segments: [],\n email: {},\n error: errorOf(error),\n },\n registries: { email: undefined, push: undefined, discord: undefined, slack: undefined },\n };\n}\n\n/**\n * Load and compile. Never throws: a config that fails to load, is not a\n * `defineConfig({...})`, holds something other than template definitions, or\n * does not compile becomes a snapshot carrying the error, which the studio\n * shows in place of its views — a compile error names the workflow and node.\n */\nexport async function loadSnapshot(options: {\n configPath: string;\n load: ModuleLoader;\n modules: LoadedModules;\n}): Promise<StudioSnapshot> {\n const { configPath, load, modules } = options;\n let config: JourneyConfig;\n let registries: StudioSnapshot['registries'];\n try {\n const exported = (await load(configPath)).default;\n if (!isConfig(exported)) {\n throw new StudioLoadError(\n `${configPath} must \\`export default defineConfig({...})\\` from '@shware/workflow'.`\n );\n }\n config = exported;\n registries = {\n email: locate('email', config.templates?.email, modules, configPath),\n push: locate('push', config.templates?.push, modules, configPath),\n discord: locate('discord', config.templates?.discord, modules, configPath),\n slack: locate('slack', config.templates?.slack, modules, configPath),\n };\n } catch (error) {\n return failed(error);\n }\n\n const unsubscribeUrl = config.email?.unsubscribeUrl;\n const quickClickMs = config.email?.tracking?.quickClickMs;\n const shared = {\n ...(config.title !== undefined ? { title: config.title } : {}),\n email: {\n ...(unsubscribeUrl !== undefined ? { unsubscribeUrl } : {}),\n ...(quickClickMs !== undefined ? { tracking: { quickClickMs } } : {}),\n },\n };\n\n try {\n const bundle = compileConfig(config);\n return {\n payload: {\n ...shared,\n workflows: Object.fromEntries(bundle.workflows.map((workflow) => [workflow.id, workflow])),\n segments: bundle.segments,\n },\n registries,\n };\n } catch (error) {\n return {\n payload: { ...shared, workflows: {}, segments: [], error: errorOf(error) },\n registries,\n };\n }\n}\n\n/* ------------------------------ Virtual module ----------------------------- */\n\n/** The `StatsSource` methods, the only names the stats endpoint answers. */\nexport const STATS_METHODS = [\n 'reports',\n 'segments',\n 'profiles',\n 'nodeStats',\n 'metrics',\n 'links',\n 'messages',\n] as const;\nexport type StatsMethod = (typeof STATS_METHODS)[number];\n\n/**\n * The module the browser imports as `virtual:workflow-config`: the payload as\n * a JSON literal, the template registries as imports from their own modules\n * (re-keyed by template id), and\n * the stats source as calls to the studio's server, one per method\n * workflow.stats.ts defines — the source itself runs there, next to the\n * database and the secrets it reads with, never in the browser.\n */\n/** An export name as an import names it: quoted (ES2022) when it is not an identifier. */\nconst exportName = (name: string) =>\n /^[A-Za-z_$][\\w$]*$/.test(name) ? name : JSON.stringify(name);\n\nexport function virtualModule(\n snapshot: StudioSnapshot,\n statsMethods: readonly StatsMethod[] | undefined\n): string {\n const imports: string[] = [];\n const importOf = (ref: ModuleRef, local: string): string => {\n /* One channel of an exported `{ email, push }`: import the whole under its own alias. */\n const binding = ref.property === undefined ? local : `${local}Source`;\n imports.push(\n ref.name === 'default'\n ? `import ${binding} from ${JSON.stringify(ref.file)};`\n : `import { ${ref.name === binding ? binding : `${exportName(ref.name)} as ${binding}`} } from ${JSON.stringify(ref.file)};`\n );\n return ref.property === undefined ? binding : `${binding}.${ref.property}`;\n };\n const registries = (Object.keys(CHANNELS) as Channel[]).map((channel) => {\n const ref = snapshot.registries[channel];\n const { field } = CHANNELS[channel];\n return ` ${field}: ${ref === undefined ? '{}' : `byId(${importOf(ref, field)})`},`;\n });\n const stats =\n statsMethods === undefined\n ? undefined\n : `{ ${statsMethods.map((method) => `${method}: call(${JSON.stringify(method)})`).join(', ')} }`;\n const call =\n stats === undefined\n ? ''\n : `\nconst call = (method) => async (...args) => {\n const response = await fetch(\\`/__studio/stats/\\${method}\\`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(args),\n });\n const body = await response.json();\n if (!response.ok) throw new Error(body.error ?? \\`stats \\${method} failed: \\${response.status}\\`);\n return body;\n};`;\n\n return `${imports.join('\\n')}${call}\n/* The views look a template up by its id, the name messages use, never by the property holding it. */\nconst byId = (registry) => Object.fromEntries(Object.values(registry).map((t) => [t.id, t]));\nconst payload = ${JSON.stringify(snapshot.payload)};\nexport default {\n ...payload,\n${registries.join('\\n')}${stats === undefined ? '' : `\\n stats: ${stats},`}\n};\n`;\n}\n","import { existsSync, realpathSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { dirname, isAbsolute, relative, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport tailwindcss from '@tailwindcss/vite';\nimport react from '@vitejs/plugin-react';\nimport {\n type Plugin,\n type ViteDevServer,\n createServer,\n normalizePath,\n searchForWorkspaceRoot,\n} from 'vite';\nimport svgr from 'vite-plugin-svgr';\nimport {\n STATS_METHODS,\n type StatsMethod,\n loadSnapshot,\n ssrModulesOf,\n virtualModule,\n} from './server/project';\n\n/**\n * The studio dev server.\n *\n * Rather than shipping a prebuilt SPA and a JSON API, the CLI runs Vite over\n * the app source with the project injected as a virtual module: compiled on\n * the server, the template registries imported by the browser from their own\n * modules. Vite serves our app and the user's react-email components as one\n * graph — HMR on every one of them for free, and email previews render with\n * exactly the component code on disk.\n */\n\nconst packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));\n\n/** `src/app` when running from source in the monorepo, the published copy otherwise. */\nfunction resolveAppRoot(): string {\n const candidates = [resolve(packageRoot, 'src/app'), resolve(packageRoot, '../src/app')];\n const found = candidates.find((path) => existsSync(resolve(path, 'index.html')));\n if (!found) throw new Error('workflow-ui: could not locate the app root');\n return found;\n}\n\nconst CONFIG_CANDIDATES = [\n 'workflow.config.ts',\n 'workflow.config.tsx',\n 'workflow.config.js',\n 'workflow.config.mjs',\n];\n\n/**\n * The project file — `export default defineConfig({...})` from\n * `@shware/workflow`. Required: it is the only place the studio reads\n * definitions from.\n */\nexport function findConfig(cwd: string, explicit?: string): string {\n if (explicit !== undefined) {\n const path = resolve(cwd, explicit);\n if (!existsSync(path)) throw new Error(`workflow-ui: config not found at ${path}`);\n return path;\n }\n const found = CONFIG_CANDIDATES.map((name) => resolve(cwd, name)).find((path) =>\n existsSync(path)\n );\n if (found === undefined) {\n throw new Error(\n `workflow-ui: no workflow.config.ts in ${cwd}.\\n` +\n `Export defineConfig({ workflows, templates }) from '@shware/workflow' there, or pass --config <path>.`\n );\n }\n return found;\n}\n\nconst STATS_CANDIDATES = ['workflow.stats.ts', 'workflow.stats.tsx', 'workflow.stats.js'];\n\n/**\n * The studio's optional stats source, apart from the project: an explicit\n * path must exist; otherwise `workflow.stats.ts` beside the config, if any.\n */\nexport function findStats(cwd: string, explicit?: string): string | undefined {\n if (explicit !== undefined) {\n const path = resolve(cwd, explicit);\n if (!existsSync(path)) throw new Error(`workflow-ui: stats source not found at ${path}`);\n return path;\n }\n return STATS_CANDIDATES.map((name) => resolve(cwd, name)).find((path) => existsSync(path));\n}\n\n/* ---------------------------------- Project --------------------------------- */\n\nconst VIRTUAL_ID = 'virtual:workflow-config';\nconst RESOLVED_ID = `\\0${VIRTUAL_ID}`;\n\nconst NODE_MODULES = /[/\\\\]node_modules[/\\\\]/;\n\n/**\n * Every file the last project load evaluated: the config and, transitively,\n * whatever it imported in Vite's SSR module graph — wherever those files live.\n * Dependencies under node_modules are left out: they change with an install,\n * not an edit.\n */\nfunction evaluatedFiles(dev: ViteDevServer, configPath: string): Set<string> {\n const files = new Set<string>([resolve(configPath)]);\n const graph = dev.environments.ssr.moduleGraph;\n const queue = [...(graph.getModulesByFile(configPath) ?? [])];\n const seen = new Set(queue);\n while (queue.length > 0) {\n const mod = queue.pop();\n if (mod === undefined) continue;\n if (mod.file !== null) {\n if (NODE_MODULES.test(mod.file)) continue;\n files.add(resolve(mod.file));\n }\n for (const imported of mod.importedModules) {\n if (!seen.has(imported)) {\n seen.add(imported);\n queue.push(imported);\n }\n }\n }\n return files;\n}\n\n/**\n * Serve `virtual:workflow-config` and keep it current.\n *\n * The project is evaluated on the server (ssrLoadModule) and compiled there;\n * see server/project.ts for what reaches the browser. After every load the\n * plugin records the files that load evaluated — the config and everything it\n * imported, inside the working directory or not (`--config ../shared/...`,\n * a contract in a sibling package) — and watches them. A change to any of\n * them drops those evaluated modules and pushes a fresh snapshot over HMR, so\n * adding a workflow or a template to the registration list shows up without a\n * reload. Template components also update through their own client-side HMR,\n * as any module does.\n */\n/** The stats source's default export, evaluated on the dev server. */\nasync function loadStats(\n dev: ViteDevServer,\n statsPath: string\n): Promise<Partial<Record<StatsMethod, (...args: unknown[]) => unknown>>> {\n const mod = await dev.ssrLoadModule(statsPath);\n const stats: unknown = mod.default;\n if (typeof stats !== 'object' || stats === null) {\n throw new Error(`workflow-ui: ${statsPath} must default-export defineStats({...})`);\n }\n return stats;\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolveBody, reject) => {\n let body = '';\n req.setEncoding('utf8');\n req.on('data', (chunk: string) => {\n body += chunk;\n });\n req.on('end', () => resolveBody(body));\n req.on('error', reject);\n });\n}\n\nexport function projectPlugin(configPath: string, statsPath: string | undefined): Plugin {\n let server: ViteDevServer | undefined;\n let evaluated = new Set<string>([resolve(configPath)]);\n return {\n name: 'workflow-ui:project',\n resolveId: (id) => (id === VIRTUAL_ID ? RESOLVED_ID : null),\n async load(id) {\n if (id !== RESOLVED_ID || server === undefined) return null;\n const dev = server;\n const snapshot = await loadSnapshot({\n configPath,\n load: (file) => dev.ssrLoadModule(file),\n modules: ssrModulesOf(dev),\n });\n evaluated = evaluatedFiles(dev, configPath);\n let methods: StatsMethod[] | undefined;\n if (statsPath !== undefined) {\n const stats = await loadStats(dev, statsPath);\n methods = STATS_METHODS.filter((method) => typeof stats[method] === 'function');\n for (const file of evaluatedFiles(dev, statsPath)) evaluated.add(file);\n }\n dev.watcher.add([...evaluated]);\n return virtualModule(snapshot, methods);\n },\n configureServer(dev) {\n server = dev;\n /* Positions the DSL captures while the project is evaluated are then lines on disk. */\n process.setSourceMapsEnabled(true);\n for (const file of [configPath, statsPath]) {\n if (file !== undefined) dev.watcher.add(file);\n }\n const refresh = (file: string): void => {\n if (!evaluated.has(resolve(file))) return;\n const virtual = dev.moduleGraph.getModuleById(RESOLVED_ID);\n if (virtual === undefined) return;\n /*\n * ssrLoadModule keeps an evaluated module until it is invalidated, and\n * the config caches everything it imported — so every evaluated module\n * goes, not just the file that changed.\n */\n for (const path of evaluated) {\n for (const mod of dev.moduleGraph.getModulesByFile(path) ?? []) {\n dev.moduleGraph.invalidateModule(mod);\n }\n }\n dev.moduleGraph.invalidateModule(virtual);\n void dev.reloadModule(virtual);\n };\n dev.watcher.on('change', refresh);\n dev.watcher.on('add', refresh);\n dev.watcher.on('unlink', refresh);\n\n /*\n * The stats source runs here, not in the browser: it reads the project's\n * own database or API, with credentials the page must never hold. The\n * page calls one method per request — the arguments as a JSON array, the\n * answer as JSON — and only the StatsSource method names are served.\n */\n dev.middlewares.use('/__studio/stats/', (req, res) => {\n const sendJson = (status: number, body: unknown): void => {\n res.statusCode = status;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify(body));\n };\n void (async () => {\n if (req.method !== 'POST') {\n res.setHeader('allow', 'POST');\n sendJson(405, { error: 'stats calls are POST' });\n return;\n }\n const rejection = studioRequestRejection(req);\n if (rejection !== undefined) {\n sendJson(403, { error: rejection });\n return;\n }\n const method = (req.url ?? '').replace(/^\\//, '').split('?')[0] as StatsMethod;\n if (statsPath === undefined || !STATS_METHODS.includes(method)) {\n sendJson(404, { error: `no stats method '${method}'` });\n return;\n }\n try {\n const args: unknown = JSON.parse((await readBody(req)) || '[]');\n if (!Array.isArray(args)) {\n sendJson(400, { error: 'the body is the arguments, as a JSON array' });\n return;\n }\n const fn = (await loadStats(dev, statsPath))[method];\n if (fn === undefined) {\n sendJson(404, { error: `workflow.stats.ts defines no '${method}'` });\n return;\n }\n sendJson(200, (await fn(...args)) ?? null);\n } catch (error) {\n dev.config.logger.error(`[workflow-ui] stats ${method} failed: ${String(error)}`);\n sendJson(500, { error: error instanceof Error ? error.message : String(error) });\n }\n })();\n });\n },\n };\n}\n\n/* -------------------------------- Studio API -------------------------------- */\n\n/** `Sec-Fetch-Site` values no other site can produce: our own page, or a direct navigation. */\nconst OWN_FETCH_SITES = new Set(['same-origin', 'none']);\n\nfunction headerValue(raw: string | string[] | undefined): string | undefined {\n const value = Array.isArray(raw) ? raw[0] : raw;\n return value === undefined || value === '' ? undefined : value;\n}\n\n/**\n * Refuse any request another website could have caused, and say why.\n *\n * The node endpoint reads the developer's source files to answer, so a page\n * they merely *visit* should not be able to probe it. Vite's CORS handling\n * decides who may read a response; this decides whether the request is served\n * at all.\n *\n * - `Sec-Fetch-Site` is attached by the browser and cannot be set from\n * script, so anything but `same-origin` (our page) or `none` (the address\n * bar) is a request some other page caused — including `same-site`, which\n * covers another port on localhost.\n * - `Origin` covers clients that send no fetch metadata: present and not our\n * own host means cross-origin. Absent is allowed on purpose — a same-origin\n * GET and a terminal `curl` both have no Origin at all, and a cross-origin\n * browser request always has one.\n */\nexport function studioRequestRejection(req: Pick<IncomingMessage, 'headers'>): string | undefined {\n const site = headerValue(req.headers['sec-fetch-site']);\n if (site !== undefined && !OWN_FETCH_SITES.has(site)) {\n return `refused: sec-fetch-site is '${site}', so another site caused this request`;\n }\n const origin = headerValue(req.headers.origin);\n if (origin !== undefined) {\n const host = headerValue(req.headers.host);\n let originHost: string | undefined;\n try {\n originHost = new URL(origin).host;\n } catch {\n /* Opaque origins ('null' from a sandboxed frame or file://) never match. */\n originHost = undefined;\n }\n if (host === undefined || originHost?.toLowerCase() !== host.toLowerCase()) {\n return `refused: cross-origin request from ${origin}`;\n }\n }\n return undefined;\n}\n\n/**\n * The studio's dev-server API — read-only. The studio views source and never\n * writes it: edits happen in the editor, and Vite's watcher and HMR bring them\n * to the page. The one endpoint resolves a node's captured position to a line\n * on disk for display; everything else under `/__studio` answers 404, so the\n * write routes earlier versions served (`/__studio/envelope`,\n * `/__studio/addresses`, POST `/__studio/node`) are gone rather than hidden.\n */\nexport function studioApiPlugin(cwd: string): Plugin {\n const sendJson = (res: ServerResponse, status: number, body: unknown): void => {\n res.statusCode = status;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify(body));\n };\n\n return {\n name: 'workflow-ui:studio-api',\n configureServer(server) {\n /*\n * The client sends the position the DSL captured (NodeMetaIR.loc). The\n * project is evaluated on the server with source maps enabled, so that\n * is already a line on disk; this checks the path stays inside the\n * project and answers it relative to it. Navigation only: the panel\n * shows the row when this answers and leaves it out when it does not.\n */\n server.middlewares.use('/__studio/node', (req, res) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n res.setHeader('allow', 'GET, HEAD');\n sendJson(res, 405, { error: 'the studio is read-only: GET only' });\n return;\n }\n const rejection = studioRequestRejection(req);\n if (rejection !== undefined) {\n sendJson(res, 403, { error: rejection });\n return;\n }\n const params = new URL(req.url ?? '/', 'http://internal').searchParams;\n const found = sourcePosition(cwd, params.get('file') ?? '', Number(params.get('line')));\n if ('error' in found) {\n sendJson(res, 422, { error: found.error });\n return;\n }\n sendJson(res, 200, { file: relative(cwd, found.file), line: found.line });\n });\n\n /* Registered after the routes above, so it only sees what none of them took. */\n server.middlewares.use('/__studio', (_req, res) => {\n sendJson(res, 404, { error: 'no such studio endpoint' });\n });\n },\n };\n}\n\ntype Located = { file: string; line: number } | { error: string };\n\n/** The two `node:path` functions containment needs, so the suite can hand in `path.win32`. */\ninterface PathOps {\n isAbsolute: (path: string) => boolean;\n relative: (from: string, to: string) => string;\n}\n\n/**\n * Is `candidate` `root` itself or something below it?\n *\n * Asked through `relative`, never a string prefix. A prefix test needs a\n * trailing separator (or `/proj-evil` passes for `/proj`), and the separator it\n * appends is the wrong one on Windows, where `resolve()` returns `C:\\proj\\…`:\n * that mismatch failed every path on Windows, which is how the whole\n * /__studio/node surface came to answer \"outside the project\" there.\n */\nexport function isInsideDir(\n root: string,\n candidate: string,\n ops: PathOps = { isAbsolute, relative }\n): boolean {\n const rel = ops.relative(root, candidate);\n if (rel === '') return true;\n /* An absolute answer means there is no way down from root — another drive. */\n if (ops.isAbsolute(rel)) return false;\n /* Segment-wise, so a file legitimately named '..rc' is not read as an escape. */\n return rel.split(/[/\\\\]/)[0] !== '..';\n}\n\n/**\n * Keep a path that arrived from the browser inside the project.\n *\n * The scope is `cwd` — the project the studio was started in — and not the\n * workspace root `searchForWorkspaceRoot` walks up to: in a monorepo that root\n * is the whole repo, so a studio started in `apps/marketing` accepted\n * `file=../../packages/billing/src/rates.ts` and read it.\n */\nexport function isInsideProject(cwd: string, candidate: string): boolean {\n const root = resolve(cwd);\n const path = resolve(candidate);\n if (!isInsideDir(root, path)) return false;\n /*\n * Then again on the real paths: a symlink inside the project may point\n * anywhere, and the check above only ever sees the link's own path. A path\n * that does not exist has nothing to resolve — the caller reports that.\n */\n if (!existsSync(path)) return true;\n return isInsideDir(realpathSync(root), realpathSync(path));\n}\n\n/**\n * Check a captured position before answering with it.\n *\n * The path is validated against cwd before anything is touched: it arrives\n * from the browser, and an endpoint that follows an arbitrary path is a\n * read-anywhere endpoint.\n */\nfunction sourcePosition(cwd: string, rawFile: string, line: number): Located {\n let path = rawFile;\n if (/^https?:\\/\\//.test(path)) path = new URL(path).pathname;\n const fsPrefix = '/@fs';\n if (path.startsWith(fsPrefix)) path = path.slice(fsPrefix.length);\n path = resolve(cwd, decodeURIComponent(path));\n\n if (!isInsideProject(cwd, path)) return { error: 'source file is outside the project' };\n if (!existsSync(path)) return { error: `no such source file: ${path}` };\n if (!Number.isInteger(line) || line < 1) return { error: 'expected a line number' };\n return { file: path, line };\n}\n\n/** Vite's own `server.fs.deny` default; setting the option replaces it, so it is spelled out. */\nconst VITE_DEFAULT_DENY = ['.env', '.env.*', '*.{crt,pem}', '**/.git/**'];\n\n/**\n * `server.fs.deny` patterns for files the page must never be served.\n *\n * `fs.allow` covers the whole workspace so the browser can import the\n * template registries, which also made `GET /@fs/<cwd>/workflow.stats.ts`\n * answer with the stats source — a file the README calls server-only, and the\n * one place a connection string is likely to be written as a literal. The\n * browser never imports the config or the stats file (the virtual module\n * imports the registries by their own paths; a registry written inline in the\n * config is refused for this reason), so both are denied outright.\n *\n * Patterns go through picomatch, so the path is spelled literally: its glob\n * characters escaped, slashes normalized the way Vite normalizes the file it\n * checks. A symlinked file is denied under both of its names.\n */\nexport function projectFileDeny(paths: readonly (string | undefined)[]): string[] {\n const deny = new Set<string>();\n for (const path of paths) {\n if (path === undefined) continue;\n const literal = resolve(path);\n deny.add(normalizePath(literal));\n if (existsSync(literal)) deny.add(normalizePath(realpathSync(literal)));\n }\n return [...deny].map((path) => path.replace(/[\\\\*?[\\]{}()!+@]/g, '\\\\$&'));\n}\n\nexport interface StartOptions {\n cwd?: string;\n config?: string;\n /** The studio's stats source (default ./workflow.stats.ts, if present). */\n stats?: string;\n port?: number;\n open?: boolean;\n}\n\nexport async function startStudio(options: StartOptions = {}): Promise<ViteDevServer> {\n const cwd = options.cwd ?? process.cwd();\n // The config is required (findConfig throws); the stats source is optional.\n // The resolved path is what the plugin loads — resolving again from cwd\n // inside it is what once made --config point at a file it does not name.\n const configPath = findConfig(cwd, options.config);\n const statsPath = findStats(cwd, options.stats);\n const appRoot = resolveAppRoot();\n\n const server = await createServer({\n root: appRoot,\n configFile: false,\n envDir: false,\n plugins: [\n react(),\n svgr(),\n tailwindcss(),\n projectPlugin(configPath, statsPath),\n studioApiPlugin(cwd),\n ],\n server: {\n port: options.port ?? 4321,\n open: options.open ?? false,\n /*\n * Both workspace roots have to be readable: the user's project (the\n * config and everything it imports) and ours — under pnpm our own\n * dependencies (fonts, css) resolve into a store beside the workspace\n * root rather than anywhere below the app.\n */\n fs: {\n allow: [\n searchForWorkspaceRoot(cwd),\n /* A config outside cwd brings its own workspace: the registries the browser imports live there. */\n searchForWorkspaceRoot(dirname(configPath)),\n searchForWorkspaceRoot(packageRoot),\n appRoot,\n ],\n deny: [...VITE_DEFAULT_DENY, ...projectFileDeny([configPath, statsPath])],\n },\n },\n // The app and the user's project each have their own react; one copy only. One\n // @shware/workflow too: the preview's <EmailProvider> and the project's layout calling\n // useEmailContext() must share the context object\n resolve: { dedupe: ['react', 'react-dom', '@shware/workflow'] },\n /*\n * @react-email/render imports react-dom/server lazily, so the dep scan never\n * sees it: the first email preview made Vite discover it, re-optimize and\n * change the deps hash under a page that still held the old one — the\n * preview then failed with \"Failed to fetch dynamically imported module\"\n * (a 504 Outdated Optimize Dep) until a reload. Bundling both up front\n * keeps the hash stable from the first request. The project's config is\n * scanned too (never served — only crawled), so its templates'\n * dependencies (@react-email/components, zod, …) are bundled before the\n * first preview rather than discovered by it.\n */\n optimizeDeps: {\n entries: ['index.html', configPath],\n include: ['@react-email/render', 'react-dom/server'],\n },\n });\n\n await server.listen();\n return server;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, relative, resolve } from 'node:path';\nimport { type JourneyConfig, isConfig } from '@shware/workflow';\nimport { renderDrizzleSchema } from '@shware/workflow/store';\nimport { runnerImport } from 'vite';\nimport { findConfig } from './server';\n\n/**\n * `workflow-ui generate` — the engine's Postgres tables as one drizzle file, on the schema the\n * project's `database.schema` names (`workflow` by default). The host re-exports the file from\n * its drizzle schema and lets drizzle-kit write the migration, so the migration history stays the\n * host's. `--check` exits non-zero when the file on disk differs (CI, after an SDK upgrade).\n */\n\nexport interface GenerateOptions {\n cwd?: string;\n config?: string;\n out: string;\n check?: boolean;\n}\n\nexport type GenerateResult = 'written' | 'unchanged' | 'outdated';\n\n/** The host's formatter may rewrap the file, change quotes or trailing commas: not a difference. */\nfunction normalize(source: string): string {\n return (\n source\n .replace(/\"/g, \"'\")\n .replace(/\\s+/g, ' ')\n // Spaces around punctuation, and trailing commas, are the formatter's choice\n .replace(/ ?([{}()[\\],;:=<>.]) ?/g, '$1')\n .replace(/,([}\\])])/g, '$1')\n .trim()\n );\n}\n\nexport async function generateSchema(options: GenerateOptions): Promise<GenerateResult> {\n const cwd = options.cwd ?? process.cwd();\n const configPath = findConfig(cwd, options.config);\n const { module } = await runnerImport<{ default?: unknown }>(configPath);\n if (!isConfig(module.default)) {\n throw new Error(\n `workflow-ui: ${relative(cwd, configPath)} must \\`export default defineConfig({...})\\``\n );\n }\n const config: JourneyConfig = module.default;\n const file = renderDrizzleSchema(config.database?.schema);\n\n const out = resolve(cwd, options.out);\n const current = existsSync(out) ? readFileSync(out, 'utf8') : undefined;\n if (current !== undefined && normalize(current) === normalize(file)) return 'unchanged';\n if (options.check) return 'outdated';\n mkdirSync(dirname(out), { recursive: true });\n writeFileSync(out, file);\n return 'written';\n}\n","#!/usr/bin/env node\nimport { generateSchema } from './generate';\nimport { startStudio } from './server';\n\n/**\n * `workflow-ui` — start the studio over the project in ./workflow.config.ts.\n *\n * npx workflow-ui # reads ./workflow.config.ts (and ./workflow.stats.ts)\n * npx workflow-ui --port 5000\n * npx workflow-ui --config apps/marketing/workflow.config.ts\n * npx workflow-ui generate --out ../../packages/db/src/schema/workflow.ts [--check]\n */\n\ninterface Args {\n port?: number;\n config?: string;\n stats?: string;\n out?: string;\n check: boolean;\n open: boolean;\n help: boolean;\n}\n\nfunction parseArgs(argv: string[]): Args {\n const args: Args = { open: false, check: false, help: false };\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === '--help' || arg === '-h') args.help = true;\n else if (arg === '--open') args.open = true;\n else if (arg === '--check') args.check = true;\n else if (arg === '--out' || arg === '-o') args.out = argv[++i];\n else if (arg === '--port' || arg === '-p') args.port = Number(argv[++i]);\n else if (arg === '--config' || arg === '-c') args.config = argv[++i];\n else if (arg === '--stats' || arg === '-s') args.stats = argv[++i];\n }\n return args;\n}\n\nconst HELP = `\n workflow-ui — review your workflows, templates and reports\n\n Usage\n $ workflow-ui [dev] [options]\n $ workflow-ui generate --out <file> [--check] [--config <path>]\n\n Options\n -p, --port <port> Port to listen on (default 4321)\n -c, --config <path> Project file (default ./workflow.config.ts)\n -s, --stats <path> Stats source (default ./workflow.stats.ts, if present)\n --open Open the browser on start\n -o, --out <file> generate: where the drizzle schema file goes\n --check generate: fail when the file is out of date, write nothing\n -h, --help Show this message\n`;\n\nasync function main(): Promise<void> {\n const [command, ...rest] = process.argv.slice(2);\n if (command === 'generate') {\n const args = parseArgs(rest);\n if (args.help || args.out === undefined) {\n console.log(HELP);\n if (args.out === undefined && !args.help) process.exitCode = 1;\n return;\n }\n try {\n const result = await generateSchema({\n out: args.out,\n check: args.check,\n ...(args.config !== undefined ? { config: args.config } : {}),\n });\n if (result === 'outdated') {\n console.error(\n `\\n ${args.out} is out of date — run workflow-ui generate, then your migration tool\\n`\n );\n process.exitCode = 1;\n } else {\n console.log(`\\n ${args.out} ${result === 'written' ? 'written' : 'is up to date'}\\n`);\n }\n } catch (error) {\n console.error(`\\n${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n return;\n }\n\n // `dev` is accepted so the command reads well; the studio is the default mode\n const argv = process.argv.slice(2).filter((arg) => arg !== 'dev');\n const args = parseArgs(argv);\n\n if (args.help) {\n console.log(HELP);\n return;\n }\n\n try {\n const server = await startStudio({\n ...(args.port !== undefined ? { port: args.port } : {}),\n ...(args.config !== undefined ? { config: args.config } : {}),\n ...(args.stats !== undefined ? { stats: args.stats } : {}),\n open: args.open,\n });\n const address = server.resolvedUrls?.local[0] ?? `http://localhost:${args.port ?? 4321}`;\n console.log(`\\n workflow-ui ready at ${address}\\n`);\n } catch (error) {\n console.error(`\\n${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n}\n\nvoid main();\n"],"mappings":";;;;;;;;;;;;AAqCA,SAAgB,aAAa,QAAsC;CACjE,OAAO,aAAa;EAClB,KAAK,MAAM,OAAO,OAAO,YAAY,cAAc,OAAO,GAAG;GAC3D,MAAM,UAAU,IAAI;GACpB,IAAI,IAAI,SAAS,QAAQ,YAAY,MAAM,MAAM,CAAC,IAAI,MAAM,OAAO;EACrE;CACF;AACF;;AAYA,MAAM,WAGF;CACF,OAAO;EAAE,IAAI;EAAiB,SAAS;EAAiB,OAAO;CAAS;CACxE,MAAM;EAAE,IAAI;EAAgB,SAAS;EAAgB,OAAO;CAAS;CACrE,SAAS;EAAE,IAAI;EAAmB,SAAS;EAAmB,OAAO;CAAW;CAChF,OAAO;EAAE,IAAI;EAAiB,SAAS;EAAiB,OAAO;CAAS;AAC1E;;AAUA,IAAM,kBAAN,cAA8B,MAAM,CAAC;;;;;;;;;AAYrC,SAAS,OACP,SACA,UACA,SACA,YACuB;CACvB,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;CACnC,MAAM,EAAE,IAAI,YAAY,YAAY,SAAS;CAC7C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAChD,IAAI,CAAC,WAAW,KAAK,GACnB,MAAM,IAAI,gBACR,aAAa,QAAQ,IAAI,IAAI,cAAc,QAAQ,0CAA0C,QAAQ,uBACvG;CAIJ,IAAI,OAAO,KAAK,QAAQ,CAAC,CAAC,W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B,KAAK,QAAQ;EAClF,QAAQ,IAAI,4BAA4B,QAAQ,GAAG;CACrD,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG;EAC7E,QAAQ,WAAW;CACrB;AACF;AAEK,KAAK"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":[],"sources":["../src/server/project.ts","../src/server.ts","../src/generate.ts","../src/cli.ts"],"sourcesContent":["import {\n ConfigCompileError,\n type JourneyConfig,\n compileConfig,\n isConfig,\n isDiscordTemplate,\n isEmailTemplate,\n isPushTemplate,\n isSlackTemplate,\n} from '@shware/workflow';\nimport type { ViteDevServer } from 'vite';\nimport type { ResolvedStudioConfig, StudioError } from '../config';\n\n/**\n * Reading the project — on the dev server, never in the browser.\n *\n * workflow.config.ts default-exports `defineConfig({...})` from\n * `@shware/workflow`, and the studio reads exactly that: its workflows,\n * segments, actions, template registries, title and what the email templates share. It is\n * compiled with `compileConfig`, the same compile the Worker deploys, so the\n * studio lists exactly what would ship.\n *\n * What crosses to the browser is decided here too. The config is a source\n * object — schemas, components, the contract, runtime settings, whatever the\n * host imports — so it stays on the server. The browser receives the compiled\n * IR as JSON, and imports the two template registries (the code a preview has\n * to run) straight from the modules that export them, located by identity in\n * Vite's SSR module graph. It never imports workflow.config.ts.\n */\n\n/** How the server evaluates a project module (Vite's ssrLoadModule in the studio). */\nexport type ModuleLoader = (file: string) => Promise<Record<string, unknown>>;\n\n/** Every module the loader has evaluated so far, with its exports. */\nexport type LoadedModules = () => Iterable<[file: string, exports: Record<string, unknown>]>;\n\n/** The modules a Vite server has evaluated for SSR — where registries are located by identity. */\nexport function ssrModulesOf(server: ViteDevServer): LoadedModules {\n return function* () {\n for (const mod of server.moduleGraph.idToModuleMap.values()) {\n const exports = mod.ssrModule as Record<string, unknown> | null;\n if (mod.file !== null && exports !== null) yield [mod.file, exports];\n }\n };\n}\n\ntype Channel = 'email' | 'push' | 'discord' | 'slack';\n\n/** One named export the browser imports — or one channel of it, for an exported `{ email, push }`. */\nexport interface ModuleRef {\n file: string;\n name: string;\n property?: Channel;\n}\n\n/** Per channel: how to recognise its entries, the factory to name, the virtual module's field. */\nconst CHANNELS: Record<\n Channel,\n { is: (value: unknown) => boolean; factory: string; field: string }\n> = {\n email: { is: isEmailTemplate, factory: 'emailTemplate', field: 'emails' },\n push: { is: isPushTemplate, factory: 'pushTemplate', field: 'pushes' },\n discord: { is: isDiscordTemplate, factory: 'discordTemplate', field: 'discords' },\n slack: { is: isSlackTemplate, factory: 'slackTemplate', field: 'slacks' },\n};\n\nexport interface StudioSnapshot {\n /** The JSON half of the virtual module: compiled output and labels only. */\n payload: Omit<ResolvedStudioConfig, 'emails' | 'pushes' | 'discords' | 'slacks' | 'stats'>;\n /** The import half: where each registry comes from. */\n registries: Record<Channel, ModuleRef | undefined>;\n}\n\n/** A project the studio cannot read: the message says what to change. */\nclass StudioLoadError extends Error {}\n\n/* --------------------------------- Imports --------------------------------- */\n\n/**\n * The module that exports `registry`, by identity: the registry itself, or\n * else an exported `{ email, push }` holding it (`export const templates =\n * { email, push }`).\n * workflow.config.ts itself is never a candidate: importing it would bring the\n * whole config (and everything it imports) into the browser. Sorted by path,\n * so the answer does not depend on load order.\n */\nfunction locate(\n channel: Channel,\n registry: Record<string, unknown> | undefined,\n modules: LoadedModules,\n configPath: string\n): ModuleRef | undefined {\n if (registry === undefined) return undefined;\n const { is: isTemplate, factory } = CHANNELS[channel];\n for (const [key, entry] of Object.entries(registry)) {\n if (!isTemplate(entry)) {\n throw new StudioLoadError(\n `templates.${channel}['${key}'] is not a ${factory}({...}) definition — every entry of the ${channel} registry must be one.`\n );\n }\n }\n /* An empty registry has nothing for the browser to import. */\n if (Object.keys(registry).length === 0) return undefined;\n const sorted = [...modules()]\n .filter(([file]) => file !== configPath)\n .sort(([a], [b]) => a.localeCompare(b));\n for (const [file, exports] of sorted) {\n for (const [name, exported] of Object.entries(exports)) {\n if (exported === registry) return { file, name };\n }\n }\n for (const [file, exports] of sorted) {\n for (const [name, exported] of Object.entries(exports)) {\n if (\n typeof exported === 'object' &&\n exported !== null &&\n (exported as Partial<Record<Channel, unknown>>)[channel] === registry\n ) {\n return { file, name, property: channel };\n }\n }\n }\n throw new StudioLoadError(\n `templates.${channel} is not exported from a module of its own. Export the registry ` +\n `(e.g. \\`export const ${channel} = {...}\\` in src/${channel}/index.ts, or ` +\n '`export const templates = { email, push }` in src/templates.ts) ' +\n 'and import it into workflow.config.ts — the studio loads that module, never the config, into the browser.'\n );\n}\n\n/* --------------------------------- Snapshot -------------------------------- */\n\nfunction errorOf(error: unknown): StudioError {\n return {\n kind: error instanceof ConfigCompileError ? 'compile' : 'load',\n message: error instanceof Error ? error.message : String(error),\n };\n}\n\nfunction failed(error: unknown, title?: string): StudioSnapshot {\n return {\n payload: {\n ...(title !== undefined ? { title } : {}),\n workflows: {},\n segments: [],\n email: {},\n error: errorOf(error),\n },\n registries: { email: undefined, push: undefined, discord: undefined, slack: undefined },\n };\n}\n\n/**\n * Load and compile. Never throws: a config that fails to load, is not a\n * `defineConfig({...})`, holds something other than template definitions, or\n * does not compile becomes a snapshot carrying the error, which the studio\n * shows in place of its views — a compile error names the workflow and node.\n */\nexport async function loadSnapshot(options: {\n configPath: string;\n load: ModuleLoader;\n modules: LoadedModules;\n}): Promise<StudioSnapshot> {\n const { configPath, load, modules } = options;\n let config: JourneyConfig;\n let registries: StudioSnapshot['registries'];\n try {\n const exported = (await load(configPath)).default;\n if (!isConfig(exported)) {\n throw new StudioLoadError(\n `${configPath} must \\`export default defineConfig({...})\\` from '@shware/workflow'.`\n );\n }\n config = exported;\n registries = {\n email: locate('email', config.templates?.email, modules, configPath),\n push: locate('push', config.templates?.push, modules, configPath),\n discord: locate('discord', config.templates?.discord, modules, configPath),\n slack: locate('slack', config.templates?.slack, modules, configPath),\n };\n } catch (error) {\n return failed(error);\n }\n\n const unsubscribeUrl = config.email?.unsubscribeUrl;\n const quickClickMs = config.email?.tracking?.quickClickMs;\n const shared = {\n ...(config.title !== undefined ? { title: config.title } : {}),\n email: {\n ...(unsubscribeUrl !== undefined ? { unsubscribeUrl } : {}),\n ...(quickClickMs !== undefined ? { tracking: { quickClickMs } } : {}),\n },\n };\n\n try {\n const bundle = compileConfig(config);\n return {\n payload: {\n ...shared,\n workflows: Object.fromEntries(bundle.workflows.map((workflow) => [workflow.id, workflow])),\n segments: bundle.segments,\n },\n registries,\n };\n } catch (error) {\n return {\n payload: { ...shared, workflows: {}, segments: [], error: errorOf(error) },\n registries,\n };\n }\n}\n\n/* ------------------------------ Virtual module ----------------------------- */\n\n/** The `StatsSource` methods, the only names the stats endpoint answers. */\nexport const STATS_METHODS = [\n 'reports',\n 'segments',\n 'profiles',\n 'nodeStats',\n 'metrics',\n 'links',\n 'messages',\n] as const;\nexport type StatsMethod = (typeof STATS_METHODS)[number];\n\n/**\n * The module the browser imports as `virtual:workflow-config`: the payload as\n * a JSON literal, the template registries as imports from their own modules\n * (re-keyed by template id), and\n * the stats source as calls to the studio's server, one per method\n * workflow.stats.ts defines — the source itself runs there, next to the\n * database and the secrets it reads with, never in the browser.\n */\n/** An export name as an import names it: quoted (ES2022) when it is not an identifier. */\nconst exportName = (name: string) =>\n /^[A-Za-z_$][\\w$]*$/.test(name) ? name : JSON.stringify(name);\n\nexport function virtualModule(\n snapshot: StudioSnapshot,\n statsMethods: readonly StatsMethod[] | undefined\n): string {\n const imports: string[] = [];\n const importOf = (ref: ModuleRef, local: string): string => {\n /* One channel of an exported `{ email, push }`: import the whole under its own alias. */\n const binding = ref.property === undefined ? local : `${local}Source`;\n imports.push(\n ref.name === 'default'\n ? `import ${binding} from ${JSON.stringify(ref.file)};`\n : `import { ${ref.name === binding ? binding : `${exportName(ref.name)} as ${binding}`} } from ${JSON.stringify(ref.file)};`\n );\n return ref.property === undefined ? binding : `${binding}.${ref.property}`;\n };\n const registries = (Object.keys(CHANNELS) as Channel[]).map((channel) => {\n const ref = snapshot.registries[channel];\n const { field } = CHANNELS[channel];\n return ` ${field}: ${ref === undefined ? '{}' : `byId(${importOf(ref, field)})`},`;\n });\n const stats =\n statsMethods === undefined\n ? undefined\n : `{ ${statsMethods.map((method) => `${method}: call(${JSON.stringify(method)})`).join(', ')} }`;\n const call =\n stats === undefined\n ? ''\n : `\nconst call = (method) => async (...args) => {\n const response = await fetch(\\`/__studio/stats/\\${method}\\`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(args),\n });\n const body = await response.json();\n if (!response.ok) throw new Error(body.error ?? \\`stats \\${method} failed: \\${response.status}\\`);\n return body;\n};`;\n\n return `${imports.join('\\n')}${call}\n/* The views look a template up by its id, the name messages use, never by the property holding it. */\nconst byId = (registry) => Object.fromEntries(Object.values(registry).map((t) => [t.id, t]));\nconst payload = ${JSON.stringify(snapshot.payload)};\nexport default {\n ...payload,\n${registries.join('\\n')}${stats === undefined ? '' : `\\n stats: ${stats},`}\n};\n`;\n}\n","import { existsSync, realpathSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { dirname, isAbsolute, relative, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport tailwindcss from '@tailwindcss/vite';\nimport react from '@vitejs/plugin-react';\nimport {\n type Plugin,\n type ViteDevServer,\n createServer,\n normalizePath,\n searchForWorkspaceRoot,\n} from 'vite';\nimport svgr from 'vite-plugin-svgr';\nimport {\n STATS_METHODS,\n type StatsMethod,\n loadSnapshot,\n ssrModulesOf,\n virtualModule,\n} from './server/project';\n\n/**\n * The studio dev server.\n *\n * Rather than shipping a prebuilt SPA and a JSON API, the CLI runs Vite over\n * the app source with the project injected as a virtual module: compiled on\n * the server, the template registries imported by the browser from their own\n * modules. Vite serves our app and the user's react-email components as one\n * graph — HMR on every one of them for free, and email previews render with\n * exactly the component code on disk.\n */\n\nconst packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));\n\n/** `src/app` when running from source in the monorepo, the published copy otherwise. */\nfunction resolveAppRoot(): string {\n const candidates = [resolve(packageRoot, 'src/app'), resolve(packageRoot, '../src/app')];\n const found = candidates.find((path) => existsSync(resolve(path, 'index.html')));\n if (!found) throw new Error('workflow-ui: could not locate the app root');\n return found;\n}\n\nconst CONFIG_CANDIDATES = [\n 'workflow.config.ts',\n 'workflow.config.tsx',\n 'workflow.config.js',\n 'workflow.config.mjs',\n];\n\n/**\n * The project file — `export default defineConfig({...})` from\n * `@shware/workflow`. Required: it is the only place the studio reads\n * definitions from.\n */\nexport function findConfig(cwd: string, explicit?: string): string {\n if (explicit !== undefined) {\n const path = resolve(cwd, explicit);\n if (!existsSync(path)) throw new Error(`workflow-ui: config not found at ${path}`);\n return path;\n }\n const found = CONFIG_CANDIDATES.map((name) => resolve(cwd, name)).find((path) =>\n existsSync(path)\n );\n if (found === undefined) {\n throw new Error(\n `workflow-ui: no workflow.config.ts in ${cwd}.\\n` +\n `Export defineConfig({ workflows, templates }) from '@shware/workflow' there, or pass --config <path>.`\n );\n }\n return found;\n}\n\nconst STATS_CANDIDATES = ['workflow.stats.ts', 'workflow.stats.tsx', 'workflow.stats.js'];\n\n/**\n * The studio's optional stats source, apart from the project: an explicit\n * path must exist; otherwise `workflow.stats.ts` beside the config, if any.\n */\nexport function findStats(cwd: string, explicit?: string): string | undefined {\n if (explicit !== undefined) {\n const path = resolve(cwd, explicit);\n if (!existsSync(path)) throw new Error(`workflow-ui: stats source not found at ${path}`);\n return path;\n }\n return STATS_CANDIDATES.map((name) => resolve(cwd, name)).find((path) => existsSync(path));\n}\n\n/* ---------------------------------- Project --------------------------------- */\n\nconst VIRTUAL_ID = 'virtual:workflow-config';\nconst RESOLVED_ID = `\\0${VIRTUAL_ID}`;\n\nconst NODE_MODULES = /[/\\\\]node_modules[/\\\\]/;\n\n/**\n * Every file the last project load evaluated: the config and, transitively,\n * whatever it imported in Vite's SSR module graph — wherever those files live.\n * Dependencies under node_modules are left out: they change with an install,\n * not an edit.\n */\nfunction evaluatedFiles(dev: ViteDevServer, configPath: string): Set<string> {\n const files = new Set<string>([resolve(configPath)]);\n const graph = dev.environments.ssr.moduleGraph;\n const queue = [...(graph.getModulesByFile(configPath) ?? [])];\n const seen = new Set(queue);\n while (queue.length > 0) {\n const mod = queue.pop();\n if (mod === undefined) continue;\n if (mod.file !== null) {\n if (NODE_MODULES.test(mod.file)) continue;\n files.add(resolve(mod.file));\n }\n for (const imported of mod.importedModules) {\n if (!seen.has(imported)) {\n seen.add(imported);\n queue.push(imported);\n }\n }\n }\n return files;\n}\n\n/**\n * Serve `virtual:workflow-config` and keep it current.\n *\n * The project is evaluated on the server (ssrLoadModule) and compiled there;\n * see server/project.ts for what reaches the browser. After every load the\n * plugin records the files that load evaluated — the config and everything it\n * imported, inside the working directory or not (`--config ../shared/...`,\n * a contract in a sibling package) — and watches them. A change to any of\n * them drops those evaluated modules and pushes a fresh snapshot over HMR, so\n * adding a workflow or a template to the registration list shows up without a\n * reload. Template components also update through their own client-side HMR,\n * as any module does.\n */\n/** The stats source's default export, evaluated on the dev server. */\nasync function loadStats(\n dev: ViteDevServer,\n statsPath: string\n): Promise<Partial<Record<StatsMethod, (...args: unknown[]) => unknown>>> {\n const mod = await dev.ssrLoadModule(statsPath);\n const stats: unknown = mod.default;\n if (typeof stats !== 'object' || stats === null) {\n throw new Error(`workflow-ui: ${statsPath} must default-export defineStats({...})`);\n }\n return stats;\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolveBody, reject) => {\n let body = '';\n req.setEncoding('utf8');\n req.on('data', (chunk: string) => {\n body += chunk;\n });\n req.on('end', () => resolveBody(body));\n req.on('error', reject);\n });\n}\n\nexport function projectPlugin(configPath: string, statsPath: string | undefined): Plugin {\n let server: ViteDevServer | undefined;\n let evaluated = new Set<string>([resolve(configPath)]);\n return {\n name: 'workflow-ui:project',\n resolveId: (id) => (id === VIRTUAL_ID ? RESOLVED_ID : null),\n async load(id) {\n if (id !== RESOLVED_ID || server === undefined) return null;\n const dev = server;\n const snapshot = await loadSnapshot({\n configPath,\n load: (file) => dev.ssrLoadModule(file),\n modules: ssrModulesOf(dev),\n });\n evaluated = evaluatedFiles(dev, configPath);\n let methods: StatsMethod[] | undefined;\n if (statsPath !== undefined) {\n const stats = await loadStats(dev, statsPath);\n methods = STATS_METHODS.filter((method) => typeof stats[method] === 'function');\n for (const file of evaluatedFiles(dev, statsPath)) evaluated.add(file);\n }\n dev.watcher.add([...evaluated]);\n return virtualModule(snapshot, methods);\n },\n configureServer(dev) {\n server = dev;\n /* Positions the DSL captures while the project is evaluated are then lines on disk. */\n process.setSourceMapsEnabled(true);\n for (const file of [configPath, statsPath]) {\n if (file !== undefined) dev.watcher.add(file);\n }\n const refresh = (file: string): void => {\n if (!evaluated.has(resolve(file))) return;\n const virtual = dev.moduleGraph.getModuleById(RESOLVED_ID);\n if (virtual === undefined) return;\n /*\n * ssrLoadModule keeps an evaluated module until it is invalidated, and\n * the config caches everything it imported — so every evaluated module\n * goes, not just the file that changed.\n */\n for (const path of evaluated) {\n for (const mod of dev.moduleGraph.getModulesByFile(path) ?? []) {\n dev.moduleGraph.invalidateModule(mod);\n }\n }\n dev.moduleGraph.invalidateModule(virtual);\n void dev.reloadModule(virtual);\n };\n dev.watcher.on('change', refresh);\n dev.watcher.on('add', refresh);\n dev.watcher.on('unlink', refresh);\n\n /*\n * The stats source runs here, not in the browser: it reads the project's\n * own database or API, with credentials the page must never hold. The\n * page calls one method per request — the arguments as a JSON array, the\n * answer as JSON — and only the StatsSource method names are served.\n */\n dev.middlewares.use('/__studio/stats/', (req, res) => {\n const sendJson = (status: number, body: unknown): void => {\n res.statusCode = status;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify(body));\n };\n void (async () => {\n if (req.method !== 'POST') {\n res.setHeader('allow', 'POST');\n sendJson(405, { error: 'stats calls are POST' });\n return;\n }\n const rejection = studioRequestRejection(req);\n if (rejection !== undefined) {\n sendJson(403, { error: rejection });\n return;\n }\n const method = (req.url ?? '').replace(/^\\//, '').split('?')[0] as StatsMethod;\n if (statsPath === undefined || !STATS_METHODS.includes(method)) {\n sendJson(404, { error: `no stats method '${method}'` });\n return;\n }\n try {\n const args: unknown = JSON.parse((await readBody(req)) || '[]');\n if (!Array.isArray(args)) {\n sendJson(400, { error: 'the body is the arguments, as a JSON array' });\n return;\n }\n const fn = (await loadStats(dev, statsPath))[method];\n if (fn === undefined) {\n sendJson(404, { error: `workflow.stats.ts defines no '${method}'` });\n return;\n }\n sendJson(200, (await fn(...args)) ?? null);\n } catch (error) {\n dev.config.logger.error(`[workflow-ui] stats ${method} failed: ${String(error)}`);\n sendJson(500, { error: error instanceof Error ? error.message : String(error) });\n }\n })();\n });\n },\n };\n}\n\n/* -------------------------------- Studio API -------------------------------- */\n\n/** `Sec-Fetch-Site` values no other site can produce: our own page, or a direct navigation. */\nconst OWN_FETCH_SITES = new Set(['same-origin', 'none']);\n\nfunction headerValue(raw: string | string[] | undefined): string | undefined {\n const value = Array.isArray(raw) ? raw[0] : raw;\n return value === undefined || value === '' ? undefined : value;\n}\n\n/**\n * Refuse any request another website could have caused, and say why.\n *\n * The node endpoint reads the developer's source files to answer, so a page\n * they merely *visit* should not be able to probe it. Vite's CORS handling\n * decides who may read a response; this decides whether the request is served\n * at all.\n *\n * - `Sec-Fetch-Site` is attached by the browser and cannot be set from\n * script, so anything but `same-origin` (our page) or `none` (the address\n * bar) is a request some other page caused — including `same-site`, which\n * covers another port on localhost.\n * - `Origin` covers clients that send no fetch metadata: present and not our\n * own host means cross-origin. Absent is allowed on purpose — a same-origin\n * GET and a terminal `curl` both have no Origin at all, and a cross-origin\n * browser request always has one.\n */\nexport function studioRequestRejection(req: Pick<IncomingMessage, 'headers'>): string | undefined {\n const site = headerValue(req.headers['sec-fetch-site']);\n if (site !== undefined && !OWN_FETCH_SITES.has(site)) {\n return `refused: sec-fetch-site is '${site}', so another site caused this request`;\n }\n const origin = headerValue(req.headers.origin);\n if (origin !== undefined) {\n const host = headerValue(req.headers.host);\n let originHost: string | undefined;\n try {\n originHost = new URL(origin).host;\n } catch {\n /* Opaque origins ('null' from a sandboxed frame or file://) never match. */\n originHost = undefined;\n }\n if (host === undefined || originHost?.toLowerCase() !== host.toLowerCase()) {\n return `refused: cross-origin request from ${origin}`;\n }\n }\n return undefined;\n}\n\n/**\n * The studio's dev-server API — read-only. The studio views source and never\n * writes it: edits happen in the editor, and Vite's watcher and HMR bring them\n * to the page. The one endpoint resolves a node's captured position to a line\n * on disk for display; everything else under `/__studio` answers 404, so the\n * write routes earlier versions served (`/__studio/envelope`,\n * `/__studio/addresses`, POST `/__studio/node`) are gone rather than hidden.\n */\nexport function studioApiPlugin(cwd: string): Plugin {\n const sendJson = (res: ServerResponse, status: number, body: unknown): void => {\n res.statusCode = status;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify(body));\n };\n\n return {\n name: 'workflow-ui:studio-api',\n configureServer(server) {\n /*\n * The client sends the position the DSL captured (NodeMetaIR.loc). The\n * project is evaluated on the server with source maps enabled, so that\n * is already a line on disk; this checks the path stays inside the\n * project and answers it relative to it. Navigation only: the panel\n * shows the row when this answers and leaves it out when it does not.\n */\n server.middlewares.use('/__studio/node', (req, res) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n res.setHeader('allow', 'GET, HEAD');\n sendJson(res, 405, { error: 'the studio is read-only: GET only' });\n return;\n }\n const rejection = studioRequestRejection(req);\n if (rejection !== undefined) {\n sendJson(res, 403, { error: rejection });\n return;\n }\n const params = new URL(req.url ?? '/', 'http://internal').searchParams;\n const found = sourcePosition(cwd, params.get('file') ?? '', Number(params.get('line')));\n if ('error' in found) {\n sendJson(res, 422, { error: found.error });\n return;\n }\n sendJson(res, 200, { file: relative(cwd, found.file), line: found.line });\n });\n\n /* Registered after the routes above, so it only sees what none of them took. */\n server.middlewares.use('/__studio', (_req, res) => {\n sendJson(res, 404, { error: 'no such studio endpoint' });\n });\n },\n };\n}\n\ntype Located = { file: string; line: number } | { error: string };\n\n/** The two `node:path` functions containment needs, so the suite can hand in `path.win32`. */\ninterface PathOps {\n isAbsolute: (path: string) => boolean;\n relative: (from: string, to: string) => string;\n}\n\n/**\n * Is `candidate` `root` itself or something below it?\n *\n * Asked through `relative`, never a string prefix. A prefix test needs a\n * trailing separator (or `/proj-evil` passes for `/proj`), and the separator it\n * appends is the wrong one on Windows, where `resolve()` returns `C:\\proj\\…`:\n * that mismatch failed every path on Windows, which is how the whole\n * /__studio/node surface came to answer \"outside the project\" there.\n */\nexport function isInsideDir(\n root: string,\n candidate: string,\n ops: PathOps = { isAbsolute, relative }\n): boolean {\n const rel = ops.relative(root, candidate);\n if (rel === '') return true;\n /* An absolute answer means there is no way down from root — another drive. */\n if (ops.isAbsolute(rel)) return false;\n /* Segment-wise, so a file legitimately named '..rc' is not read as an escape. */\n return rel.split(/[/\\\\]/)[0] !== '..';\n}\n\n/**\n * Keep a path that arrived from the browser inside the project.\n *\n * The scope is `cwd` — the project the studio was started in — and not the\n * workspace root `searchForWorkspaceRoot` walks up to: in a monorepo that root\n * is the whole repo, so a studio started in `apps/marketing` accepted\n * `file=../../packages/billing/src/rates.ts` and read it.\n */\nexport function isInsideProject(cwd: string, candidate: string): boolean {\n const root = resolve(cwd);\n const path = resolve(candidate);\n if (!isInsideDir(root, path)) return false;\n /*\n * Then again on the real paths: a symlink inside the project may point\n * anywhere, and the check above only ever sees the link's own path. A path\n * that does not exist has nothing to resolve — the caller reports that.\n */\n if (!existsSync(path)) return true;\n return isInsideDir(realpathSync(root), realpathSync(path));\n}\n\n/**\n * Check a captured position before answering with it.\n *\n * The path is validated against cwd before anything is touched: it arrives\n * from the browser, and an endpoint that follows an arbitrary path is a\n * read-anywhere endpoint.\n */\nfunction sourcePosition(cwd: string, rawFile: string, line: number): Located {\n let path = rawFile;\n if (/^https?:\\/\\//.test(path)) path = new URL(path).pathname;\n const fsPrefix = '/@fs';\n if (path.startsWith(fsPrefix)) path = path.slice(fsPrefix.length);\n path = resolve(cwd, decodeURIComponent(path));\n\n if (!isInsideProject(cwd, path)) return { error: 'source file is outside the project' };\n if (!existsSync(path)) return { error: `no such source file: ${path}` };\n if (!Number.isInteger(line) || line < 1) return { error: 'expected a line number' };\n return { file: path, line };\n}\n\n/** Vite's own `server.fs.deny` default; setting the option replaces it, so it is spelled out. */\nconst VITE_DEFAULT_DENY = ['.env', '.env.*', '*.{crt,pem}', '**/.git/**'];\n\n/**\n * `server.fs.deny` patterns for files the page must never be served.\n *\n * `fs.allow` covers the whole workspace so the browser can import the\n * template registries, which also made `GET /@fs/<cwd>/workflow.stats.ts`\n * answer with the stats source — a file the README calls server-only, and the\n * one place a connection string is likely to be written as a literal. The\n * browser never imports the config or the stats file (the virtual module\n * imports the registries by their own paths; a registry written inline in the\n * config is refused for this reason), so both are denied outright.\n *\n * Patterns go through picomatch, so the path is spelled literally: its glob\n * characters escaped, slashes normalized the way Vite normalizes the file it\n * checks. A symlinked file is denied under both of its names.\n */\nexport function projectFileDeny(paths: readonly (string | undefined)[]): string[] {\n const deny = new Set<string>();\n for (const path of paths) {\n if (path === undefined) continue;\n const literal = resolve(path);\n deny.add(normalizePath(literal));\n if (existsSync(literal)) deny.add(normalizePath(realpathSync(literal)));\n }\n return [...deny].map((path) => path.replace(/[\\\\*?[\\]{}()!+@]/g, '\\\\$&'));\n}\n\nexport interface StartOptions {\n cwd?: string;\n config?: string;\n /** The studio's stats source (default ./workflow.stats.ts, if present). */\n stats?: string;\n port?: number;\n open?: boolean;\n}\n\nexport async function startStudio(options: StartOptions = {}): Promise<ViteDevServer> {\n const cwd = options.cwd ?? process.cwd();\n // The config is required (findConfig throws); the stats source is optional.\n // The resolved path is what the plugin loads — resolving again from cwd\n // inside it is what once made --config point at a file it does not name.\n const configPath = findConfig(cwd, options.config);\n const statsPath = findStats(cwd, options.stats);\n const appRoot = resolveAppRoot();\n\n const server = await createServer({\n root: appRoot,\n configFile: false,\n envDir: false,\n plugins: [\n react(),\n svgr(),\n tailwindcss(),\n projectPlugin(configPath, statsPath),\n studioApiPlugin(cwd),\n ],\n server: {\n port: options.port ?? 4321,\n open: options.open ?? false,\n /*\n * Both workspace roots have to be readable: the user's project (the\n * config and everything it imports) and ours — under pnpm our own\n * dependencies (fonts, css) resolve into a store beside the workspace\n * root rather than anywhere below the app.\n */\n fs: {\n allow: [\n searchForWorkspaceRoot(cwd),\n /* A config outside cwd brings its own workspace: the registries the browser imports live there. */\n searchForWorkspaceRoot(dirname(configPath)),\n searchForWorkspaceRoot(packageRoot),\n appRoot,\n ],\n deny: [...VITE_DEFAULT_DENY, ...projectFileDeny([configPath, statsPath])],\n },\n },\n // The app and the user's project each have their own react; one copy only. One\n // @shware/workflow too: the preview's <EmailProvider> and the project's layout calling\n // useEmailContext() must share the context object\n resolve: { dedupe: ['react', 'react-dom', '@shware/workflow'] },\n /*\n * @react-email/render imports react-dom/server lazily, so the dep scan never\n * sees it: the first email preview made Vite discover it, re-optimize and\n * change the deps hash under a page that still held the old one — the\n * preview then failed with \"Failed to fetch dynamically imported module\"\n * (a 504 Outdated Optimize Dep) until a reload. Bundling both up front\n * keeps the hash stable from the first request. The project's config is\n * scanned too (never served — only crawled), so its templates'\n * dependencies (@react-email/components, zod, …) are bundled before the\n * first preview rather than discovered by it.\n */\n optimizeDeps: {\n entries: ['index.html', configPath],\n include: ['@react-email/render', 'react-dom/server'],\n },\n });\n\n await server.listen();\n return server;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, relative, resolve } from 'node:path';\nimport { type JourneyConfig, isConfig } from '@shware/workflow';\nimport { renderDrizzleSchema } from '@shware/workflow/store';\nimport { runnerImport } from 'vite';\nimport { findConfig } from './server';\n\n/**\n * `workflow-ui generate` — the engine's Postgres tables as one drizzle file, on the schema the\n * project's `database.schema` names (`workflow` by default). The host re-exports the file from\n * its drizzle schema and lets drizzle-kit write the migration, so the migration history stays the\n * host's. `--check` exits non-zero when the file on disk differs (CI, after an SDK upgrade).\n */\n\nexport interface GenerateOptions {\n cwd?: string;\n config?: string;\n out: string;\n check?: boolean;\n}\n\nexport type GenerateResult = 'written' | 'unchanged' | 'outdated';\n\n/** The host's formatter may rewrap the file, change quotes or trailing commas: not a difference. */\nfunction normalize(source: string): string {\n return (\n source\n .replace(/\"/g, \"'\")\n .replace(/\\s+/g, ' ')\n // Spaces around punctuation, and trailing commas, are the formatter's choice\n .replace(/ ?([{}()[\\],;:=<>.]) ?/g, '$1')\n .replace(/,([}\\])])/g, '$1')\n .trim()\n );\n}\n\nexport async function generateSchema(options: GenerateOptions): Promise<GenerateResult> {\n const cwd = options.cwd ?? process.cwd();\n const configPath = findConfig(cwd, options.config);\n const { module } = await runnerImport<{ default?: unknown }>(configPath);\n if (!isConfig(module.default)) {\n throw new Error(\n `workflow-ui: ${relative(cwd, configPath)} must \\`export default defineConfig({...})\\``\n );\n }\n const config: JourneyConfig = module.default;\n const file = renderDrizzleSchema(config.database?.schema);\n\n const out = resolve(cwd, options.out);\n const current = existsSync(out) ? readFileSync(out, 'utf8') : undefined;\n if (current !== undefined && normalize(current) === normalize(file)) return 'unchanged';\n if (options.check) return 'outdated';\n mkdirSync(dirname(out), { recursive: true });\n writeFileSync(out, file);\n return 'written';\n}\n","#!/usr/bin/env node\nimport { generateSchema } from './generate';\nimport { startStudio } from './server';\n\n/**\n * `workflow-ui` — start the studio over the project in ./workflow.config.ts.\n *\n * npx workflow-ui # reads ./workflow.config.ts (and ./workflow.stats.ts)\n * npx workflow-ui --port 5000\n * npx workflow-ui --config apps/marketing/workflow.config.ts\n * npx workflow-ui generate --out ../../packages/db/src/schema/workflow.ts [--check]\n */\n\ninterface Args {\n port?: number;\n config?: string;\n stats?: string;\n out?: string;\n check: boolean;\n open: boolean;\n help: boolean;\n}\n\nfunction parseArgs(argv: string[]): Args {\n const args: Args = { open: false, check: false, help: false };\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === '--help' || arg === '-h') args.help = true;\n else if (arg === '--open') args.open = true;\n else if (arg === '--check') args.check = true;\n else if (arg === '--out' || arg === '-o') args.out = argv[++i];\n else if (arg === '--port' || arg === '-p') args.port = Number(argv[++i]);\n else if (arg === '--config' || arg === '-c') args.config = argv[++i];\n else if (arg === '--stats' || arg === '-s') args.stats = argv[++i];\n }\n return args;\n}\n\nconst HELP = `\n workflow-ui — review your workflows, templates and reports\n\n Usage\n $ workflow-ui [dev] [options]\n $ workflow-ui generate --out <file> [--check] [--config <path>]\n\n Options\n -p, --port <port> Port to listen on (default 4321)\n -c, --config <path> Project file (default ./workflow.config.ts)\n -s, --stats <path> Stats source (default ./workflow.stats.ts, if present)\n --open Open the browser on start\n -o, --out <file> generate: where the drizzle schema file goes\n --check generate: fail when the file is out of date, write nothing\n -h, --help Show this message\n`;\n\nasync function main(): Promise<void> {\n const [command, ...rest] = process.argv.slice(2);\n if (command === 'generate') {\n const args = parseArgs(rest);\n if (args.help || args.out === undefined) {\n console.log(HELP);\n if (args.out === undefined && !args.help) process.exitCode = 1;\n return;\n }\n try {\n const result = await generateSchema({\n out: args.out,\n check: args.check,\n ...(args.config !== undefined ? { config: args.config } : {}),\n });\n if (result === 'outdated') {\n console.error(\n `\\n ${args.out} is out of date — run workflow-ui generate, then your migration tool\\n`\n );\n process.exitCode = 1;\n } else {\n console.log(`\\n ${args.out} ${result === 'written' ? 'written' : 'is up to date'}\\n`);\n }\n } catch (error) {\n console.error(`\\n${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n return;\n }\n\n // `dev` is accepted so the command reads well; the studio is the default mode\n const argv = process.argv.slice(2).filter((arg) => arg !== 'dev');\n const args = parseArgs(argv);\n\n if (args.help) {\n console.log(HELP);\n return;\n }\n\n try {\n const server = await startStudio({\n ...(args.port !== undefined ? { port: args.port } : {}),\n ...(args.config !== undefined ? { config: args.config } : {}),\n ...(args.stats !== undefined ? { stats: args.stats } : {}),\n open: args.open,\n });\n const address = server.resolvedUrls?.local[0] ?? `http://localhost:${args.port ?? 4321}`;\n console.log(`\\n workflow-ui ready at ${address}\\n`);\n } catch (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, EmailTemplate, PushTemplate, SegmentIR, SlackTemplate, WorkflowIR } from "@shware/workflow";
|
|
2
|
-
//#region src/config.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* The studio's own types: the stats source it reads numbers from
|
|
5
4
|
* (`workflow.stats.ts`, `defineStats`) and the shape the app receives from the
|
|
@@ -240,5 +239,4 @@ export interface ResolvedStudioConfig {
|
|
|
240
239
|
error?: StudioError;
|
|
241
240
|
stats?: StatsSource;
|
|
242
241
|
}
|
|
243
|
-
//#endregion
|
|
244
242
|
//# sourceMappingURL=config.d.mts.map
|
package/dist/config.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.mts","names":[],"sources":["../src/config.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"config.d.mts","names":[],"sources":["../src/config.ts"],"mappings":";;;;;;;;YAkBY,YAAY;;iBAGP;;EAEf;EACA;EACA;;EAEA;;EAEA;;EAEA;EACA;EACA;;EAEA;IACE;IACA;IACA;IACA;;;;;;;;;;;;;;;;;;;YAsBQ;;qBAWC;;YAYD;;;;;;iBAOK;EACf;EACA;;EAEA,UAAU;;;iBAIK,qBAAqB;EACpC,aAAa;;;;;;;;;;;;;;;;;;;iBAoBE;;EAEf;EACA;EACA;EACA;;;;;;;EAOA;;EAEA;EACA;;EAEA;;EAEA;;EAEA;;;;;;EAMA;;;iBAIe;;EAEf;EACA;;;;;;;;;;;iBAYe;;EAEf;;EAEA;EACA,SAAS;EACT;;EAEA;EACA;EACA;;EAEA;;;;;;;;;iBAUe;;EAEf;;EAEA;;EAEA;;;;;;;iBAQe;EACf;EACA;;EAEA;;EAEA,aAAa;;;iBAIE;EACf,UAAU;EACV;;;iBAIe;EACf;EACA;;;;;;iBAOe;;EAEf,gBAAgB,QAAQ,oBAAoB;;EAE5C,iBAAiB,QAAQ,mBAAmB;;EAE5C,YAAY,qBAAqB,OAAO,iBAAiB,QAAQ,eAAe;;EAEhF,aAAa,yBAAyB,QAAQ,aAAa;;EAE3D,WAAW,sBAAsB,OAAO,iBAAiB,QAAQ,iBAAiB;;EAElF,SAAS,sBAAsB,OAAO,eAAe,QAAQ,cAAc;;EAE3E,YAAY,sBAAsB,OAAO,eAAe,QAAQ,iBAAiB;;;;;;;;;;wBAWnE,YAAY,OAAO,cAAc;;iBAKhC;;EAEf;EACA;;;;;;;;iBASe;EACf;;EAEA,WAAW,eAAe;;EAE1B,QAAQ,eAAe;;EAEvB,QAAQ,eAAe;;EAEvB,UAAU,eAAe;;EAEzB,QAAQ,eAAe;;EAEvB,UAAU;;EAEV,OAAO;;EAEP,QAAQ;EACR,QAAQ"}
|
package/dist/config.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/config.ts
|
|
2
2
|
/** Every channel, in the order the studio's pickers list them. */
|
|
3
3
|
const METRIC_CHANNELS = [
|
|
4
4
|
"email",
|
|
@@ -21,7 +21,6 @@ const METRIC_CHANNELS = [
|
|
|
21
21
|
function defineStats(stats) {
|
|
22
22
|
return stats;
|
|
23
23
|
}
|
|
24
|
-
//#endregion
|
|
25
24
|
export { METRIC_CHANNELS, defineStats };
|
|
26
25
|
|
|
27
26
|
//# sourceMappingURL=config.mjs.map
|
package/dist/index.d.mts
CHANGED
|
@@ -2,7 +2,6 @@ import { Granularity, LinkStat, METRIC_CHANNELS, MessageStat, MetricChannel, Met
|
|
|
2
2
|
import { LucideIcon } from "lucide-react";
|
|
3
3
|
import { CSSProperties, ComponentProps, ReactNode } from "react";
|
|
4
4
|
import { DiscordTemplate, EmailConfig, EmailTemplate, PushTemplate, SlackTemplate, TemplateIssue, WorkflowIR } from "@shware/workflow";
|
|
5
|
-
//#region src/components/button/index.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* Ported from the design system in the template project — same API, so the two
|
|
8
7
|
* stay diffable. Colours resolve through the studio's CSS variables
|
|
@@ -17,8 +16,6 @@ interface Props$2 extends Omit<ComponentProps<'button'>, 'type'> {
|
|
|
17
16
|
variant?: 'text' | 'accent' | 'default' | 'secondary' | 'destructive' | 'outline';
|
|
18
17
|
}
|
|
19
18
|
export declare function Button({ children, className, size, style, type, variant, ...props }: Props$2): import("react").JSX.Element;
|
|
20
|
-
//#endregion
|
|
21
|
-
//#region src/components/corner-shape.d.ts
|
|
22
19
|
/**
|
|
23
20
|
* Every rounded surface that is not a full pill carries this.
|
|
24
21
|
*
|
|
@@ -30,8 +27,6 @@ export declare function Button({ children, className, size, style, type, variant
|
|
|
30
27
|
* Cast because `corner-shape` is not in React's CSSProperties yet.
|
|
31
28
|
*/
|
|
32
29
|
export declare const superellipse: CSSProperties;
|
|
33
|
-
//#endregion
|
|
34
|
-
//#region src/components/workflow-canvas.d.ts
|
|
35
30
|
/**
|
|
36
31
|
* Read-only workflow canvas: renders IR. Structure is code-owned, so the UI
|
|
37
32
|
* offers no editing.
|
|
@@ -60,8 +55,6 @@ interface WorkflowCanvasProps {
|
|
|
60
55
|
onSelectNode?: (id: string | undefined) => void;
|
|
61
56
|
}
|
|
62
57
|
export declare function WorkflowCanvas({ ir, stats, colorMode, selectedId, onSelectNode }: WorkflowCanvasProps): import("react").JSX.Element;
|
|
63
|
-
//#endregion
|
|
64
|
-
//#region src/utils/template-content.d.ts
|
|
65
58
|
/**
|
|
66
59
|
* What the studio reads out of a template definition.
|
|
67
60
|
*
|
|
@@ -81,8 +74,6 @@ interface TemplateFailure {
|
|
|
81
74
|
phase: 'json' | 'props' | 'content' | 'render';
|
|
82
75
|
issues: TemplateIssue[];
|
|
83
76
|
}
|
|
84
|
-
//#endregion
|
|
85
|
-
//#region src/components/template-refs.d.ts
|
|
86
77
|
/**
|
|
87
78
|
* Derive template references from IR — "which flows use which template" is not
|
|
88
79
|
* a hand-maintained list but something computed from the middle layer. It also
|
|
@@ -119,8 +110,6 @@ export declare function collectTemplates(irs: readonly WorkflowIR[], registries:
|
|
|
119
110
|
discords?: object;
|
|
120
111
|
slacks?: object;
|
|
121
112
|
}): TemplateRefInfo[];
|
|
122
|
-
//#endregion
|
|
123
|
-
//#region src/components/templates-page.d.ts
|
|
124
113
|
/**
|
|
125
114
|
* Template preview page: the list on the left comes from IR, the react-email
|
|
126
115
|
* component renders on the right. The email render is the caller's (it owns
|
|
@@ -175,8 +164,6 @@ interface TemplatesPageProps {
|
|
|
175
164
|
defaultScheme?: 'light' | 'dark';
|
|
176
165
|
}
|
|
177
166
|
export declare function TemplatesPage({ refs, emails, pushes, discords, slacks, appName, selected, selectedChannel, preview, emailConfig, previewProps, onPreviewPropsChange, defaultScheme }: TemplatesPageProps): import("react").JSX.Element;
|
|
178
|
-
//#endregion
|
|
179
|
-
//#region src/components/push-preview.d.ts
|
|
180
167
|
/**
|
|
181
168
|
* Push-notification preview: the two platforms' lock screens, side by side.
|
|
182
169
|
*
|
|
@@ -216,8 +203,6 @@ interface PushPreviewProps {
|
|
|
216
203
|
zoom: number;
|
|
217
204
|
}
|
|
218
205
|
export declare function PushPreview({ appName, title, body, scheme, zoom }: PushPreviewProps): import("react").JSX.Element;
|
|
219
|
-
//#endregion
|
|
220
|
-
//#region src/components/workflow-list.d.ts
|
|
221
206
|
/**
|
|
222
207
|
* The workflows list: one row per definition with its shape (how many
|
|
223
208
|
* messages, how many waits) and the funnel from the stats source, all inside
|
|
@@ -238,8 +223,6 @@ interface WorkflowListProps {
|
|
|
238
223
|
onOpen: (key: string) => void;
|
|
239
224
|
}
|
|
240
225
|
export declare function WorkflowList({ items, reports, onOpen }: WorkflowListProps): import("react").JSX.Element;
|
|
241
|
-
//#endregion
|
|
242
|
-
//#region src/components/metric-card.d.ts
|
|
243
226
|
/**
|
|
244
227
|
* One metric of the delivery funnel: what it is worth right now, which way it
|
|
245
228
|
* moved, and its shape over the queried range.
|
|
@@ -293,8 +276,6 @@ interface MetricCardProps {
|
|
|
293
276
|
format: (value: number) => string;
|
|
294
277
|
}
|
|
295
278
|
export declare function MetricCard({ label, value, delta, dates, series, format }: MetricCardProps): import("react").JSX.Element;
|
|
296
|
-
//#endregion
|
|
297
|
-
//#region src/components/date-range.d.ts
|
|
298
279
|
/**
|
|
299
280
|
* The range every panel on the Overview reads from. Both ends are inclusive
|
|
300
281
|
* ISO `YYYY-MM-DD` days — the same shape the stats contract takes, so the
|
|
@@ -330,8 +311,6 @@ interface Props {
|
|
|
330
311
|
* they carry is already localized and keyboard-accessible.
|
|
331
312
|
*/
|
|
332
313
|
export declare function DateRangePicker({ value, onChange, className }: Props): import("react").JSX.Element;
|
|
333
|
-
//#endregion
|
|
334
|
-
//#region src/components/channel-icon.d.ts
|
|
335
314
|
/**
|
|
336
315
|
* One glyph per delivery channel, shared by the chart cards, the channel
|
|
337
316
|
* pickers and the message table — a channel has to read the same everywhere or
|
|
@@ -345,8 +324,6 @@ export declare const CHANNEL_ICON: Record<MetricChannel, LucideIcon>;
|
|
|
345
324
|
/** Stand-in for "every channel": still a send, just not one transport. */
|
|
346
325
|
export declare const ALL_CHANNELS_ICON: LucideIcon;
|
|
347
326
|
export declare const channelIcon: (channel: MetricChannel | undefined) => LucideIcon;
|
|
348
|
-
//#endregion
|
|
349
|
-
//#region src/components/avatar.d.ts
|
|
350
327
|
/**
|
|
351
328
|
* A person's round portrait, with an initial on a tinted circle behind it.
|
|
352
329
|
*
|
|
@@ -366,8 +343,6 @@ interface AvatarProps {
|
|
|
366
343
|
size?: 'sm' | 'md';
|
|
367
344
|
}
|
|
368
345
|
export declare function Avatar({ picture, label, size }: AvatarProps): import("react").JSX.Element;
|
|
369
|
-
//#endregion
|
|
370
|
-
//#region src/components/sparkline.d.ts
|
|
371
346
|
/**
|
|
372
347
|
* Sparkline for the workflows list.
|
|
373
348
|
*
|
|
@@ -382,8 +357,6 @@ interface SparklineProps {
|
|
|
382
357
|
className?: string;
|
|
383
358
|
}
|
|
384
359
|
export declare function Sparkline({ values, width, height, className }: SparklineProps): import("react").JSX.Element;
|
|
385
|
-
//#endregion
|
|
386
|
-
//#region src/components/layout.d.ts
|
|
387
360
|
/**
|
|
388
361
|
* Tree layout: IR → react-flow nodes and edges.
|
|
389
362
|
*
|
|
@@ -443,6 +416,5 @@ export declare function layout(ir: WorkflowIR, stats?: NodeStats): {
|
|
|
443
416
|
nodes: CanvasNode[];
|
|
444
417
|
edges: CanvasEdge[];
|
|
445
418
|
};
|
|
446
|
-
//#endregion
|
|
447
419
|
export { type AvatarProps, type Size as ButtonSize, type CanvasEdge, type CanvasNode, type CanvasNodeData, type DateRange, Granularity, LinkStat, METRIC_CHANNELS, MessageStat, type MetricCardProps, MetricChannel, MetricPoint, type MetricSeries, MetricsQuery, type NodeCategory, type NodeIcon, NodeStats, Profile, ProfilePage, ProfileQuery, type PushPreviewProps, ResolvedStudioConfig, SegmentReport, type SparklineProps, StatsRange, StatsSource, StudioError, type TemplatePreview, type TemplateRefInfo, type TemplateUsage, type TemplatesPageProps, type Trend, type WorkflowCanvasProps, type WorkflowListProps, WorkflowReport, defineStats };
|
|
448
420
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":["Props","Props","Props"],"sources":["../src/components/button/index.tsx","../src/components/corner-shape.ts","../src/components/workflow-canvas.tsx","../src/utils/template-content.ts","../src/components/template-refs.ts","../src/components/templates-page.tsx","../src/components/push-preview.tsx","../src/components/workflow-list.tsx","../src/components/metric-card.tsx","../src/components/date-range.tsx","../src/components/channel-icon.ts","../src/components/avatar.tsx","../src/components/sparkline.tsx","../src/components/layout.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["Props","Props","Props"],"sources":["../src/components/button/index.tsx","../src/components/corner-shape.ts","../src/components/workflow-canvas.tsx","../src/utils/template-content.ts","../src/components/template-refs.ts","../src/components/templates-page.tsx","../src/components/push-preview.tsx","../src/components/workflow-list.tsx","../src/components/metric-card.tsx","../src/components/date-range.tsx","../src/components/channel-icon.ts","../src/components/avatar.tsx","../src/components/sparkline.tsx","../src/components/layout.ts"],"mappings":";;;;;;;;;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