@shware/workflow-ui 0.1.3 → 1.0.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 +6 -8
- package/dist/cli.mjs +8 -5
- package/dist/cli.mjs.map +1 -1
- package/dist/config.d.mts +4 -4
- package/dist/config.mjs.map +1 -1
- package/dist/index.mjs +9 -9
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/src/app/email-preview.ts +1 -1
- package/src/app/routes/workflows.tsx +1 -3
- package/src/components/templates-page.tsx +3 -3
- package/src/config.ts +4 -4
- package/src/server/project.ts +8 -5
- package/src/utils/template-content.ts +8 -12
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@ template is listed once:
|
|
|
16
16
|
|
|
17
17
|
```ts
|
|
18
18
|
import { defineConfig } from '@shware/workflow';
|
|
19
|
-
import {
|
|
19
|
+
import { templates } from './src/templates';
|
|
20
20
|
import { onboarding } from './src/workflows/onboarding';
|
|
21
21
|
import { contract } from './src/workflows/schema';
|
|
22
22
|
|
|
@@ -24,19 +24,17 @@ export default defineConfig({
|
|
|
24
24
|
title: 'Workflow Studio · Acme',
|
|
25
25
|
contract,
|
|
26
26
|
workflows: [onboarding],
|
|
27
|
-
templates
|
|
27
|
+
templates,
|
|
28
28
|
emails: { from: { email: 'hello@acme.io', name: 'Acme' } },
|
|
29
29
|
});
|
|
30
30
|
```
|
|
31
31
|
|
|
32
32
|
```ts
|
|
33
|
-
// src/templates.ts —
|
|
34
|
-
import { templates } from '@shware/workflow';
|
|
33
|
+
// src/templates.ts — what the config registers; the workflows send email.welcome
|
|
35
34
|
import { email } from './email'; // export const email = { welcome, ... }
|
|
36
35
|
import { push } from './push'; // export const push = { nudge, ... }
|
|
37
36
|
|
|
38
|
-
export const
|
|
39
|
-
export const t = templates(registry); // what the workflows reference: t.email.welcome
|
|
37
|
+
export const templates = { email, push };
|
|
40
38
|
```
|
|
41
39
|
|
|
42
40
|
- The studio compiles it with `compileConfig` — the bundle the Worker
|
|
@@ -125,8 +123,8 @@ belongs in a command of its own.
|
|
|
125
123
|
to their template, and the inspector shows a node's parameters and the line
|
|
126
124
|
that built it.
|
|
127
125
|
- **Templates** (`/templates`, `/templates/$key`) — every email and push
|
|
128
|
-
template your workflows reference, derived from IR
|
|
129
|
-
|
|
126
|
+
template your workflows reference, derived from IR and found by id; an
|
|
127
|
+
email and a push sharing an id stay two templates. Each renders
|
|
130
128
|
from its `preview` props, validated against its schema exactly as a send
|
|
131
129
|
would be; a props editor tries other values in memory, and a refusal lists
|
|
132
130
|
the failing fields. Emails render through `@react-email/render`, pushes as
|
package/dist/cli.mjs
CHANGED
|
@@ -45,8 +45,8 @@ const CHANNELS = {
|
|
|
45
45
|
var StudioLoadError = class extends Error {};
|
|
46
46
|
/**
|
|
47
47
|
* The module that exports `registry`, by identity: the registry itself, or
|
|
48
|
-
* else an exported `{ email, push }` holding it (`export const
|
|
49
|
-
* { email
|
|
48
|
+
* else an exported `{ email, push }` holding it (`export const templates =
|
|
49
|
+
* { email, push }`).
|
|
50
50
|
* workflow.config.ts itself is never a candidate: importing it would bring the
|
|
51
51
|
* whole config (and everything it imports) into the browser. Sorted by path,
|
|
52
52
|
* so the answer does not depend on load order.
|
|
@@ -66,7 +66,7 @@ function locate(channel, registry, modules, configPath) {
|
|
|
66
66
|
name,
|
|
67
67
|
property: channel
|
|
68
68
|
};
|
|
69
|
-
throw new StudioLoadError(`templates.${channel} is not exported from a module of its own. Export the registry (e.g. \`export const ${channel} = {...}\` in src/${channel}/index.ts, or \`export const
|
|
69
|
+
throw new StudioLoadError(`templates.${channel} is not exported from a module of its own. Export the registry (e.g. \`export const ${channel} = {...}\` in src/${channel}/index.ts, or \`export const templates = { email, push }\` in src/templates.ts) and import it into workflow.config.ts — the studio loads that module, never the config, into the browser.`);
|
|
70
70
|
}
|
|
71
71
|
function errorOf(error) {
|
|
72
72
|
return {
|
|
@@ -160,7 +160,8 @@ const STATS_METHODS = [
|
|
|
160
160
|
];
|
|
161
161
|
/**
|
|
162
162
|
* The module the browser imports as `virtual:workflow-config`: the payload as
|
|
163
|
-
* a JSON literal, the
|
|
163
|
+
* a JSON literal, the template registries as imports from their own modules
|
|
164
|
+
* (re-keyed by template id), and
|
|
164
165
|
* the stats source as calls to the studio's server, one per method
|
|
165
166
|
* workflow.stats.ts defines — the source itself runs there, next to the
|
|
166
167
|
* database and the secrets it reads with, never in the browser.
|
|
@@ -177,7 +178,7 @@ function virtualModule(snapshot, statsMethods) {
|
|
|
177
178
|
const registries = Object.keys(CHANNELS).map((channel) => {
|
|
178
179
|
const ref = snapshot.registries[channel];
|
|
179
180
|
const { field } = CHANNELS[channel];
|
|
180
|
-
return ` ${field}: ${ref === void 0 ? "{}" : importOf(ref, field)},`;
|
|
181
|
+
return ` ${field}: ${ref === void 0 ? "{}" : `byId(${importOf(ref, field)})`},`;
|
|
181
182
|
});
|
|
182
183
|
const stats = statsMethods === void 0 ? void 0 : `{ ${statsMethods.map((method) => `${method}: call(${JSON.stringify(method)})`).join(", ")} }`;
|
|
183
184
|
const call = stats === void 0 ? "" : `
|
|
@@ -192,6 +193,8 @@ const call = (method) => async (...args) => {
|
|
|
192
193
|
return body;
|
|
193
194
|
};`;
|
|
194
195
|
return `${imports.join("\n")}${call}
|
|
196
|
+
/* The views look a template up by its id, the name messages use, never by the property holding it. */
|
|
197
|
+
const byId = (registry) => Object.fromEntries(Object.values(registry).map((t) => [t.id, t]));
|
|
195
198
|
const payload = ${JSON.stringify(snapshot.payload)};
|
|
196
199
|
export default {
|
|
197
200
|
...payload,
|
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 EmailAddress,\n type JourneyConfig,\n compileConfig,\n formatEmailAddress,\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 email envelope. 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 registry =\n * { email: {...}, push: {...} }` next to `t = templates(registry)`).\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 registry = { 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 formatted(address: EmailAddress | undefined): string | undefined {\n return address === undefined ? undefined : formatEmailAddress(address);\n}\n\nfunction failed(error: unknown, title?: string): StudioSnapshot {\n return {\n payload: {\n ...(title !== undefined ? { title } : {}),\n workflows: {},\n segments: [],\n emailDefaults: {},\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 from = formatted(config.emails?.from);\n const replyTo = formatted(config.emails?.replyTo);\n const shared = {\n ...(config.title !== undefined ? { title: config.title } : {}),\n emailDefaults: {\n ...(from !== undefined ? { from } : {}),\n ...(replyTo !== undefined ? { replyTo } : {}),\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 two registries as imports from their own modules, 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 ? '{}' : 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}\nconst payload = ${JSON.stringify(snapshot.payload)};\nexport default {\n ...payload,\n${registries.join('\\n')}${stats === undefined ? '' : `\\n stats: ${stats},`}\n};\n`;\n}\n","import { existsSync, realpathSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { dirname, isAbsolute, relative, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport tailwindcss from '@tailwindcss/vite';\nimport react from '@vitejs/plugin-react';\nimport { type Plugin, type ViteDevServer, createServer, searchForWorkspaceRoot } 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\nexport interface StartOptions {\n cwd?: string;\n config?: string;\n /** The studio's stats source (default ./workflow.stats.ts, if present). */\n stats?: string;\n port?: number;\n open?: boolean;\n}\n\nexport async function startStudio(options: StartOptions = {}): Promise<ViteDevServer> {\n const cwd = options.cwd ?? process.cwd();\n // The config is required (findConfig throws); the stats source is optional.\n // The resolved path is what the plugin loads — resolving again from cwd\n // inside it is what once made --config point at a file it does not name.\n const configPath = findConfig(cwd, options.config);\n const statsPath = findStats(cwd, options.stats);\n const appRoot = resolveAppRoot();\n\n const server = await createServer({\n root: appRoot,\n configFile: false,\n envDir: false,\n plugins: [\n react(),\n svgr(),\n tailwindcss(),\n projectPlugin(configPath, statsPath),\n studioApiPlugin(cwd),\n ],\n server: {\n port: options.port ?? 4321,\n open: options.open ?? false,\n /*\n * Both workspace roots have to be readable: the user's project (the\n * config and everything it imports) and ours — under pnpm our own\n * dependencies (fonts, css) resolve into a store beside the workspace\n * root rather than anywhere below the app.\n */\n fs: {\n allow: [\n searchForWorkspaceRoot(cwd),\n /* A config outside cwd brings its own workspace: the registries the browser imports live there. */\n searchForWorkspaceRoot(dirname(configPath)),\n searchForWorkspaceRoot(packageRoot),\n appRoot,\n ],\n },\n },\n // The app and the user's project each have their own react; one copy only\n resolve: { dedupe: ['react', 'react-dom'] },\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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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/cli.ts"],"sourcesContent":["import {\n ConfigCompileError,\n type EmailAddress,\n type JourneyConfig,\n compileConfig,\n formatEmailAddress,\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 email envelope. 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 formatted(address: EmailAddress | undefined): string | undefined {\n return address === undefined ? undefined : formatEmailAddress(address);\n}\n\nfunction failed(error: unknown, title?: string): StudioSnapshot {\n return {\n payload: {\n ...(title !== undefined ? { title } : {}),\n workflows: {},\n segments: [],\n emailDefaults: {},\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 from = formatted(config.emails?.from);\n const replyTo = formatted(config.emails?.replyTo);\n const shared = {\n ...(config.title !== undefined ? { title: config.title } : {}),\n emailDefaults: {\n ...(from !== undefined ? { from } : {}),\n ...(replyTo !== undefined ? { replyTo } : {}),\n },\n };\n\n try {\n const bundle = compileConfig(config);\n return {\n payload: {\n ...shared,\n workflows: Object.fromEntries(bundle.workflows.map((workflow) => [workflow.id, workflow])),\n segments: bundle.segments,\n },\n registries,\n };\n } catch (error) {\n return {\n payload: { ...shared, workflows: {}, segments: [], error: errorOf(error) },\n registries,\n };\n }\n}\n\n/* ------------------------------ Virtual module ----------------------------- */\n\n/** The `StatsSource` methods, the only names the stats endpoint answers. */\nexport const STATS_METHODS = [\n 'reports',\n 'segments',\n 'profiles',\n 'nodeStats',\n 'metrics',\n 'links',\n 'messages',\n] as const;\nexport type StatsMethod = (typeof STATS_METHODS)[number];\n\n/**\n * The module the browser imports as `virtual:workflow-config`: the payload as\n * a JSON literal, the template registries as imports from their own modules\n * (re-keyed by template id), and\n * the stats source as calls to the studio's server, one per method\n * workflow.stats.ts defines — the source itself runs there, next to the\n * database and the secrets it reads with, never in the browser.\n */\n/** An export name as an import names it: quoted (ES2022) when it is not an identifier. */\nconst exportName = (name: string) =>\n /^[A-Za-z_$][\\w$]*$/.test(name) ? name : JSON.stringify(name);\n\nexport function virtualModule(\n snapshot: StudioSnapshot,\n statsMethods: readonly StatsMethod[] | undefined\n): string {\n const imports: string[] = [];\n const importOf = (ref: ModuleRef, local: string): string => {\n /* One channel of an exported `{ email, push }`: import the whole under its own alias. */\n const binding = ref.property === undefined ? local : `${local}Source`;\n imports.push(\n ref.name === 'default'\n ? `import ${binding} from ${JSON.stringify(ref.file)};`\n : `import { ${ref.name === binding ? binding : `${exportName(ref.name)} as ${binding}`} } from ${JSON.stringify(ref.file)};`\n );\n return ref.property === undefined ? binding : `${binding}.${ref.property}`;\n };\n const registries = (Object.keys(CHANNELS) as Channel[]).map((channel) => {\n const ref = snapshot.registries[channel];\n const { field } = CHANNELS[channel];\n return ` ${field}: ${ref === undefined ? '{}' : `byId(${importOf(ref, field)})`},`;\n });\n const stats =\n statsMethods === undefined\n ? undefined\n : `{ ${statsMethods.map((method) => `${method}: call(${JSON.stringify(method)})`).join(', ')} }`;\n const call =\n stats === undefined\n ? ''\n : `\nconst call = (method) => async (...args) => {\n const response = await fetch(\\`/__studio/stats/\\${method}\\`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(args),\n });\n const body = await response.json();\n if (!response.ok) throw new Error(body.error ?? \\`stats \\${method} failed: \\${response.status}\\`);\n return body;\n};`;\n\n return `${imports.join('\\n')}${call}\n/* The views look a template up by its id, the name messages use, never by the property holding it. */\nconst byId = (registry) => Object.fromEntries(Object.values(registry).map((t) => [t.id, t]));\nconst payload = ${JSON.stringify(snapshot.payload)};\nexport default {\n ...payload,\n${registries.join('\\n')}${stats === undefined ? '' : `\\n stats: ${stats},`}\n};\n`;\n}\n","import { existsSync, realpathSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { dirname, isAbsolute, relative, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport tailwindcss from '@tailwindcss/vite';\nimport react from '@vitejs/plugin-react';\nimport { type Plugin, type ViteDevServer, createServer, searchForWorkspaceRoot } 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\nexport interface StartOptions {\n cwd?: string;\n config?: string;\n /** The studio's stats source (default ./workflow.stats.ts, if present). */\n stats?: string;\n port?: number;\n open?: boolean;\n}\n\nexport async function startStudio(options: StartOptions = {}): Promise<ViteDevServer> {\n const cwd = options.cwd ?? process.cwd();\n // The config is required (findConfig throws); the stats source is optional.\n // The resolved path is what the plugin loads — resolving again from cwd\n // inside it is what once made --config point at a file it does not name.\n const configPath = findConfig(cwd, options.config);\n const statsPath = findStats(cwd, options.stats);\n const appRoot = resolveAppRoot();\n\n const server = await createServer({\n root: appRoot,\n configFile: false,\n envDir: false,\n plugins: [\n react(),\n svgr(),\n tailwindcss(),\n projectPlugin(configPath, statsPath),\n studioApiPlugin(cwd),\n ],\n server: {\n port: options.port ?? 4321,\n open: options.open ?? false,\n /*\n * Both workspace roots have to be readable: the user's project (the\n * config and everything it imports) and ours — under pnpm our own\n * dependencies (fonts, css) resolve into a store beside the workspace\n * root rather than anywhere below the app.\n */\n fs: {\n allow: [\n searchForWorkspaceRoot(cwd),\n /* A config outside cwd brings its own workspace: the registries the browser imports live there. */\n searchForWorkspaceRoot(dirname(configPath)),\n searchForWorkspaceRoot(packageRoot),\n appRoot,\n ],\n },\n },\n // The app and the user's project each have their own react; one copy only\n resolve: { dedupe: ['react', 'react-dom'] },\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":";;;;;;;;;;;;AAuCA,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,MA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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"}
|
package/dist/config.d.mts
CHANGED
|
@@ -224,13 +224,13 @@ export interface ResolvedStudioConfig {
|
|
|
224
224
|
title?: string;
|
|
225
225
|
/** Compiled workflows, keyed by workflow name (empty when `error` is set). */
|
|
226
226
|
workflows: Record<string, WorkflowIR>;
|
|
227
|
-
/** The project's email
|
|
227
|
+
/** The project's email templates by id (empty if none). */
|
|
228
228
|
emails: Record<string, EmailTemplate>;
|
|
229
|
-
/** The project's push
|
|
229
|
+
/** The project's push templates by id (empty if none). */
|
|
230
230
|
pushes: Record<string, PushTemplate>;
|
|
231
|
-
/** The project's Discord webhook
|
|
231
|
+
/** The project's Discord webhook templates by id (empty if none). */
|
|
232
232
|
discords: Record<string, DiscordTemplate>;
|
|
233
|
-
/** The project's Slack webhook
|
|
233
|
+
/** The project's Slack webhook templates by id (empty if none). */
|
|
234
234
|
slacks: Record<string, SlackTemplate>;
|
|
235
235
|
/** Compiled named segments. */
|
|
236
236
|
segments: SegmentIR[];
|
package/dist/config.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.mjs","names":[],"sources":["../src/config.ts"],"sourcesContent":["import type {\n DiscordTemplate,\n EmailTemplate,\n PushTemplate,\n SegmentIR,\n SlackTemplate,\n WorkflowIR,\n} from '@shware/workflow';\n\n/**\n * The studio's own types: the stats source it reads numbers from\n * (`workflow.stats.ts`, `defineStats`) and the shape the app receives from the\n * dev server. The project itself is `@shware/workflow`'s `defineConfig({...})`\n * in workflow.config.ts — the studio reads it, it defines nothing of its own.\n */\n\n/** Node id → how many users currently sit on that node. */\nexport type NodeStats = Record<string, number>;\n\n/** Per-workflow totals for the list and metrics views. */\nexport interface WorkflowReport {\n /** The workflow's id, matching `WorkflowIR.id`. */\n id: string;\n entered: number;\n completed: number;\n /** Reached the goal (a conversion). */\n converted: number;\n /** Currently in flight. */\n active: number;\n /** Messages delivered; rates below are computed against it. */\n delivered?: number;\n opened?: number;\n clicked?: number;\n /** Recent daily counts, oldest first — drives the sparklines in the list. */\n series?: {\n delivered?: number[];\n opened?: number[];\n clicked?: number[];\n converted?: number[];\n };\n}\n\n/* ------------------------------ Overview query ------------------------------ */\n\n/**\n * The channel dimension analytics reports on.\n *\n * Deliberately *not* the DSL's `ChannelIR`. That enum says what the author\n * asked for (\"send a push\"); this says where the message actually landed, and\n * the two do not line up: one `push` node fans out to iOS and Android, whose\n * delivery and open behaviour differ enough that reading them summed hides the\n * problem you opened this page to find. Going the other way, a project can\n * report on a transport the DSL has no builder for yet — a webhook — without\n * the IR having to grow a node type first.\n *\n * So the mapping is many-to-many and belongs to whoever measures delivery, not\n * to the compiler. In-product surfaces (`in_app`, `survey`) are absent on\n * purpose: they have no transport receipt, no open pixel and no unsubscribe,\n * so none of the funnel below is defined for them.\n */\nexport type MetricChannel =\n | 'email'\n | 'push_ios'\n | 'push_android'\n | 'push_web'\n | 'slack'\n | 'discord'\n | 'sms'\n | 'webhook';\n\n/** Every channel, in the order the studio's pickers list them. */\nexport const METRIC_CHANNELS = [\n 'email',\n 'push_ios',\n 'push_android',\n 'push_web',\n 'slack',\n 'discord',\n 'sms',\n 'webhook',\n] as const satisfies readonly MetricChannel[];\n\n/** Bucket width for a time series. */\nexport type Granularity = 'day' | 'week' | 'month';\n\n/**\n * What every Overview panel is scoped by. Dates are ISO `YYYY-MM-DD` and both\n * ends are inclusive — a report reads \"Aug 21 to Sep 19\", not \"up to but\n * excluding Sep 20\".\n */\nexport interface StatsRange {\n from: string;\n to: string;\n /** Absent means every channel summed. */\n channel?: MetricChannel;\n}\n\n/** A range plus the bucket width, for the time series behind the chart cards. */\nexport interface MetricsQuery extends StatsRange {\n granularity: Granularity;\n}\n\n/**\n * One bucket of a workflow's delivery funnel.\n *\n * `sent` and `delivered` are two different facts and the UI shows both: sent is\n * what we handed the transport, delivered is what it accepted. The gap between\n * them is the bounce rate, which is invisible if you only keep one of them —\n * which is why `delivered` was not simply renamed when the Sent card arrived.\n *\n * Opens and clicks carry an optional human/machine split. Not every transport\n * can tell the two apart — most have nothing to tell apart — so the halves are\n * optional, and the studio plots three lines only for a query whose every\n * bucket reports them. Where they are reported, `opened` must equal\n * `openedHuman + openedMachine` and `clicked` its own pair: the studio rates\n * all three against one denominator so the lines add up on screen, and a\n * source that recounts the halves independently would draw a chart that\n * visibly does not.\n */\nexport interface MetricPoint {\n /** Bucket start, ISO `YYYY-MM-DD`; used verbatim on the x axis. */\n date: string;\n sent: number;\n delivered: number;\n opened: number;\n /**\n * Opens a person caused. The rest is infrastructure: Apple's Mail Privacy\n * Protection prefetches the tracking pixel for everything it relays, whether\n * or not the mail is ever read, and Gmail's image proxy caches it — which is\n * why a raw open rate has been unusable as a measure of attention since 2021.\n */\n openedHuman?: number;\n /** Opens attributed to a proxy, relay or scanner rather than a reader. */\n openedMachine?: number;\n clicked: number;\n /** Clicks a person caused. */\n clickedHuman?: number;\n /** Clicks attributed to a link prefetcher or a security scanner following links. */\n clickedMachine?: number;\n /** Users who entered the workflow in this bucket: the conversion rate's denominator. */\n entered: number;\n /**\n * Of the users who entered in this bucket, those who reached the goal — counted against their\n * entry, not the day they converted, so `converted / entered` is a share of one cohort and\n * never passes 100%.\n */\n converted: number;\n}\n\n/** One destination URL and how often it was clicked over the queried range. */\nexport interface LinkStat {\n /** The URL as it appears in the message, before any click-tracking rewrite. */\n url: string;\n clicks: number;\n}\n\n/**\n * One message node's funnel over the queried range.\n *\n * Identity is the node id, not the template: the same template sent twice in a\n * flow is two rows, because \"which send underperforms\" is the question this\n * table answers. No display name here — the studio already holds the IR and the\n * template registries, so it resolves the label itself and this stays about\n * numbers.\n */\nexport interface MessageStat {\n /** IR node id (the structural path), pinpointing the send site. */\n nodeId: string;\n /** Template registry key; the row links to it. */\n template: string;\n channel: MetricChannel;\n sent: number;\n /** Accepted by the transport — `sent` minus bounces. */\n delivered: number;\n opened: number;\n clicked: number;\n /** Opt-outs attributed to this send. */\n unsubscribed: number;\n}\n\n/**\n * How many users a segment currently holds, and how that has moved.\n *\n * A segment's definition is code, but its size is not derivable from code at\n * all — it is a fact about the user base, and the only thing that tells you\n * whether a condition matches the population you meant.\n */\nexport interface SegmentReport {\n /** The segment's id, matching `SegmentIR.id`. */\n id: string;\n /** Users in the segment right now. */\n size: number;\n /** Recent daily sizes, oldest first — drives the sparkline in the list. */\n series?: number[];\n}\n\n/**\n * One person in the audience. `id` and the timestamps are the columns every\n * project has; everything else it knows about them lives in `properties`,\n * because a profile's shape is the user's schema, not ours.\n */\nexport interface Profile {\n id: string;\n email?: string;\n /** ISO timestamp; rendered as a date. */\n createdAt?: string;\n /** Whatever the project stores — the same keys the DSL's `u.xxx` references. */\n properties?: Record<string, unknown>;\n}\n\n/** One page of profiles, plus the total so the UI can say \"showing N of M\". */\nexport interface ProfilePage {\n profiles: Profile[];\n total: number;\n}\n\n/** Paging window for a profile query. */\nexport interface ProfileQuery {\n limit: number;\n offset: number;\n}\n\n/**\n * Where runtime numbers come from. Without one the studio renders the reports\n * view in demo mode and says so — it never passes mock data off as real.\n */\nexport interface StatsSource {\n /** Totals per workflow. */\n reports?: () => Promise<WorkflowReport[]> | WorkflowReport[];\n /** Size per segment. */\n segments?: () => Promise<SegmentReport[]> | SegmentReport[];\n /** Who is in one segment right now, a page at a time. */\n profiles?: (segmentName: string, query: ProfileQuery) => Promise<ProfilePage> | ProfilePage;\n /** Users waiting on each node of one workflow (drives the canvas badges). */\n nodeStats?: (workflowName: string) => Promise<NodeStats> | NodeStats;\n /** Time series behind the Overview's chart cards, bucketed as asked. */\n metrics?: (workflowName: string, query: MetricsQuery) => Promise<MetricPoint[]> | MetricPoint[];\n /** Most-clicked destinations across the whole workflow, any order. */\n links?: (workflowName: string, query: StatsRange) => Promise<LinkStat[]> | LinkStat[];\n /** Per-send funnel, one row per message node. */\n messages?: (workflowName: string, query: StatsRange) => Promise<MessageStat[]> | MessageStat[];\n}\n\n/**\n * Identity helper for `workflow.stats.ts` — the studio's optional runtime\n * data source, kept apart from the project: the project describes what is\n * deployed, this is how the studio reads numbers about it. It runs on the\n * studio's dev server (Node), so it can query the project's database or API\n * with credentials from the environment; the page calls it over HTTP, and\n * every answer must be JSON.\n */\nexport function defineStats(stats: StatsSource): StatsSource {\n return stats;\n}\n\n/** Why the studio has nothing to show: the project failed to load, or to compile. */\nexport interface StudioError {\n /** `compile`: compileConfig refused it (the message names the workflow and node). */\n kind: 'load' | 'compile';\n message: string;\n}\n\n/**\n * What the app actually receives from the virtual config module. Everything\n * here is either compiled output (workflow and segment IR, from the same\n * `compileConfig` the Worker deploys) or preview-safe template data — the\n * project object itself never reaches the browser.\n */\nexport interface ResolvedStudioConfig {\n title?: string;\n /** Compiled workflows, keyed by workflow name (empty when `error` is set). */\n workflows: Record<string, WorkflowIR>;\n /** The project's email registry (empty if none). */\n emails: Record<string, EmailTemplate>;\n /** The project's push registry (empty if none). */\n pushes: Record<string, PushTemplate>;\n /** The project's Discord webhook registry (empty if none). */\n discords: Record<string, DiscordTemplate>;\n /** The project's Slack webhook registry (empty if none). */\n slacks: Record<string, SlackTemplate>;\n /** Compiled named segments. */\n segments: SegmentIR[];\n /** The project's envelope (`emails.from` / `replyTo`), formatted as `Name <email>`. */\n emailDefaults: { from?: string; replyTo?: string };\n /** Set when the project failed to load or compile; the shell shows it instead of the views. */\n error?: StudioError;\n stats?: StatsSource;\n}\n"],"mappings":";;AAuEA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AA2KA,SAAgB,YAAY,OAAiC;CAC3D,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"config.mjs","names":[],"sources":["../src/config.ts"],"sourcesContent":["import type {\n DiscordTemplate,\n EmailTemplate,\n PushTemplate,\n SegmentIR,\n SlackTemplate,\n WorkflowIR,\n} from '@shware/workflow';\n\n/**\n * The studio's own types: the stats source it reads numbers from\n * (`workflow.stats.ts`, `defineStats`) and the shape the app receives from the\n * dev server. The project itself is `@shware/workflow`'s `defineConfig({...})`\n * in workflow.config.ts — the studio reads it, it defines nothing of its own.\n */\n\n/** Node id → how many users currently sit on that node. */\nexport type NodeStats = Record<string, number>;\n\n/** Per-workflow totals for the list and metrics views. */\nexport interface WorkflowReport {\n /** The workflow's id, matching `WorkflowIR.id`. */\n id: string;\n entered: number;\n completed: number;\n /** Reached the goal (a conversion). */\n converted: number;\n /** Currently in flight. */\n active: number;\n /** Messages delivered; rates below are computed against it. */\n delivered?: number;\n opened?: number;\n clicked?: number;\n /** Recent daily counts, oldest first — drives the sparklines in the list. */\n series?: {\n delivered?: number[];\n opened?: number[];\n clicked?: number[];\n converted?: number[];\n };\n}\n\n/* ------------------------------ Overview query ------------------------------ */\n\n/**\n * The channel dimension analytics reports on.\n *\n * Deliberately *not* the DSL's `ChannelIR`. That enum says what the author\n * asked for (\"send a push\"); this says where the message actually landed, and\n * the two do not line up: one `push` node fans out to iOS and Android, whose\n * delivery and open behaviour differ enough that reading them summed hides the\n * problem you opened this page to find. Going the other way, a project can\n * report on a transport the DSL has no builder for yet — a webhook — without\n * the IR having to grow a node type first.\n *\n * So the mapping is many-to-many and belongs to whoever measures delivery, not\n * to the compiler. In-product surfaces (`in_app`, `survey`) are absent on\n * purpose: they have no transport receipt, no open pixel and no unsubscribe,\n * so none of the funnel below is defined for them.\n */\nexport type MetricChannel =\n | 'email'\n | 'push_ios'\n | 'push_android'\n | 'push_web'\n | 'slack'\n | 'discord'\n | 'sms'\n | 'webhook';\n\n/** Every channel, in the order the studio's pickers list them. */\nexport const METRIC_CHANNELS = [\n 'email',\n 'push_ios',\n 'push_android',\n 'push_web',\n 'slack',\n 'discord',\n 'sms',\n 'webhook',\n] as const satisfies readonly MetricChannel[];\n\n/** Bucket width for a time series. */\nexport type Granularity = 'day' | 'week' | 'month';\n\n/**\n * What every Overview panel is scoped by. Dates are ISO `YYYY-MM-DD` and both\n * ends are inclusive — a report reads \"Aug 21 to Sep 19\", not \"up to but\n * excluding Sep 20\".\n */\nexport interface StatsRange {\n from: string;\n to: string;\n /** Absent means every channel summed. */\n channel?: MetricChannel;\n}\n\n/** A range plus the bucket width, for the time series behind the chart cards. */\nexport interface MetricsQuery extends StatsRange {\n granularity: Granularity;\n}\n\n/**\n * One bucket of a workflow's delivery funnel.\n *\n * `sent` and `delivered` are two different facts and the UI shows both: sent is\n * what we handed the transport, delivered is what it accepted. The gap between\n * them is the bounce rate, which is invisible if you only keep one of them —\n * which is why `delivered` was not simply renamed when the Sent card arrived.\n *\n * Opens and clicks carry an optional human/machine split. Not every transport\n * can tell the two apart — most have nothing to tell apart — so the halves are\n * optional, and the studio plots three lines only for a query whose every\n * bucket reports them. Where they are reported, `opened` must equal\n * `openedHuman + openedMachine` and `clicked` its own pair: the studio rates\n * all three against one denominator so the lines add up on screen, and a\n * source that recounts the halves independently would draw a chart that\n * visibly does not.\n */\nexport interface MetricPoint {\n /** Bucket start, ISO `YYYY-MM-DD`; used verbatim on the x axis. */\n date: string;\n sent: number;\n delivered: number;\n opened: number;\n /**\n * Opens a person caused. The rest is infrastructure: Apple's Mail Privacy\n * Protection prefetches the tracking pixel for everything it relays, whether\n * or not the mail is ever read, and Gmail's image proxy caches it — which is\n * why a raw open rate has been unusable as a measure of attention since 2021.\n */\n openedHuman?: number;\n /** Opens attributed to a proxy, relay or scanner rather than a reader. */\n openedMachine?: number;\n clicked: number;\n /** Clicks a person caused. */\n clickedHuman?: number;\n /** Clicks attributed to a link prefetcher or a security scanner following links. */\n clickedMachine?: number;\n /** Users who entered the workflow in this bucket: the conversion rate's denominator. */\n entered: number;\n /**\n * Of the users who entered in this bucket, those who reached the goal — counted against their\n * entry, not the day they converted, so `converted / entered` is a share of one cohort and\n * never passes 100%.\n */\n converted: number;\n}\n\n/** One destination URL and how often it was clicked over the queried range. */\nexport interface LinkStat {\n /** The URL as it appears in the message, before any click-tracking rewrite. */\n url: string;\n clicks: number;\n}\n\n/**\n * One message node's funnel over the queried range.\n *\n * Identity is the node id, not the template: the same template sent twice in a\n * flow is two rows, because \"which send underperforms\" is the question this\n * table answers. No display name here — the studio already holds the IR and the\n * template registries, so it resolves the label itself and this stays about\n * numbers.\n */\nexport interface MessageStat {\n /** IR node id (the structural path), pinpointing the send site. */\n nodeId: string;\n /** Template registry key; the row links to it. */\n template: string;\n channel: MetricChannel;\n sent: number;\n /** Accepted by the transport — `sent` minus bounces. */\n delivered: number;\n opened: number;\n clicked: number;\n /** Opt-outs attributed to this send. */\n unsubscribed: number;\n}\n\n/**\n * How many users a segment currently holds, and how that has moved.\n *\n * A segment's definition is code, but its size is not derivable from code at\n * all — it is a fact about the user base, and the only thing that tells you\n * whether a condition matches the population you meant.\n */\nexport interface SegmentReport {\n /** The segment's id, matching `SegmentIR.id`. */\n id: string;\n /** Users in the segment right now. */\n size: number;\n /** Recent daily sizes, oldest first — drives the sparkline in the list. */\n series?: number[];\n}\n\n/**\n * One person in the audience. `id` and the timestamps are the columns every\n * project has; everything else it knows about them lives in `properties`,\n * because a profile's shape is the user's schema, not ours.\n */\nexport interface Profile {\n id: string;\n email?: string;\n /** ISO timestamp; rendered as a date. */\n createdAt?: string;\n /** Whatever the project stores — the same keys the DSL's `u.xxx` references. */\n properties?: Record<string, unknown>;\n}\n\n/** One page of profiles, plus the total so the UI can say \"showing N of M\". */\nexport interface ProfilePage {\n profiles: Profile[];\n total: number;\n}\n\n/** Paging window for a profile query. */\nexport interface ProfileQuery {\n limit: number;\n offset: number;\n}\n\n/**\n * Where runtime numbers come from. Without one the studio renders the reports\n * view in demo mode and says so — it never passes mock data off as real.\n */\nexport interface StatsSource {\n /** Totals per workflow. */\n reports?: () => Promise<WorkflowReport[]> | WorkflowReport[];\n /** Size per segment. */\n segments?: () => Promise<SegmentReport[]> | SegmentReport[];\n /** Who is in one segment right now, a page at a time. */\n profiles?: (segmentName: string, query: ProfileQuery) => Promise<ProfilePage> | ProfilePage;\n /** Users waiting on each node of one workflow (drives the canvas badges). */\n nodeStats?: (workflowName: string) => Promise<NodeStats> | NodeStats;\n /** Time series behind the Overview's chart cards, bucketed as asked. */\n metrics?: (workflowName: string, query: MetricsQuery) => Promise<MetricPoint[]> | MetricPoint[];\n /** Most-clicked destinations across the whole workflow, any order. */\n links?: (workflowName: string, query: StatsRange) => Promise<LinkStat[]> | LinkStat[];\n /** Per-send funnel, one row per message node. */\n messages?: (workflowName: string, query: StatsRange) => Promise<MessageStat[]> | MessageStat[];\n}\n\n/**\n * Identity helper for `workflow.stats.ts` — the studio's optional runtime\n * data source, kept apart from the project: the project describes what is\n * deployed, this is how the studio reads numbers about it. It runs on the\n * studio's dev server (Node), so it can query the project's database or API\n * with credentials from the environment; the page calls it over HTTP, and\n * every answer must be JSON.\n */\nexport function defineStats(stats: StatsSource): StatsSource {\n return stats;\n}\n\n/** Why the studio has nothing to show: the project failed to load, or to compile. */\nexport interface StudioError {\n /** `compile`: compileConfig refused it (the message names the workflow and node). */\n kind: 'load' | 'compile';\n message: string;\n}\n\n/**\n * What the app actually receives from the virtual config module. Everything\n * here is either compiled output (workflow and segment IR, from the same\n * `compileConfig` the Worker deploys) or preview-safe template data — the\n * project object itself never reaches the browser.\n */\nexport interface ResolvedStudioConfig {\n title?: string;\n /** Compiled workflows, keyed by workflow name (empty when `error` is set). */\n workflows: Record<string, WorkflowIR>;\n /** The project's email templates by id (empty if none). */\n emails: Record<string, EmailTemplate>;\n /** The project's push templates by id (empty if none). */\n pushes: Record<string, PushTemplate>;\n /** The project's Discord webhook templates by id (empty if none). */\n discords: Record<string, DiscordTemplate>;\n /** The project's Slack webhook templates by id (empty if none). */\n slacks: Record<string, SlackTemplate>;\n /** Compiled named segments. */\n segments: SegmentIR[];\n /** The project's envelope (`emails.from` / `replyTo`), formatted as `Name <email>`. */\n emailDefaults: { from?: string; replyTo?: string };\n /** Set when the project failed to load or compile; the shell shows it instead of the views. */\n error?: StudioError;\n stats?: StatsSource;\n}\n"],"mappings":";;AAuEA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AA2KA,SAAgB,YAAY,OAAiC;CAC3D,OAAO;AACT"}
|
package/dist/index.mjs
CHANGED
|
@@ -747,11 +747,11 @@ function failureOf(error, phase) {
|
|
|
747
747
|
* over the parsed props, through the SDK (output checked, nothing
|
|
748
748
|
* placeholder-filled afterwards).
|
|
749
749
|
*/
|
|
750
|
-
function resolvePush(entry,
|
|
750
|
+
function resolvePush(entry, props) {
|
|
751
751
|
try {
|
|
752
752
|
return {
|
|
753
753
|
ok: true,
|
|
754
|
-
push: renderPushContent(entry,
|
|
754
|
+
push: renderPushContent(entry, props ?? previewPropsOf(entry))
|
|
755
755
|
};
|
|
756
756
|
} catch (error) {
|
|
757
757
|
return {
|
|
@@ -761,11 +761,11 @@ function resolvePush(entry, key, props) {
|
|
|
761
761
|
}
|
|
762
762
|
}
|
|
763
763
|
/** The Discord message a template posts for some props, checked like a send checks it. */
|
|
764
|
-
function resolveDiscord(entry,
|
|
764
|
+
function resolveDiscord(entry, props) {
|
|
765
765
|
try {
|
|
766
766
|
return {
|
|
767
767
|
ok: true,
|
|
768
|
-
message: renderDiscordContent(entry,
|
|
768
|
+
message: renderDiscordContent(entry, props ?? previewPropsOf(entry))
|
|
769
769
|
};
|
|
770
770
|
} catch (error) {
|
|
771
771
|
return {
|
|
@@ -775,11 +775,11 @@ function resolveDiscord(entry, key, props) {
|
|
|
775
775
|
}
|
|
776
776
|
}
|
|
777
777
|
/** The Slack message a template posts for some props, checked like a send checks it. */
|
|
778
|
-
function resolveSlack(entry,
|
|
778
|
+
function resolveSlack(entry, props) {
|
|
779
779
|
try {
|
|
780
780
|
return {
|
|
781
781
|
ok: true,
|
|
782
|
-
message: renderSlackContent(entry,
|
|
782
|
+
message: renderSlackContent(entry, props ?? previewPropsOf(entry))
|
|
783
783
|
};
|
|
784
784
|
} catch (error) {
|
|
785
785
|
return {
|
|
@@ -1754,11 +1754,11 @@ function TemplatesPage({ refs, emails, pushes = {}, discords = {}, slacks = {},
|
|
|
1754
1754
|
}]
|
|
1755
1755
|
} : void 0;
|
|
1756
1756
|
const failure = propsFailure ?? preview.failure;
|
|
1757
|
-
const pushResolution = active !== void 0 && activePush !== void 0 ? resolvePush(activePush,
|
|
1757
|
+
const pushResolution = active !== void 0 && activePush !== void 0 ? resolvePush(activePush, previewProps) : void 0;
|
|
1758
1758
|
const push = propsFailure === void 0 && pushResolution?.ok === true ? pushResolution.push : void 0;
|
|
1759
1759
|
const pushFailure = propsFailure ?? (pushResolution?.ok === false ? pushResolution.failure : void 0);
|
|
1760
|
-
const discordResolution = active !== void 0 && activeDiscord !== void 0 ? resolveDiscord(activeDiscord,
|
|
1761
|
-
const slackResolution = active !== void 0 && activeSlack !== void 0 ? resolveSlack(activeSlack,
|
|
1760
|
+
const discordResolution = active !== void 0 && activeDiscord !== void 0 ? resolveDiscord(activeDiscord, previewProps) : void 0;
|
|
1761
|
+
const slackResolution = active !== void 0 && activeSlack !== void 0 ? resolveSlack(activeSlack, previewProps) : void 0;
|
|
1762
1762
|
const chatResolution = discordResolution ?? slackResolution;
|
|
1763
1763
|
const chatFailure = propsFailure ?? (chatResolution?.ok === false ? chatResolution.failure : void 0);
|
|
1764
1764
|
const chatReady = propsFailure === void 0 && chatResolution?.ok === true;
|