@styx-api/core 0.4.0 → 0.5.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/index.cjs +966 -249
- package/dist/index.d.cts +226 -5
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +226 -5
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +959 -250
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/backend/index.ts +13 -1
- package/src/backend/nipype/emit.ts +270 -0
- package/src/backend/nipype/index.ts +3 -0
- package/src/backend/nipype/nipype.ts +70 -0
- package/src/backend/pydra/emit.ts +318 -0
- package/src/backend/pydra/index.ts +3 -0
- package/src/backend/pydra/pydra.ts +67 -0
- package/src/backend/python/index.ts +6 -1
- package/src/backend/python/outputs-emit.ts +1 -1
- package/src/backend/python/packaging.ts +33 -5
- package/src/backend/python/python.ts +28 -3
- package/src/backend/schema/jsonschema.ts +34 -4
- package/src/backend/styxdefs-compat.ts +6 -4
- package/src/backend/typed-spec.ts +258 -0
package/dist/index.mjs
CHANGED
|
@@ -3387,196 +3387,6 @@ function resolveTypeName(namedTypes) {
|
|
|
3387
3387
|
};
|
|
3388
3388
|
}
|
|
3389
3389
|
|
|
3390
|
-
//#endregion
|
|
3391
|
-
//#region src/backend/styxdefs-compat.ts
|
|
3392
|
-
/**
|
|
3393
|
-
* Runtime version floors baked into generated dependency metadata.
|
|
3394
|
-
*
|
|
3395
|
-
* styx2-generated code calls `mutable_copy` / `mutableCopy` (introduced in the
|
|
3396
|
-
* styxdefs 0.7.0 / styxdefs-js 0.2.0 release), so emitted packages genuinely
|
|
3397
|
-
* require that runtime floor. This is the single source of truth: bump here and
|
|
3398
|
-
* both the Python and TypeScript backends pick it up.
|
|
3399
|
-
*/
|
|
3400
|
-
const STYXDEFS_COMPAT = {
|
|
3401
|
-
python: ">=0.7.0,<0.8.0",
|
|
3402
|
-
npm: "^0.2.0"
|
|
3403
|
-
};
|
|
3404
|
-
/**
|
|
3405
|
-
* Extra Python runtime packages the root distribution pulls in (container +
|
|
3406
|
-
* graph runners). Left unpinned - styxdefs's floor constrains them transitively
|
|
3407
|
-
* via their own inter-package pins.
|
|
3408
|
-
*/
|
|
3409
|
-
const PYTHON_RUNNER_DEPS = [
|
|
3410
|
-
"styxdocker",
|
|
3411
|
-
"styxsingularity",
|
|
3412
|
-
"styxgraph"
|
|
3413
|
-
];
|
|
3414
|
-
|
|
3415
|
-
//#endregion
|
|
3416
|
-
//#region src/backend/python/packaging.ts
|
|
3417
|
-
const REQUIRES_PYTHON = ">=3.10";
|
|
3418
|
-
const BUILD_SYSTEM = `[build-system]
|
|
3419
|
-
requires = ["setuptools>=61"]
|
|
3420
|
-
build-backend = "setuptools.build_meta"`;
|
|
3421
|
-
/** Escape a value for embedding in a TOML basic string. */
|
|
3422
|
-
function tomlStr(s) {
|
|
3423
|
-
return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/[\r\n]+/g, " ").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "").trim();
|
|
3424
|
-
}
|
|
3425
|
-
/** Suite directory / importable package name; matches the CLI's `pkgDir` fallback. */
|
|
3426
|
-
function pkgDir(pkg) {
|
|
3427
|
-
return pkg.name ?? "package";
|
|
3428
|
-
}
|
|
3429
|
-
/** Distribution (PyPI) name for a package: `<project>_<package>`, or just `<package>`. */
|
|
3430
|
-
function pyDistName(proj, pkg) {
|
|
3431
|
-
const name = pkgDir(pkg);
|
|
3432
|
-
return proj.name ? `${proj.name}_${name}` : name;
|
|
3433
|
-
}
|
|
3434
|
-
const SUMMARY_MAX_LEN = 512;
|
|
3435
|
-
/**
|
|
3436
|
-
* Clamp a description to a <=512-char one-line summary. Prefer cutting at the
|
|
3437
|
-
* last complete sentence that fits (clean, no dangling fragment); if there is no
|
|
3438
|
-
* sentence boundary early enough, cut at a word boundary and mark the elision.
|
|
3439
|
-
*/
|
|
3440
|
-
function clampSummary(s) {
|
|
3441
|
-
if (s.length <= SUMMARY_MAX_LEN) return s;
|
|
3442
|
-
const window = s.slice(0, SUMMARY_MAX_LEN);
|
|
3443
|
-
const lastSentence = window.lastIndexOf(". ");
|
|
3444
|
-
if (lastSentence >= 0) return s.slice(0, lastSentence + 1);
|
|
3445
|
-
const ellipsis = "...";
|
|
3446
|
-
const body = window.slice(0, SUMMARY_MAX_LEN - 3);
|
|
3447
|
-
const lastSpace = body.lastIndexOf(" ");
|
|
3448
|
-
return (lastSpace > 0 ? body.slice(0, lastSpace) : body).replace(/[.,;:\s]+$/, "") + ellipsis;
|
|
3449
|
-
}
|
|
3450
|
-
function description$1(doc, fallbackName) {
|
|
3451
|
-
return clampSummary(doc?.description ?? `Styx generated wrappers for ${doc?.title ?? fallbackName ?? "tools"}.`);
|
|
3452
|
-
}
|
|
3453
|
-
function authorsField(doc) {
|
|
3454
|
-
return `[${(doc?.authors?.length ? doc.authors : ["unknown"]).map((a) => `{ name = "${tomlStr(a)}" }`).join(", ")}]`;
|
|
3455
|
-
}
|
|
3456
|
-
function licenseField(proj) {
|
|
3457
|
-
return `{ text = "${tomlStr(proj.license?.description ?? "unknown")}" }`;
|
|
3458
|
-
}
|
|
3459
|
-
/**
|
|
3460
|
-
* Per-suite `pyproject.toml`. The flat layout (`python/<pkg>/bet.py`) makes the
|
|
3461
|
-
* directory itself the importable package, so setuptools' `package-dir` maps the
|
|
3462
|
-
* import name (`<pkg>`) onto the distribution's root directory. The styxdefs
|
|
3463
|
-
* floor is the only runtime dependency.
|
|
3464
|
-
*
|
|
3465
|
-
* Precondition: `pkg.name` must be a valid Python identifier - the flat layout's
|
|
3466
|
-
* relative imports (`from .bet import *`) already require this, and the CLI uses
|
|
3467
|
-
* it verbatim as the directory name, so this stays consistent with that.
|
|
3468
|
-
*/
|
|
3469
|
-
function generateSubPyproject(proj, pkg) {
|
|
3470
|
-
const importName = pkgDir(pkg);
|
|
3471
|
-
const cb = new CodeBuilder(" ");
|
|
3472
|
-
cb.line("[project]");
|
|
3473
|
-
cb.line(`name = "${tomlStr(pyDistName(proj, pkg))}"`);
|
|
3474
|
-
cb.line(`version = "${tomlStr(proj.version ?? "0.0.0")}"`);
|
|
3475
|
-
cb.line(`description = "${tomlStr(description$1(pkg.doc, pkg.name))}"`);
|
|
3476
|
-
cb.line(`readme = "README.md"`);
|
|
3477
|
-
cb.line(`license = ${licenseField(proj)}`);
|
|
3478
|
-
cb.line(`authors = ${authorsField(pkg.doc ?? proj.doc)}`);
|
|
3479
|
-
cb.line(`requires-python = "${REQUIRES_PYTHON}"`);
|
|
3480
|
-
cb.line("dependencies = [");
|
|
3481
|
-
cb.line(` "styxdefs${STYXDEFS_COMPAT.python}",`);
|
|
3482
|
-
cb.line("]");
|
|
3483
|
-
cb.blank();
|
|
3484
|
-
cb.line("[tool.setuptools]");
|
|
3485
|
-
cb.line(`packages = ["${importName}"]`);
|
|
3486
|
-
cb.line(`package-dir = { "${importName}" = "." }`);
|
|
3487
|
-
cb.blank();
|
|
3488
|
-
cb.line("[tool.setuptools.package-data]");
|
|
3489
|
-
cb.line(`"${importName}" = ["py.typed"]`);
|
|
3490
|
-
cb.blank();
|
|
3491
|
-
cb.line(BUILD_SYSTEM);
|
|
3492
|
-
return cb.toString() + "\n";
|
|
3493
|
-
}
|
|
3494
|
-
/**
|
|
3495
|
-
* Root `pyproject.toml`: a metapackage depending on each per-suite distribution
|
|
3496
|
-
* plus the container/graph runner packages. `packages = []` keeps setuptools
|
|
3497
|
-
* from sweeping the sibling suite directories into this distribution.
|
|
3498
|
-
*/
|
|
3499
|
-
function generateRootPyproject(proj, distNames) {
|
|
3500
|
-
const cb = new CodeBuilder(" ");
|
|
3501
|
-
cb.line("[project]");
|
|
3502
|
-
cb.line(`name = "${tomlStr(proj.name ?? "project")}"`);
|
|
3503
|
-
cb.line(`version = "${tomlStr(proj.version ?? "0.0.0")}"`);
|
|
3504
|
-
cb.line(`description = "${tomlStr(description$1(proj.doc, proj.name))}"`);
|
|
3505
|
-
cb.line(`readme = "README.md"`);
|
|
3506
|
-
cb.line(`license = ${licenseField(proj)}`);
|
|
3507
|
-
cb.line(`authors = ${authorsField(proj.doc)}`);
|
|
3508
|
-
cb.line(`requires-python = "${REQUIRES_PYTHON}"`);
|
|
3509
|
-
cb.line("dependencies = [");
|
|
3510
|
-
for (const dep of PYTHON_RUNNER_DEPS) cb.line(` "${dep}",`);
|
|
3511
|
-
for (const dist of distNames) cb.line(` "${tomlStr(dist)}",`);
|
|
3512
|
-
cb.line("]");
|
|
3513
|
-
cb.blank();
|
|
3514
|
-
cb.line("[tool.setuptools]");
|
|
3515
|
-
cb.line("packages = []");
|
|
3516
|
-
cb.blank();
|
|
3517
|
-
cb.line(BUILD_SYSTEM);
|
|
3518
|
-
return cb.toString() + "\n";
|
|
3519
|
-
}
|
|
3520
|
-
/** Per-suite README crediting the upstream tool authors. */
|
|
3521
|
-
function generateSubReadme(proj, pkg) {
|
|
3522
|
-
const projectTitle = proj.doc?.title ?? proj.name ?? "Styx";
|
|
3523
|
-
const packageTitle = pkg.doc?.title ?? pkg.name ?? "package";
|
|
3524
|
-
const url = pkg.doc?.urls?.[0];
|
|
3525
|
-
const titleMd = url ? `[${packageTitle}](${url})` : packageTitle;
|
|
3526
|
-
const credits = pkg.doc?.authors?.length ? pkg.doc.authors.join(", ") : pkg.doc?.urls?.join(", ") ?? "unknown";
|
|
3527
|
-
return `# ${projectTitle} wrappers for ${titleMd}${pkg.doc?.description ? `\n\n${pkg.doc.description}` : ""}\n\n${packageTitle} is made by ${credits}.\n\nThis package contains wrappers only and has no affiliation with the original authors.\n`;
|
|
3528
|
-
}
|
|
3529
|
-
/** Root README listing the bundled per-suite distributions. */
|
|
3530
|
-
function generateRootReadme(proj, distNames) {
|
|
3531
|
-
return `# ${proj.doc?.title ?? proj.name ?? "Styx"}\n${proj.doc?.description ? `\n${proj.doc.description}\n` : ""}\nAuto-generated Styx wrappers. This project bundles the following packages:\n\n${distNames.map((d) => `- ${d}`).join("\n")}\n`;
|
|
3532
|
-
}
|
|
3533
|
-
/** Local-install manifest: each suite directory first, then the root metapackage. */
|
|
3534
|
-
function generateRequirementsTxt(pkgDirs) {
|
|
3535
|
-
return [...pkgDirs.map((d) => `./${d}`), "./"].join("\n") + "\n";
|
|
3536
|
-
}
|
|
3537
|
-
|
|
3538
|
-
//#endregion
|
|
3539
|
-
//#region src/backend/sig-entries.ts
|
|
3540
|
-
/**
|
|
3541
|
-
* Build per-field signature entries for the kwarg wrapper and params factory.
|
|
3542
|
-
* Skips `@type` (the factory injects it as a constant). Required-no-default
|
|
3543
|
-
* entries are placed before defaulted ones so the resulting signature is
|
|
3544
|
-
* syntactically valid in both Python and TS.
|
|
3545
|
-
*
|
|
3546
|
-
* `registerLocal` is called once per field with the wire key; it must return
|
|
3547
|
-
* a scrubbed, unique host identifier (typically by combining a language-aware
|
|
3548
|
-
* scrub function with `Scope.add()`). The caller's scope should already have
|
|
3549
|
-
* the function's other locals (`params`, `runner`, ...) reserved so this
|
|
3550
|
-
* registration cannot collide with them.
|
|
3551
|
-
*/
|
|
3552
|
-
function buildSigEntries(rootType, fieldInfo, registerLocal, opts) {
|
|
3553
|
-
const entries = [];
|
|
3554
|
-
for (const [fieldName, fieldType] of Object.entries(rootType.fields)) {
|
|
3555
|
-
if (fieldType.kind === "literal") continue;
|
|
3556
|
-
const fi = fieldInfo.get(fieldName);
|
|
3557
|
-
const isOptional = fieldType.kind === "optional";
|
|
3558
|
-
const inner = isOptional ? fieldType.inner : fieldType;
|
|
3559
|
-
let sigType = opts.renderType(inner);
|
|
3560
|
-
if (isOptional) sigType += opts.nullableSuffix;
|
|
3561
|
-
let sigDefault;
|
|
3562
|
-
const hasExplicitDefault = fi?.defaultValue !== void 0;
|
|
3563
|
-
if (hasExplicitDefault) sigDefault = opts.renderDefault(fi.defaultValue);
|
|
3564
|
-
else if (isOptional) sigDefault = opts.nullableDefault;
|
|
3565
|
-
entries.push({
|
|
3566
|
-
name: registerLocal(fieldName),
|
|
3567
|
-
wireKey: fieldName,
|
|
3568
|
-
sigType,
|
|
3569
|
-
sigDefault,
|
|
3570
|
-
isOptional,
|
|
3571
|
-
hasExplicitDefault,
|
|
3572
|
-
doc: fi?.doc
|
|
3573
|
-
});
|
|
3574
|
-
}
|
|
3575
|
-
const required = entries.filter((e) => e.sigDefault === void 0);
|
|
3576
|
-
const defaulted = entries.filter((e) => e.sigDefault !== void 0);
|
|
3577
|
-
return [...required, ...defaulted];
|
|
3578
|
-
}
|
|
3579
|
-
|
|
3580
3390
|
//#endregion
|
|
3581
3391
|
//#region src/backend/union-variants.ts
|
|
3582
3392
|
/**
|
|
@@ -4345,54 +4155,444 @@ function emitParamsFactory$1(entries, funcName, paramsType, typeTag, cb) {
|
|
|
4345
4155
|
});
|
|
4346
4156
|
}
|
|
4347
4157
|
/**
|
|
4348
|
-
* Emit the user-facing kwarg wrapper: takes the same kwargs as `_params()`
|
|
4349
|
-
* plus `runner`, builds the params dict, and delegates to the dict-style
|
|
4350
|
-
* execute function.
|
|
4158
|
+
* Emit the user-facing kwarg wrapper: takes the same kwargs as `_params()`
|
|
4159
|
+
* plus `runner`, builds the params dict, and delegates to the dict-style
|
|
4160
|
+
* execute function.
|
|
4161
|
+
*/
|
|
4162
|
+
function emitKwargWrapper$1(ctx, entries, funcName, paramsFnName, executeFnName, outputsType, cb) {
|
|
4163
|
+
cb.line(`def ${funcName}(`);
|
|
4164
|
+
cb.indent(() => {
|
|
4165
|
+
emitSigParams$1(entries, cb);
|
|
4166
|
+
cb.line("runner: Runner | None = None,");
|
|
4167
|
+
});
|
|
4168
|
+
const returnType = outputsType ?? "None";
|
|
4169
|
+
cb.line(`) -> ${returnType}:`);
|
|
4170
|
+
cb.indent(() => {
|
|
4171
|
+
const appDoc = ctx.app?.doc;
|
|
4172
|
+
cb.line("\"\"\"");
|
|
4173
|
+
if (appDoc?.title) cb.line(appDoc.title);
|
|
4174
|
+
if (appDoc?.description) {
|
|
4175
|
+
if (appDoc?.title) cb.blank();
|
|
4176
|
+
cb.line(appDoc.description);
|
|
4177
|
+
}
|
|
4178
|
+
if (appDoc?.authors?.length) {
|
|
4179
|
+
cb.blank();
|
|
4180
|
+
cb.line(`Author: ${appDoc.authors.join(", ")}`);
|
|
4181
|
+
}
|
|
4182
|
+
if (appDoc?.urls?.length) {
|
|
4183
|
+
cb.blank();
|
|
4184
|
+
cb.line(`URL: ${appDoc.urls[0]}`);
|
|
4185
|
+
}
|
|
4186
|
+
cb.blank();
|
|
4187
|
+
emitArgsBlock([...entries, {
|
|
4188
|
+
name: "runner",
|
|
4189
|
+
doc: "Command runner (defaults to global runner)."
|
|
4190
|
+
}], cb);
|
|
4191
|
+
cb.blank();
|
|
4192
|
+
cb.line("Returns:");
|
|
4193
|
+
cb.line(outputsType ? " Tool outputs (paths to files produced by the tool)." : " None.");
|
|
4194
|
+
cb.line("\"\"\"");
|
|
4195
|
+
if (entries.length === 0) cb.line(`params = ${paramsFnName}()`);
|
|
4196
|
+
else {
|
|
4197
|
+
cb.line(`params = ${paramsFnName}(`);
|
|
4198
|
+
cb.indent(() => {
|
|
4199
|
+
for (const e of entries) cb.line(`${e.name}=${e.name},`);
|
|
4200
|
+
});
|
|
4201
|
+
cb.line(")");
|
|
4202
|
+
}
|
|
4203
|
+
if (outputsType) cb.line(`return ${executeFnName}(params, runner)`);
|
|
4204
|
+
else cb.line(`${executeFnName}(params, runner)`);
|
|
4205
|
+
});
|
|
4206
|
+
}
|
|
4207
|
+
|
|
4208
|
+
//#endregion
|
|
4209
|
+
//#region src/backend/nipype/emit.ts
|
|
4210
|
+
function call(ctor, args) {
|
|
4211
|
+
return `${ctor}(${args.join(", ")})`;
|
|
4212
|
+
}
|
|
4213
|
+
/**
|
|
4214
|
+
* Render a numeric literal, forcing a float form (e.g. `0.0`) for a float field.
|
|
4215
|
+
* `traits.Range` infers its numeric type from the bound literals, so integer
|
|
4216
|
+
* bounds on a float field (e.g. `low=0, high=1`) would build an *integer* range
|
|
4217
|
+
* that rejects `0.5`. Emitting `0.0`/`1.0` keeps it a float range.
|
|
4218
|
+
*/
|
|
4219
|
+
function renderNum(value, asFloat) {
|
|
4220
|
+
if (asFloat && typeof value === "number" && Number.isInteger(value)) return `${value}.0`;
|
|
4221
|
+
return renderPyLiteral(value);
|
|
4222
|
+
}
|
|
4223
|
+
/** Human-readable `desc=` text: doc + degrade/media-type notes. */
|
|
4224
|
+
function descText(p) {
|
|
4225
|
+
const parts = [];
|
|
4226
|
+
if (p.doc) parts.push(p.doc);
|
|
4227
|
+
if (p.kind === "struct" || p.kind === "union") parts.push("(nested configuration; pass a dict)");
|
|
4228
|
+
if (p.mediaTypes && p.mediaTypes.length > 0) parts.push(`(media types: ${p.mediaTypes.join(", ")})`);
|
|
4229
|
+
return parts.length > 0 ? parts.join(" ") : void 0;
|
|
4230
|
+
}
|
|
4231
|
+
/** Map a list element descriptor to a (bare) nipype inner trait. */
|
|
4232
|
+
function renderItemTrait(item) {
|
|
4233
|
+
if (!item) return "traits.Any()";
|
|
4234
|
+
switch (item.kind) {
|
|
4235
|
+
case "path": return "File(exists=True)";
|
|
4236
|
+
case "int":
|
|
4237
|
+
case "count": return "traits.Int()";
|
|
4238
|
+
case "float": return "traits.Float()";
|
|
4239
|
+
case "str": return "traits.Str()";
|
|
4240
|
+
case "bool": return "traits.Bool()";
|
|
4241
|
+
case "enum": return call("traits.Enum", (item.choices ?? []).map((c) => renderPyLiteral(c)));
|
|
4242
|
+
default: return "traits.Any()";
|
|
4243
|
+
}
|
|
4244
|
+
}
|
|
4245
|
+
/** Map a parameter to its nipype input trait expression, carrying rich constraints. */
|
|
4246
|
+
function renderInputTrait(p) {
|
|
4247
|
+
const tail = [];
|
|
4248
|
+
if (p.mandatory) tail.push("mandatory=True");
|
|
4249
|
+
const desc = descText(p);
|
|
4250
|
+
if (desc) tail.push(`desc=${pyStr(desc)}`);
|
|
4251
|
+
const hasDef = p.hasDefault && p.default !== void 0;
|
|
4252
|
+
const def = p.default;
|
|
4253
|
+
switch (p.kind) {
|
|
4254
|
+
case "path": return call("File", ["exists=True", ...tail]);
|
|
4255
|
+
case "bool": return call("traits.Bool", [...hasDef ? [renderPyLiteral(def), "usedefault=True"] : [], ...tail]);
|
|
4256
|
+
case "count": return call("traits.Int", [...hasDef ? [renderPyLiteral(def), "usedefault=True"] : [], ...tail]);
|
|
4257
|
+
case "int":
|
|
4258
|
+
case "float": {
|
|
4259
|
+
const asFloat = p.kind === "float";
|
|
4260
|
+
if (p.range) {
|
|
4261
|
+
const a = [];
|
|
4262
|
+
if (hasDef) a.push(`value=${renderNum(def, asFloat)}`);
|
|
4263
|
+
if (p.range.min !== void 0) a.push(`low=${renderNum(p.range.min, asFloat)}`);
|
|
4264
|
+
if (p.range.max !== void 0) a.push(`high=${renderNum(p.range.max, asFloat)}`);
|
|
4265
|
+
if (hasDef) a.push("usedefault=True");
|
|
4266
|
+
return call("traits.Range", [...a, ...tail]);
|
|
4267
|
+
}
|
|
4268
|
+
return call(p.kind === "int" ? "traits.Int" : "traits.Float", [...hasDef ? [renderNum(def, asFloat), "usedefault=True"] : [], ...tail]);
|
|
4269
|
+
}
|
|
4270
|
+
case "str": return call("traits.Str", [...hasDef ? [renderPyLiteral(def), "usedefault=True"] : [], ...tail]);
|
|
4271
|
+
case "enum": {
|
|
4272
|
+
const choices = p.choices ?? [];
|
|
4273
|
+
return call("traits.Enum", [
|
|
4274
|
+
...(hasDef ? [def, ...choices.filter((c) => c !== def)] : choices).map((c) => renderPyLiteral(c)),
|
|
4275
|
+
...hasDef ? ["usedefault=True"] : [],
|
|
4276
|
+
...tail
|
|
4277
|
+
]);
|
|
4278
|
+
}
|
|
4279
|
+
case "list": {
|
|
4280
|
+
const inner = renderItemTrait(p.itemType);
|
|
4281
|
+
const bounds = [];
|
|
4282
|
+
if (p.listBounds?.min !== void 0) bounds.push(`minlen=${p.listBounds.min}`);
|
|
4283
|
+
if (p.listBounds?.max !== void 0) bounds.push(`maxlen=${p.listBounds.max}`);
|
|
4284
|
+
return call("traits.List", [
|
|
4285
|
+
inner,
|
|
4286
|
+
...bounds,
|
|
4287
|
+
...tail
|
|
4288
|
+
]);
|
|
4289
|
+
}
|
|
4290
|
+
case "struct":
|
|
4291
|
+
case "union": return call("traits.Any", tail);
|
|
4292
|
+
}
|
|
4293
|
+
}
|
|
4294
|
+
/**
|
|
4295
|
+
* Map an output field to its nipype output trait expression. `isRoot` is the
|
|
4296
|
+
* synthetic output directory, typed as a `Directory` rather than a `File`.
|
|
4297
|
+
*/
|
|
4298
|
+
function renderOutputTrait(f, isRoot) {
|
|
4299
|
+
const tail = f.doc ? [`desc=${pyStr(f.doc)}`] : [];
|
|
4300
|
+
if (f.shape.kind === "list") return call("traits.List", ["File()", ...tail]);
|
|
4301
|
+
if (isRoot) return call("Directory", tail);
|
|
4302
|
+
return call("File", tail);
|
|
4303
|
+
}
|
|
4304
|
+
/**
|
|
4305
|
+
* Emit the nipype interface module for one tool: a typed InputSpec/OutputSpec and
|
|
4306
|
+
* a BaseInterface that delegates execution to the co-emitted styx Python wrapper.
|
|
4307
|
+
*/
|
|
4308
|
+
function emitNipypeInterface(ctx, spec, names) {
|
|
4309
|
+
const cb = new CodeBuilder(" ");
|
|
4310
|
+
cb.comment("This file was auto generated by Styx.", "# ");
|
|
4311
|
+
cb.comment("Do not edit this file directly.", "# ");
|
|
4312
|
+
cb.blank();
|
|
4313
|
+
cb.line("from nipype.interfaces.base import (");
|
|
4314
|
+
cb.indent(() => {
|
|
4315
|
+
cb.line("BaseInterface,");
|
|
4316
|
+
cb.line("BaseInterfaceInputSpec,");
|
|
4317
|
+
cb.line("Directory,");
|
|
4318
|
+
cb.line("File,");
|
|
4319
|
+
cb.line("TraitedSpec,");
|
|
4320
|
+
cb.line("isdefined,");
|
|
4321
|
+
cb.line("traits,");
|
|
4322
|
+
});
|
|
4323
|
+
cb.line(")");
|
|
4324
|
+
cb.blank();
|
|
4325
|
+
cb.line(`from .${names.styxStem} import ${spec.delegation.wrapperFn}, ${spec.delegation.outputsClass}`);
|
|
4326
|
+
cb.blank();
|
|
4327
|
+
cb.blank();
|
|
4328
|
+
cb.line(`class ${names.inputSpec}(BaseInterfaceInputSpec):`);
|
|
4329
|
+
cb.indent(() => {
|
|
4330
|
+
if (!spec.rootIsStruct || spec.params.length === 0) {
|
|
4331
|
+
cb.line("pass");
|
|
4332
|
+
return;
|
|
4333
|
+
}
|
|
4334
|
+
for (const p of spec.params) cb.line(`${p.hostName} = ${renderInputTrait(p)}`);
|
|
4335
|
+
});
|
|
4336
|
+
cb.blank();
|
|
4337
|
+
cb.blank();
|
|
4338
|
+
cb.line(`class ${names.outputSpec}(TraitedSpec):`);
|
|
4339
|
+
cb.indent(() => {
|
|
4340
|
+
if (spec.outputs.length === 0 && spec.streams.length === 0) {
|
|
4341
|
+
cb.line("pass");
|
|
4342
|
+
return;
|
|
4343
|
+
}
|
|
4344
|
+
spec.outputs.forEach((f, i) => cb.line(`${f.id} = ${renderOutputTrait(f, i === 0)}`));
|
|
4345
|
+
for (const s of spec.streams) {
|
|
4346
|
+
const tail = s.doc ? `, desc=${pyStr(s.doc)}` : "";
|
|
4347
|
+
cb.line(`${s.id} = traits.List(traits.Str()${tail})`);
|
|
4348
|
+
}
|
|
4349
|
+
});
|
|
4350
|
+
cb.blank();
|
|
4351
|
+
cb.blank();
|
|
4352
|
+
cb.line(`class ${names.cls}(BaseInterface):`);
|
|
4353
|
+
cb.indent(() => {
|
|
4354
|
+
emitDocstring(cb, [ctx.app?.doc?.title, ctx.app?.doc?.description].filter(Boolean).join("\n\n") || void 0);
|
|
4355
|
+
cb.line(`input_spec = ${names.inputSpec}`);
|
|
4356
|
+
cb.line(`output_spec = ${names.outputSpec}`);
|
|
4357
|
+
cb.blank();
|
|
4358
|
+
cb.line("def _run_interface(self, runtime):");
|
|
4359
|
+
cb.indent(() => {
|
|
4360
|
+
if (!spec.rootIsStruct) {
|
|
4361
|
+
cb.line("raise NotImplementedError(");
|
|
4362
|
+
cb.indent(() => cb.line(pyStr("styx nipype backend: tools with a non-struct root are not supported.")));
|
|
4363
|
+
cb.line(")");
|
|
4364
|
+
return;
|
|
4365
|
+
}
|
|
4366
|
+
cb.line("kwargs = {}");
|
|
4367
|
+
for (const p of spec.params) if (p.mandatory) cb.line(`kwargs[${pyStr(p.hostName)}] = self.inputs.${p.hostName}`);
|
|
4368
|
+
else {
|
|
4369
|
+
cb.line(`if isdefined(self.inputs.${p.hostName}):`);
|
|
4370
|
+
cb.indent(() => cb.line(`kwargs[${pyStr(p.hostName)}] = self.inputs.${p.hostName}`));
|
|
4371
|
+
}
|
|
4372
|
+
cb.line(`self._result: ${spec.delegation.outputsClass} = ${spec.delegation.wrapperFn}(**kwargs)`);
|
|
4373
|
+
cb.line("return runtime");
|
|
4374
|
+
});
|
|
4375
|
+
cb.blank();
|
|
4376
|
+
cb.line("def _list_outputs(self):");
|
|
4377
|
+
cb.indent(() => {
|
|
4378
|
+
if (!spec.rootIsStruct) {
|
|
4379
|
+
cb.line("return self._outputs().get()");
|
|
4380
|
+
return;
|
|
4381
|
+
}
|
|
4382
|
+
cb.line("result = self._result");
|
|
4383
|
+
cb.line("outputs = self._outputs().get()");
|
|
4384
|
+
for (const f of spec.outputs) if (f.shape.kind === "single" && f.shape.optional) {
|
|
4385
|
+
cb.line(`if result.${f.id} is not None:`);
|
|
4386
|
+
cb.indent(() => cb.line(`outputs[${pyStr(f.id)}] = result.${f.id}`));
|
|
4387
|
+
} else cb.line(`outputs[${pyStr(f.id)}] = result.${f.id}`);
|
|
4388
|
+
for (const s of spec.streams) cb.line(`outputs[${pyStr(s.id)}] = result.${s.id}`);
|
|
4389
|
+
cb.line("return outputs");
|
|
4390
|
+
});
|
|
4391
|
+
});
|
|
4392
|
+
return cb.toString();
|
|
4393
|
+
}
|
|
4394
|
+
|
|
4395
|
+
//#endregion
|
|
4396
|
+
//#region src/backend/styxdefs-compat.ts
|
|
4397
|
+
/**
|
|
4398
|
+
* Runtime version floors baked into generated dependency metadata.
|
|
4399
|
+
*
|
|
4400
|
+
* styx2-generated code calls `mutable_copy` / `mutableCopy` (introduced in the
|
|
4401
|
+
* styxdefs 0.7.0 / styxdefs-js 0.2.0 release), so emitted packages genuinely
|
|
4402
|
+
* require that runtime floor. This is the single source of truth: bump here and
|
|
4403
|
+
* both the Python and TypeScript backends pick it up.
|
|
4404
|
+
*/
|
|
4405
|
+
const STYXDEFS_COMPAT = {
|
|
4406
|
+
python: ">=0.7.0,<0.8.0",
|
|
4407
|
+
npm: "^0.2.0"
|
|
4408
|
+
};
|
|
4409
|
+
/**
|
|
4410
|
+
* Extra Python runtime packages the root metapackage pulls in. `styxkit[all]`
|
|
4411
|
+
* provides the cross-backend runner-selection helpers (`use_docker`, `use_auto`,
|
|
4412
|
+
* ...) that the metapackage's `__init__` re-exports, and transitively installs
|
|
4413
|
+
* every container/graph runner backend. Left unpinned - styxkit's own styxdefs
|
|
4414
|
+
* floor constrains the stack.
|
|
4415
|
+
*/
|
|
4416
|
+
const PYTHON_RUNNER_DEPS = ["styxkit[all]"];
|
|
4417
|
+
|
|
4418
|
+
//#endregion
|
|
4419
|
+
//#region src/backend/python/packaging.ts
|
|
4420
|
+
const REQUIRES_PYTHON = ">=3.10";
|
|
4421
|
+
const BUILD_SYSTEM = `[build-system]
|
|
4422
|
+
requires = ["setuptools>=61"]
|
|
4423
|
+
build-backend = "setuptools.build_meta"`;
|
|
4424
|
+
/** Escape a value for embedding in a TOML basic string. */
|
|
4425
|
+
function tomlStr(s) {
|
|
4426
|
+
return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/[\r\n]+/g, " ").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "").trim();
|
|
4427
|
+
}
|
|
4428
|
+
/** Suite directory / importable package name; matches the CLI's `pkgDir` fallback. */
|
|
4429
|
+
function pkgDir(pkg) {
|
|
4430
|
+
return pkg.name ?? "package";
|
|
4431
|
+
}
|
|
4432
|
+
/** Distribution (PyPI) name for a package: `<project>_<package>`, or just `<package>`. */
|
|
4433
|
+
function pyDistName(proj, pkg) {
|
|
4434
|
+
const name = pkgDir(pkg);
|
|
4435
|
+
return proj.name ? `${proj.name}_${name}` : name;
|
|
4436
|
+
}
|
|
4437
|
+
const SUMMARY_MAX_LEN = 512;
|
|
4438
|
+
/**
|
|
4439
|
+
* Clamp a description to a <=512-char one-line summary. Prefer cutting at the
|
|
4440
|
+
* last complete sentence that fits (clean, no dangling fragment); if there is no
|
|
4441
|
+
* sentence boundary early enough, cut at a word boundary and mark the elision.
|
|
4442
|
+
*/
|
|
4443
|
+
function clampSummary(s) {
|
|
4444
|
+
if (s.length <= SUMMARY_MAX_LEN) return s;
|
|
4445
|
+
const window = s.slice(0, SUMMARY_MAX_LEN);
|
|
4446
|
+
const lastSentence = window.lastIndexOf(". ");
|
|
4447
|
+
if (lastSentence >= 0) return s.slice(0, lastSentence + 1);
|
|
4448
|
+
const ellipsis = "...";
|
|
4449
|
+
const body = window.slice(0, SUMMARY_MAX_LEN - 3);
|
|
4450
|
+
const lastSpace = body.lastIndexOf(" ");
|
|
4451
|
+
return (lastSpace > 0 ? body.slice(0, lastSpace) : body).replace(/[.,;:\s]+$/, "") + ellipsis;
|
|
4452
|
+
}
|
|
4453
|
+
function description$1(doc, fallbackName) {
|
|
4454
|
+
return clampSummary(doc?.description ?? `Styx generated wrappers for ${doc?.title ?? fallbackName ?? "tools"}.`);
|
|
4455
|
+
}
|
|
4456
|
+
function authorsField(doc) {
|
|
4457
|
+
return `[${(doc?.authors?.length ? doc.authors : ["unknown"]).map((a) => `{ name = "${tomlStr(a)}" }`).join(", ")}]`;
|
|
4458
|
+
}
|
|
4459
|
+
function licenseField(proj) {
|
|
4460
|
+
return `{ text = "${tomlStr(proj.license?.description ?? "unknown")}" }`;
|
|
4461
|
+
}
|
|
4462
|
+
/**
|
|
4463
|
+
* Per-suite `pyproject.toml`. The flat layout (`python/<pkg>/bet.py`) makes the
|
|
4464
|
+
* directory itself the importable package, so setuptools' `package-dir` maps the
|
|
4465
|
+
* import name (`<pkg>`) onto the distribution's root directory. The styxdefs
|
|
4466
|
+
* floor is the only runtime dependency.
|
|
4467
|
+
*
|
|
4468
|
+
* Precondition: `pkg.name` must be a valid Python identifier - the flat layout's
|
|
4469
|
+
* relative imports (`from .bet import *`) already require this, and the CLI uses
|
|
4470
|
+
* it verbatim as the directory name, so this stays consistent with that.
|
|
4471
|
+
*/
|
|
4472
|
+
function generateSubPyproject(proj, pkg) {
|
|
4473
|
+
const importName = pkgDir(pkg);
|
|
4474
|
+
const cb = new CodeBuilder(" ");
|
|
4475
|
+
cb.line("[project]");
|
|
4476
|
+
cb.line(`name = "${tomlStr(pyDistName(proj, pkg))}"`);
|
|
4477
|
+
cb.line(`version = "${tomlStr(proj.version ?? "0.0.0")}"`);
|
|
4478
|
+
cb.line(`description = "${tomlStr(description$1(pkg.doc, pkg.name))}"`);
|
|
4479
|
+
cb.line(`readme = "README.md"`);
|
|
4480
|
+
cb.line(`license = ${licenseField(proj)}`);
|
|
4481
|
+
cb.line(`authors = ${authorsField(pkg.doc ?? proj.doc)}`);
|
|
4482
|
+
cb.line(`requires-python = "${REQUIRES_PYTHON}"`);
|
|
4483
|
+
cb.line("dependencies = [");
|
|
4484
|
+
cb.line(` "styxdefs${STYXDEFS_COMPAT.python}",`);
|
|
4485
|
+
cb.line("]");
|
|
4486
|
+
cb.blank();
|
|
4487
|
+
cb.line("[tool.setuptools]");
|
|
4488
|
+
cb.line(`packages = ["${importName}"]`);
|
|
4489
|
+
cb.line(`package-dir = { "${importName}" = "." }`);
|
|
4490
|
+
cb.blank();
|
|
4491
|
+
cb.line("[tool.setuptools.package-data]");
|
|
4492
|
+
cb.line(`"${importName}" = ["py.typed"]`);
|
|
4493
|
+
cb.blank();
|
|
4494
|
+
cb.line(BUILD_SYSTEM);
|
|
4495
|
+
return cb.toString() + "\n";
|
|
4496
|
+
}
|
|
4497
|
+
/**
|
|
4498
|
+
* The metapackage's `__init__.py`. A thin re-export of styxkit so the runner
|
|
4499
|
+
* configuration helpers (`use_docker`, `use_local`, `set_global_runner`, ...)
|
|
4500
|
+
* are reachable as `<project>.<name>` - the v1 ergonomic that the v2 split into
|
|
4501
|
+
* per-suite distributions otherwise dropped. The logic lives in styxkit (pulled
|
|
4502
|
+
* in via `styxkit[all]`), so this stays a wildcard re-export and never re-emits
|
|
4503
|
+
* the runner-config code itself.
|
|
4504
|
+
*/
|
|
4505
|
+
function generateRootInitPy() {
|
|
4506
|
+
return "# This file was auto generated by Styx.\n# Do not edit this file directly.\n\n# Re-export styxkit's runner-configuration helpers (use_docker, use_local,\n# use_auto, set_global_runner, get_global_runner, ...) so they are available\n# directly on this package, e.g. `import niwrap; niwrap.use_docker()`.\nfrom styxkit import * # noqa: F401,F403\n";
|
|
4507
|
+
}
|
|
4508
|
+
/**
|
|
4509
|
+
* Root `pyproject.toml`: a metapackage depending on `styxkit[all]` (the runner
|
|
4510
|
+
* stack it re-exports) plus each per-suite distribution. `packages` lists only
|
|
4511
|
+
* the metapackage's own module so setuptools ships the styxkit re-export without
|
|
4512
|
+
* sweeping the sibling suite directories into this distribution.
|
|
4513
|
+
*/
|
|
4514
|
+
function generateRootPyproject(proj, distNames, moduleName) {
|
|
4515
|
+
const cb = new CodeBuilder(" ");
|
|
4516
|
+
cb.line("[project]");
|
|
4517
|
+
cb.line(`name = "${tomlStr(proj.name ?? "project")}"`);
|
|
4518
|
+
cb.line(`version = "${tomlStr(proj.version ?? "0.0.0")}"`);
|
|
4519
|
+
cb.line(`description = "${tomlStr(description$1(proj.doc, proj.name))}"`);
|
|
4520
|
+
cb.line(`readme = "README.md"`);
|
|
4521
|
+
cb.line(`license = ${licenseField(proj)}`);
|
|
4522
|
+
cb.line(`authors = ${authorsField(proj.doc)}`);
|
|
4523
|
+
cb.line(`requires-python = "${REQUIRES_PYTHON}"`);
|
|
4524
|
+
cb.line("dependencies = [");
|
|
4525
|
+
for (const dep of PYTHON_RUNNER_DEPS) cb.line(` "${dep}",`);
|
|
4526
|
+
for (const dist of distNames) cb.line(` "${tomlStr(dist)}",`);
|
|
4527
|
+
cb.line("]");
|
|
4528
|
+
cb.blank();
|
|
4529
|
+
cb.line("[tool.setuptools]");
|
|
4530
|
+
cb.line(`packages = ["${moduleName}"]`);
|
|
4531
|
+
cb.blank();
|
|
4532
|
+
cb.line("[tool.setuptools.package-data]");
|
|
4533
|
+
cb.line(`"${moduleName}" = ["py.typed"]`);
|
|
4534
|
+
cb.blank();
|
|
4535
|
+
cb.line(BUILD_SYSTEM);
|
|
4536
|
+
return cb.toString() + "\n";
|
|
4537
|
+
}
|
|
4538
|
+
/** Per-suite README crediting the upstream tool authors. */
|
|
4539
|
+
function generateSubReadme(proj, pkg) {
|
|
4540
|
+
const projectTitle = proj.doc?.title ?? proj.name ?? "Styx";
|
|
4541
|
+
const packageTitle = pkg.doc?.title ?? pkg.name ?? "package";
|
|
4542
|
+
const url = pkg.doc?.urls?.[0];
|
|
4543
|
+
const titleMd = url ? `[${packageTitle}](${url})` : packageTitle;
|
|
4544
|
+
const credits = pkg.doc?.authors?.length ? pkg.doc.authors.join(", ") : pkg.doc?.urls?.join(", ") ?? "unknown";
|
|
4545
|
+
return `# ${projectTitle} wrappers for ${titleMd}${pkg.doc?.description ? `\n\n${pkg.doc.description}` : ""}\n\n${packageTitle} is made by ${credits}.\n\nThis package contains wrappers only and has no affiliation with the original authors.\n`;
|
|
4546
|
+
}
|
|
4547
|
+
/** Root README listing the bundled per-suite distributions. */
|
|
4548
|
+
function generateRootReadme(proj, distNames) {
|
|
4549
|
+
return `# ${proj.doc?.title ?? proj.name ?? "Styx"}\n${proj.doc?.description ? `\n${proj.doc.description}\n` : ""}\nAuto-generated Styx wrappers. This project bundles the following packages:\n\n${distNames.map((d) => `- ${d}`).join("\n")}\n`;
|
|
4550
|
+
}
|
|
4551
|
+
/** Local-install manifest: each suite directory first, then the root metapackage. */
|
|
4552
|
+
function generateRequirementsTxt(pkgDirs) {
|
|
4553
|
+
return [...pkgDirs.map((d) => `./${d}`), "./"].join("\n") + "\n";
|
|
4554
|
+
}
|
|
4555
|
+
|
|
4556
|
+
//#endregion
|
|
4557
|
+
//#region src/backend/sig-entries.ts
|
|
4558
|
+
/**
|
|
4559
|
+
* Build per-field signature entries for the kwarg wrapper and params factory.
|
|
4560
|
+
* Skips `@type` (the factory injects it as a constant). Required-no-default
|
|
4561
|
+
* entries are placed before defaulted ones so the resulting signature is
|
|
4562
|
+
* syntactically valid in both Python and TS.
|
|
4563
|
+
*
|
|
4564
|
+
* `registerLocal` is called once per field with the wire key; it must return
|
|
4565
|
+
* a scrubbed, unique host identifier (typically by combining a language-aware
|
|
4566
|
+
* scrub function with `Scope.add()`). The caller's scope should already have
|
|
4567
|
+
* the function's other locals (`params`, `runner`, ...) reserved so this
|
|
4568
|
+
* registration cannot collide with them.
|
|
4351
4569
|
*/
|
|
4352
|
-
function
|
|
4353
|
-
|
|
4354
|
-
|
|
4355
|
-
|
|
4356
|
-
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
|
|
4360
|
-
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
if (
|
|
4364
|
-
if (
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
|
|
4371
|
-
|
|
4372
|
-
|
|
4373
|
-
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
name: "runner",
|
|
4379
|
-
doc: "Command runner (defaults to global runner)."
|
|
4380
|
-
}], cb);
|
|
4381
|
-
cb.blank();
|
|
4382
|
-
cb.line("Returns:");
|
|
4383
|
-
cb.line(outputsType ? " Tool outputs (paths to files produced by the tool)." : " None.");
|
|
4384
|
-
cb.line("\"\"\"");
|
|
4385
|
-
if (entries.length === 0) cb.line(`params = ${paramsFnName}()`);
|
|
4386
|
-
else {
|
|
4387
|
-
cb.line(`params = ${paramsFnName}(`);
|
|
4388
|
-
cb.indent(() => {
|
|
4389
|
-
for (const e of entries) cb.line(`${e.name}=${e.name},`);
|
|
4390
|
-
});
|
|
4391
|
-
cb.line(")");
|
|
4392
|
-
}
|
|
4393
|
-
if (outputsType) cb.line(`return ${executeFnName}(params, runner)`);
|
|
4394
|
-
else cb.line(`${executeFnName}(params, runner)`);
|
|
4395
|
-
});
|
|
4570
|
+
function buildSigEntries(rootType, fieldInfo, registerLocal, opts) {
|
|
4571
|
+
const entries = [];
|
|
4572
|
+
for (const [fieldName, fieldType] of Object.entries(rootType.fields)) {
|
|
4573
|
+
if (fieldType.kind === "literal") continue;
|
|
4574
|
+
const fi = fieldInfo.get(fieldName);
|
|
4575
|
+
const isOptional = fieldType.kind === "optional";
|
|
4576
|
+
const inner = isOptional ? fieldType.inner : fieldType;
|
|
4577
|
+
let sigType = opts.renderType(inner);
|
|
4578
|
+
if (isOptional) sigType += opts.nullableSuffix;
|
|
4579
|
+
let sigDefault;
|
|
4580
|
+
const hasExplicitDefault = fi?.defaultValue !== void 0;
|
|
4581
|
+
if (hasExplicitDefault) sigDefault = opts.renderDefault(fi.defaultValue);
|
|
4582
|
+
else if (isOptional) sigDefault = opts.nullableDefault;
|
|
4583
|
+
entries.push({
|
|
4584
|
+
name: registerLocal(fieldName),
|
|
4585
|
+
wireKey: fieldName,
|
|
4586
|
+
sigType,
|
|
4587
|
+
sigDefault,
|
|
4588
|
+
isOptional,
|
|
4589
|
+
hasExplicitDefault,
|
|
4590
|
+
doc: fi?.doc
|
|
4591
|
+
});
|
|
4592
|
+
}
|
|
4593
|
+
const required = entries.filter((e) => e.sigDefault === void 0);
|
|
4594
|
+
const defaulted = entries.filter((e) => e.sigDefault !== void 0);
|
|
4595
|
+
return [...required, ...defaulted];
|
|
4396
4596
|
}
|
|
4397
4597
|
|
|
4398
4598
|
//#endregion
|
|
@@ -5156,7 +5356,7 @@ function computePublicNames$1(appId) {
|
|
|
5156
5356
|
* (the `reg` registrations and the `sigScope` child), so passing the same scope
|
|
5157
5357
|
* the emitter continues with keeps later local registrations consistent.
|
|
5158
5358
|
*/
|
|
5159
|
-
function buildEmitModel
|
|
5359
|
+
function buildEmitModel(ctx, scope = new Scope(PY_RESERVED)) {
|
|
5160
5360
|
const appId = ctx.app?.id;
|
|
5161
5361
|
const pkg = ctx.package?.name;
|
|
5162
5362
|
const publicNames = computePublicNames$1(appId);
|
|
@@ -5199,7 +5399,7 @@ function buildEmitModel$1(ctx, scope = new Scope(PY_RESERVED)) {
|
|
|
5199
5399
|
function generatePython(ctx, packageScope) {
|
|
5200
5400
|
const cb = new CodeBuilder(" ");
|
|
5201
5401
|
const scope = packageScope ?? new Scope(PY_RESERVED);
|
|
5202
|
-
const { names, rootType, rootIsStruct, namedTypes, typeDecls, rootTypeTag, paramsType, sigEntries } = buildEmitModel
|
|
5402
|
+
const { names, rootType, rootIsStruct, namedTypes, typeDecls, rootTypeTag, paramsType, sigEntries } = buildEmitModel(ctx, scope);
|
|
5203
5403
|
cb.comment("This file was auto generated by Styx.", "# ");
|
|
5204
5404
|
cb.comment("Do not edit this file directly.", "# ");
|
|
5205
5405
|
cb.blank();
|
|
@@ -5346,6 +5546,7 @@ var PythonBackend = class {
|
|
|
5346
5546
|
const files = /* @__PURE__ */ new Map();
|
|
5347
5547
|
const distNames = [];
|
|
5348
5548
|
const pkgDirs = [];
|
|
5549
|
+
const warnings = [];
|
|
5349
5550
|
for (const p of packages) {
|
|
5350
5551
|
const pkg = p.meta ?? {};
|
|
5351
5552
|
const dir = pkg.name ?? "package";
|
|
@@ -5354,13 +5555,21 @@ var PythonBackend = class {
|
|
|
5354
5555
|
files.set(`${dir}/pyproject.toml`, generateSubPyproject(proj, pkg));
|
|
5355
5556
|
files.set(`${dir}/README.md`, generateSubReadme(proj, pkg));
|
|
5356
5557
|
}
|
|
5357
|
-
|
|
5558
|
+
let rootMod = pyScrubIdent(proj.name && proj.name.trim() ? proj.name : "project", PY_RESERVED);
|
|
5559
|
+
if (pkgDirs.includes(rootMod)) {
|
|
5560
|
+
const collided = rootMod;
|
|
5561
|
+
while (pkgDirs.includes(rootMod)) rootMod += "_";
|
|
5562
|
+
warnings.push({ message: `metapackage module "${collided}" collides with a suite directory; emitting as "${rootMod}" instead` });
|
|
5563
|
+
}
|
|
5564
|
+
files.set(`${rootMod}/__init__.py`, generateRootInitPy());
|
|
5565
|
+
files.set(`${rootMod}/py.typed`, "");
|
|
5566
|
+
files.set("pyproject.toml", generateRootPyproject(proj, distNames, rootMod));
|
|
5358
5567
|
files.set("README.md", generateRootReadme(proj, distNames));
|
|
5359
5568
|
files.set("requirements.txt", generateRequirementsTxt(pkgDirs));
|
|
5360
5569
|
return {
|
|
5361
5570
|
files,
|
|
5362
5571
|
errors: [],
|
|
5363
|
-
warnings
|
|
5572
|
+
warnings
|
|
5364
5573
|
};
|
|
5365
5574
|
}
|
|
5366
5575
|
};
|
|
@@ -5506,7 +5715,7 @@ const pyDialect = {
|
|
|
5506
5715
|
* @param opts - Import and package-root options.
|
|
5507
5716
|
*/
|
|
5508
5717
|
function renderPythonCall(ctx, config, opts = {}) {
|
|
5509
|
-
const model = buildEmitModel
|
|
5718
|
+
const model = buildEmitModel(ctx);
|
|
5510
5719
|
const pkg = ctx.package?.name;
|
|
5511
5720
|
const callee = pkg ? `${pkg}.${model.names.wrapper}` : model.names.wrapper;
|
|
5512
5721
|
const call = model.rootIsStruct && model.rootType.kind === "struct" ? renderKwargCall(callee, model.sigEntries, model.rootType, config) : `${callee}(${renderValue(config, model.rootType, "", pyDialect)})`;
|
|
@@ -5529,6 +5738,495 @@ function renderKwargCall(callee, sigEntries, rootType, config) {
|
|
|
5529
5738
|
return `${callee}(\n${lines.join("\n")}\n)`;
|
|
5530
5739
|
}
|
|
5531
5740
|
|
|
5741
|
+
//#endregion
|
|
5742
|
+
//#region src/backend/typed-spec.ts
|
|
5743
|
+
/** Project a tool's solved tree into the flat typed spec for delegation backends. */
|
|
5744
|
+
function buildTypedSpec(ctx) {
|
|
5745
|
+
const model = buildEmitModel(ctx);
|
|
5746
|
+
const delegation = {
|
|
5747
|
+
moduleName: appModuleName$1(ctx.app),
|
|
5748
|
+
wrapperFn: model.names.wrapper,
|
|
5749
|
+
outputsClass: model.names.outputs
|
|
5750
|
+
};
|
|
5751
|
+
const outputs = collectOutputFields(ctx, pyId);
|
|
5752
|
+
const streams = streamFields(ctx, pyId);
|
|
5753
|
+
if (!model.rootIsStruct || model.rootType.kind !== "struct") return {
|
|
5754
|
+
rootIsStruct: false,
|
|
5755
|
+
params: [],
|
|
5756
|
+
outputs,
|
|
5757
|
+
streams,
|
|
5758
|
+
delegation
|
|
5759
|
+
};
|
|
5760
|
+
const rootType = model.rootType;
|
|
5761
|
+
const fieldByName = new Map(structFields(ctx, rootType, ctx.expr).map((f) => [f.name, f]));
|
|
5762
|
+
const fieldInfo = collectFieldInfo(ctx, rootType);
|
|
5763
|
+
return {
|
|
5764
|
+
rootIsStruct: true,
|
|
5765
|
+
params: model.sigEntries.map((e) => {
|
|
5766
|
+
const fe = fieldByName.get(e.wireKey);
|
|
5767
|
+
const fi = fieldInfo.get(e.wireKey);
|
|
5768
|
+
return describeParam(e, fe?.type, fe?.node, fi?.defaultValue, fi?.doc);
|
|
5769
|
+
}),
|
|
5770
|
+
outputs,
|
|
5771
|
+
streams,
|
|
5772
|
+
delegation
|
|
5773
|
+
};
|
|
5774
|
+
}
|
|
5775
|
+
function describeParam(e, type, node, defaultValue, fallbackDoc) {
|
|
5776
|
+
const optional = e.isOptional;
|
|
5777
|
+
const hasDefault = e.hasExplicitDefault;
|
|
5778
|
+
const base = {
|
|
5779
|
+
hostName: e.name,
|
|
5780
|
+
wireKey: e.wireKey,
|
|
5781
|
+
optional,
|
|
5782
|
+
hasDefault,
|
|
5783
|
+
mandatory: !optional && !hasDefault,
|
|
5784
|
+
default: defaultValue,
|
|
5785
|
+
doc: e.doc ?? fallbackDoc
|
|
5786
|
+
};
|
|
5787
|
+
const inner = type && type.kind === "optional" ? type.inner : type;
|
|
5788
|
+
const choices = inner ? literalChoices(inner, node) : void 0;
|
|
5789
|
+
if (choices) return {
|
|
5790
|
+
...base,
|
|
5791
|
+
kind: "enum",
|
|
5792
|
+
choices
|
|
5793
|
+
};
|
|
5794
|
+
switch (inner?.kind) {
|
|
5795
|
+
case "scalar":
|
|
5796
|
+
if (inner.scalar === "path") return {
|
|
5797
|
+
...base,
|
|
5798
|
+
kind: "path",
|
|
5799
|
+
scalarKind: "path",
|
|
5800
|
+
mediaTypes: pathMediaTypes(node)
|
|
5801
|
+
};
|
|
5802
|
+
if (inner.scalar === "int" || inner.scalar === "float") return {
|
|
5803
|
+
...base,
|
|
5804
|
+
kind: inner.scalar,
|
|
5805
|
+
scalarKind: inner.scalar,
|
|
5806
|
+
range: numericRange(node)
|
|
5807
|
+
};
|
|
5808
|
+
return {
|
|
5809
|
+
...base,
|
|
5810
|
+
kind: "str",
|
|
5811
|
+
scalarKind: "str"
|
|
5812
|
+
};
|
|
5813
|
+
case "bool": return {
|
|
5814
|
+
...base,
|
|
5815
|
+
kind: "bool"
|
|
5816
|
+
};
|
|
5817
|
+
case "count": return {
|
|
5818
|
+
...base,
|
|
5819
|
+
kind: "count"
|
|
5820
|
+
};
|
|
5821
|
+
case "list": return {
|
|
5822
|
+
...base,
|
|
5823
|
+
kind: "list",
|
|
5824
|
+
listBounds: listBounds(node),
|
|
5825
|
+
itemType: describeItem(inner.item, node)
|
|
5826
|
+
};
|
|
5827
|
+
case "struct": return {
|
|
5828
|
+
...base,
|
|
5829
|
+
kind: "struct"
|
|
5830
|
+
};
|
|
5831
|
+
case "union": return {
|
|
5832
|
+
...base,
|
|
5833
|
+
kind: "union"
|
|
5834
|
+
};
|
|
5835
|
+
default: return {
|
|
5836
|
+
...base,
|
|
5837
|
+
kind: "str"
|
|
5838
|
+
};
|
|
5839
|
+
}
|
|
5840
|
+
}
|
|
5841
|
+
function describeItem(item, node) {
|
|
5842
|
+
const inner = item.kind === "optional" ? item.inner : item;
|
|
5843
|
+
const choices = literalChoices(inner, node);
|
|
5844
|
+
if (choices) return {
|
|
5845
|
+
kind: "enum",
|
|
5846
|
+
choices
|
|
5847
|
+
};
|
|
5848
|
+
switch (inner.kind) {
|
|
5849
|
+
case "scalar":
|
|
5850
|
+
if (inner.scalar === "path") return {
|
|
5851
|
+
kind: "path",
|
|
5852
|
+
scalarKind: "path",
|
|
5853
|
+
mediaTypes: pathMediaTypes(node)
|
|
5854
|
+
};
|
|
5855
|
+
return {
|
|
5856
|
+
kind: inner.scalar,
|
|
5857
|
+
scalarKind: inner.scalar
|
|
5858
|
+
};
|
|
5859
|
+
case "bool": return { kind: "bool" };
|
|
5860
|
+
case "count": return { kind: "count" };
|
|
5861
|
+
case "struct": return { kind: "struct" };
|
|
5862
|
+
case "union": return { kind: "union" };
|
|
5863
|
+
default: return { kind: "str" };
|
|
5864
|
+
}
|
|
5865
|
+
}
|
|
5866
|
+
/** Allowed values when `inner` is a literal or a union of literals (else undefined). */
|
|
5867
|
+
function literalChoices(inner, node) {
|
|
5868
|
+
if (inner.kind === "literal") return [inner.value];
|
|
5869
|
+
if (inner.kind === "union" && inner.variants.length > 0 && inner.variants.every((v) => v.type.kind === "literal")) return inner.variants.map((v) => v.type.value);
|
|
5870
|
+
const altNode = node ? findNode(node, (n) => n.kind === "alternative") : void 0;
|
|
5871
|
+
if (altNode && altNode.kind === "alternative") {
|
|
5872
|
+
const alts = altNode.attrs.alts;
|
|
5873
|
+
if (alts.length > 0 && alts.every((a) => a.kind === "literal")) return alts.map((a) => a.attrs.str);
|
|
5874
|
+
}
|
|
5875
|
+
}
|
|
5876
|
+
function numericRange(node) {
|
|
5877
|
+
const r = findRangeNode(node);
|
|
5878
|
+
if (!r) return void 0;
|
|
5879
|
+
const { minValue, maxValue } = r.attrs;
|
|
5880
|
+
if (minValue === void 0 && maxValue === void 0) return void 0;
|
|
5881
|
+
return {
|
|
5882
|
+
min: minValue,
|
|
5883
|
+
max: maxValue
|
|
5884
|
+
};
|
|
5885
|
+
}
|
|
5886
|
+
function listBounds(node) {
|
|
5887
|
+
const r = findRepeatNode(node);
|
|
5888
|
+
if (!r) return void 0;
|
|
5889
|
+
const { countMin, countMax } = r.attrs;
|
|
5890
|
+
if (countMin === void 0 && countMax === void 0) return void 0;
|
|
5891
|
+
return {
|
|
5892
|
+
min: countMin,
|
|
5893
|
+
max: countMax
|
|
5894
|
+
};
|
|
5895
|
+
}
|
|
5896
|
+
function pathMediaTypes(node) {
|
|
5897
|
+
const p = node ? findNode(node, (n) => n.kind === "path") : void 0;
|
|
5898
|
+
if (p && p.kind === "path") {
|
|
5899
|
+
const mt = p.attrs.mediaTypes;
|
|
5900
|
+
if (mt && mt.length > 0) return mt;
|
|
5901
|
+
}
|
|
5902
|
+
}
|
|
5903
|
+
|
|
5904
|
+
//#endregion
|
|
5905
|
+
//#region src/backend/nipype/nipype.ts
|
|
5906
|
+
/** Derive the per-tool nipype module/class names. */
|
|
5907
|
+
function nipypeNames(ctx) {
|
|
5908
|
+
const mod = appModuleName$1(ctx.app);
|
|
5909
|
+
const rawId = ctx.app?.id ?? "tool";
|
|
5910
|
+
const cls = pascalCase(/^[0-9]/.test(rawId) ? "v_" + rawId : rawId);
|
|
5911
|
+
return {
|
|
5912
|
+
styxStem: `_${mod}`,
|
|
5913
|
+
ifaceStem: mod,
|
|
5914
|
+
cls,
|
|
5915
|
+
inputSpec: `${cls}InputSpec`,
|
|
5916
|
+
outputSpec: `${cls}OutputSpec`
|
|
5917
|
+
};
|
|
5918
|
+
}
|
|
5919
|
+
/** Generate the nipype interface module source for one tool. */
|
|
5920
|
+
function generateNipype(ctx) {
|
|
5921
|
+
return emitNipypeInterface(ctx, buildTypedSpec(ctx), nipypeNames(ctx));
|
|
5922
|
+
}
|
|
5923
|
+
/**
|
|
5924
|
+
* Emits nipype `Interface` definitions whose typed InputSpec/OutputSpec carry
|
|
5925
|
+
* rich constraints (numeric ranges, list bounds, enum choices, file types) and
|
|
5926
|
+
* which delegate execution to the styx Python wrapper (Option B): no command-line
|
|
5927
|
+
* arg-building or output-path resolution is re-implemented here.
|
|
5928
|
+
*
|
|
5929
|
+
* Per tool, two co-located files are emitted so the output is a self-contained,
|
|
5930
|
+
* importable Python package: `_<tool>.py` (the styx Python module) and
|
|
5931
|
+
* `<tool>.py` (the interface, importing the wrapper via a relative import).
|
|
5932
|
+
*/
|
|
5933
|
+
var NipypeBackend = class {
|
|
5934
|
+
name = "nipype";
|
|
5935
|
+
target = "nipype";
|
|
5936
|
+
emitApp(ctx, _scope) {
|
|
5937
|
+
const names = nipypeNames(ctx);
|
|
5938
|
+
const spec = buildTypedSpec(ctx);
|
|
5939
|
+
const warnings = [];
|
|
5940
|
+
if (!spec.rootIsStruct) warnings.push({ message: `nipype: '${ctx.app?.id ?? "?"}' has a non-struct root; emitted interface has no typed inputs and raises on run.` });
|
|
5941
|
+
const styxCode = generatePython(ctx);
|
|
5942
|
+
const ifaceCode = emitNipypeInterface(ctx, spec, names);
|
|
5943
|
+
return {
|
|
5944
|
+
meta: ctx.app,
|
|
5945
|
+
files: new Map([[`${names.styxStem}.py`, styxCode], [`${names.ifaceStem}.py`, ifaceCode]]),
|
|
5946
|
+
errors: [],
|
|
5947
|
+
warnings
|
|
5948
|
+
};
|
|
5949
|
+
}
|
|
5950
|
+
};
|
|
5951
|
+
|
|
5952
|
+
//#endregion
|
|
5953
|
+
//#region src/backend/pydra/emit.ts
|
|
5954
|
+
/** A scalar enum's Python type: int when every choice is numeric, else str. */
|
|
5955
|
+
function enumScalar(choices) {
|
|
5956
|
+
return (choices ?? []).every((c) => typeof c === "number") ? "int" : "str";
|
|
5957
|
+
}
|
|
5958
|
+
/** True when a parameter is a file path (a path scalar or a list of paths). */
|
|
5959
|
+
function isPathParam(p) {
|
|
5960
|
+
return p.kind === "path" || p.kind === "list" && p.itemType?.kind === "path";
|
|
5961
|
+
}
|
|
5962
|
+
function itemTypeStr(item, imp) {
|
|
5963
|
+
if (!item) {
|
|
5964
|
+
imp.typing = true;
|
|
5965
|
+
return "ty.Any";
|
|
5966
|
+
}
|
|
5967
|
+
switch (item.kind) {
|
|
5968
|
+
case "path":
|
|
5969
|
+
imp.file = true;
|
|
5970
|
+
return "File";
|
|
5971
|
+
case "int":
|
|
5972
|
+
case "count": return "int";
|
|
5973
|
+
case "float": return "float";
|
|
5974
|
+
case "str": return "str";
|
|
5975
|
+
case "bool": return "bool";
|
|
5976
|
+
case "enum": return enumScalar(item.choices);
|
|
5977
|
+
default:
|
|
5978
|
+
imp.typing = true;
|
|
5979
|
+
return "ty.Any";
|
|
5980
|
+
}
|
|
5981
|
+
}
|
|
5982
|
+
/** Base (non-optional) Python type expression for a parameter. */
|
|
5983
|
+
function baseType(p, imp) {
|
|
5984
|
+
switch (p.kind) {
|
|
5985
|
+
case "path":
|
|
5986
|
+
imp.file = true;
|
|
5987
|
+
return "File";
|
|
5988
|
+
case "int":
|
|
5989
|
+
case "count": return "int";
|
|
5990
|
+
case "float": return "float";
|
|
5991
|
+
case "str": return "str";
|
|
5992
|
+
case "bool": return "bool";
|
|
5993
|
+
case "enum": return enumScalar(p.choices);
|
|
5994
|
+
case "list": return `list[${itemTypeStr(p.itemType, imp)}]`;
|
|
5995
|
+
case "struct":
|
|
5996
|
+
case "union":
|
|
5997
|
+
imp.typing = true;
|
|
5998
|
+
return "ty.Any";
|
|
5999
|
+
}
|
|
6000
|
+
}
|
|
6001
|
+
/** Full input type, wrapping in `ty.Optional[...]` for an omittable-no-default field. */
|
|
6002
|
+
function inputType(p, imp) {
|
|
6003
|
+
const base = baseType(p, imp);
|
|
6004
|
+
if (p.optional && !p.hasDefault) {
|
|
6005
|
+
imp.typing = true;
|
|
6006
|
+
return `ty.Optional[${base}]`;
|
|
6007
|
+
}
|
|
6008
|
+
return base;
|
|
6009
|
+
}
|
|
6010
|
+
/** An attrs validator enforcing numeric range / list-length bounds, or undefined. */
|
|
6011
|
+
function validatorExpr(p, imp) {
|
|
6012
|
+
const checks = [];
|
|
6013
|
+
if (p.range) {
|
|
6014
|
+
if (p.range.min !== void 0) checks.push(`attrs.validators.ge(${renderPyLiteral(p.range.min)})`);
|
|
6015
|
+
if (p.range.max !== void 0) checks.push(`attrs.validators.le(${renderPyLiteral(p.range.max)})`);
|
|
6016
|
+
}
|
|
6017
|
+
if (p.listBounds) {
|
|
6018
|
+
if (p.listBounds.min !== void 0) checks.push(`attrs.validators.min_len(${p.listBounds.min})`);
|
|
6019
|
+
if (p.listBounds.max !== void 0) checks.push(`attrs.validators.max_len(${p.listBounds.max})`);
|
|
6020
|
+
}
|
|
6021
|
+
if (checks.length === 0) return void 0;
|
|
6022
|
+
imp.attrs = true;
|
|
6023
|
+
return `_styx_optional(${checks.length === 1 ? checks[0] : `attrs.validators.and_(${checks.join(", ")})`})`;
|
|
6024
|
+
}
|
|
6025
|
+
/** Help text: doc + degrade / media-type notes. */
|
|
6026
|
+
function helpText(p) {
|
|
6027
|
+
const parts = [];
|
|
6028
|
+
if (p.doc) parts.push(p.doc);
|
|
6029
|
+
if (p.kind === "struct" || p.kind === "union") parts.push("(nested configuration; pass a dict)");
|
|
6030
|
+
if (p.mediaTypes && p.mediaTypes.length > 0) parts.push(`(media types: ${p.mediaTypes.join(", ")})`);
|
|
6031
|
+
return parts.length > 0 ? parts.join(" ") : void 0;
|
|
6032
|
+
}
|
|
6033
|
+
/** Render a `python.arg(...)` field for one parameter. */
|
|
6034
|
+
function renderInputArg(p, imp) {
|
|
6035
|
+
const args = [`type=${inputType(p, imp)}`];
|
|
6036
|
+
if (p.mandatory) {} else if (p.optional && !p.hasDefault) args.push("default=None");
|
|
6037
|
+
else args.push(`default=${renderPyLiteral(p.default)}`);
|
|
6038
|
+
if (p.kind === "enum") args.push(`allowed_values=[${(p.choices ?? []).map((c) => renderPyLiteral(c)).join(", ")}]`);
|
|
6039
|
+
const v = validatorExpr(p, imp);
|
|
6040
|
+
if (v) args.push(`validator=${v}`);
|
|
6041
|
+
const h = helpText(p);
|
|
6042
|
+
if (h) args.push(`help=${pyStr(h)}`);
|
|
6043
|
+
return `python.arg(${args.join(", ")})`;
|
|
6044
|
+
}
|
|
6045
|
+
/** Python type for an output field. `isRoot` is the synthetic output directory. */
|
|
6046
|
+
function outputType(f, isRoot, imp) {
|
|
6047
|
+
if (f.shape.kind === "list") {
|
|
6048
|
+
imp.file = true;
|
|
6049
|
+
return "list[File]";
|
|
6050
|
+
}
|
|
6051
|
+
if (isRoot) {
|
|
6052
|
+
imp.directory = true;
|
|
6053
|
+
return "Directory";
|
|
6054
|
+
}
|
|
6055
|
+
imp.file = true;
|
|
6056
|
+
if (f.shape.optional) {
|
|
6057
|
+
imp.typing = true;
|
|
6058
|
+
return "ty.Optional[File]";
|
|
6059
|
+
}
|
|
6060
|
+
return "File";
|
|
6061
|
+
}
|
|
6062
|
+
function renderOutputArg(f, isRoot, imp) {
|
|
6063
|
+
const args = [`type=${outputType(f, isRoot, imp)}`];
|
|
6064
|
+
if (f.doc) args.push(`help=${pyStr(f.doc)}`);
|
|
6065
|
+
return `python.out(${args.join(", ")})`;
|
|
6066
|
+
}
|
|
6067
|
+
/**
|
|
6068
|
+
* Emit the pydra task module for one tool: a `@python.define` task whose typed
|
|
6069
|
+
* inputs/outputs carry rich constraints and whose body delegates execution to the
|
|
6070
|
+
* co-emitted styx Python wrapper (Option B). Targets the post-rewrite
|
|
6071
|
+
* `pydra.compose` API (pydra >= 1.0a, Python >= 3.11).
|
|
6072
|
+
*/
|
|
6073
|
+
function emitPydraTask(ctx, spec, names) {
|
|
6074
|
+
const imp = {
|
|
6075
|
+
typing: false,
|
|
6076
|
+
attrs: false,
|
|
6077
|
+
file: false,
|
|
6078
|
+
directory: false
|
|
6079
|
+
};
|
|
6080
|
+
const inputEntries = spec.params.map((p) => ({
|
|
6081
|
+
key: p.hostName,
|
|
6082
|
+
expr: renderInputArg(p, imp)
|
|
6083
|
+
}));
|
|
6084
|
+
const outputEntries = spec.outputs.map((f, i) => ({
|
|
6085
|
+
key: f.id,
|
|
6086
|
+
expr: renderOutputArg(f, i === 0, imp)
|
|
6087
|
+
}));
|
|
6088
|
+
for (const s of spec.streams) outputEntries.push({
|
|
6089
|
+
key: s.id,
|
|
6090
|
+
expr: `python.out(type=list[str]${s.doc ? `, help=${pyStr(s.doc)}` : ""})`
|
|
6091
|
+
});
|
|
6092
|
+
const needsPath = spec.params.some(isPathParam);
|
|
6093
|
+
const cb = new CodeBuilder(" ");
|
|
6094
|
+
cb.comment("This file was auto generated by Styx.", "# ");
|
|
6095
|
+
cb.comment("Do not edit this file directly.", "# ");
|
|
6096
|
+
cb.comment("Targets the pydra.compose API (pydra >= 1.0a, Python >= 3.11).", "# ");
|
|
6097
|
+
cb.blank();
|
|
6098
|
+
if (needsPath) cb.line("import os");
|
|
6099
|
+
if (imp.typing) cb.line("import typing as ty");
|
|
6100
|
+
if (imp.attrs) cb.line("import attrs.validators");
|
|
6101
|
+
cb.line("from pydra.compose import python");
|
|
6102
|
+
const ff = [];
|
|
6103
|
+
if (imp.directory) ff.push("Directory");
|
|
6104
|
+
if (imp.file) ff.push("File");
|
|
6105
|
+
if (ff.length > 0) cb.line(`from fileformats.generic import ${ff.join(", ")}`);
|
|
6106
|
+
cb.blank();
|
|
6107
|
+
cb.line(`from .${names.styxStem} import ${spec.delegation.wrapperFn}`);
|
|
6108
|
+
cb.blank();
|
|
6109
|
+
cb.blank();
|
|
6110
|
+
if (imp.attrs) {
|
|
6111
|
+
cb.line("def _styx_optional(validator):");
|
|
6112
|
+
cb.indent(() => {
|
|
6113
|
+
cb.line("\"\"\"Apply an attrs validator only to a set (non-NOTHING), non-None value.\"\"\"");
|
|
6114
|
+
cb.line("def _check(instance, attribute, value):");
|
|
6115
|
+
cb.indent(() => {
|
|
6116
|
+
cb.line("if value is attrs.NOTHING or value is None:");
|
|
6117
|
+
cb.indent(() => cb.line("return"));
|
|
6118
|
+
cb.line("validator(instance, attribute, value)");
|
|
6119
|
+
});
|
|
6120
|
+
cb.line("return _check");
|
|
6121
|
+
});
|
|
6122
|
+
cb.blank();
|
|
6123
|
+
cb.blank();
|
|
6124
|
+
}
|
|
6125
|
+
if (needsPath) {
|
|
6126
|
+
cb.line("def _styx_path(value):");
|
|
6127
|
+
cb.indent(() => {
|
|
6128
|
+
cb.line("\"\"\"Convert fileformats / Path inputs into a styxdefs-accepted path.\"\"\"");
|
|
6129
|
+
cb.line("if value is None:");
|
|
6130
|
+
cb.indent(() => cb.line("return None"));
|
|
6131
|
+
cb.line("if isinstance(value, (list, tuple)):");
|
|
6132
|
+
cb.indent(() => cb.line("return [os.fspath(v) for v in value]"));
|
|
6133
|
+
cb.line("return os.fspath(value)");
|
|
6134
|
+
});
|
|
6135
|
+
cb.blank();
|
|
6136
|
+
cb.blank();
|
|
6137
|
+
}
|
|
6138
|
+
cb.line("@python.define(");
|
|
6139
|
+
cb.indent(() => {
|
|
6140
|
+
if (inputEntries.length === 0) cb.line("inputs={},");
|
|
6141
|
+
else {
|
|
6142
|
+
cb.line("inputs={");
|
|
6143
|
+
cb.indent(() => {
|
|
6144
|
+
for (const e of inputEntries) cb.line(`${pyStr(e.key)}: ${e.expr},`);
|
|
6145
|
+
});
|
|
6146
|
+
cb.line("},");
|
|
6147
|
+
}
|
|
6148
|
+
cb.line("outputs={");
|
|
6149
|
+
cb.indent(() => {
|
|
6150
|
+
for (const e of outputEntries) cb.line(`${pyStr(e.key)}: ${e.expr},`);
|
|
6151
|
+
});
|
|
6152
|
+
cb.line("},");
|
|
6153
|
+
});
|
|
6154
|
+
cb.line(")");
|
|
6155
|
+
const paramList = spec.params.map((p) => p.hostName);
|
|
6156
|
+
cb.line(`def ${names.cls}(${paramList.join(", ")}):`);
|
|
6157
|
+
cb.indent(() => {
|
|
6158
|
+
emitDocstring(cb, [ctx.app?.doc?.title, ctx.app?.doc?.description].filter(Boolean).join("\n\n") || void 0);
|
|
6159
|
+
if (!spec.rootIsStruct) {
|
|
6160
|
+
cb.line("raise NotImplementedError(");
|
|
6161
|
+
cb.indent(() => cb.line(pyStr("styx pydra backend: tools with a non-struct root are not supported.")));
|
|
6162
|
+
cb.line(")");
|
|
6163
|
+
return;
|
|
6164
|
+
}
|
|
6165
|
+
if (spec.params.length === 0) cb.line(`result = ${spec.delegation.wrapperFn}()`);
|
|
6166
|
+
else {
|
|
6167
|
+
cb.line(`result = ${spec.delegation.wrapperFn}(`);
|
|
6168
|
+
cb.indent(() => {
|
|
6169
|
+
for (const p of spec.params) {
|
|
6170
|
+
const expr = isPathParam(p) ? `_styx_path(${p.hostName})` : p.hostName;
|
|
6171
|
+
cb.line(`${p.hostName}=${expr},`);
|
|
6172
|
+
}
|
|
6173
|
+
});
|
|
6174
|
+
cb.line(")");
|
|
6175
|
+
}
|
|
6176
|
+
const returns = [...spec.outputs.map((f) => `result.${f.id}`), ...spec.streams.map((s) => `result.${s.id}`)];
|
|
6177
|
+
if (returns.length === 1) cb.line(`return ${returns[0]}`);
|
|
6178
|
+
else cb.line(`return ${returns.join(", ")}`);
|
|
6179
|
+
});
|
|
6180
|
+
return cb.toString();
|
|
6181
|
+
}
|
|
6182
|
+
|
|
6183
|
+
//#endregion
|
|
6184
|
+
//#region src/backend/pydra/pydra.ts
|
|
6185
|
+
/** Derive the per-tool pydra module/class names. */
|
|
6186
|
+
function pydraNames(ctx) {
|
|
6187
|
+
const mod = appModuleName$1(ctx.app);
|
|
6188
|
+
const rawId = ctx.app?.id ?? "tool";
|
|
6189
|
+
const safeId = /^[0-9]/.test(rawId) ? "v_" + rawId : rawId;
|
|
6190
|
+
return {
|
|
6191
|
+
styxStem: `_${mod}`,
|
|
6192
|
+
ifaceStem: mod,
|
|
6193
|
+
cls: pascalCase(safeId)
|
|
6194
|
+
};
|
|
6195
|
+
}
|
|
6196
|
+
/** Generate the pydra task module source for one tool. */
|
|
6197
|
+
function generatePydra(ctx) {
|
|
6198
|
+
return emitPydraTask(ctx, buildTypedSpec(ctx), pydraNames(ctx));
|
|
6199
|
+
}
|
|
6200
|
+
/**
|
|
6201
|
+
* Emits pydra tasks (`@python.define`, the post-rewrite pydra.compose API) whose
|
|
6202
|
+
* typed inputs/outputs carry rich constraints (numeric ranges and list bounds via
|
|
6203
|
+
* attrs validators, enum choices, file types, defaults) and which delegate
|
|
6204
|
+
* execution to the styx Python wrapper (Option B): no command-line arg-building
|
|
6205
|
+
* or output-path resolution is re-implemented here.
|
|
6206
|
+
*
|
|
6207
|
+
* Per tool, two co-located files are emitted so the output is a self-contained,
|
|
6208
|
+
* importable Python package: `_<tool>.py` (the styx Python module) and
|
|
6209
|
+
* `<tool>.py` (the task, importing the wrapper via a relative import).
|
|
6210
|
+
*/
|
|
6211
|
+
var PydraBackend = class {
|
|
6212
|
+
name = "pydra";
|
|
6213
|
+
target = "pydra";
|
|
6214
|
+
emitApp(ctx, _scope) {
|
|
6215
|
+
const names = pydraNames(ctx);
|
|
6216
|
+
const spec = buildTypedSpec(ctx);
|
|
6217
|
+
const warnings = [];
|
|
6218
|
+
if (!spec.rootIsStruct) warnings.push({ message: `pydra: '${ctx.app?.id ?? "?"}' has a non-struct root; emitted task has no typed inputs and raises on run.` });
|
|
6219
|
+
const styxCode = generatePython(ctx);
|
|
6220
|
+
const taskCode = emitPydraTask(ctx, spec, names);
|
|
6221
|
+
return {
|
|
6222
|
+
meta: ctx.app,
|
|
6223
|
+
files: new Map([[`${names.styxStem}.py`, styxCode], [`${names.ifaceStem}.py`, taskCode]]),
|
|
6224
|
+
errors: [],
|
|
6225
|
+
warnings
|
|
6226
|
+
};
|
|
6227
|
+
}
|
|
6228
|
+
};
|
|
6229
|
+
|
|
5532
6230
|
//#endregion
|
|
5533
6231
|
//#region src/backend/schema/jsonschema.ts
|
|
5534
6232
|
var SchemaBuilder = class {
|
|
@@ -5574,7 +6272,7 @@ var SchemaBuilder = class {
|
|
|
5574
6272
|
case "literal": return { const: type.value };
|
|
5575
6273
|
case "optional": return this.fromType(type.inner, node?.kind === "optional" ? node.attrs.node : void 0);
|
|
5576
6274
|
case "list": {
|
|
5577
|
-
const repeat = node
|
|
6275
|
+
const repeat = findRepeatNode(node);
|
|
5578
6276
|
const schema = {
|
|
5579
6277
|
type: "array",
|
|
5580
6278
|
items: this.fromType(type.item, repeat?.attrs.node)
|
|
@@ -5584,7 +6282,7 @@ var SchemaBuilder = class {
|
|
|
5584
6282
|
return schema;
|
|
5585
6283
|
}
|
|
5586
6284
|
case "struct": return this.structSchema(type, node);
|
|
5587
|
-
case "union": return this.unionSchema(type);
|
|
6285
|
+
case "union": return this.unionSchema(type, node);
|
|
5588
6286
|
}
|
|
5589
6287
|
}
|
|
5590
6288
|
findTerminal(node) {
|
|
@@ -5645,9 +6343,20 @@ var SchemaBuilder = class {
|
|
|
5645
6343
|
if (required.length > 0) schema.required = required;
|
|
5646
6344
|
return schema;
|
|
5647
6345
|
}
|
|
5648
|
-
unionSchema(type) {
|
|
6346
|
+
unionSchema(type, node) {
|
|
5649
6347
|
if (type.variants.every((v) => v.type.kind === "literal")) return { enum: type.variants.map((v) => v.type.kind === "literal" ? v.type.value : "") };
|
|
5650
|
-
|
|
6348
|
+
const altNode = findAlternativeNode(node);
|
|
6349
|
+
return { oneOf: type.variants.map((v, i) => {
|
|
6350
|
+
const schema = this.fromType(v.type, altNode?.attrs.alts[i]);
|
|
6351
|
+
if (v.type.kind === "struct" && "@type" in v.type.fields && schema.properties && !("@type" in schema.properties)) {
|
|
6352
|
+
schema.properties = {
|
|
6353
|
+
"@type": this.fromType(v.type.fields["@type"]),
|
|
6354
|
+
...schema.properties
|
|
6355
|
+
};
|
|
6356
|
+
schema.required = ["@type", ...schema.required ?? []];
|
|
6357
|
+
}
|
|
6358
|
+
return schema;
|
|
6359
|
+
}) };
|
|
5651
6360
|
}
|
|
5652
6361
|
};
|
|
5653
6362
|
function generateSchema(ctx) {
|
|
@@ -6899,7 +7608,7 @@ function computePublicNames(appId) {
|
|
|
6899
7608
|
* (the `reg` registrations and the `sigScope` child), so passing the same scope
|
|
6900
7609
|
* the emitter continues with keeps later local registrations consistent.
|
|
6901
7610
|
*/
|
|
6902
|
-
function buildEmitModel(ctx, scope = new Scope(TS_RESERVED)) {
|
|
7611
|
+
function buildEmitModel$1(ctx, scope = new Scope(TS_RESERVED)) {
|
|
6903
7612
|
const appId = ctx.app?.id;
|
|
6904
7613
|
const pkg = ctx.package?.name ?? "unknown";
|
|
6905
7614
|
const publicNames = computePublicNames(appId);
|
|
@@ -6942,7 +7651,7 @@ function buildEmitModel(ctx, scope = new Scope(TS_RESERVED)) {
|
|
|
6942
7651
|
function generateTypeScript(ctx, packageScope) {
|
|
6943
7652
|
const cb = new CodeBuilder(" ");
|
|
6944
7653
|
const scope = packageScope ?? new Scope(TS_RESERVED);
|
|
6945
|
-
const { appId, pkg, names, rootType, rootIsStruct, namedTypes, typeDecls, rootTypeTag, paramsType, sigEntries } = buildEmitModel(ctx, scope);
|
|
7654
|
+
const { appId, pkg, names, rootType, rootIsStruct, namedTypes, typeDecls, rootTypeTag, paramsType, sigEntries } = buildEmitModel$1(ctx, scope);
|
|
6946
7655
|
cb.comment("This file was auto generated by Styx.");
|
|
6947
7656
|
cb.comment("Do not edit this file directly.");
|
|
6948
7657
|
cb.blank();
|
|
@@ -7125,7 +7834,7 @@ const tsDialect = {
|
|
|
7125
7834
|
* @param opts - Import and package-root options.
|
|
7126
7835
|
*/
|
|
7127
7836
|
function renderTypeScriptCall(ctx, config, opts = {}) {
|
|
7128
|
-
const model = buildEmitModel(ctx);
|
|
7837
|
+
const model = buildEmitModel$1(ctx);
|
|
7129
7838
|
const pkg = ctx.package?.name;
|
|
7130
7839
|
const fnName = model.rootIsStruct ? model.names.execute : model.names.wrapper;
|
|
7131
7840
|
const call = `${pkg ? `${pkg}.${fnName}` : fnName}(${model.rootIsStruct && model.rootType.kind === "struct" ? renderStructLiteral(config, model.rootType, "", tsDialect, model.rootTypeTag) : renderValue(config, model.rootType, "", tsDialect)})`;
|
|
@@ -8287,5 +8996,5 @@ function compile(source, filenameOrOptions) {
|
|
|
8287
8996
|
}
|
|
8288
8997
|
|
|
8289
8998
|
//#endregion
|
|
8290
|
-
export { BoutiquesBackend, CodeBuilder, JsonSchemaBackend, PYTHON_RUNNER_DEPS, PassStatus, PythonBackend, STYXDEFS_COMPAT, Scope, TypeScriptBackend, alt, appEntrypoint, atomKey, buildSigEntries, camelCase, canonicalize, collectFieldInfo, collectNamedTypes, compactTokens, compile, compose, createContext, createPipeline, createRegistry, defaultNamingStrategy, defaultPipeline, detectFormat, effectiveOutputName, findDoc, findStructNode, fixpoint, flatten, float, format, formatSolveResult, generateBoutiques, generateOutputsSchema, generatePython, generateSchema, generateTypeScript, int, isGated, isIterated, isStructural, isTerminal, lit, nodeRef, opt, outputGate, pascalCase, path, planOutput, planScope, removeEmpty, renderPythonCall, renderStructLiteral, renderTypeScriptCall, renderValue, rep, repJoin, resolveFieldBinding, resolveOutputs, resolveTypeName, screamingSnakeCase, seq, seqJoin, simplify, snakeCase, solve, str, structKey, typeKey, unionKey };
|
|
8999
|
+
export { BoutiquesBackend, CodeBuilder, JsonSchemaBackend, NipypeBackend, PYTHON_RUNNER_DEPS, PassStatus, PydraBackend, PythonBackend, STYXDEFS_COMPAT, Scope, TypeScriptBackend, alt, appEntrypoint, atomKey, buildEmitModel, buildSigEntries, buildTypedSpec, camelCase, canonicalize, collectFieldInfo, collectNamedTypes, compactTokens, compile, compose, createContext, createPipeline, createRegistry, defaultNamingStrategy, defaultPipeline, detectFormat, effectiveOutputName, findDoc, findStructNode, fixpoint, flatten, float, format, formatSolveResult, generateBoutiques, generateNipype, generateOutputsSchema, generatePydra, generatePython, generateSchema, generateTypeScript, int, isGated, isIterated, isStructural, isTerminal, lit, nipypeNames, nodeRef, opt, outputGate, pascalCase, path, planOutput, planScope, pydraNames, removeEmpty, renderPythonCall, renderStructLiteral, renderTypeScriptCall, renderValue, rep, repJoin, resolveFieldBinding, resolveOutputs, resolveTypeName, screamingSnakeCase, seq, seqJoin, simplify, snakeCase, solve, str, structKey, typeKey, unionKey };
|
|
8291
9000
|
//# sourceMappingURL=index.mjs.map
|