@nanobpm/urban 0.17.1 → 0.18.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/dist/cli.js CHANGED
@@ -2,7 +2,8 @@
2
2
  //
3
3
  // urban new <name> scaffold a new app (delegates to create-urban-app)
4
4
  // urban check load + validate the manifest, report issues
5
- // urban gen derive generated artifacts (migrations, worker I/O)
5
+ // urban gen derive generated artifacts (migrations, worker I/O, code-first models)
6
+ // urban derive derive code-first models only (workflows/*.ts → processes/*.bpmn)
6
7
  // urban run materialize + serve the app (deploy, data, workers, surfaces, triggers)
7
8
  // urban dev like run, plus watch sources and hot-reload on change
8
9
  // urban deploy deploy models only, then exit
@@ -11,7 +12,7 @@
11
12
  // --port <n>, -h/--help, -v/--version.
12
13
  import { collectManifestIssues, installSignalHandlers, loadManifest, runDev, runFromEnv, selectHost, } from "./runtime/index.js";
13
14
  import { scaffold, slugify } from "create-urban-app";
14
- import { createNodeGenIO, runGen, scaffoldWorkers } from "./toolkit/index.js";
15
+ import { createNodeGenIO, previewModels, runGen, scaffoldWorkers } from "./toolkit/index.js";
15
16
  import { pathToFileURL } from "node:url";
16
17
  import { readFileSync } from "node:fs";
17
18
  // Read the package version from package.json (one hop up from both src/cli.ts and the
@@ -27,7 +28,7 @@ function readVersion() {
27
28
  }
28
29
  const VERSION = readVersion();
29
30
  function parse(argv) {
30
- const f = { root: ".", manifest: "nano.app.json", check: false, write: false, deno: false, help: false, version: false, _: [] };
31
+ const f = { root: ".", manifest: "nano.app.json", check: false, write: false, deno: false, models: true, stdout: false, help: false, version: false, _: [] };
31
32
  const need = (i, flag) => {
32
33
  const v = argv[i];
33
34
  if (v === undefined || v.startsWith("-"))
@@ -46,6 +47,12 @@ function parse(argv) {
46
47
  f.write = true;
47
48
  else if (a === "--deno")
48
49
  f.deno = true;
50
+ else if (a === "--no-models")
51
+ f.models = false;
52
+ else if (a === "--models")
53
+ f.models = true;
54
+ else if (a === "--stdout")
55
+ f.stdout = true;
49
56
  else if (a === "--code-first")
50
57
  f.style = "code";
51
58
  else if (a === "--style") {
@@ -81,7 +88,10 @@ Usage:
81
88
  urban new <name> [--root <path>] [--deno] [--style model|code] scaffold a new Urban app
82
89
  (--code-first is shorthand for --style code)
83
90
  urban check validate the manifest
84
- urban gen [--check] derive artifacts (migrations, worker-io)
91
+ urban gen [--check] [--no-models] derive artifacts (migrations, worker-io, + code-first models)
92
+ (--no-models: skip writing derived .bpmn; type-contracts only)
93
+ urban derive [--check|--stdout] derive code-first models only (workflows/*.ts → processes/*.bpmn)
94
+ (--stdout: print {models,incomplete} JSON without writing)
85
95
  urban stubs [--write] scaffold write-once handler stubs from the model
86
96
  urban run materialize + serve the app
87
97
  urban dev run + watch sources, hot-reload on change
@@ -113,7 +123,13 @@ async function cmdCheck(f) {
113
123
  }
114
124
  async function cmdGen(f) {
115
125
  const io = createNodeGenIO();
116
- const res = await runGen({ root: f.root, io, manifestFile: f.manifest, check: f.check });
126
+ const res = await runGen({ root: f.root, io, manifestFile: f.manifest, check: f.check, emitModels: f.models });
127
+ if (res.incomplete) {
128
+ console.error(`✖ ${res.modelErrors.length} workflow(s) failed to derive:`);
129
+ for (const e of res.modelErrors)
130
+ console.error(` • ${e.path}: ${e.message}`);
131
+ return 1;
132
+ }
117
133
  if (f.check) {
118
134
  if (res.drift.length === 0) {
119
135
  console.log(`✔ generated artifacts are up to date (${res.artifacts.length} checked)`);
@@ -129,6 +145,52 @@ async function cmdGen(f) {
129
145
  console.log(` • ${a.path}`);
130
146
  return 0;
131
147
  }
148
+ async function cmdDerive(f) {
149
+ // `urban derive` IS model derivation, so `--no-models` is contradictory. Reject it explicitly
150
+ // rather than silently ignoring it (flags are global, so it's easy to pass by accident).
151
+ if (!f.models) {
152
+ console.error("✖ `urban derive` derives models — `--no-models` is contradictory. Use `urban gen --no-models` for type-contracts only.");
153
+ return 2;
154
+ }
155
+ const io = createNodeGenIO();
156
+ // Non-writing preview: emit `{ models: [{ id, kind, xml }], incomplete }` to stdout for the
157
+ // console's read-only model viewer (never touches `processes/`).
158
+ if (f.stdout) {
159
+ const d = await previewModels({ root: f.root, io, manifestFile: f.manifest });
160
+ process.stdout.write(JSON.stringify({
161
+ models: d.list.map((m) => ({ id: m.id, kind: m.kind, xml: m.xml })),
162
+ incomplete: d.incomplete,
163
+ }) + "\n");
164
+ if (d.incomplete) {
165
+ for (const e of d.errors)
166
+ console.error(` • ${e.path}: ${e.message}`);
167
+ return 1;
168
+ }
169
+ return 0;
170
+ }
171
+ // Derive + write models only (skip the type-contract derivers); `generate_models` delegates here.
172
+ const res = await runGen({ root: f.root, io, manifestFile: f.manifest, check: f.check, modelsOnly: true });
173
+ if (res.incomplete) {
174
+ console.error(`✖ ${res.modelErrors.length} workflow(s) failed to derive:`);
175
+ for (const e of res.modelErrors)
176
+ console.error(` • ${e.path}: ${e.message}`);
177
+ return 1;
178
+ }
179
+ if (f.check) {
180
+ if (res.drift.length === 0) {
181
+ console.log(`✔ derived models are up to date (${res.artifacts.length} checked)`);
182
+ return 0;
183
+ }
184
+ console.error(`✖ ${res.drift.length} derived model(s) are out of date — run \`urban derive\`:`);
185
+ for (const p of res.drift)
186
+ console.error(` • ${p}`);
187
+ return 1;
188
+ }
189
+ console.log(`✔ derived ${res.artifacts.length} model(s):`);
190
+ for (const a of res.artifacts)
191
+ console.log(` • ${a.path}`);
192
+ return 0;
193
+ }
132
194
  async function cmdStubs(f) {
133
195
  const io = createNodeGenIO();
134
196
  const run = await scaffoldWorkers({ root: f.root, io, manifestFile: f.manifest, write: f.write });
@@ -232,6 +294,8 @@ export async function main(argv) {
232
294
  return cmdCheck(f);
233
295
  case "gen":
234
296
  return cmdGen(f);
297
+ case "derive":
298
+ return cmdDerive(f);
235
299
  case "stubs":
236
300
  return cmdStubs(f);
237
301
  case "run":
@@ -1,7 +1,16 @@
1
1
  // Node/Deno filesystem implementation of the GenIO port. Uses node:fs/promises, which both
2
2
  // Node and Deno provide, so a single implementation serves both runtimes.
3
- import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
4
- import { dirname } from "node:path";
3
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
4
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
5
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
6
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
7
+ });
8
+ }
9
+ return path;
10
+ };
11
+ import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
12
+ import { dirname, resolve } from "node:path";
13
+ import { pathToFileURL } from "node:url";
5
14
  export function createNodeGenIO() {
6
15
  return {
7
16
  async readText(path) {
@@ -31,5 +40,25 @@ export function createNodeGenIO() {
31
40
  return false;
32
41
  }
33
42
  },
43
+ async remove(path) {
44
+ await rm(path, { force: true });
45
+ },
46
+ // Import an app module for code-first model derivation. `import()` of a file URL loads TS on
47
+ // Deno natively and on Node with type-stripping (≥22.18 default, or `--experimental-strip-types`).
48
+ // The cache key is the file's mtime, not a monotonic clock: an unchanged workflow reuses the
49
+ // cached module instance (bounding the ESM module map in long-lived processes like `urban dev`)
50
+ // while an edited one still reloads.
51
+ async importModule(path) {
52
+ const abs = resolve(path);
53
+ let version = "";
54
+ try {
55
+ version = `?v=${(await stat(abs)).mtimeMs}`;
56
+ }
57
+ catch {
58
+ // stat failed (e.g. a virtual path); fall back to no cache key and let import() surface it.
59
+ }
60
+ const href = `${pathToFileURL(abs).href}${version}`;
61
+ return import(__rewriteRelativeImportExtension(href));
62
+ },
34
63
  };
35
64
  }
@@ -1,5 +1,6 @@
1
1
  import type { DerivedArtifact } from "./artifact.ts";
2
2
  import { type ModelSource } from "./derivers/worker-io.ts";
3
+ import { type DerivedModels, type ModelError } from "./models.ts";
3
4
  /** Minimal filesystem port. Node/Deno impls live in `fsio.ts`. */
4
5
  export interface GenIO {
5
6
  readText(path: string): Promise<string>;
@@ -7,19 +8,43 @@ export interface GenIO {
7
8
  /** File names (not paths) in a directory; empty if it does not exist. */
8
9
  listDir(path: string): Promise<string[]>;
9
10
  exists(path: string): Promise<boolean>;
11
+ /**
12
+ * Import an app module and return its exports. Optional: only present when the caller runs on
13
+ * a runtime that can load the app's TypeScript (Node with type-stripping, or Deno). Code-first
14
+ * model derivation (`workflows/*.ts` → BPMN) needs it; when absent, gen still derives everything
15
+ * else (migrations, domain, worker I/O from authored/derived models).
16
+ */
17
+ importModule?(path: string): Promise<Record<string, unknown>>;
18
+ /** Delete a file. Optional: enables the provenance-scoped stale-model sweep (skipped when absent). */
19
+ remove?(path: string): Promise<void>;
10
20
  }
11
21
  export interface GenOptions {
12
22
  root: string;
13
23
  io: GenIO;
14
24
  manifestFile?: string;
25
+ /**
26
+ * Whether to emit (write) derived `.bpmn` models. Default true. When false, code-first models
27
+ * are still derived *in-memory* to feed the type-contract derivers (worker I/O, meta, messages)
28
+ * — they are just not written to disk or swept. This is the `urban gen --no-models` path, so
29
+ * the console's type-contract regen never mutates `processes/*.bpmn`.
30
+ */
31
+ emitModels?: boolean;
32
+ /** Derive ONLY the models (skip migrations/domain/worker-I/O). The `urban derive` path. */
33
+ modelsOnly?: boolean;
15
34
  }
16
35
  export interface GenResult {
17
36
  artifacts: DerivedArtifact[];
18
37
  /** Paths that differ from disk (only populated by `check`). */
19
38
  drift: string[];
39
+ /** True if any code-first workflow failed to import/derive. */
40
+ incomplete: boolean;
41
+ /** Per-file model-derivation errors (empty on success). */
42
+ modelErrors: ModelError[];
20
43
  }
21
44
  declare function join(root: string, rel: string): string;
22
45
  declare function dirOf(p: string): string;
46
+ /** Resolve a `dir/*.ext` (or literal) manifest pattern to file paths relative to root. */
47
+ export declare function expandPattern(root: string, io: GenIO, pattern: string): Promise<string[]>;
23
48
  /** Read + resolve the app's process models from the manifest's `models.processes` patterns. */
24
49
  export declare function readModels(root: string, io: GenIO, manifest: {
25
50
  models?: {
@@ -33,3 +58,6 @@ export declare function runGen(opts: GenOptions & {
33
58
  check?: boolean;
34
59
  }): Promise<GenResult>;
35
60
  export { dirOf, join as joinPath };
61
+ /** Derive code-first models in-memory (no writes) — backs `urban derive --stdout`, the
62
+ * non-mutating preview the console's read-only model viewer uses. */
63
+ export declare function previewModels(opts: GenOptions): Promise<DerivedModels>;
@@ -8,6 +8,7 @@ import { deriveDomain } from "./derivers/domain.js";
8
8
  import { deriveWorkerBindings } from "./derivers/worker-io.js";
9
9
  import { deriveMeta } from "./derivers/meta.js";
10
10
  import { deriveMessageBindings } from "./derivers/messages.js";
11
+ import { deriveModels, MODEL_PROVENANCE } from "./models.js";
11
12
  function join(root, rel) {
12
13
  // Trim either separator so callers may pass Windows-style paths; GenIO
13
14
  // implementations accept forward slashes on all platforms.
@@ -18,7 +19,7 @@ function dirOf(p) {
18
19
  return i <= 0 ? "." : p.slice(0, i);
19
20
  }
20
21
  /** Resolve a `dir/*.ext` (or literal) manifest pattern to file paths relative to root. */
21
- async function expandPattern(root, io, pattern) {
22
+ export async function expandPattern(root, io, pattern) {
22
23
  const star = pattern.indexOf("*");
23
24
  if (star === -1) {
24
25
  return (await io.exists(join(root, pattern))) ? [pattern] : [];
@@ -46,29 +47,47 @@ export async function readModels(root, io, manifest) {
46
47
  }
47
48
  /** Collect all artifacts a run would produce, without touching disk beyond reads. */
48
49
  export async function collectArtifacts(opts) {
50
+ return (await collectAll(opts)).artifacts;
51
+ }
52
+ /** Internal: collect artifacts AND the model-derivation details (needed by `runGen` for the
53
+ * incomplete signal + the provenance-scoped stale sweep). */
54
+ async function collectAll(opts) {
49
55
  const { root, io } = opts;
56
+ const emitModels = opts.emitModels ?? true;
50
57
  const manifestPath = join(root, opts.manifestFile ?? "nano.app.json");
51
58
  const manifest = JSON.parse(await io.readText(manifestPath));
52
59
  const artifacts = [];
53
60
  // 1. types → migrations + domain row types (DomainTables spine + DomainTypes registry)
54
- if (manifest.types && Object.keys(manifest.types).length > 0) {
61
+ if (!opts.modelsOnly && manifest.types && Object.keys(manifest.types).length > 0) {
55
62
  artifacts.push(...deriveMigrations(manifest));
56
63
  artifacts.push(...deriveDomain(manifest));
57
64
  }
58
- // 2. models → worker I/O index + model-metadata accessor + message payload map
59
- const models = await readModels(root, io, manifest);
60
- if (models.length > 0) {
61
- const declaredTypeIds = Object.keys(manifest.types ?? {});
62
- artifacts.push(...deriveWorkerBindings(models, declaredTypeIds));
63
- artifacts.push(...deriveMeta(models));
64
- artifacts.push(...deriveMessageBindings(models, declaredTypeIds));
65
+ // 2. code-first models → derive BPMN from `workflows/*.ts` (executes the app's TS). The derived
66
+ // `.bpmn` are emitted only when `emitModels` (default), but always fed to the type-contract
67
+ // derivers below so worker I/O works for a code-first app even on a `--no-models` run.
68
+ const derived = await deriveModels(root, io, manifest);
69
+ if (emitModels)
70
+ artifacts.push(...derived.artifacts);
71
+ // 3. models (authored on-disk + derived) → worker I/O index + meta accessor + message map.
72
+ // Drop any on-disk model whose path a derived model already covers, to avoid double-counting.
73
+ if (!opts.modelsOnly) {
74
+ const derivedPaths = new Set(derived.artifacts.map((a) => a.path));
75
+ const diskModels = (await readModels(root, io, manifest)).filter((m) => !derivedPaths.has(m.path));
76
+ const models = [...diskModels, ...derived.models];
77
+ if (models.length > 0) {
78
+ const declaredTypeIds = Object.keys(manifest.types ?? {});
79
+ artifacts.push(...deriveWorkerBindings(models, declaredTypeIds));
80
+ artifacts.push(...deriveMeta(models));
81
+ artifacts.push(...deriveMessageBindings(models, declaredTypeIds));
82
+ }
65
83
  }
66
- return sortArtifacts(artifacts);
84
+ return { artifacts: sortArtifacts(artifacts), derived };
67
85
  }
68
86
  /** Run the derivers and write artifacts (or, with `check`, report drift without writing). */
69
87
  export async function runGen(opts) {
70
- const artifacts = await collectArtifacts(opts);
88
+ const { artifacts, derived } = await collectAll(opts);
71
89
  const { root, io } = opts;
90
+ const emitModels = opts.emitModels ?? true;
72
91
  const drift = [];
73
92
  for (const a of artifacts) {
74
93
  const abs = join(root, a.path);
@@ -81,6 +100,30 @@ export async function runGen(opts) {
81
100
  await io.writeText(abs, a.content);
82
101
  }
83
102
  }
84
- return { artifacts, drift };
103
+ // Provenance-scoped stale sweep: delete derived `.bpmn` for flows that no longer exist. Only
104
+ // in write mode, only when we emitted models, only on a complete derivation (never delete when
105
+ // a workflow failed to load), and only files bearing our marker (authored models are untouched).
106
+ if (!opts.check && emitModels && derived.attempted && !derived.incomplete && io.remove) {
107
+ const keep = new Set(derived.artifacts.map((a) => a.path));
108
+ for (const name of await io.listDir(join(root, derived.outDir))) {
109
+ if (!name.endsWith(".bpmn"))
110
+ continue;
111
+ const rel = `${derived.outDir}/${name}`;
112
+ if (keep.has(rel))
113
+ continue;
114
+ const content = await io.readText(join(root, rel));
115
+ if (content.includes(MODEL_PROVENANCE))
116
+ await io.remove(join(root, rel));
117
+ }
118
+ }
119
+ return { artifacts, drift, incomplete: derived.incomplete, modelErrors: derived.errors };
85
120
  }
86
121
  export { dirOf, join as joinPath };
122
+ /** Derive code-first models in-memory (no writes) — backs `urban derive --stdout`, the
123
+ * non-mutating preview the console's read-only model viewer uses. */
124
+ export async function previewModels(opts) {
125
+ const { root, io } = opts;
126
+ const manifestPath = join(root, opts.manifestFile ?? "nano.app.json");
127
+ const manifest = JSON.parse(await io.readText(manifestPath));
128
+ return deriveModels(root, io, manifest);
129
+ }
@@ -20,9 +20,11 @@ export declare const DERIVERS: readonly [import("./artifact.ts").Deriver<import(
20
20
  models: import("./derivers/worker-io.ts").ModelSource[];
21
21
  declaredTypeIds: Iterable<string>;
22
22
  }>];
23
- export { collectArtifacts, runGen, joinPath, readModels } from "./gen.ts";
23
+ export { collectArtifacts, runGen, joinPath, readModels, expandPattern, previewModels } from "./gen.ts";
24
24
  export type { GenIO, GenOptions, GenResult } from "./gen.ts";
25
25
  export { createNodeGenIO } from "./fsio.ts";
26
+ export { deriveModels, isWorkflow, bpmnFilename, processesOutDir, DEFAULT_WORKFLOW_PATTERNS, PROCESSES_DIR, MODEL_PROVENANCE, } from "./models.ts";
27
+ export type { DerivedModels, DerivedModelInfo, ModelError, ModelsManifest } from "./models.ts";
26
28
  export { planWorkerScaffold, renderWorkerStub, slugifyTaskType, } from "./scaffold/workers.ts";
27
29
  export type { ScaffoldWorker, SkippedWorker, SkipReason, StubManifestEntry, WorkerScaffoldPlan, WorkerStubPlan, } from "./scaffold/workers.ts";
28
30
  export { scaffoldWorkers } from "./scaffold.ts";
@@ -18,8 +18,10 @@ import { metaDeriver } from "./derivers/meta.js";
18
18
  import { messagesDeriver } from "./derivers/messages.js";
19
19
  export const DERIVERS = [migrationsDeriver, domainDeriver, workerIoDeriver, metaDeriver, messagesDeriver];
20
20
  // Gen orchestrator + IO
21
- export { collectArtifacts, runGen, joinPath, readModels } from "./gen.js";
21
+ export { collectArtifacts, runGen, joinPath, readModels, expandPattern, previewModels } from "./gen.js";
22
22
  export { createNodeGenIO } from "./fsio.js";
23
+ // Code-first model derivation (workflows/*.ts → BPMN)
24
+ export { deriveModels, isWorkflow, bpmnFilename, processesOutDir, DEFAULT_WORKFLOW_PATTERNS, PROCESSES_DIR, MODEL_PROVENANCE, } from "./models.js";
23
25
  // Worker-stub scaffolder (ADR 0056): write-once handler stubs from the model.
24
26
  export { planWorkerScaffold, renderWorkerStub, slugifyTaskType, } from "./scaffold/workers.js";
25
27
  export { scaffoldWorkers } from "./scaffold.js";
@@ -0,0 +1,63 @@
1
+ import type { Workflow } from "@nanobpm/workflow";
2
+ import type { DerivedArtifact } from "./artifact.ts";
3
+ import type { GenIO } from "./gen.ts";
4
+ import type { ModelSource } from "./derivers/worker-io.ts";
5
+ /** Default source glob for code-first flows (matches the code-first scaffold layout). */
6
+ export declare const DEFAULT_WORKFLOW_PATTERNS: string[];
7
+ /** Default output dir for derived models (matches the model-first scaffold, so a derived
8
+ * model is ejectable to model-first and picked up by `models.processes: ["processes/*.bpmn"]`). */
9
+ export declare const PROCESSES_DIR = "processes";
10
+ /** Marker stamped into every derived `.bpmn` (an XML comment) so re-gen overwrites and the
11
+ * stale sweep deletes ONLY derived output — never an authored, human-owned model. */
12
+ export declare const MODEL_PROVENANCE = "Generated by @nanobpm/urban from workflows/*.ts \u2014 do not edit; edit the flow and re-run `urban gen`.";
13
+ /** Minimal shape a code-first manifest declares for model derivation. */
14
+ export interface ModelsManifest {
15
+ models?: {
16
+ processes?: string[];
17
+ workflows?: string[];
18
+ };
19
+ }
20
+ /** A `defineFlow` export: has a string `id` and an `imperative`/`declarative` `kind`. */
21
+ export declare function isWorkflow(v: unknown): v is Workflow;
22
+ /** Sanitize a flow id into a safe `.bpmn` filename (mirrors the host generator). */
23
+ export declare function bpmnFilename(id: string): string;
24
+ /** The directory derived models are written to: the dir of the first `models.processes`
25
+ * glob if the manifest declares one, else the `processes/` default. */
26
+ export declare function processesOutDir(manifest: ModelsManifest): string;
27
+ export interface ModelError {
28
+ path: string;
29
+ message: string;
30
+ }
31
+ export interface DerivedModels {
32
+ /** `processes/<id>.bpmn` artifacts (path + provenance-stamped content). */
33
+ artifacts: DerivedArtifact[];
34
+ /** The same models, in-memory, for feeding the type-contract derivers (worker I/O, meta, messages). */
35
+ models: ModelSource[];
36
+ /** Derived flow ids (used for the provenance-scoped stale sweep). */
37
+ ids: string[];
38
+ /** Per-flow `{ id, kind, xml }` for the non-writing preview (`urban derive --stdout`). */
39
+ list: DerivedModelInfo[];
40
+ /** The output directory the artifacts were written into. */
41
+ outDir: string;
42
+ /** True once we attempted derivation (loader present AND at least one workflow file matched). */
43
+ attempted: boolean;
44
+ /** True if any workflow module failed to import/derive — suppresses the destructive sweep. */
45
+ incomplete: boolean;
46
+ /** Per-file derivation errors (empty on full success). */
47
+ errors: ModelError[];
48
+ }
49
+ export interface DerivedModelInfo {
50
+ id: string;
51
+ kind: Workflow["kind"];
52
+ xml: string;
53
+ }
54
+ /**
55
+ * Derive executable BPMN models from an app's code-first `workflows/*.ts`.
56
+ *
57
+ * Returns everything in-memory (artifacts + `ModelSource`s + ids). The caller decides whether
58
+ * to write the `.bpmn` to disk (`urban gen` / `urban derive`) or keep them in memory to feed
59
+ * the type-contract derivers only (`urban gen --no-models`) or preview them (`urban derive
60
+ * --stdout`). Never throws on a bad workflow: a failing module is recorded in `errors`,
61
+ * `incomplete` is set, and the sweep is suppressed so a partial failure can't delete good models.
62
+ */
63
+ export declare function deriveModels(root: string, io: GenIO, manifest: ModelsManifest): Promise<DerivedModels>;
@@ -0,0 +1,142 @@
1
+ // Model derivation for code-first apps — the toolkit's one *executing* edge.
2
+ //
3
+ // Unlike the pure derivers (migrations, domain, worker I/O), which transform strings, this
4
+ // imports the app's `workflows/*.ts`, turns each `defineFlow` into executable BPMN via
5
+ // `@nanobpm/workflow` (`toBpmn` + `bpmn-auto-layout` DI), and writes `processes/<id>.bpmn`.
6
+ // Executing the app's TypeScript needs a runtime module loader, so this is gated on the
7
+ // optional `GenIO.importModule` (present on Node with type-stripping, and on Deno). When the
8
+ // loader is absent — or the app authors its models directly (model-first) — derivation is a
9
+ // no-op and the rest of `urban gen` proceeds on the authored/derived models unchanged.
10
+ import { toDeployableBpmn } from "@nanobpm/workflow";
11
+ import { expandPattern, joinPath } from "./gen.js";
12
+ /** Default source glob for code-first flows (matches the code-first scaffold layout). */
13
+ export const DEFAULT_WORKFLOW_PATTERNS = ["workflows/*.ts"];
14
+ /** Default output dir for derived models (matches the model-first scaffold, so a derived
15
+ * model is ejectable to model-first and picked up by `models.processes: ["processes/*.bpmn"]`). */
16
+ export const PROCESSES_DIR = "processes";
17
+ /** Marker stamped into every derived `.bpmn` (an XML comment) so re-gen overwrites and the
18
+ * stale sweep deletes ONLY derived output — never an authored, human-owned model. */
19
+ export const MODEL_PROVENANCE = "Generated by @nanobpm/urban from workflows/*.ts — do not edit; edit the flow and re-run `urban gen`.";
20
+ /** A `defineFlow` export: has a string `id` and an `imperative`/`declarative` `kind`. */
21
+ export function isWorkflow(v) {
22
+ if (!v || typeof v !== "object")
23
+ return false;
24
+ const o = v;
25
+ return typeof o.id === "string" && (o.kind === "imperative" || o.kind === "declarative");
26
+ }
27
+ /** Sanitize a flow id into a safe `.bpmn` filename (mirrors the host generator). */
28
+ export function bpmnFilename(id) {
29
+ return `${id.replace(/[^A-Za-z0-9._-]/g, "-")}.bpmn`;
30
+ }
31
+ /** The directory derived models are written to: the dir of the first `models.processes`
32
+ * glob if the manifest declares one, else the `processes/` default. */
33
+ export function processesOutDir(manifest) {
34
+ for (const pat of manifest.models?.processes ?? []) {
35
+ const star = pat.indexOf("*");
36
+ const slash = star === -1 ? pat.lastIndexOf("/") : pat.lastIndexOf("/", star);
37
+ if (slash > 0)
38
+ return pat.slice(0, slash);
39
+ }
40
+ return PROCESSES_DIR;
41
+ }
42
+ /** Insert the provenance marker as an XML comment right after the `<?xml … ?>` prolog. */
43
+ function withProvenance(xml) {
44
+ const comment = `<!-- ${MODEL_PROVENANCE} -->`;
45
+ const m = xml.match(/^\uFEFF?\s*<\?xml[^>]*\?>/);
46
+ if (m)
47
+ return `${m[0]}\n${comment}\n${xml.slice(m[0].length).replace(/^\r?\n/, "")}`;
48
+ return `${comment}\n${xml}`;
49
+ }
50
+ function emptyDerived(outDir) {
51
+ return {
52
+ artifacts: [],
53
+ models: [],
54
+ ids: [],
55
+ list: [],
56
+ outDir,
57
+ attempted: false,
58
+ incomplete: false,
59
+ errors: [],
60
+ };
61
+ }
62
+ function messageOf(e) {
63
+ return e instanceof Error ? e.message : String(e);
64
+ }
65
+ /** Append an actionable hint when a `.ts` import fails because the runtime can't strip types. */
66
+ function importHint(rel, e) {
67
+ const base = messageOf(e);
68
+ const code = e?.code ?? "";
69
+ const looksLikeNoTsLoader = rel.endsWith(".ts") &&
70
+ (code === "ERR_UNKNOWN_FILE_EXTENSION" || /Unknown file extension "\.ts"/.test(base));
71
+ if (!looksLikeNoTsLoader)
72
+ return base;
73
+ return (`${base}\n ↳ importing TypeScript workflows needs a runtime that strips types: ` +
74
+ "Node ≥22.18 (default) or `node --experimental-strip-types`, or run under Deno.");
75
+ }
76
+ /**
77
+ * Derive executable BPMN models from an app's code-first `workflows/*.ts`.
78
+ *
79
+ * Returns everything in-memory (artifacts + `ModelSource`s + ids). The caller decides whether
80
+ * to write the `.bpmn` to disk (`urban gen` / `urban derive`) or keep them in memory to feed
81
+ * the type-contract derivers only (`urban gen --no-models`) or preview them (`urban derive
82
+ * --stdout`). Never throws on a bad workflow: a failing module is recorded in `errors`,
83
+ * `incomplete` is set, and the sweep is suppressed so a partial failure can't delete good models.
84
+ */
85
+ export async function deriveModels(root, io, manifest) {
86
+ const outDir = processesOutDir(manifest);
87
+ const importModule = io.importModule;
88
+ if (!importModule)
89
+ return emptyDerived(outDir);
90
+ const patterns = manifest.models?.workflows ?? DEFAULT_WORKFLOW_PATTERNS;
91
+ const files = [];
92
+ for (const pat of patterns) {
93
+ for (const rel of await expandPattern(root, io, pat))
94
+ files.push(rel);
95
+ }
96
+ if (files.length === 0)
97
+ return emptyDerived(outDir);
98
+ const out = { ...emptyDerived(outDir), attempted: true };
99
+ // id → { source file, workflow ref } — distinguishes a genuine re-export (same
100
+ // object under two export names) from a true collision (two distinct flows, one id).
101
+ const byId = new Map();
102
+ for (const rel of files.sort()) {
103
+ let mod;
104
+ try {
105
+ mod = await importModule(joinPath(root, rel));
106
+ }
107
+ catch (e) {
108
+ out.incomplete = true;
109
+ out.errors.push({ path: rel, message: importHint(rel, e) });
110
+ continue;
111
+ }
112
+ for (const value of Object.values(mod)) {
113
+ if (!isWorkflow(value))
114
+ continue;
115
+ const id = value.id;
116
+ const prior = byId.get(id);
117
+ if (prior) {
118
+ if (prior.ref === value && prior.rel === rel)
119
+ continue; // genuine intra-module re-export
120
+ out.incomplete = true;
121
+ const where = prior.rel === rel ? "also defined in the same module" : `also defined in ${prior.rel}`;
122
+ out.errors.push({ path: rel, message: `duplicate flow id "${id}" (${where})` });
123
+ continue;
124
+ }
125
+ byId.set(id, { rel, ref: value });
126
+ try {
127
+ const semantic = await toDeployableBpmn(value);
128
+ const xml = withProvenance(semantic);
129
+ const path = `${outDir}/${bpmnFilename(id)}`;
130
+ out.artifacts.push({ path, content: xml });
131
+ out.models.push({ path, xml });
132
+ out.list.push({ id, kind: value.kind, xml });
133
+ out.ids.push(id);
134
+ }
135
+ catch (e) {
136
+ out.incomplete = true;
137
+ out.errors.push({ path: rel, message: `deriving "${id}": ${messageOf(e)}` });
138
+ }
139
+ }
140
+ }
141
+ return out;
142
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nanobpm/urban",
3
- "version": "0.17.1",
3
+ "version": "0.18.0",
4
4
  "description": "Urban: build and run code-first apps on Nano — runtime, derivation toolkit, and CLI in one. Author durable processes with @nanobpm/workflow (defineFlow), a typed datasource, forms, triggers and surfaces from a nano.app.json manifest, on Node or Deno.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",