@shware/workflow-ui 2.1.17 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/cli.mjs +84 -1
- package/dist/cli.mjs.map +1 -1
- package/package.json +2 -2
- package/src/cli.ts +32 -0
- package/src/plan.ts +116 -0
package/README.md
CHANGED
|
@@ -127,6 +127,20 @@ drizzle file on the config's `database.schema` (`workflow` by default), for
|
|
|
127
127
|
your drizzle-kit to migrate. `--check` writes nothing and fails when the file
|
|
128
128
|
is out of date; formatting differences do not count.
|
|
129
129
|
|
|
130
|
+
## plan
|
|
131
|
+
|
|
132
|
+
`workflow-ui plan --database-url <url>` (or `DATABASE_URL`) is the deploy-time
|
|
133
|
+
check run before the deploy. It compiles the project, reads from the database
|
|
134
|
+
which workflow versions journeys are still running on, and holds the bundle —
|
|
135
|
+
with the templates this code would serve — against them: a segment or action a
|
|
136
|
+
pinned journey names that the bundle drops, a template gone or moved to another
|
|
137
|
+
channel, a new required prop the pinned props never supplied. It prints the
|
|
138
|
+
pinned versions, what the database still lacks (migrations), and what would
|
|
139
|
+
break, and exits non-zero on a problem. Run it in CI ahead of `wrangler deploy`:
|
|
140
|
+
on Cloudflare a new version's code serves the moment it is published, so the
|
|
141
|
+
host's own refusal (`409` on deploy) comes too late to protect a running
|
|
142
|
+
journey from a template change. See `@shware/workflow`'s README, "Versioning".
|
|
143
|
+
|
|
130
144
|
## Read-only
|
|
131
145
|
|
|
132
146
|
The studio views your project; it never changes it. Edit workflows, templates
|
|
@@ -169,6 +183,9 @@ belongs in a command of its own.
|
|
|
169
183
|
generate
|
|
170
184
|
-o, --out <file> Where the drizzle schema file goes
|
|
171
185
|
--check Fail when the file is out of date, write nothing
|
|
186
|
+
|
|
187
|
+
plan
|
|
188
|
+
-d, --database-url The engine's database (default $DATABASE_URL)
|
|
172
189
|
```
|
|
173
190
|
|
|
174
191
|
## How it is built
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { ConfigCompileError, compileConfig, isConfig, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSlackTemplate } from "@shware/workflow";
|
|
2
|
+
import { ConfigCompileError, checkInFlight, compileConfig, describeInFlight, isConfig, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSlackTemplate, pinnedWorkflows } from "@shware/workflow";
|
|
3
3
|
import { renderDrizzleSchema } from "@shware/workflow/store";
|
|
4
4
|
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
@@ -8,6 +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
|
+
import { postgresJsStore } from "@shware/workflow/postgres-js";
|
|
11
12
|
// src/server/project.ts
|
|
12
13
|
/** The modules a Vite server has evaluated for SSR — where registries are located by identity. */
|
|
13
14
|
function ssrModulesOf(server) {
|
|
@@ -708,6 +709,60 @@ async function generateSchema(options) {
|
|
|
708
709
|
writeFileSync(out, file);
|
|
709
710
|
return "written";
|
|
710
711
|
}
|
|
712
|
+
// src/plan.ts
|
|
713
|
+
async function planDeploy(options) {
|
|
714
|
+
const cwd = options.cwd ?? process.cwd();
|
|
715
|
+
const configPath = findConfig(cwd, options.config);
|
|
716
|
+
const { module } = await runnerImport(configPath);
|
|
717
|
+
if (!isConfig(module.default)) throw new Error(`workflow-ui: ${relative(cwd, configPath)} must \`export default defineConfig({...})\``);
|
|
718
|
+
const config = module.default;
|
|
719
|
+
const bundle = compileConfig(config);
|
|
720
|
+
const schemaName = config.database?.schema;
|
|
721
|
+
const { store, close } = postgresJsStore(options.databaseUrl, schemaName === void 0 ? {} : { schema: schemaName });
|
|
722
|
+
try {
|
|
723
|
+
const schema = await store.checkSchema();
|
|
724
|
+
const pinned = schema.some((problem) => problem.startsWith("table ")) ? [] : await pinnedWorkflows(store);
|
|
725
|
+
const carried = new Set(bundle.workflows.map((w) => w.contentHash));
|
|
726
|
+
return {
|
|
727
|
+
pinned: pinned.map((pin) => ({
|
|
728
|
+
workflow: pin.workflow,
|
|
729
|
+
contentHash: pin.contentHash,
|
|
730
|
+
running: pin.running,
|
|
731
|
+
ir: pin.ir,
|
|
732
|
+
carried: carried.has(pin.contentHash)
|
|
733
|
+
})),
|
|
734
|
+
problems: checkInFlight(pinned, bundle, config),
|
|
735
|
+
schema
|
|
736
|
+
};
|
|
737
|
+
} finally {
|
|
738
|
+
await close();
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
742
|
+
/** The report as the lines the CLI prints. */
|
|
743
|
+
function formatPlan(report) {
|
|
744
|
+
const lines = [];
|
|
745
|
+
const journeys = report.pinned.reduce((sum, pin) => sum + pin.running, 0);
|
|
746
|
+
if (report.pinned.length === 0) lines.push("no journey is running: nothing is pinned");
|
|
747
|
+
else {
|
|
748
|
+
lines.push(`${plural(report.pinned.length, "pinned version")}, ${plural(journeys, "running journey")}:`);
|
|
749
|
+
for (const pin of report.pinned) {
|
|
750
|
+
const note = pin.carried ? "" : " (finish on their version; this bundle changes the workflow)";
|
|
751
|
+
lines.push(` ${pin.workflow}@${pin.contentHash.slice(0, 8)} ${pin.running} running${note}`);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
if (report.schema.length > 0) {
|
|
755
|
+
lines.push("the database lacks (run the migrations before deploying):");
|
|
756
|
+
for (const problem of report.schema) lines.push(` ${problem}`);
|
|
757
|
+
}
|
|
758
|
+
if (report.problems.length === 0) lines.push("this bundle keeps every running journey: safe to deploy");
|
|
759
|
+
else {
|
|
760
|
+
lines.push("this bundle would break running journeys:");
|
|
761
|
+
for (const line of describeInFlight(report.problems)) lines.push(` ${line}`);
|
|
762
|
+
lines.push("fix the bundle (keep the segment or action, give the template a new id, make the prop optional), or deploy with POST /bundle/deploy?force=1 to fail them");
|
|
763
|
+
}
|
|
764
|
+
return lines;
|
|
765
|
+
}
|
|
711
766
|
// src/cli.ts
|
|
712
767
|
function parseArgs(argv) {
|
|
713
768
|
const args = {
|
|
@@ -721,6 +776,7 @@ function parseArgs(argv) {
|
|
|
721
776
|
else if (arg === "--open") args.open = true;
|
|
722
777
|
else if (arg === "--check") args.check = true;
|
|
723
778
|
else if (arg === "--out" || arg === "-o") args.out = argv[++i];
|
|
779
|
+
else if (arg === "--database-url" || arg === "-d") args.databaseUrl = argv[++i];
|
|
724
780
|
else if (arg === "--port" || arg === "-p") args.port = Number(argv[++i]);
|
|
725
781
|
else if (arg === "--config" || arg === "-c") args.config = argv[++i];
|
|
726
782
|
else if (arg === "--stats" || arg === "-s") args.stats = argv[++i];
|
|
@@ -733,6 +789,7 @@ const HELP = `
|
|
|
733
789
|
Usage
|
|
734
790
|
$ workflow-ui [dev] [options]
|
|
735
791
|
$ workflow-ui generate --out <file> [--check] [--config <path>]
|
|
792
|
+
$ workflow-ui plan --database-url <url> [--config <path>]
|
|
736
793
|
|
|
737
794
|
Options
|
|
738
795
|
-p, --port <port> Port to listen on (default 4321)
|
|
@@ -741,6 +798,8 @@ const HELP = `
|
|
|
741
798
|
--open Open the browser on start
|
|
742
799
|
-o, --out <file> generate: where the drizzle schema file goes
|
|
743
800
|
--check generate: fail when the file is out of date, write nothing
|
|
801
|
+
-d, --database-url plan: the engine's database (default $DATABASE_URL); exits 1 when the
|
|
802
|
+
bundle would break journeys still running there
|
|
744
803
|
-h, --help Show this message
|
|
745
804
|
`;
|
|
746
805
|
async function main() {
|
|
@@ -768,6 +827,30 @@ async function main() {
|
|
|
768
827
|
}
|
|
769
828
|
return;
|
|
770
829
|
}
|
|
830
|
+
if (command === "plan") {
|
|
831
|
+
const args = parseArgs(rest);
|
|
832
|
+
const databaseUrl = args.databaseUrl ?? process.env.DATABASE_URL;
|
|
833
|
+
if (args.help || databaseUrl === void 0) {
|
|
834
|
+
console.log(HELP);
|
|
835
|
+
if (!args.help) {
|
|
836
|
+
console.error("\n plan needs --database-url <url> (or DATABASE_URL in the environment)\n");
|
|
837
|
+
process.exitCode = 1;
|
|
838
|
+
}
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
try {
|
|
842
|
+
const report = await planDeploy({
|
|
843
|
+
databaseUrl,
|
|
844
|
+
...args.config !== void 0 ? { config: args.config } : {}
|
|
845
|
+
});
|
|
846
|
+
console.log(`\n ${formatPlan(report).join("\n ")}\n`);
|
|
847
|
+
if (report.problems.length > 0) process.exitCode = 1;
|
|
848
|
+
} catch (error) {
|
|
849
|
+
console.error(`\n${error instanceof Error ? error.message : String(error)}\n`);
|
|
850
|
+
process.exitCode = 1;
|
|
851
|
+
}
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
771
854
|
const args = parseArgs(process.argv.slice(2).filter((arg) => arg !== "dev"));
|
|
772
855
|
if (args.help) {
|
|
773
856
|
console.log(HELP);
|
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, lstatSync, readdirSync, realpathSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { dirname, isAbsolute, join, relative, resolve, sep } 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 * What `server.fs.deny` refuses whatever the project: Vite's default, plus the credentials a\n * journey project keeps beside its code. `fs.allow` spans the project and its linked workspace\n * packages (see {@link studioFsAllow}), so without these\n * `/@fs/<path>/.dev.vars` (wrangler's secrets), an APNs `.p8` or a Firebase service account would\n * be one request away for any page that can reach the port.\n */\nexport const STUDIO_FS_DENY: readonly string[] = [\n ...VITE_DEFAULT_DENY,\n '**/.dev.vars*',\n '**/*.p8',\n '**/*.plist',\n '**/google-services.json',\n '**/*.pfx',\n '**/*.pem',\n '**/*.key',\n];\n\n/**\n * `server.fs.deny` patterns for files the page must never be served.\n *\n * `fs.allow` covers the project so the browser can import the template\n * 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\n/** Whether `path` lies inside some `node_modules` directory (a store entry, not a workspace link). */\nfunction inNodeModules(path: string): boolean {\n return path.split(sep).includes('node_modules');\n}\n\n/**\n * Real paths of the workspace packages `dir` links in through `node_modules` (pnpm's\n * `workspace:` dependencies, npm/yarn workspaces), followed transitively. A link that resolves\n * into a `node_modules` directory is a store entry, covered by the store's own allow entry.\n */\nfunction linkedWorkspacePackages(dir: string, found = new Set<string>()): Set<string> {\n const modules = join(dir, 'node_modules');\n let names: string[];\n try {\n names = readdirSync(modules);\n } catch {\n return found;\n }\n const entries = names.flatMap((name) => {\n if (!name.startsWith('@')) return [join(modules, name)];\n try {\n return readdirSync(join(modules, name)).map((child) => join(modules, name, child));\n } catch {\n return [];\n }\n });\n for (const entry of entries) {\n let real: string;\n try {\n if (!lstatSync(entry).isSymbolicLink()) continue;\n real = realpathSync(entry);\n } catch {\n continue; // a dangling link\n }\n if (inNodeModules(real) || found.has(real)) continue;\n found.add(real);\n linkedWorkspacePackages(real, found);\n }\n return found;\n}\n\n/**\n * `server.fs.allow` for the studio: only what the page actually imports.\n *\n * - the studio package itself (the app source, its css and fonts);\n * - the consuming project: the directory the studio is started from, and the config's own\n * directory when `--config` points outside it (the registries the browser imports live there);\n * - the workspace packages those link in (a template importing `@acme/contract` from a sibling\n * workspace package), followed transitively;\n * - the `node_modules` of each workspace root involved: under pnpm every dependency's real path is\n * in the virtual store `node_modules/.pnpm` beside the workspace root rather than below the app,\n * and with npm/yarn or a hoisted pnpm layout they are directly in `node_modules`.\n *\n * Nothing else in the workspace: a sibling app's source and secrets are not one `/@fs/` request\n * away. The deny list still applies inside every one of these.\n */\nexport function studioFsAllow(options: {\n cwd: string;\n configPath: string;\n packageRoot: string;\n appRoot: string;\n}): string[] {\n const { cwd, configPath, packageRoot, appRoot } = options;\n const projectDirs = [cwd, dirname(configPath)];\n const allow = new Set<string>([packageRoot, appRoot, ...projectDirs]);\n for (const dir of [...projectDirs, packageRoot]) {\n for (const linked of linkedWorkspacePackages(dir)) allow.add(linked);\n allow.add(join(searchForWorkspaceRoot(dir), 'node_modules'));\n }\n return [...allow];\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 fs: {\n allow: studioFsAllow({ cwd, configPath, packageRoot, appRoot }),\n deny: [...STUDIO_FS_DENY, ...projectFileDeny([configPath, statsPath])],\n },\n // The studio is its own origin and calls no one else's; no page elsewhere may read it\n cors: false,\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,SA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AAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG;GAC7E,QAAQ,WAAW;EACrB;EACA;CACF;CAIA,MAAM,OAAO,UADA,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,QAAQ,QAAQ,KACjC,CAAC;CAE3B,IAAI,KAAK,MAAM;EACb,QAAQ,IAAI,IAAI;EAChB;CACF;CAEA,IAAI;EAOF,MAAM,WAAU,MANK,YAAY;GAC/B,GAAI,KAAK,SAAS,KAAA,IAAY,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;GACrD,GAAI,KAAK,WAAW,KAAA,IAAY,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;GAC3D,GAAI,KAAK,UAAU,KAAA,IAAY,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;GACxD,MAAM,KAAK;EACb,CAAC,EAAA,CACsB,cAAc,MAAM,MAAM,oBAAoB,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/plan.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, lstatSync, readdirSync, realpathSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { dirname, isAbsolute, join, relative, resolve, sep } 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 * What `server.fs.deny` refuses whatever the project: Vite's default, plus the credentials a\n * journey project keeps beside its code. `fs.allow` spans the project and its linked workspace\n * packages (see {@link studioFsAllow}), so without these\n * `/@fs/<path>/.dev.vars` (wrangler's secrets), an APNs `.p8` or a Firebase service account would\n * be one request away for any page that can reach the port.\n */\nexport const STUDIO_FS_DENY: readonly string[] = [\n ...VITE_DEFAULT_DENY,\n '**/.dev.vars*',\n '**/*.p8',\n '**/*.plist',\n '**/google-services.json',\n '**/*.pfx',\n '**/*.pem',\n '**/*.key',\n];\n\n/**\n * `server.fs.deny` patterns for files the page must never be served.\n *\n * `fs.allow` covers the project so the browser can import the template\n * 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\n/** Whether `path` lies inside some `node_modules` directory (a store entry, not a workspace link). */\nfunction inNodeModules(path: string): boolean {\n return path.split(sep).includes('node_modules');\n}\n\n/**\n * Real paths of the workspace packages `dir` links in through `node_modules` (pnpm's\n * `workspace:` dependencies, npm/yarn workspaces), followed transitively. A link that resolves\n * into a `node_modules` directory is a store entry, covered by the store's own allow entry.\n */\nfunction linkedWorkspacePackages(dir: string, found = new Set<string>()): Set<string> {\n const modules = join(dir, 'node_modules');\n let names: string[];\n try {\n names = readdirSync(modules);\n } catch {\n return found;\n }\n const entries = names.flatMap((name) => {\n if (!name.startsWith('@')) return [join(modules, name)];\n try {\n return readdirSync(join(modules, name)).map((child) => join(modules, name, child));\n } catch {\n return [];\n }\n });\n for (const entry of entries) {\n let real: string;\n try {\n if (!lstatSync(entry).isSymbolicLink()) continue;\n real = realpathSync(entry);\n } catch {\n continue; // a dangling link\n }\n if (inNodeModules(real) || found.has(real)) continue;\n found.add(real);\n linkedWorkspacePackages(real, found);\n }\n return found;\n}\n\n/**\n * `server.fs.allow` for the studio: only what the page actually imports.\n *\n * - the studio package itself (the app source, its css and fonts);\n * - the consuming project: the directory the studio is started from, and the config's own\n * directory when `--config` points outside it (the registries the browser imports live there);\n * - the workspace packages those link in (a template importing `@acme/contract` from a sibling\n * workspace package), followed transitively;\n * - the `node_modules` of each workspace root involved: under pnpm every dependency's real path is\n * in the virtual store `node_modules/.pnpm` beside the workspace root rather than below the app,\n * and with npm/yarn or a hoisted pnpm layout they are directly in `node_modules`.\n *\n * Nothing else in the workspace: a sibling app's source and secrets are not one `/@fs/` request\n * away. The deny list still applies inside every one of these.\n */\nexport function studioFsAllow(options: {\n cwd: string;\n configPath: string;\n packageRoot: string;\n appRoot: string;\n}): string[] {\n const { cwd, configPath, packageRoot, appRoot } = options;\n const projectDirs = [cwd, dirname(configPath)];\n const allow = new Set<string>([packageRoot, appRoot, ...projectDirs]);\n for (const dir of [...projectDirs, packageRoot]) {\n for (const linked of linkedWorkspacePackages(dir)) allow.add(linked);\n allow.add(join(searchForWorkspaceRoot(dir), 'node_modules'));\n }\n return [...allow];\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 fs: {\n allow: studioFsAllow({ cwd, configPath, packageRoot, appRoot }),\n deny: [...STUDIO_FS_DENY, ...projectFileDeny([configPath, statsPath])],\n },\n // The studio is its own origin and calls no one else's; no page elsewhere may read it\n cors: false,\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","import { relative } from 'node:path';\nimport {\n type InFlightProblem,\n type JourneyConfig,\n type PinnedWorkflow,\n checkInFlight,\n compileConfig,\n describeInFlight,\n isConfig,\n pinnedWorkflows,\n} from '@shware/workflow';\nimport { postgresJsStore } from '@shware/workflow/postgres-js';\nimport { runnerImport } from 'vite';\nimport { findConfig } from './server';\n\n/**\n * `workflow-ui plan` — the deploy-time check, before the deploy: compiles the project and holds\n * the bundle, with the templates this code would serve, against the workflow versions journeys\n * are still running on in the database (`checkInFlight` in `@shware/workflow`). On Cloudflare a\n * new version's code serves the moment it is published, so the host's own refusal comes too late\n * to protect a running journey from a template change; CI runs this ahead of `wrangler deploy`\n * and stops on a non-zero exit.\n */\n\nexport interface PlanOptions {\n cwd?: string;\n config?: string;\n /** The engine's database, as `postgres` connects to it. */\n databaseUrl: string;\n}\n\nexport interface PlanReport {\n /**\n * Every workflow version with running journeys; `carried` when this bundle still contains that\n * exact version (otherwise those journeys finish on theirs, and new ones enter the new version).\n */\n pinned: (PinnedWorkflow & { carried: boolean })[];\n /** What this bundle would take from them; empty when the deploy is safe. */\n problems: InFlightProblem[];\n /** What the database lacks against the SDK's tables: migrations to run before the deploy. */\n schema: string[];\n}\n\nexport async function planDeploy(options: PlanOptions): Promise<PlanReport> {\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 bundle = compileConfig(config);\n const schemaName = config.database?.schema;\n const { store, close } = postgresJsStore(\n options.databaseUrl,\n schemaName === undefined ? {} : { schema: schemaName }\n );\n try {\n const schema = await store.checkSchema();\n // Without the tables there are no journeys to keep; with columns missing, the pins still read\n const pinned = schema.some((problem) => problem.startsWith('table '))\n ? []\n : await pinnedWorkflows(store);\n const carried = new Set(bundle.workflows.map((w) => w.contentHash));\n return {\n pinned: pinned.map((pin) => ({\n workflow: pin.workflow,\n contentHash: pin.contentHash,\n running: pin.running,\n ir: pin.ir,\n carried: carried.has(pin.contentHash),\n })),\n problems: checkInFlight(pinned, bundle, config),\n schema,\n };\n } finally {\n await close();\n }\n}\n\nconst plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;\n\n/** The report as the lines the CLI prints. */\nexport function formatPlan(report: PlanReport): string[] {\n const lines: string[] = [];\n const journeys = report.pinned.reduce((sum, pin) => sum + pin.running, 0);\n if (report.pinned.length === 0) {\n lines.push('no journey is running: nothing is pinned');\n } else {\n lines.push(\n `${plural(report.pinned.length, 'pinned version')}, ${plural(journeys, 'running journey')}:`\n );\n for (const pin of report.pinned) {\n const note = pin.carried\n ? ''\n : ' (finish on their version; this bundle changes the workflow)';\n lines.push(` ${pin.workflow}@${pin.contentHash.slice(0, 8)} ${pin.running} running${note}`);\n }\n }\n if (report.schema.length > 0) {\n lines.push('the database lacks (run the migrations before deploying):');\n for (const problem of report.schema) lines.push(` ${problem}`);\n }\n if (report.problems.length === 0) {\n lines.push('this bundle keeps every running journey: safe to deploy');\n } else {\n lines.push('this bundle would break running journeys:');\n for (const line of describeInFlight(report.problems)) lines.push(` ${line}`);\n lines.push(\n 'fix the bundle (keep the segment or action, give the template a new id, make the prop optional), or deploy with POST /bundle/deploy?force=1 to fail them'\n );\n }\n return lines;\n}\n","#!/usr/bin/env node\nimport { generateSchema } from './generate';\nimport { formatPlan, planDeploy } from './plan';\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 * npx workflow-ui plan --database-url $DATABASE_URL\n */\n\ninterface Args {\n port?: number;\n config?: string;\n stats?: string;\n out?: string;\n databaseUrl?: 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 === '--database-url' || arg === '-d') args.databaseUrl = 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 $ workflow-ui plan --database-url <url> [--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 -d, --database-url plan: the engine's database (default $DATABASE_URL); exits 1 when the\n bundle would break journeys still running there\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 if (command === 'plan') {\n const args = parseArgs(rest);\n const databaseUrl = args.databaseUrl ?? process.env.DATABASE_URL;\n if (args.help || databaseUrl === undefined) {\n console.log(HELP);\n if (!args.help) {\n console.error('\\n plan needs --database-url <url> (or DATABASE_URL in the environment)\\n');\n process.exitCode = 1;\n }\n return;\n }\n try {\n const report = await planDeploy({\n databaseUrl,\n ...(args.config !== undefined ? { config: args.config } : {}),\n });\n console.log(`\\n ${formatPlan(report).join('\\n ')}\\n`);\n if (report.problems.length > 0) process.exitCode = 1;\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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2.2.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/ShwareHQ/shware-sdk.git"
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"@floating-ui/react": "^0.27.20",
|
|
41
41
|
"@fontsource-variable/inter": "^5.3.0",
|
|
42
42
|
"@react-email/render": "^2.1.1",
|
|
43
|
-
"@shware/workflow": "
|
|
43
|
+
"@shware/workflow": "10.0.0",
|
|
44
44
|
"@tailwindcss/vite": "^4.3.3",
|
|
45
45
|
"@tanstack/react-query": "^5.104.5",
|
|
46
46
|
"@tanstack/react-router": "^1.170.46",
|
package/src/cli.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { generateSchema } from './generate';
|
|
3
|
+
import { formatPlan, planDeploy } from './plan';
|
|
3
4
|
import { startStudio } from './server';
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -9,6 +10,7 @@ import { startStudio } from './server';
|
|
|
9
10
|
* npx workflow-ui --port 5000
|
|
10
11
|
* npx workflow-ui --config apps/marketing/workflow.config.ts
|
|
11
12
|
* npx workflow-ui generate --out ../../packages/db/src/schema/workflow.ts [--check]
|
|
13
|
+
* npx workflow-ui plan --database-url $DATABASE_URL
|
|
12
14
|
*/
|
|
13
15
|
|
|
14
16
|
interface Args {
|
|
@@ -16,6 +18,7 @@ interface Args {
|
|
|
16
18
|
config?: string;
|
|
17
19
|
stats?: string;
|
|
18
20
|
out?: string;
|
|
21
|
+
databaseUrl?: string;
|
|
19
22
|
check: boolean;
|
|
20
23
|
open: boolean;
|
|
21
24
|
help: boolean;
|
|
@@ -29,6 +32,7 @@ function parseArgs(argv: string[]): Args {
|
|
|
29
32
|
else if (arg === '--open') args.open = true;
|
|
30
33
|
else if (arg === '--check') args.check = true;
|
|
31
34
|
else if (arg === '--out' || arg === '-o') args.out = argv[++i];
|
|
35
|
+
else if (arg === '--database-url' || arg === '-d') args.databaseUrl = argv[++i];
|
|
32
36
|
else if (arg === '--port' || arg === '-p') args.port = Number(argv[++i]);
|
|
33
37
|
else if (arg === '--config' || arg === '-c') args.config = argv[++i];
|
|
34
38
|
else if (arg === '--stats' || arg === '-s') args.stats = argv[++i];
|
|
@@ -42,6 +46,7 @@ const HELP = `
|
|
|
42
46
|
Usage
|
|
43
47
|
$ workflow-ui [dev] [options]
|
|
44
48
|
$ workflow-ui generate --out <file> [--check] [--config <path>]
|
|
49
|
+
$ workflow-ui plan --database-url <url> [--config <path>]
|
|
45
50
|
|
|
46
51
|
Options
|
|
47
52
|
-p, --port <port> Port to listen on (default 4321)
|
|
@@ -50,6 +55,8 @@ const HELP = `
|
|
|
50
55
|
--open Open the browser on start
|
|
51
56
|
-o, --out <file> generate: where the drizzle schema file goes
|
|
52
57
|
--check generate: fail when the file is out of date, write nothing
|
|
58
|
+
-d, --database-url plan: the engine's database (default $DATABASE_URL); exits 1 when the
|
|
59
|
+
bundle would break journeys still running there
|
|
53
60
|
-h, --help Show this message
|
|
54
61
|
`;
|
|
55
62
|
|
|
@@ -83,6 +90,31 @@ async function main(): Promise<void> {
|
|
|
83
90
|
return;
|
|
84
91
|
}
|
|
85
92
|
|
|
93
|
+
if (command === 'plan') {
|
|
94
|
+
const args = parseArgs(rest);
|
|
95
|
+
const databaseUrl = args.databaseUrl ?? process.env.DATABASE_URL;
|
|
96
|
+
if (args.help || databaseUrl === undefined) {
|
|
97
|
+
console.log(HELP);
|
|
98
|
+
if (!args.help) {
|
|
99
|
+
console.error('\n plan needs --database-url <url> (or DATABASE_URL in the environment)\n');
|
|
100
|
+
process.exitCode = 1;
|
|
101
|
+
}
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
const report = await planDeploy({
|
|
106
|
+
databaseUrl,
|
|
107
|
+
...(args.config !== undefined ? { config: args.config } : {}),
|
|
108
|
+
});
|
|
109
|
+
console.log(`\n ${formatPlan(report).join('\n ')}\n`);
|
|
110
|
+
if (report.problems.length > 0) process.exitCode = 1;
|
|
111
|
+
} catch (error) {
|
|
112
|
+
console.error(`\n${error instanceof Error ? error.message : String(error)}\n`);
|
|
113
|
+
process.exitCode = 1;
|
|
114
|
+
}
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
|
|
86
118
|
// `dev` is accepted so the command reads well; the studio is the default mode
|
|
87
119
|
const argv = process.argv.slice(2).filter((arg) => arg !== 'dev');
|
|
88
120
|
const args = parseArgs(argv);
|
package/src/plan.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { relative } from 'node:path';
|
|
2
|
+
import {
|
|
3
|
+
type InFlightProblem,
|
|
4
|
+
type JourneyConfig,
|
|
5
|
+
type PinnedWorkflow,
|
|
6
|
+
checkInFlight,
|
|
7
|
+
compileConfig,
|
|
8
|
+
describeInFlight,
|
|
9
|
+
isConfig,
|
|
10
|
+
pinnedWorkflows,
|
|
11
|
+
} from '@shware/workflow';
|
|
12
|
+
import { postgresJsStore } from '@shware/workflow/postgres-js';
|
|
13
|
+
import { runnerImport } from 'vite';
|
|
14
|
+
import { findConfig } from './server';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* `workflow-ui plan` — the deploy-time check, before the deploy: compiles the project and holds
|
|
18
|
+
* the bundle, with the templates this code would serve, against the workflow versions journeys
|
|
19
|
+
* are still running on in the database (`checkInFlight` in `@shware/workflow`). On Cloudflare a
|
|
20
|
+
* new version's code serves the moment it is published, so the host's own refusal comes too late
|
|
21
|
+
* to protect a running journey from a template change; CI runs this ahead of `wrangler deploy`
|
|
22
|
+
* and stops on a non-zero exit.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
export interface PlanOptions {
|
|
26
|
+
cwd?: string;
|
|
27
|
+
config?: string;
|
|
28
|
+
/** The engine's database, as `postgres` connects to it. */
|
|
29
|
+
databaseUrl: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface PlanReport {
|
|
33
|
+
/**
|
|
34
|
+
* Every workflow version with running journeys; `carried` when this bundle still contains that
|
|
35
|
+
* exact version (otherwise those journeys finish on theirs, and new ones enter the new version).
|
|
36
|
+
*/
|
|
37
|
+
pinned: (PinnedWorkflow & { carried: boolean })[];
|
|
38
|
+
/** What this bundle would take from them; empty when the deploy is safe. */
|
|
39
|
+
problems: InFlightProblem[];
|
|
40
|
+
/** What the database lacks against the SDK's tables: migrations to run before the deploy. */
|
|
41
|
+
schema: string[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function planDeploy(options: PlanOptions): Promise<PlanReport> {
|
|
45
|
+
const cwd = options.cwd ?? process.cwd();
|
|
46
|
+
const configPath = findConfig(cwd, options.config);
|
|
47
|
+
const { module } = await runnerImport<{ default?: unknown }>(configPath);
|
|
48
|
+
if (!isConfig(module.default)) {
|
|
49
|
+
throw new Error(
|
|
50
|
+
`workflow-ui: ${relative(cwd, configPath)} must \`export default defineConfig({...})\``
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
const config: JourneyConfig = module.default;
|
|
54
|
+
const bundle = compileConfig(config);
|
|
55
|
+
const schemaName = config.database?.schema;
|
|
56
|
+
const { store, close } = postgresJsStore(
|
|
57
|
+
options.databaseUrl,
|
|
58
|
+
schemaName === undefined ? {} : { schema: schemaName }
|
|
59
|
+
);
|
|
60
|
+
try {
|
|
61
|
+
const schema = await store.checkSchema();
|
|
62
|
+
// Without the tables there are no journeys to keep; with columns missing, the pins still read
|
|
63
|
+
const pinned = schema.some((problem) => problem.startsWith('table '))
|
|
64
|
+
? []
|
|
65
|
+
: await pinnedWorkflows(store);
|
|
66
|
+
const carried = new Set(bundle.workflows.map((w) => w.contentHash));
|
|
67
|
+
return {
|
|
68
|
+
pinned: pinned.map((pin) => ({
|
|
69
|
+
workflow: pin.workflow,
|
|
70
|
+
contentHash: pin.contentHash,
|
|
71
|
+
running: pin.running,
|
|
72
|
+
ir: pin.ir,
|
|
73
|
+
carried: carried.has(pin.contentHash),
|
|
74
|
+
})),
|
|
75
|
+
problems: checkInFlight(pinned, bundle, config),
|
|
76
|
+
schema,
|
|
77
|
+
};
|
|
78
|
+
} finally {
|
|
79
|
+
await close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
84
|
+
|
|
85
|
+
/** The report as the lines the CLI prints. */
|
|
86
|
+
export function formatPlan(report: PlanReport): string[] {
|
|
87
|
+
const lines: string[] = [];
|
|
88
|
+
const journeys = report.pinned.reduce((sum, pin) => sum + pin.running, 0);
|
|
89
|
+
if (report.pinned.length === 0) {
|
|
90
|
+
lines.push('no journey is running: nothing is pinned');
|
|
91
|
+
} else {
|
|
92
|
+
lines.push(
|
|
93
|
+
`${plural(report.pinned.length, 'pinned version')}, ${plural(journeys, 'running journey')}:`
|
|
94
|
+
);
|
|
95
|
+
for (const pin of report.pinned) {
|
|
96
|
+
const note = pin.carried
|
|
97
|
+
? ''
|
|
98
|
+
: ' (finish on their version; this bundle changes the workflow)';
|
|
99
|
+
lines.push(` ${pin.workflow}@${pin.contentHash.slice(0, 8)} ${pin.running} running${note}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (report.schema.length > 0) {
|
|
103
|
+
lines.push('the database lacks (run the migrations before deploying):');
|
|
104
|
+
for (const problem of report.schema) lines.push(` ${problem}`);
|
|
105
|
+
}
|
|
106
|
+
if (report.problems.length === 0) {
|
|
107
|
+
lines.push('this bundle keeps every running journey: safe to deploy');
|
|
108
|
+
} else {
|
|
109
|
+
lines.push('this bundle would break running journeys:');
|
|
110
|
+
for (const line of describeInFlight(report.problems)) lines.push(` ${line}`);
|
|
111
|
+
lines.push(
|
|
112
|
+
'fix the bundle (keep the segment or action, give the template a new id, make the prop optional), or deploy with POST /bundle/deploy?force=1 to fail them'
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
return lines;
|
|
116
|
+
}
|