@shware/workflow-ui 2.2.2 → 2.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.mjs","names":[],"sources":["../src/postgres.ts"],"sourcesContent":["import { type JourneyConfig, resolveRuntime } from '@shware/workflow';\nimport { DEFAULT_SCHEMA } from '@shware/workflow/store';\nimport postgres from 'postgres';\nimport {\n type Granularity,\n type MetricChannel,\n type StatsRange,\n type StatsSource,\n defineStats,\n} from './config';\n\n/**\n * `@shware/workflow-ui/postgres` — the Studio's numbers read straight from the reporting a\n * journeyWorker on Postgres keeps (the engine's schema, `database.schema` in the config). The\n * Studio runs a stats source on its dev server, never in the browser, so it connects with a real\n * connection string:\n *\n * // workflow.stats.ts\n * export default postgresStats({ config, connectionString: process.env.STATS_DATABASE_URL });\n *\n * Time: a fast-forwarded environment (`runtime.<environment>.timeScale`) plays a journey day out\n * in minutes, so every timestamp is read on the journey's clock — `now - (anchor - t) ×\n * timeScale`, the anchor being the latest activity — and the Studio's date ranges are mapped back\n * the same way. A local run of an hour then reads as weeks of history; production (scale 1) is\n * unchanged.\n *\n * Days: the Studio's dates are the viewer's calendar days, so buckets are cut in the same time\n * zone (this machine's by default). Cut in UTC instead, \"today\" east of Greenwich is an empty\n * bucket on every chart.\n */\n\nexport interface PostgresStatsOptions {\n /** The project's `workflow.config.ts`: its database schema, and the runtime's time scale. */\n config: JourneyConfig;\n connectionString: string;\n /**\n * Which `runtime` entry the data was written under; `production` by default. A fast-forwarded\n * environment stretches every date by its `timeScale`, so name the environment the database\n * belongs to: a production database read as `development` had every journey day plotted as\n * minutes.\n */\n environment?: string;\n /** The zone the Studio's days are cut in; this machine's by default. */\n timeZone?: string;\n}\n\n/** A calendar day `count` days from a `YYYY-MM-DD` one: plain date math, no zone in it. */\nconst addDays = (day: string, count: number) =>\n new Date(Date.parse(`${day}T00:00:00Z`) + count * 86_400_000).toISOString().slice(0, 10);\n\n/**\n * One pool per database across reloads: the dev server re-evaluates the stats module on every\n * config change, and a pool per evaluation kept its connections open until Postgres ran out.\n */\nconst pools = ((\n globalThis as { __workflowStatsPools?: Map<string, postgres.Sql> }\n).__workflowStatsPools ??= new Map());\n\nfunction pool(connectionString: string): postgres.Sql {\n let sql = pools.get(connectionString);\n if (sql === undefined) {\n sql = postgres(connectionString, { max: 4, idle_timeout: 20, fetch_types: false });\n pools.set(connectionString, sql);\n }\n return sql;\n}\n\n/**\n * The time scale the data was written at: the config's `runtime` entry for `environment`,\n * `production` when none is named. The old default, `development`, read a production database\n * at the fast-forwarded scale and plotted every journey day as minutes.\n */\nexport function statsTimeScale(config: JourneyConfig, environment = 'production'): number {\n return resolveRuntime(config.runtime, environment).timeScale;\n}\n\nexport function postgresStats(options: PostgresStatsOptions): StatsSource {\n const sql = pool(options.connectionString);\n const schema = options.config.database?.schema ?? DEFAULT_SCHEMA;\n /** A table of the engine's schema. */\n const t = (name: string) => sql(`${schema}.${name}`);\n const scale = statsTimeScale(options.config, options.environment);\n const timeZone = options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n /**\n * The moment the journey clock reads \"now\": the latest activity in the data, so a\n * fast-forwarded run keeps reading as the history up to today however long ago it ran —\n * anchored on the real now instead, a run from last night had drifted hundreds of journey days\n * out of every range by morning. Refreshed at the start of every call; with scale 1 it is now.\n */\n let anchor = Date.now();\n\n async function refreshAnchor(): Promise<void> {\n if (scale === 1) {\n anchor = Date.now();\n return;\n }\n const rows = await sql<{ latest: Date | null }[]>`\n select greatest(\n (select max(sent_at) from ${t('message')}),\n (select max(node_at) from ${t('instance')}),\n (select max(finished_at) from ${t('instance')}),\n (select max(taken_at) from ${t('segment_snapshot')})\n ) as latest`;\n const row = rows.at(0);\n const latest =\n row?.latest === null || row?.latest === undefined\n ? Date.now()\n : new Date(row.latest).getTime();\n anchor = Math.min(latest, Date.now());\n }\n\n /** An instant on the journey's clock: `now - (anchor - t) × timeScale`. */\n const onJourneyClock = (instant: postgres.PendingQuery<postgres.Row[]>) =>\n sql`(${new Date().toISOString()}::timestamptz - (${new Date(anchor).toISOString()}::timestamptz - ${instant}) * ${scale}::float)`;\n const virtual = (column: string) => onJourneyClock(sql`${sql(column)}`);\n\n /** A column on the journey's clock, as a wall-clock time in the viewer's zone. */\n const local = (column: string) => sql`(${virtual(column)} at time zone ${timeZone})`;\n\n /** `YYYY-MM-DD` of an instant in the viewer's zone. */\n const localDate = (ms: number) =>\n new Intl.DateTimeFormat('en-CA', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).format(ms);\n\n /** The instant a local calendar day starts. */\n function startOfLocalDay(day: string): number {\n const utcMidnight = Date.parse(`${day}T00:00:00Z`);\n // The zone's offset at that moment: how far its wall clock reads from UTC\n const parts = Object.fromEntries(\n new Intl.DateTimeFormat('en-US', {\n timeZone,\n hourCycle: 'h23',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n .formatToParts(utcMidnight)\n .map((part) => [part.type, part.value])\n );\n const n = (type: string) => Number(parts[type] ?? 0);\n const wall = Date.UTC(n('year'), n('month') - 1, n('day'), n('hour'), n('minute'), n('second'));\n return utcMidnight - (wall - utcMidnight);\n }\n\n /** The real instants a virtual `YYYY-MM-DD` range (both ends inclusive, local days) covers. */\n function realRange({ from, to }: StatsRange): { from: string; to: string } {\n const now = Date.now();\n const back = (ms: number) => new Date(anchor - (now - ms) / scale).toISOString();\n // The end is the start of the next local day, not 24 hours on: a DST day is 23 or 25\n return { from: back(startOfLocalDay(from)), to: back(startOfLocalDay(addDays(to, 1))) };\n }\n\n /**\n * When a copy reached its recipient: the transport's acceptance for email and Android, the\n * device's own report for iOS and the web — a push APNs or a push service accepted can still\n * never arrive (the app was deleted, the device stayed off). An app version without the\n * reporting extension shows its iOS pushes undelivered.\n */\n const reached = sql`(case when m.channel in ('push_ios', 'push_web') then m.device_delivered_at else m.delivered_at end)`;\n\n /**\n * A converted instance: `converted_at` is set whatever the status (with `exitOnMatch: false` a\n * conversion ends `completed`); rows written before the column existed only had status `goal`.\n */\n const converted = sql`(converted_at is not null or status = 'goal')`;\n\n const channelFilter = (channel: MetricChannel | undefined) =>\n channel === undefined ? sql`true` : sql`m.channel = ${channel}`;\n\n /** The last 14 journey days, oldest first, as local `YYYY-MM-DD`. */\n function lastDays(count = 14): string[] {\n const today = localDate(Date.now());\n return Array.from({ length: count }, (_, i) => addDays(today, i - (count - 1)));\n }\n\n return defineStats({\n async reports() {\n await refreshAnchor();\n const totals = await sql<\n { id: string; entered: number; active: number; completed: number; converted: number }[]\n >`\n select workflow as id,\n count(*)::int as entered,\n count(*) filter (where status = 'running')::int as active,\n count(*) filter (where status in ('completed', 'exited', 'exit_when', 'goal'))::int as completed,\n count(*) filter (where ${converted})::int as converted\n from ${t('instance')} group by workflow`;\n const engagement = await sql<\n { id: string; delivered: number; opened: number; clicked: number }[]\n >`\n select workflow as id,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked\n from ${t('message')} m group by workflow`;\n const days = lastDays();\n const series = await sql<\n { id: string; day: string; delivered: number; opened: number; clicked: number }[]\n >`\n select workflow as id, to_char(${local('delivered_at')}, 'YYYY-MM-DD') as day,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked\n from ${t('message')} m where delivered_at is not null\n group by 1, 2`;\n const conversions = await sql<{ id: string; day: string; converted: number }[]>`\n select workflow as id,\n to_char(${onJourneyClock(sql`coalesce(converted_at, finished_at)`)} at time zone ${timeZone}, 'YYYY-MM-DD') as day,\n count(*)::int as converted\n from ${t('instance')} where ${converted} group by 1, 2`;\n const daily = (id: string, rows: { id: string; day: string }[], key: string) =>\n days.map(\n (day) =>\n (\n rows.find((r) => r.id === id && r.day === day) as Record<string, number> | undefined\n )?.[key] ?? 0\n );\n return totals.map((total) => {\n const e = engagement.find((row) => row.id === total.id);\n return {\n id: total.id,\n entered: total.entered,\n active: total.active,\n completed: total.completed,\n converted: total.converted,\n delivered: e?.delivered ?? 0,\n opened: e?.opened ?? 0,\n clicked: e?.clicked ?? 0,\n series: {\n delivered: daily(total.id, series, 'delivered'),\n opened: daily(total.id, series, 'opened'),\n clicked: daily(total.id, series, 'clicked'),\n converted: daily(total.id, conversions, 'converted'),\n },\n };\n });\n },\n\n async nodeStats(workflow) {\n await refreshAnchor();\n const rows = await sql<{ node_id: string; users: number }[]>`\n select node_id, count(*)::int as users from ${t('instance')}\n where workflow = ${workflow} and status = 'running' and node_id is not null\n group by node_id`;\n return Object.fromEntries(rows.map((row) => [row.node_id, row.users]));\n },\n\n async metrics(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n const unit: Granularity = query.granularity;\n const bucket = (column: string) =>\n sql`to_char(date_trunc(${unit}, ${local(column)}), 'YYYY-MM-DD')`;\n const messages = await sql<\n {\n day: string;\n sent: number;\n delivered: number;\n opened: number;\n opened_human: number;\n clicked: number;\n clicked_human: number;\n }[]\n >`\n with m as (\n select * from ${t('message')} m\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n ),\n events as (\n select ${bucket('sent_at')} as day, 'sent' as kind, false as human from m\n where sent_at between ${from} and ${to}\n union all select ${bucket('delivered_at')}, 'delivered', false from m\n where ${reached} is not null and delivered_at between ${from} and ${to}\n -- Opens and clicks count against the bucket the message was delivered in (its cohort),\n -- not the day they happened: the rates drawn are opened / delivered, and an open\n -- counted on another day than its delivery reads as 160% on a quiet day\n union all select ${bucket('delivered_at')}, 'opened', human_opened_at is not null from m\n where opened_at is not null and ${reached} is not null and delivered_at between ${from} and ${to}\n union all select ${bucket('delivered_at')}, 'clicked', human_clicked_at is not null from m\n where clicked_at is not null and ${reached} is not null and delivered_at between ${from} and ${to}\n )\n select day,\n count(*) filter (where kind = 'sent')::int as sent,\n count(*) filter (where kind = 'delivered')::int as delivered,\n count(*) filter (where kind = 'opened')::int as opened,\n count(*) filter (where kind = 'opened' and human)::int as opened_human,\n count(*) filter (where kind = 'clicked')::int as clicked,\n count(*) filter (where kind = 'clicked' and human)::int as clicked_human\n from events group by day`;\n // Users by the bucket they entered in, and how many of each cohort reached the goal: the\n // conversion rate is a share of one group of people, so it stays within 100%\n const cohorts = await sql<{ day: string; entered: number; converted: number }[]>`\n select ${bucket('entered_at')} as day, count(*)::int as entered,\n count(*) filter (where ${converted})::int as converted\n from ${t('instance')}\n where workflow = ${workflow} and entered_at between ${from} and ${to}\n group by 1`;\n const buckets = await sql<{ day: string }[]>`\n select to_char(d, 'YYYY-MM-DD') as day\n from generate_series(date_trunc(${unit}, ${query.from}::date), ${query.to}::date, ${`1 ${unit}`}::interval) d`;\n return buckets.map(({ day }) => {\n const m = messages.find((row) => row.day === day);\n const opened = m?.opened ?? 0;\n const clicked = m?.clicked ?? 0;\n const cohort = cohorts.find((row) => row.day === day);\n return {\n date: day,\n sent: m?.sent ?? 0,\n delivered: m?.delivered ?? 0,\n opened,\n openedHuman: m?.opened_human ?? 0,\n openedMachine: opened - (m?.opened_human ?? 0),\n clicked,\n clickedHuman: m?.clicked_human ?? 0,\n clickedMachine: clicked - (m?.clicked_human ?? 0),\n entered: cohort?.entered ?? 0,\n converted: cohort?.converted ?? 0,\n };\n });\n },\n\n async links(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n return sql<{ url: string; clicks: number }[]>`\n select c.url, count(*)::int as clicks\n from ${t('message_click')} c\n join ${t('message')} m on m.id = c.message_id\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n and c.clicked_at between ${from} and ${to}\n -- People's clicks only: a scanner follows every link, the footer's included\n and not c.machine\n group by c.url order by clicks desc limit 50`;\n },\n\n async messages(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n return sql<\n {\n nodeId: string;\n template: string;\n channel: MetricChannel;\n sent: number;\n delivered: number;\n opened: number;\n clicked: number;\n unsubscribed: number;\n }[]\n >`\n select node_id as \"nodeId\", template, channel,\n count(*)::int as sent,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked,\n count(unsubscribed_at)::int as unsubscribed\n from ${t('message')} m\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n and m.sent_at between ${from} and ${to}\n group by node_id, template, channel order by node_id, channel`;\n },\n\n async segments() {\n await refreshAnchor();\n const sizes = await sql<{ id: string; size: number }[]>`\n select s.id, count(m.user_id)::int as size\n from ${t('segment')} s\n left join ${t('segment_member')} m on m.segment = s.id\n group by s.id`;\n const days = lastDays();\n // The last snapshot of each journey day\n const snapshots = await sql<{ id: string; day: string; size: number }[]>`\n select distinct on (segment, day) segment as id, day, size from (\n select segment, size, taken_at, to_char(${local('taken_at')}, 'YYYY-MM-DD') as day\n from ${t('segment_snapshot')}\n ) s order by segment, day, taken_at desc`;\n return sizes.map(({ id, size }) => {\n let last = 0;\n const series = days.map((day) => {\n last = snapshots.find((s) => s.id === id && s.day === day)?.size ?? last;\n return last;\n });\n return { id, size, series };\n });\n },\n\n async profiles(segment, { limit, offset }) {\n await refreshAnchor();\n const counts = await sql<{ total: number }[]>`\n select count(*)::int as total from ${t('segment_member')} where segment = ${segment}`;\n const count = counts.at(0);\n // \"Created\" is the user's first event: the engine knows nothing older about them\n const rows = await sql<\n { id: string; props: Record<string, unknown> | null; created_at: Date | null }[]\n >`\n select m.user_id as id, p.props,\n ${onJourneyClock(sql`first_event.ts`)} as created_at\n from ${t('segment_member')} m\n left join ${t('profile')} p on p.user_id = m.user_id\n left join lateral (\n select min(ts) as ts from ${t('event')} e where e.user_id = m.user_id\n ) first_event on true\n where m.segment = ${segment}\n order by m.ts desc, m.user_id\n limit ${limit} offset ${offset}`;\n return {\n total: count?.total ?? 0,\n profiles: rows.map(({ id, props, created_at }) => {\n const { email, ...properties } = props ?? {};\n const profile: { id: string; email?: string; createdAt?: string } & {\n properties: Record<string, unknown>;\n } = { id, properties };\n if (typeof email === 'string') profile.email = email;\n if (created_at !== null) profile.createdAt = new Date(created_at).toISOString();\n return profile;\n }),\n };\n },\n });\n}\n"],"mappings":";;;;;;AA+CA,MAAM,WAAW,KAAa,UAC5B,IAAI,KAAK,KAAK,MAAM,GAAG,IAAI,WAAW,IAAI,QAAQ,KAAU,CAAC,CAAC,YAAY,CAAC,CAAC,MAAM,GAAG,EAAE;;;;;AAMzF,MAAM,QAAS,WAEb,yCAAyB,IAAI,IAAI;AAEnC,SAAS,KAAK,kBAAwC;CACpD,IAAI,MAAM,MAAM,IAAI,gBAAgB;CACpC,IAAI,QAAQ,KAAA,GAAW;EACrB,MAAM,SAAS,kBAAkB;GAAE,KAAK;GAAG,cAAc;GAAI,aAAa;EAAM,CAAC;EACjF,MAAM,IAAI,kBAAkB,GAAG;CACjC;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,eAAe,QAAuB,cAAc,cAAsB;CACxF,OAAO,eAAe,OAAO,SAAS,WAAW,CAAC,CAAC;AACrD;AAEA,SAAgB,cAAc,SAA4C;CACxE,MAAM,MAAM,KAAK,QAAQ,gBAAgB;CACzC,MAAM,SAAS,QAAQ,OAAO,UAAU,UAAU;;CAElD,MAAM,KAAK,SAAiB,IAAI,GAAG,OAAO,GAAG,MAAM;CACnD,MAAM,QAAQ,eAAe,QAAQ,QAAQ,QAAQ,WAAW;CAChE,MAAM,WAAW,QAAQ,YAAY,KAAK,eAAe,CAAC,CAAC,gBAAgB,CAAC,CAAC;;;;;;;CAQ7E,IAAI,SAAS,KAAK,IAAI;CAEtB,eAAe,gBAA+B;EAC5C,IAAI,UAAU,GAAG;GACf,SAAS,KAAK,IAAI;GAClB;EACF;EAQA,MAAM,OAAM,MAPO,GAA8B;;oCAEjB,EAAE,SAAS,EAAE;oCACb,EAAE,UAAU,EAAE;wCACV,EAAE,UAAU,EAAE;qCACjB,EAAE,kBAAkB,EAAE;mBAEvC,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ElC,MAAM,OAAO,SAAS;GAEtB,MAAM,YAAY,MAAM,GAAgD;;oDAE1B,MAAM,UAAU,EAAE;iBACrD,EAAE,kBAAkB,EAAE;;GAEjC,OAAO,MAAM,KAAK,EAAE,IAAI,WAAW;IACjC,IAAI,OAAO;IAKX,OAAO;KAAE;KAAI;KAAM,QAJJ,KAAK,KAAK,QAAQ;MAC/B,OAAO,UAAU,MAAM,MAAM,EAAE,OAAO,MAAM,EAAE,QAAQ,GAAG,CAAC,EAAE,QAAQ;MACpE,OAAO;KACT,CACwB;IAAE;GAC5B,CAAC;EACH;EAEA,MAAM,SAAS,SAAS,EAAE,OAAO,UAAU;GACzC,MAAM,cAAc;GAGpB,MAAM,SAAQ,MAFO,GAAwB;6CACN,EAAE,gBAAgB,EAAE,mBAAmB,UAAA,CACzD,GAAG,CAAC;GAEzB,MAAM,OAAO,MAAM,GAElB;;YAEK,eAAe,GAAG,gBAAgB,EAAE;eACjC,EAAE,gBAAgB,EAAE;oBACf,EAAE,SAAS,EAAE;;sCAEK,EAAE,OAAO,EAAE;;4BAErB,QAAQ;;gBAEpB,MAAM,UAAU;GAC1B,OAAO;IACL,OAAO,OAAO,SAAS;IACvB,UAAU,KAAK,KAAK,EAAE,IAAI,OAAO,iBAAiB;KAChD,MAAM,EAAE,OAAO,GAAG,eAAe,SAAS,CAAC;KAC3C,MAAM,UAEF;MAAE;MAAI;KAAW;KACrB,IAAI,OAAO,UAAU,UAAU,QAAQ,QAAQ;KAC/C,IAAI,eAAe,MAAM,QAAQ,YAAY,IAAI,KAAK,UAAU,CAAC,CAAC,YAAY;KAC9E,OAAO;IACT,CAAC;GACH;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"postgres.mjs","names":[],"sources":["../src/postgres.ts"],"sourcesContent":["import { type JourneyConfig, resolveRuntime } from '@shware/workflow';\nimport { DEFAULT_SCHEMA } from '@shware/workflow/store';\nimport postgres from 'postgres';\nimport {\n type Granularity,\n type MetricChannel,\n type StatsRange,\n type StatsSource,\n defineStats,\n} from './config';\n\n/**\n * `@shware/workflow-ui/postgres` — the Studio's numbers read straight from the reporting a\n * journeyWorker on Postgres keeps (the engine's schema, `database.schema` in the config). The\n * Studio runs a stats source on its dev server, never in the browser, so it connects with a real\n * connection string:\n *\n * // workflow.stats.ts\n * export default postgresStats({ config, connectionString: process.env.STATS_DATABASE_URL });\n *\n * Time: a fast-forwarded environment (`runtime.<environment>.timeScale`) plays a journey day out\n * in minutes, so every timestamp is read on the journey's clock — `now - (anchor - t) ×\n * timeScale`, the anchor being the latest activity — and the Studio's date ranges are mapped back\n * the same way. A local run of an hour then reads as weeks of history; production (scale 1) is\n * unchanged.\n *\n * Days: the Studio's dates are the viewer's calendar days, so buckets are cut in the same time\n * zone (this machine's by default). Cut in UTC instead, \"today\" east of Greenwich is an empty\n * bucket on every chart.\n */\n\nexport interface PostgresStatsOptions {\n /** The project's `workflow.config.ts`: its database schema, and the runtime's time scale. */\n config: JourneyConfig;\n connectionString: string;\n /**\n * Which `runtime` entry the data was written under; `production` by default. A fast-forwarded\n * environment stretches every date by its `timeScale`, so name the environment the database\n * belongs to: a production database read as `development` had every journey day plotted as\n * minutes.\n */\n environment?: string;\n /** The zone the Studio's days are cut in; this machine's by default. */\n timeZone?: string;\n}\n\n/** A calendar day `count` days from a `YYYY-MM-DD` one: plain date math, no zone in it. */\nconst addDays = (day: string, count: number) =>\n new Date(Date.parse(`${day}T00:00:00Z`) + count * 86_400_000).toISOString().slice(0, 10);\n\n/**\n * One pool per database across reloads: the dev server re-evaluates the stats module on every\n * config change, and a pool per evaluation kept its connections open until Postgres ran out.\n */\nconst pools = ((\n globalThis as { __workflowStatsPools?: Map<string, postgres.Sql> }\n).__workflowStatsPools ??= new Map());\n\nfunction pool(connectionString: string): postgres.Sql {\n let sql = pools.get(connectionString);\n if (sql === undefined) {\n sql = postgres(connectionString, { max: 4, idle_timeout: 20, fetch_types: false });\n pools.set(connectionString, sql);\n }\n return sql;\n}\n\n/**\n * The time scale the data was written at: the config's `runtime` entry for `environment`,\n * `production` when none is named. The old default, `development`, read a production database\n * at the fast-forwarded scale and plotted every journey day as minutes.\n */\nexport function statsTimeScale(config: JourneyConfig, environment = 'production'): number {\n return resolveRuntime(config.runtime, environment).timeScale;\n}\n\nexport function postgresStats(options: PostgresStatsOptions): StatsSource {\n const sql = pool(options.connectionString);\n const schema = options.config.database?.schema ?? DEFAULT_SCHEMA;\n /** A table of the engine's schema. */\n const t = (name: string) => sql(`${schema}.${name}`);\n const scale = statsTimeScale(options.config, options.environment);\n const timeZone = options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n /**\n * The moment the journey clock reads \"now\": the latest activity in the data, so a\n * fast-forwarded run keeps reading as the history up to today however long ago it ran —\n * anchored on the real now instead, a run from last night had drifted hundreds of journey days\n * out of every range by morning. Refreshed at the start of every call; with scale 1 it is now.\n */\n let anchor = Date.now();\n\n async function refreshAnchor(): Promise<void> {\n if (scale === 1) {\n anchor = Date.now();\n return;\n }\n const rows = await sql<{ latest: Date | null }[]>`\n select greatest(\n (select max(sent_at) from ${t('message')}),\n (select max(node_at) from ${t('instance')}),\n (select max(finished_at) from ${t('instance')}),\n (select max(taken_at) from ${t('segment_snapshot')})\n ) as latest`;\n const row = rows.at(0);\n const latest =\n row?.latest === null || row?.latest === undefined\n ? Date.now()\n : new Date(row.latest).getTime();\n anchor = Math.min(latest, Date.now());\n }\n\n /** An instant on the journey's clock: `now - (anchor - t) × timeScale`. */\n const onJourneyClock = (instant: postgres.PendingQuery<postgres.Row[]>) =>\n sql`(${new Date().toISOString()}::timestamptz - (${new Date(anchor).toISOString()}::timestamptz - ${instant}) * ${scale}::float)`;\n const virtual = (column: string) => onJourneyClock(sql`${sql(column)}`);\n\n /** A column on the journey's clock, as a wall-clock time in the viewer's zone. */\n const local = (column: string) => sql`(${virtual(column)} at time zone ${timeZone})`;\n\n /** `YYYY-MM-DD` of an instant in the viewer's zone. */\n const localDate = (ms: number) =>\n new Intl.DateTimeFormat('en-CA', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).format(ms);\n\n /** The instant a local calendar day starts. */\n function startOfLocalDay(day: string): number {\n const utcMidnight = Date.parse(`${day}T00:00:00Z`);\n // The zone's offset at that moment: how far its wall clock reads from UTC\n const parts = Object.fromEntries(\n new Intl.DateTimeFormat('en-US', {\n timeZone,\n hourCycle: 'h23',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n .formatToParts(utcMidnight)\n .map((part) => [part.type, part.value])\n );\n const n = (type: string) => Number(parts[type] ?? 0);\n const wall = Date.UTC(n('year'), n('month') - 1, n('day'), n('hour'), n('minute'), n('second'));\n return utcMidnight - (wall - utcMidnight);\n }\n\n /** The real instants a virtual `YYYY-MM-DD` range (both ends inclusive, local days) covers. */\n function realRange({ from, to }: StatsRange): { from: string; to: string } {\n const now = Date.now();\n const back = (ms: number) => new Date(anchor - (now - ms) / scale).toISOString();\n // The end is the start of the next local day, not 24 hours on: a DST day is 23 or 25\n return { from: back(startOfLocalDay(from)), to: back(startOfLocalDay(addDays(to, 1))) };\n }\n\n /**\n * When a copy reached its recipient: the transport's acceptance for email and Android, the\n * device's own report for iOS and the web — a push APNs or a push service accepted can still\n * never arrive (the app was deleted, the device stayed off). An app version without the\n * reporting extension shows its iOS pushes undelivered.\n */\n const reached = sql`(case when m.channel in ('push_ios', 'push_web') then m.device_delivered_at else m.delivered_at end)`;\n\n /**\n * A converted instance: `converted_at` is set whatever the status (with `exitOnMatch: false` a\n * conversion ends `completed`); rows written before the column existed only had status `goal`.\n */\n const converted = sql`(converted_at is not null or status = 'goal')`;\n\n const channelFilter = (channel: MetricChannel | undefined) =>\n channel === undefined ? sql`true` : sql`m.channel = ${channel}`;\n\n /** The last 14 journey days, oldest first, as local `YYYY-MM-DD`. */\n function lastDays(count = 14): string[] {\n const today = localDate(Date.now());\n return Array.from({ length: count }, (_, i) => addDays(today, i - (count - 1)));\n }\n\n return defineStats({\n async reports() {\n await refreshAnchor();\n const totals = await sql<\n { id: string; entered: number; active: number; completed: number; converted: number }[]\n >`\n select workflow as id,\n count(*)::int as entered,\n count(*) filter (where status = 'running')::int as active,\n count(*) filter (where status in ('completed', 'exited', 'exit_when', 'goal'))::int as completed,\n count(*) filter (where ${converted})::int as converted\n from ${t('instance')} group by workflow`;\n const engagement = await sql<\n { id: string; delivered: number; opened: number; clicked: number }[]\n >`\n select workflow as id,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked\n from ${t('message')} m group by workflow`;\n const days = lastDays();\n const series = await sql<\n { id: string; day: string; delivered: number; opened: number; clicked: number }[]\n >`\n select workflow as id, to_char(${local('delivered_at')}, 'YYYY-MM-DD') as day,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked\n from ${t('message')} m where delivered_at is not null\n group by 1, 2`;\n const conversions = await sql<{ id: string; day: string; converted: number }[]>`\n select workflow as id,\n to_char(${onJourneyClock(sql`coalesce(converted_at, finished_at)`)} at time zone ${timeZone}, 'YYYY-MM-DD') as day,\n count(*)::int as converted\n from ${t('instance')} where ${converted} group by 1, 2`;\n const daily = (id: string, rows: { id: string; day: string }[], key: string) =>\n days.map(\n (day) =>\n (\n rows.find((r) => r.id === id && r.day === day) as Record<string, number> | undefined\n )?.[key] ?? 0\n );\n return totals.map((total) => {\n const e = engagement.find((row) => row.id === total.id);\n return {\n id: total.id,\n entered: total.entered,\n active: total.active,\n completed: total.completed,\n converted: total.converted,\n delivered: e?.delivered ?? 0,\n opened: e?.opened ?? 0,\n clicked: e?.clicked ?? 0,\n series: {\n delivered: daily(total.id, series, 'delivered'),\n opened: daily(total.id, series, 'opened'),\n clicked: daily(total.id, series, 'clicked'),\n converted: daily(total.id, conversions, 'converted'),\n },\n };\n });\n },\n\n async nodeStats(workflow) {\n await refreshAnchor();\n const rows = await sql<{ node_id: string; users: number }[]>`\n select node_id, count(*)::int as users from ${t('instance')}\n where workflow = ${workflow} and status = 'running' and node_id is not null\n group by node_id`;\n return Object.fromEntries(rows.map((row) => [row.node_id, row.users]));\n },\n\n async metrics(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n const unit: Granularity = query.granularity;\n const bucket = (column: string) =>\n sql`to_char(date_trunc(${unit}, ${local(column)}), 'YYYY-MM-DD')`;\n const messages = await sql<\n {\n day: string;\n sent: number;\n delivered: number;\n opened: number;\n opened_human: number;\n clicked: number;\n clicked_human: number;\n }[]\n >`\n with m as (\n select * from ${t('message')} m\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n ),\n events as (\n select ${bucket('sent_at')} as day, 'sent' as kind, false as human from m\n where sent_at between ${from} and ${to}\n union all select ${bucket('delivered_at')}, 'delivered', false from m\n where ${reached} is not null and delivered_at between ${from} and ${to}\n -- Opens and clicks count against the bucket the message was delivered in (its cohort),\n -- not the day they happened: the rates drawn are opened / delivered, and an open\n -- counted on another day than its delivery reads as 160% on a quiet day\n union all select ${bucket('delivered_at')}, 'opened', human_opened_at is not null from m\n where opened_at is not null and ${reached} is not null and delivered_at between ${from} and ${to}\n union all select ${bucket('delivered_at')}, 'clicked', human_clicked_at is not null from m\n where clicked_at is not null and ${reached} is not null and delivered_at between ${from} and ${to}\n )\n select day,\n count(*) filter (where kind = 'sent')::int as sent,\n count(*) filter (where kind = 'delivered')::int as delivered,\n count(*) filter (where kind = 'opened')::int as opened,\n count(*) filter (where kind = 'opened' and human)::int as opened_human,\n count(*) filter (where kind = 'clicked')::int as clicked,\n count(*) filter (where kind = 'clicked' and human)::int as clicked_human\n from events group by day`;\n // Users by the bucket they entered in, and how many of each cohort reached the goal: the\n // conversion rate is a share of one group of people, so it stays within 100%\n const cohorts = await sql<{ day: string; entered: number; converted: number }[]>`\n select ${bucket('entered_at')} as day, count(*)::int as entered,\n count(*) filter (where ${converted})::int as converted\n from ${t('instance')}\n where workflow = ${workflow} and entered_at between ${from} and ${to}\n group by 1`;\n const buckets = await sql<{ day: string }[]>`\n select to_char(d, 'YYYY-MM-DD') as day\n from generate_series(date_trunc(${unit}, ${query.from}::date), ${query.to}::date, ${`1 ${unit}`}::interval) d`;\n return buckets.map(({ day }) => {\n const m = messages.find((row) => row.day === day);\n const opened = m?.opened ?? 0;\n const clicked = m?.clicked ?? 0;\n const cohort = cohorts.find((row) => row.day === day);\n return {\n date: day,\n sent: m?.sent ?? 0,\n delivered: m?.delivered ?? 0,\n opened,\n openedHuman: m?.opened_human ?? 0,\n openedMachine: opened - (m?.opened_human ?? 0),\n clicked,\n clickedHuman: m?.clicked_human ?? 0,\n clickedMachine: clicked - (m?.clicked_human ?? 0),\n entered: cohort?.entered ?? 0,\n converted: cohort?.converted ?? 0,\n };\n });\n },\n\n async links(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n return sql<{ url: string; clicks: number }[]>`\n select c.url, count(*)::int as clicks\n from ${t('message_click')} c\n join ${t('message')} m on m.id = c.message_id\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n and c.clicked_at between ${from} and ${to}\n -- People's clicks only: a scanner follows every link, the footer's included\n and not c.machine\n group by c.url order by clicks desc limit 50`;\n },\n\n async messages(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n return sql<\n {\n nodeId: string;\n template: string;\n channel: MetricChannel;\n sent: number;\n delivered: number;\n opened: number;\n clicked: number;\n unsubscribed: number;\n }[]\n >`\n select node_id as \"nodeId\", template, channel,\n count(*)::int as sent,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked,\n count(unsubscribed_at)::int as unsubscribed\n from ${t('message')} m\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n and m.sent_at between ${from} and ${to}\n group by node_id, template, channel order by node_id, channel`;\n },\n\n async segments() {\n await refreshAnchor();\n const sizes = await sql<{ id: string; size: number }[]>`\n select s.id, count(m.user_id)::int as size\n from ${t('segment')} s\n left join ${t('segment_member')} m on m.segment = s.id\n group by s.id`;\n const days = lastDays();\n // The last snapshot of each journey day\n const snapshots = await sql<{ id: string; day: string; size: number }[]>`\n select distinct on (segment, day) segment as id, day, size from (\n select segment, size, taken_at, to_char(${local('taken_at')}, 'YYYY-MM-DD') as day\n from ${t('segment_snapshot')}\n ) s order by segment, day, taken_at desc`;\n return sizes.map(({ id, size }) => {\n let last = 0;\n const series = days.map((day) => {\n last = snapshots.find((s) => s.id === id && s.day === day)?.size ?? last;\n return last;\n });\n return { id, size, series };\n });\n },\n\n async profiles(segment, { limit, offset }) {\n await refreshAnchor();\n const counts = await sql<{ total: number }[]>`\n select count(*)::int as total from ${t('segment_member')} where segment = ${segment}`;\n const count = counts.at(0);\n // \"Created\" is the user's first event: the engine knows nothing older about them\n const rows = await sql<\n { id: string; props: Record<string, unknown> | null; created_at: Date | null }[]\n >`\n select m.user_id as id, p.props,\n ${onJourneyClock(sql`first_event.ts`)} as created_at\n from ${t('segment_member')} m\n left join ${t('profile')} p on p.user_id = m.user_id\n left join lateral (\n select min(ts) as ts from ${t('event')} e where e.user_id = m.user_id\n ) first_event on true\n where m.segment = ${segment}\n order by m.ts desc, m.user_id\n limit ${limit} offset ${offset}`;\n return {\n total: count?.total ?? 0,\n profiles: rows.map(({ id, props, created_at }) => {\n const { email, ...properties } = props ?? {};\n const profile: { id: string; email?: string; createdAt?: string } & {\n properties: Record<string, unknown>;\n } = { id, properties };\n if (typeof email === 'string') profile.email = email;\n if (created_at !== null) profile.createdAt = new Date(created_at).toISOString();\n return profile;\n }),\n };\n },\n });\n}\n"],"mappings":";;;;;;AA+CA,MAAM,WAAW,KAAa,UAC5B,IAAI,KAAK,KAAK,MAAM,GAAG,IAAI,WAAW,IAAI,QAAQ,KAAU,CAAC,CAAC,YAAY,CAAC,CAAC,MAAM,GAAG,EAAE;;;;;AAMzF,MAAM,QACJ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,OAAO;KACT,CACwB;IAAE;GAC5B,CAAC;EACH;EAEA,MAAM,SAAS,SAAS,EAAE,OAAO,UAAU;GACzC,MAAM,cAAc;GAGpB,MAAM,SAAQ,MAFO,GAAwB;6CACN,EAAE,gBAAgB,EAAE,mBAAmB,UAAA,CACzD,GAAG,CAAC;GAEzB,MAAM,OAAO,MAAM,GAElB;;YAEK,eAAe,GAAG,gBAAgB,EAAE;eACjC,EAAE,gBAAgB,EAAE;oBACf,EAAE,SAAS,EAAE;;sCAEK,EAAE,OAAO,EAAE;;4BAErB,QAAQ;;gBAEpB,MAAM,UAAU;GAC1B,OAAO;IACL,OAAO,OAAO,SAAS;IACvB,UAAU,KAAK,KAAK,EAAE,IAAI,OAAO,iBAAiB;KAChD,MAAM,EAAE,OAAO,GAAG,eAAe,SAAS,CAAC;KAC3C,MAAM,UAEF;MAAE;MAAI;KAAW;KACrB,IAAI,OAAO,UAAU,UAAU,QAAQ,QAAQ;KAC/C,IAAI,eAAe,MAAM,QAAQ,YAAY,IAAI,KAAK,UAAU,CAAC,CAAC,YAAY;KAC9E,OAAO;IACT,CAAC;GACH;EACF;CACF,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shware/workflow-ui",
3
- "version": "2.2.2",
3
+ "version": "2.2.4",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/ShwareHQ/shware-sdk.git"
@@ -39,39 +39,39 @@
39
39
  "dependencies": {
40
40
  "@floating-ui/react": "^0.27.20",
41
41
  "@fontsource-variable/inter": "^5.3.0",
42
- "@react-email/render": "^2.1.1",
43
- "@shware/workflow": "12.0.0",
44
- "@tailwindcss/vite": "^4.3.3",
45
- "@tanstack/react-query": "^5.104.5",
42
+ "@react-email/render": "^2.3.1",
43
+ "@shware/workflow": "12.0.2",
44
+ "@tailwindcss/vite": "^4.3.5",
45
+ "@tanstack/react-query": "^5.107.1",
46
46
  "@tanstack/react-router": "^1.170.46",
47
- "@vitejs/plugin-react": "^6.1.2",
48
- "@xyflow/react": "^12.12.0",
47
+ "@vitejs/plugin-react": "^6.3.0",
48
+ "@xyflow/react": "^13.0.1",
49
49
  "clsx": "^2.1.1",
50
- "i18next": "^26.5.10",
51
- "i18next-browser-languagedetector": "^8.2.2",
52
- "lucide-react": "^1.61.0",
53
- "react-i18next": "^17.1.8",
50
+ "i18next": "^27.1.3",
51
+ "i18next-browser-languagedetector": "^8.3.0",
52
+ "lucide-react": "^1.73.0",
53
+ "react-i18next": "^18.0.2",
54
54
  "sonner": "^2.0.8",
55
55
  "tailwind-merge": "^3.7.0",
56
- "tailwindcss": "^4.3.3",
57
- "vite": "^8.3.5",
56
+ "tailwindcss": "^4.3.5",
57
+ "vite": "^8.3.8",
58
58
  "vite-plugin-svgr": "^5.2.0"
59
59
  },
60
60
  "devDependencies": {
61
61
  "@repo/typescript-config": "0.0.0",
62
- "@tanstack/react-query-devtools": "^5.104.5",
62
+ "@tanstack/react-query-devtools": "^5.107.1",
63
63
  "@testing-library/react": "^16.3.3",
64
- "@testing-library/user-event": "^14.6.8",
65
- "@types/node": "^26.6.5",
64
+ "@testing-library/user-event": "^14.6.12",
65
+ "@types/node": "^26.6.6",
66
66
  "@types/react": "^19.3.0",
67
67
  "@types/react-dom": "^19.3.0",
68
68
  "country-flag-icons": "^1.6.20",
69
- "jsdom": "^30.1.3",
70
- "postgres": "^3.4.9",
69
+ "jsdom": "^31.0.1",
70
+ "postgres": "^4.1.1",
71
71
  "react": "^19.3.1",
72
72
  "react-dom": "^19.3.1",
73
73
  "typescript": "^7.0.2",
74
- "vitest": "^5.0.5",
74
+ "vitest": "^5.1.0",
75
75
  "zod": "^4.6.7"
76
76
  },
77
77
  "peerDependencies": {
package/src/app/index.css CHANGED
@@ -168,9 +168,9 @@
168
168
  * react-flow's own chrome (the zoom controls) on the studio's ramp instead of
169
169
  * its stock palette. Its components read `--xy-*` with a `-default` fallback,
170
170
  * so setting the un-suffixed names wins in both of its colour modes. Unlayered
171
- * on purpose: react-flow's stylesheet is unlayered too, and a rule inside
172
- * @layer base would lose to it. Only custom properties are set here, so no
173
- * utility class can be shadowed.
171
+ * on purpose: react-flow's stylesheet sits in `@layer xyflow`, declared after
172
+ * Tailwind's layers, so a rule inside @layer base would lose to it. Only custom
173
+ * properties are set here, so no utility class can be shadowed.
174
174
  */
175
175
  .react-flow {
176
176
  --xy-controls-button-background-color: var(--color-card);
@@ -480,7 +480,7 @@ function CanvasSurface({
480
480
  edges={edges}
481
481
  nodeTypes={nodeTypes}
482
482
  edgeTypes={edgeTypes}
483
- colorMode={colorMode}
483
+ forceColorMode={colorMode}
484
484
  onNodeClick={(_event, node) => onSelectNode?.(node.id)}
485
485
  onPaneClick={() => onSelectNode?.(undefined)}
486
486
  // Overrides react-flow's own dark surface, which sits between our page and card