From 8d45d708d8a1e72b1071db62a740a9904f1d3e2e Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 07:20:13 +0100 Subject: [PATCH 01/19] feat(wes): check I/O Schemas against the profile Bundle the GA4GH IO Schema Profile 0.3.0 (meta-schema and vocabularies, pinned at ga4gh-io-schema 2c3dc49, the pin of #609) and check IO schemas offline: $schema names the profile, the meta-schema passes with format assertion, and every $ref resolves within the document. A valid schema comes with a validator of its input values, whose errors carry JSON Pointers, the failed keyword and a message. The validator is @hyperjump/json-schema (no 'unsafe-eval' needed), behind the internal IoSchemaValidator interface, so that the component owner can swap it (open question 2 of #444). scripts/sync-io-schema.mjs copies the profile, its conformance suite, file-value vectors and example schemas from a checkout at the pin. The tests run the whole conformance suite and the examples offline. The test runner now takes the browser builds of dependencies and serves the CommonJS dependencies of hyperjump (content-type, idn-hostname, punycode) as modules with their named exports. Part of #444. Co-Authored-By: Claude Opus 5.5 --- apps/documentation/pages/docs/wes/_meta.json | 3 +- .../pages/docs/wes/io-schema.mdx | 31 + package-lock.json | 366 +- package.json | 3 + packages/ecc-client-ga4gh-wes/package.json | 2 + .../scripts/sync-io-schema.mjs | 166 + .../src/io-schema/messages.ts | 139 + .../src/io-schema/pointer.ts | 53 + .../src/io-schema/profile.ts | 1173 ++++++ .../io-schema/tests/fixtures/conformance.ts | 3250 +++++++++++++++++ .../src/io-schema/tests/fixtures/examples.ts | 1012 +++++ .../io-schema/tests/fixtures/file-values.ts | 293 ++ .../src/io-schema/tests/validator.test.ts | 245 ++ .../src/io-schema/validator.ts | 337 ++ .../ecc-client-ga4gh-wes/tsconfig.prod.json | 2 +- web-test.runner-config.mjs | 51 + 16 files changed, 7099 insertions(+), 27 deletions(-) create mode 100644 apps/documentation/pages/docs/wes/io-schema.mdx create mode 100644 packages/ecc-client-ga4gh-wes/scripts/sync-io-schema.mjs create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/messages.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/pointer.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/profile.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/conformance.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/examples.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/file-values.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts diff --git a/apps/documentation/pages/docs/wes/_meta.json b/apps/documentation/pages/docs/wes/_meta.json index d4ae7c6b..8a5e5efc 100644 --- a/apps/documentation/pages/docs/wes/_meta.json +++ b/apps/documentation/pages/docs/wes/_meta.json @@ -1,5 +1,6 @@ { "introduction": "Introduction", "providers": "Providers", + "io-schema": "I/O Schemas", "components": "Components" -} \ No newline at end of file +} diff --git a/apps/documentation/pages/docs/wes/io-schema.mdx b/apps/documentation/pages/docs/wes/io-schema.mdx new file mode 100644 index 00000000..94764b9f --- /dev/null +++ b/apps/documentation/pages/docs/wes/io-schema.mdx @@ -0,0 +1,31 @@ +import { Callout } from 'nextra/components' + +# I/O Schemas + +The WES components understand the [GA4GH IO Schema Profile](https://github.com/elixir-cloud-aai/ga4gh-io-schema) ([docs](https://ga4gh-io-schema.readthedocs.io/en/latest/)): JSON Schema 2020-12 with `x-ga4gh-*` keywords that describe the inputs and outputs of a workflow, for example to render input forms and to show outputs. + +## Profile version + +The package supports version **0.3.0** of the profile, pinned at commit [`2c3dc49`](https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/2c3dc49ad89f0a556272f160369a2a2d7a21dac3). Its meta-schema and vocabularies are bundled with the package; `scripts/sync-io-schema.mjs` in the package copies them, the conformance suite and the example schemas from a checkout of the profile's repository at the pinned commit. + +## Checks + +Before a component uses an IO schema, it checks it **offline**, as the profile asks: + +1. `$schema` must name the profile's meta-schema. +2. The schema must pass the meta-schema, with formats asserted. +3. Every `$ref` must resolve within the schema. Nothing is fetched over the network: a schema that refers to a remote schema is rejected. + +Input values are then validated against the schema's `inputs` with the semantics of JSON Schema 2020-12. Failures are reported with the JSON Pointer of the value, the keyword that failed and a message. + +The checks pass the profile's conformance suite (every valid case is accepted, every invalid one rejected) and accept the profile's example schemas. + +## Validator and Content Security Policy + +The checks use [@hyperjump/json-schema](https://github.com/hyperjump-io/json-schema), which doesn't compile schemas into code, so pages that embed the components need **no `'unsafe-eval'`** in their Content Security Policy. + + + hyperjump's settings are global to the page: the package turns off its retrieval of schemas over HTTP(S) and turns on format assertion. Pages that use hyperjump themselves get these settings, too. + + +The validator sits behind a small internal interface (`IoSchemaValidator`), so that another library could replace it without changing the components. diff --git a/package-lock.json b/package-lock.json index 67e7b4db..9477b988 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,9 +17,12 @@ "@lit/react": "^1.0.2", "@open-wc/eslint-config": "^12.0.3", "@open-wc/testing": "^4.0.0", + "@rollup/plugin-commonjs": "^29.0.3", + "@rollup/plugin-json": "^6.1.0", "@turbo/gen": "^2.11.10", "@web/dev-server": "^0.4.1", "@web/dev-server-esbuild": "^2.0.0", + "@web/dev-server-rollup": "^1.0.1", "@web/test-runner-playwright": "^1.0.0", "commander": "^12.0.0", "concurrently": "^8.2.2", @@ -3047,6 +3050,106 @@ "dev": true, "license": "BSD-3-Clause" }, + "node_modules/@hyperjump/browser": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@hyperjump/browser/-/browser-1.6.0.tgz", + "integrity": "sha512-FcD0B9cOTIj8bJCrX7RtsLSnA2CrX43KCdaFOpS2cH9VnNMuKX4EJ3mgSdQFWF6vz/fbXUNYU1LpIYXYn3TTXA==", + "license": "MIT", + "dependencies": { + "@hyperjump/json-pointer": "^1.1.0", + "@hyperjump/uri": "^1.2.0", + "content-type": "^1.0.5" + }, + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jdesrosiers" + } + }, + "node_modules/@hyperjump/json-pointer": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@hyperjump/json-pointer/-/json-pointer-1.1.4.tgz", + "integrity": "sha512-c6slpSqSiNL10JA78HdQOx50xaXHy1dKsPZOiEVjr/RqcVg5MgnWcP7vbvpxa42CD7pMkU6TtTCS+redjpjc2w==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jdesrosiers" + } + }, + "node_modules/@hyperjump/json-schema": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/@hyperjump/json-schema/-/json-schema-1.18.1.tgz", + "integrity": "sha512-RJkZloGX6BupKOdkWINajsityuyn8RG9XZA1EbLf98HCEzfcWI9V7sSMpQOTOU/DrUY/0ceBNuw0VXAhnJE34Q==", + "license": "MIT", + "dependencies": { + "@hyperjump/json-pointer": "^1.1.0", + "@hyperjump/json-schema-formats": "^1.1.0", + "@hyperjump/pact": "^1.2.0", + "@hyperjump/uri": "^1.2.0", + "content-type": "^1.0.4", + "just-curry-it": "^5.3.0", + "uuid": "^14.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jdesrosiers" + }, + "peerDependencies": { + "@hyperjump/browser": "^1.6.0" + } + }, + "node_modules/@hyperjump/json-schema-formats": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@hyperjump/json-schema-formats/-/json-schema-formats-1.2.0.tgz", + "integrity": "sha512-2nhOLInnldMRwyDWM43ciaX8vuxvOZNfqrouKCF1pwBZLS2mP6P1M++BB+y9WzX1aY8WZEXv5zgnnTgjxiHCRg==", + "license": "MIT", + "dependencies": { + "@hyperjump/uri": "^2.0.2", + "idn-hostname": "^16.0.4" + }, + "engines": { + "node": ">=22.12.0 <23 || >=24.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/hyperjump-io" + } + }, + "node_modules/@hyperjump/json-schema-formats/node_modules/@hyperjump/uri": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@hyperjump/uri/-/uri-2.0.2.tgz", + "integrity": "sha512-gNQzKwYQzfYWVV8bzr17WZiyc7ep6Cx36ZMilz2LYs0xRbwUDNMfLM7lSSpj6lDD2ChPNj6hMQkmyvbB7pVjLA==", + "license": "MIT", + "engines": { + "node": ">=22.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/hyperjump-io" + } + }, + "node_modules/@hyperjump/pact": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@hyperjump/pact/-/pact-1.5.1.tgz", + "integrity": "sha512-AmMAUpM5FzqMo5Ip4r9XQ7P8eAEuRlyeeMaOPqcv9ItS0Gogl+Sbod19CZZlzSO5n16SNPFijFwEwrid1eCY9Q==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/hyperjump-io" + } + }, + "node_modules/@hyperjump/uri": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@hyperjump/uri/-/uri-1.4.1.tgz", + "integrity": "sha512-AvzrZhbAXctdMe1WQXKtfymmK+nSTVE3f2edfMdAt4QwK8147HKPH+vr5AyzjEgReFetX5x5NGtIBYy/NO4tNQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jdesrosiers" + } + }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", @@ -5415,6 +5518,95 @@ "react": ">=18.2.0" } }, + "node_modules/@rollup/plugin-commonjs": { + "version": "29.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-29.0.3.tgz", + "integrity": "sha512-ZaOxZceP7SOUW7Lqw5IRVweSQYWaeIPnXIGLiB690EBA3FGJTO40EEr2L5yZplJWsgTCogILRSpcAe7+U0Otdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "commondir": "^1.0.1", + "estree-walker": "^2.0.2", + "fdir": "^6.2.0", + "is-reference": "1.2.1", + "magic-string": "^0.30.3", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=16.0.0 || 14 >= 14.17" + }, + "peerDependencies": { + "rollup": "^2.68.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-commonjs/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-commonjs/node_modules/is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/@rollup/plugin-commonjs/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/@rollup/plugin-json": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-6.1.0.tgz", + "integrity": "sha512-EGI2te5ENk1coGeADSIwZ7G2Q8CJS2sF120T7jLw4xFw9n7wIOXHo+kIYRAoVpJAN+kmqZSoO3Fp4JtoNF4ReA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.1.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, "node_modules/@rollup/plugin-node-resolve": { "version": "15.3.1", "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-15.3.1.tgz", @@ -8392,21 +8584,99 @@ } }, "node_modules/@web/dev-server-rollup": { - "version": "0.6.4", - "resolved": "https://registry.npmjs.org/@web/dev-server-rollup/-/dev-server-rollup-0.6.4.tgz", - "integrity": "sha512-sJZfTGCCrdku5xYnQQG51odGI092hKY9YFM0X3Z0tRY3iXKXcYRaLZrErw5KfCxr6g0JRuhe4BBhqXTA5Q2I3Q==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@web/dev-server-rollup/-/dev-server-rollup-1.0.1.tgz", + "integrity": "sha512-sdpnmTzwDPc27Vye/4jaSAq16Ghs5rLDxACtCo0MYIW3x4mkCBCOwx5rMB0mMXr/dWXQQBv6vYZM4bhRfVoCHA==", "dev": true, "license": "MIT", "dependencies": { "@rollup/plugin-node-resolve": "^15.0.1", - "@web/dev-server-core": "^0.7.2", + "@web/dev-server-core": "^1.0.3", "nanocolors": "^0.2.1", "parse5": "^6.0.1", "rollup": "^4.4.0", "whatwg-url": "^14.0.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" + } + }, + "node_modules/@web/dev-server-rollup/node_modules/@web/dev-server-core": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@web/dev-server-core/-/dev-server-core-1.0.5.tgz", + "integrity": "sha512-ljUKKuwDLqUE/f9s25Cg7L9RZNxIP2kkZHzC8eVtFwf+jww5aNdnzVVT4kcMAl1KWjMuUt7KOUlLP8vWjs1Nng==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/koa": "^2.11.6", + "@types/ws": "^7.4.0", + "@web/parse5-utils": "^3.0.1", + "chokidar": "^4.0.1", + "clone": "^2.1.2", + "es-module-lexer": "^1.0.0", + "get-stream": "^6.0.0", + "is-stream": "^2.0.0", + "isbinaryfile": "^5.0.0", + "koa": "^2.16.1", + "koa-etag": "^4.0.0", + "koa-send": "^5.0.1", + "koa-static": "^5.0.0", + "lru-cache": "^8.0.4", + "mime-types": "^2.1.27", + "parse5": "^6.0.1", + "picomatch": "^2.3.2", + "portfinder": "^1.0.32", + "ws": "^7.5.10" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@web/dev-server-rollup/node_modules/@web/parse5-utils": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@web/parse5-utils/-/parse5-utils-3.0.1.tgz", + "integrity": "sha512-bkjaP87set5BWuAiP2tL7RZQ6YvNzT7cKJknKwKKIZf+bQQNufN7FfIZt/xlSKpG5IyMUwTrWoIdfVuSRFwlQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/parse5": "^6.0.1", + "parse5": "^6.0.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@web/dev-server-rollup/node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@web/dev-server-rollup/node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@web/dev-server-rollup/node_modules/lru-cache": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-8.0.5.tgz", + "integrity": "sha512-MhWWlVnuab1RG5/zMRRcVGXZLCXrZTgfwMikgzCegsPnG62yDQo5JnqKkrK4jO5iKqDAZGItAqN5CtKBCBWRUA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=16.14" } }, "node_modules/@web/dev-server-rollup/node_modules/parse5": { @@ -8416,6 +8686,20 @@ "dev": true, "license": "MIT" }, + "node_modules/@web/dev-server-rollup/node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@web/dev-server/node_modules/@web/config-loader": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/@web/config-loader/-/config-loader-0.3.3.tgz", @@ -8426,6 +8710,31 @@ "node": ">=18.0.0" } }, + "node_modules/@web/dev-server/node_modules/@web/dev-server-rollup": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/@web/dev-server-rollup/-/dev-server-rollup-0.6.4.tgz", + "integrity": "sha512-sJZfTGCCrdku5xYnQQG51odGI092hKY9YFM0X3Z0tRY3iXKXcYRaLZrErw5KfCxr6g0JRuhe4BBhqXTA5Q2I3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/plugin-node-resolve": "^15.0.1", + "@web/dev-server-core": "^0.7.2", + "nanocolors": "^0.2.1", + "parse5": "^6.0.1", + "rollup": "^4.4.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@web/dev-server/node_modules/parse5": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", + "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", + "dev": true, + "license": "MIT" + }, "node_modules/@web/parse5-utils": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/@web/parse5-utils/-/parse5-utils-2.1.0.tgz", @@ -9456,24 +9765,6 @@ "node": ">=22.0.0" } }, - "node_modules/@web/test-runner/node_modules/@web/dev-server-rollup": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@web/dev-server-rollup/-/dev-server-rollup-1.0.0.tgz", - "integrity": "sha512-73eZNb5IA/ecrxZKZQq+lRFlPNl75XQ+hltVoWgsP3vQa5aTGWppBc/uuYLc74tGT7jp5WCdpsno7u5uX6GkcQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@rollup/plugin-node-resolve": "^15.0.1", - "@web/dev-server-core": "^1.0.0", - "nanocolors": "^0.2.1", - "parse5": "^6.0.1", - "rollup": "^4.4.0", - "whatwg-url": "^14.0.0" - }, - "engines": { - "node": ">=22.0.0" - } - }, "node_modules/@web/test-runner/node_modules/@web/parse5-utils": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@web/parse5-utils/-/parse5-utils-3.0.0.tgz", @@ -11258,6 +11549,13 @@ "node": ">= 12.0.0" } }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "dev": true, + "license": "MIT" + }, "node_modules/compute-scroll-into-view": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.1.1.tgz", @@ -11356,7 +11654,6 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -15435,6 +15732,18 @@ "node": ">=0.10.0" } }, + "node_modules/idn-hostname": { + "version": "16.0.4", + "resolved": "https://registry.npmjs.org/idn-hostname/-/idn-hostname-16.0.4.tgz", + "integrity": "sha512-U+LwefPYZbZyZQcRryjB4rNKkrK7ylbYkKFU2NnaQKjIw466vqDWnxaLa62rCG++Iv8NAm8emnn1NZScKjPTIw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=22.12.0 <23 || >=24.0.0" + } + }, "node_modules/ieee754": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", @@ -16605,6 +16914,12 @@ "setimmediate": "^1.0.5" } }, + "node_modules/just-curry-it": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/just-curry-it/-/just-curry-it-5.3.0.tgz", + "integrity": "sha512-silMIRiFjUWlfaDhkgSzpuAyQ6EX/o09Eu8ZBfmFwQMbax7+LQzeIU2CBrICT6Ne4l86ITCGvUCBpCubWYy0Yw==", + "license": "MIT" + }, "node_modules/just-extend": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-6.2.0.tgz", @@ -20536,7 +20851,6 @@ "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -35588,6 +35902,8 @@ "license": "Apache-2.0", "dependencies": { "@elixir-cloud/design": "*", + "@hyperjump/browser": "^1.6.0", + "@hyperjump/json-schema": "^1.18.1", "@lit/react": "^1.0.2", "lit": "^2.8.0" }, diff --git a/package.json b/package.json index 13a3e73d..cceaaf98 100644 --- a/package.json +++ b/package.json @@ -32,9 +32,12 @@ "@lit/react": "^1.0.2", "@open-wc/eslint-config": "^12.0.3", "@open-wc/testing": "^4.0.0", + "@rollup/plugin-commonjs": "^29.0.3", + "@rollup/plugin-json": "^6.1.0", "@turbo/gen": "^2.11.10", "@web/dev-server": "^0.4.1", "@web/dev-server-esbuild": "^2.0.0", + "@web/dev-server-rollup": "^1.0.1", "@web/test-runner-playwright": "^1.0.0", "commander": "^12.0.0", "concurrently": "^8.2.2", diff --git a/packages/ecc-client-ga4gh-wes/package.json b/packages/ecc-client-ga4gh-wes/package.json index afcc35aa..3c7e3747 100644 --- a/packages/ecc-client-ga4gh-wes/package.json +++ b/packages/ecc-client-ga4gh-wes/package.json @@ -47,6 +47,8 @@ }, "dependencies": { "@elixir-cloud/design": "*", + "@hyperjump/browser": "^1.6.0", + "@hyperjump/json-schema": "^1.18.1", "@lit/react": "^1.0.2", "lit": "^2.8.0" }, diff --git a/packages/ecc-client-ga4gh-wes/scripts/sync-io-schema.mjs b/packages/ecc-client-ga4gh-wes/scripts/sync-io-schema.mjs new file mode 100644 index 00000000..9f2bafe1 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/scripts/sync-io-schema.mjs @@ -0,0 +1,166 @@ +#!/usr/bin/env node +/** + * Copies the GA4GH IO Schema Profile from a checkout of + * https://github.com/elixir-cloud-aai/ga4gh-io-schema into this package, so + * that nothing of it is fetched at runtime: + * + * - `src/io-schema/profile.ts`: the meta-schema and its vocabularies, with + * the commit and the version of the profile; + * - `src/io-schema/tests/fixtures/*.ts`: the conformance suite, the test + * vectors of file reference values and the example schemas, for the tests + * and the demos. + * + * Usage, from the package directory: + * + * node scripts/sync-io-schema.mjs [] + * + * The checkout must be clean and at the commit to pin; `` is the + * profile version that the commit implements (default `0.3.0`). Run + * `npx prettier --write src/io-schema` afterwards. + */ +import { execFileSync } from "child_process"; +import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "fs"; +import path from "path"; + +const [checkout, version = "0.3.0"] = process.argv.slice(2); +if (!checkout) { + console.error( + "Usage: node scripts/sync-io-schema.mjs []" + ); + process.exit(2); +} + +const git = (...args) => + execFileSync("git", ["-C", checkout, ...args], { encoding: "utf-8" }).trim(); +const commit = git("rev-parse", "HEAD"); +if (git("status", "--porcelain")) { + console.error(`${checkout} has local changes; check out a clean commit.`); + process.exit(1); +} + +const readJson = (...parts) => + JSON.parse(readFileSync(path.join(checkout, ...parts), "utf-8")); +/** The `*.schema.json` documents of a directory, sorted by name. */ +const documents = (...parts) => + readdirSync(path.join(checkout, ...parts)) + .filter((name) => name.endsWith(".schema.json")) + .sort() + .map((name) => [ + name.replace(/\.schema\.json$/, ""), + readJson(...parts, name), + ]); + +const source = `https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/${commit}`; +const header = (what) => `/** + * ${what} + * + * Generated by \`scripts/sync-io-schema.mjs\` from ${source} + * (profile version ${version}; Apache-2.0, as this package). Don't edit. + */ +/* eslint-disable */ +`; +const json = (value) => JSON.stringify(value, null, 2); +const write = (file, text) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, text); + console.log(`Wrote ${file}`); +}; + +const profile = readJson("schemas", "ga4gh-io-profile.schema.json"); +const vocabularies = documents("schemas", "vocabularies").map(([, s]) => s); +write( + "src/io-schema/profile.ts", + `${header( + "The meta-schema of the GA4GH IO Schema Profile and its vocabularies." + )} +/** Commit of the profile's repository that the schemas come from. */ +export const PROFILE_COMMIT = ${json(commit)}; + +/** Version of the profile that the schemas implement. */ +export const PROFILE_VERSION = ${json(version)}; + +/** The meta-schema (\`schemas/ga4gh-io-profile.schema.json\`). */ +export const PROFILE_SCHEMA: Record = ${json(profile)}; + +/** The vocabularies (\`schemas/vocabularies/*.schema.json\`). */ +export const VOCABULARY_SCHEMAS: Record[] = ${json( + vocabularies + )}; +` +); + +const suite = ["tests", "conformance", "schema-documents"]; +write( + "src/io-schema/tests/fixtures/conformance.ts", + `${header( + "The conformance suite of the profile (`tests/conformance/schema-documents/`)." + )} +/** Documents that a validator must accept, by name. */ +export const VALID: [string, unknown][] = ${json(documents(...suite, "valid"))}; + +/** Documents that a validator must reject, by name (the rule they break). */ +export const INVALID: [string, unknown][] = ${json( + documents(...suite, "invalid") + )}; +` +); + +write( + "src/io-schema/tests/fixtures/file-values.ts", + `${header( + "Test vectors of file reference values (`tests/vectors/file-values/cases.json`)." + )} +export interface FileValueCase { + name: string; + annotation: Record; + value: string; + valid: boolean; + allowedSchemes?: string[]; + allowAbsolutePaths?: boolean; +} + +export const FILE_VALUE_CASES: FileValueCase[] = ${json( + readJson("tests", "vectors", "file-values", "cases.json") + )}; +` +); + +const examples = { + example_tool: readJson("tests", "data", "example_tool.schema.json"), + example_wdl: readJson("tests", "data", "example_wdl.schema.json"), + example_workflow: readJson("tests", "data", "example_workflow.schema.json"), + demo: readJson("examples", "demo", "ga4gh-io.schema.json"), + "greetings-nextflow": readJson( + "examples", + "workflows", + "greetings-nextflow", + "ga4gh-io.schema.json" + ), + "report-snakemake": readJson( + "examples", + "workflows", + "report-snakemake", + "ga4gh-io.schema.json" + ), + "word-count-cwl": readJson( + "examples", + "workflows", + "word-count-cwl", + "ga4gh-io.schema.json" + ), + "nextflow-fetchngs": readJson( + "tests", + "data", + "nextflow", + "fetchngs", + "expected.json" + ), +}; +write( + "src/io-schema/tests/fixtures/examples.ts", + `${header("Example IO schemas of the profile (`tests/data/`, `examples/`).")} +export const EXAMPLES: Record> = ${json( + examples + )}; +` +); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/messages.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/messages.ts new file mode 100644 index 00000000..775d3b2c --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/messages.ts @@ -0,0 +1,139 @@ +/** + * Messages for failed JSON Schema keywords, for validators that report the + * keyword but no text (e.g. @hyperjump/json-schema). The profile defines no + * texts: a failure that no `x-ga4gh-error-message` covers gets a message + * "built from the location and the keyword that failed" (Error messages). + */ + +const MAX_SHOWN = 80; + +/** A value as short JSON, for a message. */ +function show(value: unknown): string { + let text: string; + try { + text = JSON.stringify(value) ?? String(value); + } catch { + text = String(value); + } + return text.length > MAX_SHOWN ? `${text.slice(0, MAX_SHOWN - 1)}…` : text; +} + +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const plural = (count: unknown, one: string, many: string) => + `${count} ${count === 1 ? one : many}`; + +/** + * The message for a failed keyword. + * + * @param keyword - Name of the keyword, e.g. `minimum`. + * @param schemaValue - The value of the keyword in the schema, if known. + * @param instance - The value that failed, if known. + */ +export function keywordMessage( + keyword: string, + schemaValue: unknown, + instance: unknown +): string { + switch (keyword) { + case "type": + return `Must be ${ + Array.isArray(schemaValue) + ? schemaValue.map(String).join(" or ") + : `of type ${String(schemaValue)}` + }.`; + case "enum": + return Array.isArray(schemaValue) + ? `Must be one of ${schemaValue.map(show).join(", ")}.` + : "Must be one of the allowed values."; + case "const": + return `Must be ${show(schemaValue)}.`; + case "minimum": + return `Must be at least ${schemaValue}.`; + case "maximum": + return `Must be at most ${schemaValue}.`; + case "exclusiveMinimum": + return `Must be greater than ${schemaValue}.`; + case "exclusiveMaximum": + return `Must be less than ${schemaValue}.`; + case "multipleOf": + return `Must be a multiple of ${schemaValue}.`; + case "minLength": + return `Must have at least ${plural( + schemaValue, + "character", + "characters" + )}.`; + case "maxLength": + return `Must have at most ${plural( + schemaValue, + "character", + "characters" + )}.`; + case "pattern": + return `Must match the pattern ${show(schemaValue)}.`; + case "format": + return `Must be a valid ${String(schemaValue)}.`; + case "minItems": + return `Must have at least ${plural(schemaValue, "item", "items")}.`; + case "maxItems": + return `Must have at most ${plural(schemaValue, "item", "items")}.`; + case "uniqueItems": + return "Must not have duplicate items."; + case "contains": + case "minContains": + case "maxContains": + return "Must contain the expected items."; + case "minProperties": + return `Must have at least ${plural( + schemaValue, + "property", + "properties" + )}.`; + case "maxProperties": + return `Must have at most ${plural( + schemaValue, + "property", + "properties" + )}.`; + case "required": { + const missing = Array.isArray(schemaValue) + ? schemaValue.filter( + (name) => + typeof name === "string" && + !( + isObject(instance) && + Object.prototype.hasOwnProperty.call(instance, name) + ) + ) + : []; + return missing.length + ? `Missing ${ + missing.length === 1 ? "a required value" : "required values" + }: ${missing.join(", ")}.` + : "Missing a required value."; + } + case "dependentRequired": + return "Missing a value that another value requires."; + case "additionalProperties": + case "unevaluatedProperties": + return "Has a property that isn't allowed here."; + case "propertyNames": + return "Has a property name that isn't allowed."; + case "unevaluatedItems": + case "items": + case "prefixItems": + return "Has items that aren't allowed here."; + case "anyOf": + return "Must match at least one of the allowed forms."; + case "oneOf": + return "Must match exactly one of the allowed forms."; + case "not": + return "Must not match the excluded form."; + case "$schema": + return "Must name the GA4GH IO Schema Profile in $schema."; + default: + return `Fails "${keyword}".`; + } +} diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/pointer.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/pointer.ts new file mode 100644 index 00000000..8ea440bb --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/pointer.ts @@ -0,0 +1,53 @@ +/** JSON Pointers (RFC 6901). */ + +/** Escapes one segment of a JSON Pointer. */ +export const escapeSegment = (segment: string | number): string => + String(segment).replace(/~/g, "~0").replace(/\//g, "~1"); + +/** The JSON Pointer of a path of property names and array indexes. */ +export const toPointer = (path: readonly (string | number)[]): string => + path.map((segment) => `/${escapeSegment(segment)}`).join(""); + +/** The segments of a JSON Pointer; throws if it isn't one. */ +export function parsePointer(pointer: string): string[] { + if (pointer === "") return []; + if (!pointer.startsWith("/")) + throw new Error(`Not a JSON Pointer: ${pointer}`); + return pointer + .slice(1) + .split("/") + .map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~")); +} + +/** + * The JSON Pointer in the fragment of a URI (e.g. `#/a%20b`), or `null` if + * the fragment isn't one. + */ +export function fragmentPointer(uri: string): string | null { + const hash = uri.indexOf("#"); + const fragment = hash === -1 ? "" : uri.slice(hash + 1); + let pointer: string; + try { + pointer = decodeURIComponent(fragment); + } catch { + return null; + } + return pointer === "" || pointer.startsWith("/") ? pointer : null; +} + +/** The value at a JSON Pointer, or `undefined` if there is none. */ +export function valueAt(document: unknown, pointer: string): unknown { + let value = document; + for (const segment of parsePointer(pointer)) { + if (Array.isArray(value) && /^(0|[1-9][0-9]*)$/.test(segment)) { + value = value[Number(segment)]; + } else if ( + typeof value === "object" && + value !== null && + Object.prototype.hasOwnProperty.call(value, segment) + ) { + value = (value as Record)[segment]; + } else return undefined; + } + return value; +} diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/profile.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/profile.ts new file mode 100644 index 00000000..9bbc2fd9 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/profile.ts @@ -0,0 +1,1173 @@ +/** + * The meta-schema of the GA4GH IO Schema Profile and its vocabularies. + * + * Generated by `scripts/sync-io-schema.mjs` from https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/2c3dc49ad89f0a556272f160369a2a2d7a21dac3 + * (profile version 0.3.0; Apache-2.0, as this package). Don't edit. + */ +/* eslint-disable */ + +/** Commit of the profile's repository that the schemas come from. */ +export const PROFILE_COMMIT = "2c3dc49ad89f0a556272f160369a2a2d7a21dac3"; + +/** Version of the profile that the schemas implement. */ +export const PROFILE_VERSION = "0.3.0"; + +/** The meta-schema (`schemas/ga4gh-io-profile.schema.json`). */ +export const PROFILE_SCHEMA: Record = { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $vocabulary: { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true, + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/ga4gh-io": + false, + }, + title: "GA4GH IO Profile Meta-Schema", + description: + "Meta-schema for validating GA4GH workflow and tool IO JSON Schema profiles. The top level requires the inputs/outputs wrapper and may carry the top-level keywords of the workflow vocabulary; every schema, at any depth, must follow the rules of $defs/node, which combines one vocabulary file per keyword group.", + allOf: [ + { + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile-node#/$defs/schema", + }, + { + $comment: + "The keywords of every schema plus the top-level keywords; other x-ga4gh-* keywords are rejected. The check of unevaluated keywords sits in this branch, next to the rules that reach nested schemas, so that it doesn't evaluate the nested schemas a second time (see $defs/node).", + allOf: [ + { + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile-node#/$defs/keywords", + }, + { + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/workflow.schema.json", + }, + { + patternProperties: { + "^(?!x-ga4gh-)": true, + }, + }, + ], + unevaluatedProperties: false, + }, + ], + type: "object", + required: ["properties"], + properties: { + $schema: { + description: + "IO schemas must name this meta-schema. Validators check that $schema is present before they apply the meta-schema; the meta-schema doesn't require it, because some validators (e.g., @hyperjump/json-schema) remove $schema from a schema before they check it against its dialect.", + const: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + }, + $id: { + description: + "The identifier of the IO schema: an absolute URI that is stable and versioned, never the URL of a branch.", + type: "string", + format: "uri", + pattern: "^[A-Za-z][A-Za-z0-9+.-]*:", + not: { + description: + "URLs of branches at GitHub and GitLab: refs/heads/ or a common branch name (main, master, dev, develop, HEAD) in place of a tag or commit. A best-effort check: it is case-sensitive and doesn't know other branch names.", + pattern: + "^https?://(?:[^/@]+@)?(?:raw\\.githubusercontent\\.com(?::\\d+)?/[^/]+/[^/]+/|(?:www\\.)?github\\.com(?::\\d+)?/[^/]+/[^/]+/(?:blob|raw|tree)/|gitlab\\.com(?::\\d+)?/(?:(?!-/)[^/]+/)+-/(?:blob|raw|tree)/)(?:refs/heads/|(?:main|master|dev|develop|HEAD)/)", + }, + }, + type: { + const: "object", + }, + properties: { + type: "object", + properties: { + inputs: { + description: + "JSON Schema block defining the expected input parameters for the workflow or tool.", + properties: { + properties: { + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/ui-widgets.schema.json#/$defs/inputParameters", + }, + }, + }, + outputs: { + description: + "JSON Schema block defining the outputs of the workflow or tool: an object schema whose properties are the outputs. Optional; without it, the schema describes no outputs.", + $comment: + "The outputs are the direct properties of this schema, so that normalisers find them without resolving references or applicators.", + type: "object", + properties: { + type: { + const: "object", + }, + $ref: false, + $dynamicRef: false, + allOf: false, + anyOf: false, + oneOf: false, + not: false, + if: false, + then: false, + else: false, + dependentSchemas: false, + properties: { + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/ui-widgets.schema.json#/$defs/outputParameters", + }, + }, + }, + }, + required: ["inputs"], + }, + }, + $comment: + "The top level takes the rules of every schema from $defs/node ($defs/schema and $defs/keywords, without its check of unevaluated keywords), adds the top-level keywords, and rejects other x-ga4gh-* keywords itself. Nested schemas get all of $defs/node, so top-level keywords are rejected there.", + $defs: { + node: { + $id: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile-node", + title: "GA4GH IO Profile Schema Rules", + description: + "Applies to every schema of an IO schema, at any depth: JSON Schema Draft 2020-12 plus the x-ga4gh-* keywords of the vocabularies. Keywords starting with x-ga4gh- that no vocabulary defines are rejected.", + $comment: + "Two branches: the rules that reach nested schemas ($defs/subschemas) and the check of the x-ga4gh-* keywords. The check of unevaluated keywords sees only the vocabularies: validators that evaluate what such a check sees once more, to collect annotations, would otherwise validate every nested schema again at each level, in time exponential in the depth of nesting. The Draft 2020-12 meta-schema is not applied here but once per tree ($defs/schema), because it checks the whole tree below the schema it is applied to.", + allOf: [ + { + $ref: "#/$defs/subschemas", + }, + { + $comment: + "Every keyword that doesn't start with x-ga4gh- counts as evaluated; the vocabularies evaluate the x-ga4gh-* keywords they define; any other x-ga4gh-* keyword is unevaluated and rejected. The pattern is in an allOf that always passes, so that its annotations survive when $defs/keywords fails (otherwise validators that report all errors flag every standard keyword as unevaluated), and Ajv handles it with allErrors.", + $ref: "#/$defs/keywords", + allOf: [ + { + patternProperties: { + "^(?!x-ga4gh-)": true, + }, + }, + ], + unevaluatedProperties: false, + }, + ], + $defs: { + schema: { + title: "GA4GH IO Profile Schema Tree", + description: + "The rules of a tree of schemas without its x-ga4gh-* keywords: JSON Schema Draft 2020-12 for the schema and, through its applicators, every schema nested in it, and $defs/node for every subschema ($defs/subschemas). Applied to the top level and to each x-ga4gh-tabular-schema, which Draft 2020-12 doesn't reach.", + allOf: [ + { + $ref: "https://json-schema.org/draft/2020-12/schema", + }, + { + $ref: "#/$defs/subschemas", + }, + ], + }, + keywords: { + title: "GA4GH IO Profile Keywords", + description: + "The x-ga4gh-* keywords of every schema, one vocabulary file per keyword group. None of them applies $defs/node to a nested schema ($defs/subschemas does). Used by $defs/node and, without the check of unevaluated keywords, by the top level.", + allOf: [ + { + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/annotations.schema.json", + }, + { + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/file.schema.json", + }, + { + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/parameter.schema.json", + }, + { + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/outputs.schema.json", + }, + ], + }, + subschemas: { + title: "GA4GH IO Profile Subschemas", + description: + "Applies $defs/node to every subschema: the values of the applicators of JSON Schema Draft 2020-12, of the deprecated definitions and dependencies (which the Draft 2020-12 meta-schema also checks), and of x-ga4gh-tabular-schema.", + $comment: + "Explicit $refs instead of the $dynamicRef of the Draft 2020-12 meta-schema: some validators (e.g., Ajv) support $dynamicAnchor only at the root of a schema and would skip these rules. The Draft 2020-12 meta-schema ($defs/schema) still checks every subschema against plain JSON Schema. A new applicator of JSON Schema, or a new x-ga4gh-* keyword whose value is a schema, needs an entry here.", + properties: { + $defs: { + additionalProperties: { + $ref: "#", + }, + }, + definitions: { + additionalProperties: { + $ref: "#", + }, + }, + dependencies: { + additionalProperties: { + anyOf: [ + { + $ref: "#", + }, + { + type: "array", + }, + ], + }, + }, + prefixItems: { + items: { + $ref: "#", + }, + }, + items: { + $ref: "#", + }, + contains: { + $ref: "#", + }, + additionalProperties: { + $ref: "#", + }, + properties: { + additionalProperties: { + $ref: "#", + }, + }, + patternProperties: { + additionalProperties: { + $ref: "#", + }, + }, + dependentSchemas: { + additionalProperties: { + $ref: "#", + }, + }, + propertyNames: { + $ref: "#", + }, + if: { + $ref: "#", + }, + then: { + $ref: "#", + }, + else: { + $ref: "#", + }, + allOf: { + items: { + $ref: "#", + }, + }, + anyOf: { + items: { + $ref: "#", + }, + }, + oneOf: { + items: { + $ref: "#", + }, + }, + not: { + $ref: "#", + }, + unevaluatedItems: { + $ref: "#", + }, + unevaluatedProperties: { + $ref: "#", + }, + contentSchema: { + $ref: "#", + }, + "x-ga4gh-tabular-schema": { + $comment: "A new tree: Draft 2020-12 doesn't reach it.", + allOf: [ + { + $ref: "https://json-schema.org/draft/2020-12/schema", + }, + { + $ref: "#", + }, + ], + }, + }, + }, + }, + }, + }, +}; + +/** The vocabularies (`schemas/vocabularies/*.schema.json`). */ +export const VOCABULARY_SCHEMAS: Record[] = [ + { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/annotations.schema.json", + title: "GA4GH IO Profile Annotations", + description: + "Keywords that annotate a parameter for clients: UI hints, error message, description format and ontology term.", + properties: { + "x-ga4gh-ontology": { + type: "string", + format: "uri", + description: + "URI to an ontology term (e.g., an EDAM data term) semantically describing the data of the parameter. The format of a file goes into ontology of x-ga4gh-file.", + }, + "x-ga4gh-ui-widget": { + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/ui-widgets.schema.json", + description: + "Hint for UI clients on how to render this input/output. References an external standardized vocabulary.", + }, + "x-ga4gh-description-format": { + type: "string", + enum: ["plain_text", "markdown"], + default: "plain_text", + description: + "Hint for UI/CLI clients on how to parse and render the standard JSON Schema 'description' field, avoiding redundant text properties. 'markdown' is CommonMark 0.31.2 with raw HTML shown as text, images shown as their alt text, links only with allowed schemes, and of the GFM extensions only tables, strikethrough and autolinks (see Markdown descriptions in the specification).", + }, + "x-ga4gh-hidden": { + type: "boolean", + description: + "Inspired by nf-core. If true, UI generators should hide this parameter from default user views, unless users must set it (required without a default) or its value fails validation.", + }, + "x-ga4gh-error-message": { + type: "string", + description: + "Inspired by nf-core. Custom, human-readable error message to display, in place of the validator's message, if validation fails at the location of the value that this schema describes (not for nested values); the outermost message wins where several apply.", + }, + }, + allOf: [ + { + $comment: + "dependentSchemas is wrapped in an allOf: Ajv drops the properties that this schema evaluates (properties) when dependentSchemas sits next to them and its keyword is absent, and would reject them as unevaluated.", + dependentSchemas: { + "x-ga4gh-ui-widget": { + $comment: + "A widget of the vocabulary needs the keywords that it fits in the same schema (e.g., a slider a numeric type and both bounds); see the table of widgets in the specification.", + $ref: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/ui-widgets.schema.json#/$defs/fit", + }, + }, + }, + ], + }, + { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/file.schema.json", + title: "GA4GH IO Profile File Keywords", + description: + "Keywords that describe file parameters: file references and the structure of tabular files.", + properties: { + "x-ga4gh-file": { + $ref: "#/$defs/fileReference", + }, + "x-ga4gh-tabular-schema": { + description: + "Experimental. A nested JSON schema describing the rows of a tabular file (e.g., a sample sheet), as a hint for clients (e.g., to offer a spreadsheet editor). Not a validation rule: validation of tabular files is deferred. Checked by the same rules as every other schema of the IO schema ($defs/subschemas of the meta-schema).", + }, + }, + allOf: [ + { + $comment: + "dependentSchemas is wrapped in an allOf: Ajv drops the properties that this schema evaluates (properties) when dependentSchemas sits next to them and its keyword is absent, and would reject them as unevaluated.", + dependentSchemas: { + "x-ga4gh-file": { + $comment: + "A file reference is a flat string schema. The profile defines its value syntax, not `format` (e.g., `uri` rejects compact DRS identifiers); `contentMediaType`, `contentEncoding` and `contentSchema` describe the string itself, not the referenced file. In-place applicators are not allowed on the annotated schema, so that it stays flat for converters and clients. This checks only the annotated schema: schemas that apply at the same location (e.g., a sibling in a parent allOf) can't be checked here; the specification forbids them to add these keywords.", + required: ["type"], + properties: { + type: { + const: "string", + }, + format: false, + contentMediaType: false, + contentEncoding: false, + contentSchema: false, + allOf: false, + anyOf: false, + oneOf: false, + not: false, + if: false, + then: false, + else: false, + $ref: false, + $dynamicRef: false, + }, + }, + }, + }, + ], + $defs: { + fileReference: { + type: "object", + description: + "Marks a string as a reference to a file or directory and describes what it refers to.", + required: ["kind"], + additionalProperties: false, + properties: { + kind: { + enum: ["file", "directory"], + description: + "Whether the string refers to a file or to a directory.", + }, + mediaType: { + type: "string", + pattern: + "^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}$", + description: + "Media type of the referenced file (RFC 6838, e.g., text/csv), without parameters.", + }, + ontology: { + type: "string", + format: "uri", + description: + "HTTP(S) IRI of an ontology term for the format of the referenced file or directory (e.g., an EDAM format term), with namespace prefixes expanded.", + pattern: "^https?://", + }, + compression: { + enum: ["gzip", "bgzip", "bzip2", "xz", "zstd"], + description: + "Compression of the referenced file. bgzip is block-compressed gzip: gzip tools read it, and index tools (e.g., tabix) need it.", + }, + secondaryFiles: { + type: "array", + minItems: 1, + uniqueItems: true, + description: + "Files that must exist next to the referenced file (e.g., indexes), as suffix patterns in the style of CWL with at least one character other than a dot: the suffix is appended to the name of the referenced file, after each leading ^ has removed one extension (e.g., .bai for sample.bam.bai, ^.bai for sample.bai).", + items: { + type: "string", + pattern: "^\\^*[.]*[A-Za-z0-9_+-][A-Za-z0-9_.+-]*$", + }, + }, + schemes: { + type: "array", + minItems: 1, + uniqueItems: true, + description: + "URI schemes that values may use (e.g., drs, https, s3), in lowercase. If given, values must be absolute URIs with one of them; paths are not allowed. The schemes javascript, vbscript, livescript, data, blob, filesystem, file, jar, view-source and about are rejected; for all others, the deployment's allow-list is the control.", + items: { + type: "string", + pattern: "^[a-z][a-z0-9+.-]*$", + not: { + enum: [ + "javascript", + "vbscript", + "livescript", + "data", + "blob", + "filesystem", + "file", + "jar", + "view-source", + "about", + ], + }, + }, + }, + }, + if: { + required: ["kind"], + properties: { + kind: { + const: "directory", + }, + }, + }, + then: { + $comment: + "Media types, compression and secondary files apply to files only.", + properties: { + mediaType: false, + compression: false, + secondaryFiles: false, + }, + }, + }, + }, + }, + { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/outputs.schema.json", + title: "GA4GH IO Profile Output Keywords", + description: + "Keywords that tell clients where to find the outputs of a run when the engine doesn't report them by name.", + properties: { + "x-ga4gh-output-glob": { + $ref: "#/$defs/outputGlob", + }, + }, + allOf: [ + { + $comment: + "dependentSchemas is wrapped in an allOf: Ajv drops the properties that this schema evaluates (properties) when dependentSchemas sits next to them and its keyword is absent, and would reject them as unevaluated.", + dependentSchemas: { + "x-ga4gh-output-glob": { + $comment: + "A glob finds files or directories, so it belongs on a file reference or on a list of file references (a schema whose items are one; tuples with prefixItems are not lists). It has a meaning only on the schema of a property of outputs; elsewhere, clients ignore it; this is deliberately not enforced.", + required: ["type"], + properties: { + type: { + enum: ["string", "array"], + }, + }, + if: { + properties: { + type: { + const: "string", + }, + }, + }, + then: { + required: ["x-ga4gh-file"], + }, + else: { + required: ["items"], + properties: { + prefixItems: false, + items: { + $comment: + "The file vocabulary makes a schema with x-ga4gh-file a string schema.", + type: "object", + required: ["x-ga4gh-file"], + }, + }, + }, + }, + }, + }, + ], + $defs: { + outputGlob: { + type: "string", + description: + "Glob pattern, relative to the output directory of the run, that finds the output among the files of the run when the engine doesn't report the output by name. Segments are separated by /; * matches any characters within a segment, ? one character, and a segment ** any number of segments. Not allowed: absolute paths, empty segments, . and .. segments, a colon in the first segment, backslashes, control characters (C0, DEL, C1), line and paragraph separators, brackets and braces.", + $comment: + "pattern: non-empty segments without backslashes, brackets, braces and control characters; not: no . or .. segment, no ** that is not a whole segment, no colon in the first segment (it would look like a URI scheme), and no control characters anywhere (Python's $ also matches before a final newline, ECMA-262's doesn't, so the anchors alone don't reject one).", + pattern: + "^[^/\\\\\\[\\]{}\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]+(/[^/\\\\\\[\\]{}\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]+)*$", + not: { + pattern: + "(^|/)[.][.]?(/|$)|[^/][*][*]|[*][*][^/]|^[^/]*:|[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]", + }, + }, + }, + }, + { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/parameter.schema.json", + title: "GA4GH IO Profile Parameter Keywords", + description: + "Keywords that bind a parameter of an IO schema (a property of inputs or outputs) to the parameter of the engine, where their names or types differ.", + properties: { + "x-ga4gh-parameter": { + type: "object", + description: + "The engine's parameter for this property of inputs or outputs.", + minProperties: 1, + properties: { + name: { + type: "string", + minLength: 1, + description: + "The name of the parameter in the engine, relative to the entry point (e.g., align.threads for an input of the WDL call align); defaults to the name of the property.", + }, + type: { + type: "string", + minLength: 1, + description: + "The type of the parameter as declared in the workflow language (e.g., Array[File]+ or Pair[Int,String] in WDL, File[]? in CWL), for translators and converters that need more than the JSON Schema type.", + }, + }, + additionalProperties: false, + }, + }, + }, + { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/ui-widgets.schema.json", + title: "GA4GH UI Widgets Vocabulary", + description: + "Controlled vocabulary defining UI rendering hints for input and output properties.", + type: "string", + anyOf: [ + { + enum: [ + "text", + "textarea", + "number", + "slider", + "dropdown", + "typeahead", + "radio", + "checkbox", + "switch", + "date-picker", + "time-picker", + "datetime-picker", + "color-picker", + "file-picker", + "directory-picker", + "tags", + "html-viewer", + "table-viewer", + ], + }, + { + type: "string", + pattern: "^custom:[a-z0-9-]+$", + not: { + pattern: "\\n", + }, + description: + "Custom widget fallback allowing platform-specific experimental UI components (e.g., custom:my-widget).", + }, + ], + $defs: { + inputParameters: { + description: + "The value of properties of inputs: the parameters directly under inputs take no output viewer. A best-effort check: it doesn't reach nested schemas or definitions, where clients ignore viewers on inputs.", + additionalProperties: { + properties: { + "x-ga4gh-ui-widget": { + not: { + enum: ["html-viewer", "table-viewer"], + }, + }, + }, + }, + }, + outputParameters: { + description: + "The value of properties of outputs: the outputs take output viewers and custom widgets only, no input widget. A best-effort check: it doesn't reach nested schemas, where clients ignore input widgets on outputs.", + additionalProperties: { + properties: { + "x-ga4gh-ui-widget": { + not: { + enum: [ + "text", + "textarea", + "number", + "slider", + "dropdown", + "typeahead", + "radio", + "checkbox", + "switch", + "date-picker", + "time-picker", + "datetime-picker", + "color-picker", + "file-picker", + "directory-picker", + "tags", + ], + }, + }, + }, + }, + }, + type: { + description: + 'Rules for the type keyword of a schema with a widget: the type, or an array of types with null (e.g., ["string", "null"]).', + $defs: { + string: { + required: ["type"], + properties: { + type: { + anyOf: [ + { + enum: ["string"], + }, + { + type: "array", + items: { + enum: ["string", "null"], + }, + contains: { + enum: ["string"], + }, + }, + ], + }, + }, + }, + numeric: { + required: ["type"], + properties: { + type: { + anyOf: [ + { + enum: ["integer", "number"], + }, + { + type: "array", + items: { + enum: ["integer", "number", "null"], + }, + contains: { + enum: ["integer", "number"], + }, + }, + ], + }, + }, + }, + boolean: { + required: ["type"], + properties: { + type: { + anyOf: [ + { + enum: ["boolean"], + }, + { + type: "array", + items: { + enum: ["boolean", "null"], + }, + contains: { + enum: ["boolean"], + }, + }, + ], + }, + }, + }, + array: { + required: ["type"], + properties: { + type: { + anyOf: [ + { + enum: ["array"], + }, + { + type: "array", + items: { + enum: ["array", "null"], + }, + contains: { + enum: ["array"], + }, + }, + ], + }, + }, + }, + }, + }, + fit: { + title: "Widget fit", + description: + "The keywords that each widget of the vocabulary needs in the schema that carries it (see the table of widgets in the specification). Applied to every schema; custom widgets are not checked. The keywords must be in the same schema as the widget, not only in a schema that it refers to.", + allOf: [ + { + $comment: "Strings: one line, several lines, or a colour #rrggbb.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["text", "textarea", "color-picker"], + }, + }, + }, + then: { + $ref: "#/$defs/type/$defs/string", + }, + }, + { + $comment: "A number field for integer or number.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["number"], + }, + }, + }, + then: { + $ref: "#/$defs/type/$defs/numeric", + }, + }, + { + $comment: "A slider needs both bounds.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["slider"], + }, + }, + }, + then: { + allOf: [ + { + $ref: "#/$defs/type/$defs/numeric", + }, + { + anyOf: [ + { + required: ["minimum"], + }, + { + required: ["exclusiveMinimum"], + }, + ], + }, + { + anyOf: [ + { + required: ["maximum"], + }, + { + required: ["exclusiveMaximum"], + }, + ], + }, + ], + }, + }, + { + $comment: + "One value of enum, or several (an array whose items have enum).", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["dropdown"], + }, + }, + }, + then: { + anyOf: [ + { + required: ["enum"], + }, + { + allOf: [ + { + $ref: "#/$defs/type/$defs/array", + }, + { + required: ["items"], + properties: { + items: { + type: "object", + required: ["enum"], + }, + }, + }, + ], + }, + ], + }, + }, + { + $comment: "One value of enum.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["radio"], + }, + }, + }, + then: { + required: ["enum"], + }, + }, + { + $comment: + "Suggestions from enum (values restricted) or examples (free text).", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["typeahead"], + }, + }, + }, + then: { + allOf: [ + { + $ref: "#/$defs/type/$defs/string", + }, + { + anyOf: [ + { + required: ["enum"], + }, + { + required: ["examples"], + }, + ], + }, + ], + }, + }, + { + $comment: "A boolean.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["checkbox", "switch"], + }, + }, + }, + then: { + $ref: "#/$defs/type/$defs/boolean", + }, + }, + { + $comment: "An RFC 3339 full-date.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["date-picker"], + }, + }, + }, + then: { + allOf: [ + { + $ref: "#/$defs/type/$defs/string", + }, + { + required: ["format"], + properties: { + format: { + const: "date", + }, + }, + }, + ], + }, + }, + { + $comment: "An RFC 3339 full-time, with offset.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["time-picker"], + }, + }, + }, + then: { + allOf: [ + { + $ref: "#/$defs/type/$defs/string", + }, + { + required: ["format"], + properties: { + format: { + const: "time", + }, + }, + }, + ], + }, + }, + { + $comment: "An RFC 3339 date-time.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["datetime-picker"], + }, + }, + }, + then: { + allOf: [ + { + $ref: "#/$defs/type/$defs/string", + }, + { + required: ["format"], + properties: { + format: { + const: "date-time", + }, + }, + }, + ], + }, + }, + { + $comment: "A file reference to a file.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["file-picker", "html-viewer", "table-viewer"], + }, + }, + }, + then: { + required: ["x-ga4gh-file"], + properties: { + "x-ga4gh-file": { + properties: { + kind: { + const: "file", + }, + }, + }, + }, + }, + }, + { + $comment: "A file reference to a directory.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["directory-picker"], + }, + }, + }, + then: { + required: ["x-ga4gh-file"], + properties: { + "x-ga4gh-file": { + properties: { + kind: { + const: "directory", + }, + }, + }, + }, + }, + }, + { + $comment: "An array of strings, one per tag.", + if: { + required: ["x-ga4gh-ui-widget"], + properties: { + "x-ga4gh-ui-widget": { + enum: ["tags"], + }, + }, + }, + then: { + allOf: [ + { + $ref: "#/$defs/type/$defs/array", + }, + { + required: ["items"], + properties: { + items: { + type: "object", + required: ["type"], + properties: { + type: { + const: "string", + }, + }, + }, + }, + }, + ], + }, + }, + ], + }, + }, + }, + { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/vocabularies/workflow.schema.json", + title: "GA4GH IO Profile Workflow Keywords", + description: + "Keywords of the top level of an IO schema that tie it to one version of a workflow or tool in a TRS and to the engine that runs it. They are allowed only at the top level.", + properties: { + "x-ga4gh-workflow": { + $ref: "#/$defs/workflow", + }, + }, + $defs: { + workflow: { + type: "object", + description: + "The workflow or tool version that the IO schema describes, and the engine binding: the TRS identifiers, the descriptor type, the checksum of the primary descriptor and the entry point.", + required: ["descriptor_type"], + properties: { + trs_tool_id: { + type: "string", + minLength: 1, + description: "The id of the tool in the TRS (Tool.id).", + }, + trs_version_id: { + type: "string", + minLength: 1, + description: + "The id of the tool version in the TRS (ToolVersion.id).", + }, + descriptor_type: { + type: "string", + enum: ["CWL", "WDL", "NFL", "SMK", "GALAXY"], + description: + "The TRS descriptor type of the workflow or tool, which is also the WES workflow_type. An IO schema describes one descriptor type.", + }, + descriptor_type_version: { + type: "string", + minLength: 1, + description: + "The version of the workflow language (e.g., 1.1 for WDL, DSL2 for Nextflow, v1.2 for CWL), as listed in the descriptor_type_version of the TRS tool version; the WES workflow_type_version.", + }, + primary_descriptor_path: { + type: "string", + minLength: 1, + description: + "The path of the primary descriptor (TRS file type PRIMARY_DESCRIPTOR), relative to the root of the tool version's files, as listed by TRS.", + }, + checksum: { + type: "array", + minItems: 1, + description: + "Checksums of the primary descriptor, in the format of TRS checksums.", + items: { + type: "object", + required: ["checksum", "type"], + properties: { + checksum: { + type: "string", + pattern: "^[0-9a-fA-F]+$", + description: + "The hex-encoded checksum of the bytes of the primary descriptor.", + }, + type: { + type: "string", + minLength: 1, + description: + "The checksum algorithm, as in TRS: its Hash Name String in the GA4GH Checksum Hash Algorithm Registry (e.g., sha-256), which includes the IANA names.", + }, + }, + additionalProperties: false, + }, + }, + entry_point: { + type: "string", + minLength: 1, + description: + "The entry point of the engine: the name of the WDL workflow (or of the task, for a document with a single task and no workflow), the Nextflow workflow run with -entry, or the CWL process (e.g., #main in a packed document). Required for WDL, which qualifies the names of inputs with it.", + }, + }, + additionalProperties: false, + if: { + properties: { + descriptor_type: { + const: "WDL", + }, + }, + required: ["descriptor_type"], + }, + then: { + required: ["entry_point"], + }, + }, + }, + }, +]; diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/conformance.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/conformance.ts new file mode 100644 index 00000000..39abd239 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/conformance.ts @@ -0,0 +1,3250 @@ +/** + * The conformance suite of the profile (`tests/conformance/schema-documents/`). + * + * Generated by `scripts/sync-io-schema.mjs` from https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/2c3dc49ad89f0a556272f160369a2a2d7a21dac3 + * (profile version 0.3.0; Apache-2.0, as this package). Don't edit. + */ +/* eslint-disable */ + +/** Documents that a validator must accept, by name. */ +export const VALID: [string, unknown][] = [ + [ + "annotated", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/valid-workflow-schema.json", + title: "Valid Workflow IO Schema", + description: + "An example schema defining inputs and outputs for a bioinformatics workflow.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + description: "The ID of the sample to process.", + "x-ga4gh-ui-widget": "text", + }, + input_bam: { + type: "string", + description: + "The aligned reads file in BAM format, with its index (sample.bai).", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + secondaryFiles: ["^.bai"], + schemes: ["drs"], + }, + "x-ga4gh-ui-widget": "file-picker", + }, + threads: { + type: "integer", + minimum: 1, + default: 8, + "x-ga4gh-ui-widget": "number", + "x-ga4gh-hidden": true, + }, + }, + required: ["sample_id", "input_bam"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + output_vcf: { + type: "string", + description: "The resulting variant calls in VCF format.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_3016", + compression: "bgzip", + secondaryFiles: [".tbi"], + }, + }, + }, + }, + }, + required: ["inputs"], + }, + ], + [ + "description-markdown", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/description-markdown.schema.json", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + description: + 'Reads in **FASTQ** format, see [the format](https://en.wikipedia.org/wiki/FASTQ_format).\n\n![Quality plot](https://example.org/plot.png)\n\nPaired-end reads go into two files.', + "x-ga4gh-description-format": "markdown", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + required: ["reads"], + }, + }, + }, + ], + [ + "error-message-scope", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/error-message-scope.schema.json", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + samples: { + type: "array", + items: { + $ref: "#/$defs/sample_id", + }, + minItems: 1, + "x-ga4gh-error-message": "Give at least one sample", + }, + control: { + $ref: "#/$defs/sample_id", + "x-ga4gh-error-message": "The control is a sample ID such as S1", + }, + }, + required: ["samples"], + }, + }, + $defs: { + sample_id: { + type: "string", + pattern: "^S[0-9]+$", + "x-ga4gh-error-message": + "Sample IDs are S followed by digits, e.g., S1", + }, + }, + }, + ], + [ + "minimal", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/minimal.schema.json", + properties: { + inputs: {}, + }, + }, + ], + [ + "nested", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/nested.schema.json", + $comment: + "Deeply nested parameters: an array of arrays, 8 levels deep, and records nested 4 levels deep with 2 or 3 fields each. A validator that evaluates nested schemas several times per level takes time exponential in the depth here.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "array", + "x-ga4gh-parameter": { + type: "File[][][][][][][][]", + }, + items: { + type: "array", + items: { + type: "array", + items: { + type: "array", + items: { + type: "array", + items: { + type: "array", + items: { + type: "array", + items: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + settings: { + type: "object", + "x-ga4gh-parameter": { + type: "record", + }, + properties: { + a: { + $ref: "#/$defs/level1", + }, + b: { + $ref: "#/$defs/level1", + }, + c: { + $ref: "#/$defs/level1", + }, + }, + }, + }, + }, + }, + $defs: { + level1: { + type: "object", + "x-ga4gh-hidden": false, + properties: { + a: { + type: "object", + properties: { + a: { + type: "object", + properties: { + a: { + type: "string", + "x-ga4gh-hidden": true, + }, + b: { + type: "integer", + "x-ga4gh-ui-widget": "number", + }, + c: { + type: "boolean", + "x-ga4gh-ui-widget": "checkbox", + }, + }, + }, + b: { + type: "object", + properties: { + a: { + type: "string", + "x-ga4gh-hidden": true, + }, + b: { + type: "integer", + "x-ga4gh-ui-widget": "number", + }, + c: { + type: "boolean", + "x-ga4gh-ui-widget": "checkbox", + }, + }, + }, + c: { + type: "object", + properties: { + a: { + type: "string", + "x-ga4gh-hidden": true, + }, + b: { + type: "integer", + "x-ga4gh-ui-widget": "number", + }, + c: { + type: "boolean", + "x-ga4gh-ui-widget": "checkbox", + }, + }, + }, + }, + }, + b: { + type: "object", + properties: { + a: { + type: "object", + properties: { + a: { + type: "string", + "x-ga4gh-hidden": true, + }, + b: { + type: "integer", + "x-ga4gh-ui-widget": "number", + }, + c: { + type: "boolean", + "x-ga4gh-ui-widget": "checkbox", + }, + }, + }, + b: { + type: "object", + properties: { + a: { + type: "string", + "x-ga4gh-hidden": true, + }, + b: { + type: "integer", + "x-ga4gh-ui-widget": "number", + }, + c: { + type: "boolean", + "x-ga4gh-ui-widget": "checkbox", + }, + }, + }, + c: { + type: "object", + properties: { + a: { + type: "string", + "x-ga4gh-hidden": true, + }, + b: { + type: "integer", + "x-ga4gh-ui-widget": "number", + }, + c: { + type: "boolean", + "x-ga4gh-ui-widget": "checkbox", + }, + }, + }, + }, + }, + }, + }, + }, + }, + ], + [ + "other-extension-keywords", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/other-extension-keywords.schema.json", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-my-platform-hint": { + any: "value", + }, + "x-ga4ghost": 1, + }, + }, + }, + }, + }, + ], + [ + "ui-widgets", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/ui-widgets", + title: "Valid: ui-widgets", + description: + "Every widget of the vocabulary on a schema that it fits, including nullable types, a multi-select dropdown, nested inputs and a custom widget.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + name: { + type: "string", + "x-ga4gh-ui-widget": "text", + }, + notes: { + type: ["string", "null"], + "x-ga4gh-ui-widget": "textarea", + }, + threads: { + type: ["integer", "null"], + minimum: 1, + "x-ga4gh-ui-widget": "number", + }, + quality: { + type: "number", + minimum: 0, + exclusiveMaximum: 1, + "x-ga4gh-ui-widget": "slider", + }, + genome: { + type: "string", + enum: ["GRCh38", "GRCm39"], + "x-ga4gh-ui-widget": "dropdown", + }, + stages: { + type: "array", + items: { + enum: ["trim", "align", "count"], + }, + uniqueItems: true, + "x-ga4gh-ui-widget": "dropdown", + }, + species: { + type: "string", + examples: ["Homo sapiens", "Mus musculus"], + "x-ga4gh-ui-widget": "typeahead", + }, + assay: { + type: "string", + enum: ["RNA-seq", "ATAC-seq"], + "x-ga4gh-ui-widget": "typeahead", + }, + strand: { + enum: ["forward", "reverse", "unstranded"], + "x-ga4gh-ui-widget": "radio", + }, + paired: { + type: ["boolean", "null"], + "x-ga4gh-ui-widget": "checkbox", + }, + verbose: { + type: "boolean", + default: false, + "x-ga4gh-ui-widget": "switch", + }, + date: { + type: "string", + format: "date", + "x-ga4gh-ui-widget": "date-picker", + }, + start: { + type: "string", + format: "time", + "x-ga4gh-ui-widget": "time-picker", + }, + deadline: { + type: "string", + format: "date-time", + "x-ga4gh-ui-widget": "datetime-picker", + }, + colour: { + type: "string", + pattern: "^#[0-9a-f]{6}$", + "x-ga4gh-ui-widget": "color-picker", + }, + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-ui-widget": "file-picker", + }, + index: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + "x-ga4gh-ui-widget": "directory-picker", + }, + labels: { + type: ["array", "null"], + items: { + type: "string", + }, + "x-ga4gh-ui-widget": "tags", + }, + advanced: { + type: "object", + properties: { + seed: { + type: "integer", + minimum: 0, + maximum: 99, + "x-ga4gh-ui-widget": "slider", + }, + }, + }, + layout: { + type: "string", + "x-ga4gh-ui-widget": "custom:my-widget", + }, + }, + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-ui-widget": "html-viewer", + }, + counts: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + }, + "x-ga4gh-ui-widget": "table-viewer", + }, + }, + summary: { + type: "string", + "x-ga4gh-ui-widget": "custom:my-viewer", + }, + }, + }, + }, + }, + ], +]; + +/** Documents that a validator must reject, by name (the rule they break). */ +export const INVALID: [string, unknown][] = [ + [ + "description-format-rst", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/description-format-rst", + title: "Invalid: description-format-rst", + description: "The rst description format was removed in version 0.3.0.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + description: "Sample *identifier*.", + "x-ga4gh-description-format": "rst", + }, + }, + }, + }, + }, + ], + [ + "description-format-unknown", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/description-format-unknown", + title: "Invalid: description-format-unknown", + description: + "x-ga4gh-description-format isn't one of the allowed formats.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-description-format": "html", + }, + }, + }, + }, + }, + ], + [ + "draft-keyword-in-tabular", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/draft-keyword-in-tabular.schema.json", + $comment: + "A column of a tabular schema breaks Draft 2020-12: type must name a type.", + properties: { + inputs: { + type: "object", + properties: { + sample_sheet: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + }, + "x-ga4gh-tabular-schema": { + type: "object", + properties: { + condition: { + type: "text", + }, + }, + }, + }, + }, + }, + }, + }, + ], + [ + "draft-keyword-nested-deep", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/draft-keyword-nested-deep.schema.json", + $comment: + "A schema nested deep in arrays of records breaks Draft 2020-12: minLength must be a non-negative integer.", + properties: { + inputs: { + type: "object", + properties: { + samples: { + type: "array", + items: { + type: "object", + properties: { + reads: { + type: "array", + items: { + type: "string", + minLength: -1, + }, + }, + }, + }, + }, + }, + }, + }, + }, + ], + [ + "drs-uri-removed", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/drs-uri-removed", + title: "Invalid: drs-uri-removed", + description: + "x-ga4gh-drs-uri was removed in version 0.3.0; schemes of x-ga4gh-file replaces it.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-drs-uri": true, + }, + }, + }, + }, + }, + ], + ["empty", {}], + [ + "error-message-not-string", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/error-message-not-string", + title: "Invalid: error-message-not-string", + description: "x-ga4gh-error-message is a number, not a string.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-error-message": 404, + }, + }, + }, + }, + }, + ], + [ + "fa-icon-removed", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/fa-icon-removed", + title: "Invalid: fa-icon-removed", + description: "x-ga4gh-fa-icon was removed in version 0.3.0.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-fa-icon": "fas fa-dna", + }, + }, + }, + }, + }, + ], + [ + "file-compression-unknown", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-compression-unknown", + title: "Invalid: file-compression-unknown", + description: "The compression of a file reference is unknown.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + compression: "rar", + }, + }, + }, + }, + }, + }, + ], + [ + "file-content-encoding", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-content-encoding", + title: "Invalid: file-content-encoding", + description: + "A file reference declares a content encoding of the string.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + contentEncoding: "base64", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + ], + [ + "file-content-media-type", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-content-media-type", + title: "Invalid: file-content-media-type", + description: + "A file reference gives the media type of the referenced file in contentMediaType.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + contentMediaType: "text/csv", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + ], + [ + "file-directory-media-type", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-directory-media-type", + title: "Invalid: file-directory-media-type", + description: "A directory reference has a media type.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + mediaType: "text/csv", + }, + }, + }, + }, + }, + }, + ], + [ + "file-directory-secondary", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-directory-secondary", + title: "Invalid: file-directory-secondary", + description: "A directory reference has secondary files.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + secondaryFiles: [".bai"], + }, + }, + }, + }, + }, + }, + ], + [ + "file-format-uri", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-format-uri", + title: "Invalid: file-format-uri", + description: "A file reference also uses format: uri.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + format: "uri", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + ], + [ + "file-in-array-items", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-in-array-items", + title: "Invalid: file-in-array-items", + description: "A file reference in the items of an array is checked too.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "folder", + }, + }, + }, + }, + }, + }, + }, + ], + [ + "file-in-outputs", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-in-outputs", + title: "Invalid: file-in-outputs", + description: + "A file reference of an output doesn't say whether it is a file or a directory.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + compression: "gzip", + }, + }, + }, + }, + }, + }, + ], + [ + "file-in-place-applicator", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-in-place-applicator", + title: "Invalid: file-in-place-applicator", + description: "A file reference brings format: uri back through allOf.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + allOf: [ + { + format: "uri", + }, + ], + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + ], + [ + "file-in-tabular-column", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-in-tabular-column", + title: "Invalid: file-in-tabular-column", + description: + "A file reference in a column of a tabular schema is checked too.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + }, + "x-ga4gh-tabular-schema": { + type: "array", + items: { + type: "object", + properties: { + fastq_1: { + type: "string", + "x-ga4gh-file": {}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + ], + [ + "file-kind-missing", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-kind-missing", + title: "Invalid: file-kind-missing", + description: + "A file reference doesn't say whether it refers to a file or a directory.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + mediaType: "text/csv", + }, + }, + }, + }, + }, + }, + ], + [ + "file-kind-unknown", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-kind-unknown", + title: "Invalid: file-kind-unknown", + description: + "The kind of a file reference is neither file nor directory.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "symlink", + }, + }, + }, + }, + }, + }, + ], + [ + "file-media-type-bad", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-media-type-bad", + title: "Invalid: file-media-type-bad", + description: "The media type of a file reference has no subtype.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "csv", + }, + }, + }, + }, + }, + }, + ], + [ + "file-not-string", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-not-string", + title: "Invalid: file-not-string", + description: "A file reference annotates an integer.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "integer", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + ], + [ + "file-ontology-not-uri", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-ontology-not-uri", + title: "Invalid: file-ontology-not-uri", + description: "The ontology term of a file reference isn't a URI.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "format_2572", + }, + }, + }, + }, + }, + }, + ], + [ + "file-ontology-prefixed", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-ontology-prefixed", + title: "Invalid: file-ontology-prefixed", + description: + "The ontology term of a file reference is a prefixed name, not an HTTP(S) IRI.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "edam:format_2572", + }, + }, + }, + }, + }, + }, + ], + [ + "file-scheme-bad", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-scheme-bad", + title: "Invalid: file-scheme-bad", + description: "A file reference allows the javascript scheme.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + schemes: ["https", "javascript"], + }, + }, + }, + }, + }, + }, + ], + [ + "file-scheme-pattern-bad", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-scheme-pattern-bad", + title: "Invalid: file-scheme-pattern-bad", + description: "A scheme of a file reference has the separator.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + schemes: ["s3://"], + }, + }, + }, + }, + }, + }, + ], + [ + "file-schemes-empty", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-schemes-empty", + title: "Invalid: file-schemes-empty", + description: "A file reference has an empty list of schemes.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + schemes: [], + }, + }, + }, + }, + }, + }, + ], + [ + "file-secondary-dots", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-secondary-dots", + title: "Invalid: file-secondary-dots", + description: + "A secondary file pattern has only dots, which could name the parent directory.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: ["^.."], + }, + }, + }, + }, + }, + }, + ], + [ + "file-secondary-pattern-bad", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-secondary-pattern-bad", + title: "Invalid: file-secondary-pattern-bad", + description: "A secondary file pattern is a path, not a suffix.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: ["../etc/passwd"], + }, + }, + }, + }, + }, + }, + ], + [ + "file-type-missing", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-type-missing", + title: "Invalid: file-type-missing", + description: "A file reference annotates a schema without a type.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + ], + [ + "file-unknown-key", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/file-unknown-key", + title: "Invalid: file-unknown-key", + description: + "A file reference has a key that the annotation doesn't define.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mimetype: "text/csv", + }, + }, + }, + }, + }, + }, + ], + [ + "foreign-schema", + { + $schema: "http://json-schema.org/draft-07/schema#", + $id: "https://example.org/schemas/invalid/foreign-schema", + title: "Invalid: foreign-schema", + description: + "The schema names another meta-schema (JSON Schema draft-07) in $schema.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "hidden-not-boolean", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/hidden-not-boolean", + title: "Invalid: hidden-not-boolean", + description: "x-ga4gh-hidden is a string, not a boolean.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-hidden": "true", + }, + }, + }, + }, + }, + ], + [ + "id-branch-url", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://raw.githubusercontent.com/example/workflows/refs/heads/dev/ga4gh-io.schema.json", + title: "Invalid: id-branch-url", + description: "The $id names a branch, which moves, not a version.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "id-relative", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "schemas/my-workflow/v1", + title: "Invalid: id-relative", + description: "The $id is a relative reference, not an absolute URI.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "missing-inputs", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/missing-inputs", + title: "Invalid: missing-inputs", + description: "The inputs/outputs wrapper lacks the mandatory inputs.", + type: "object", + properties: { + outputs: { + type: "object", + }, + }, + }, + ], + [ + "missing-schema", + { + $id: "https://example.org/schemas/invalid/missing-schema", + title: "Invalid: missing-schema", + description: "The schema doesn't name the meta-schema in $schema.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "misspelled-keyword", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/misspelled-keyword", + title: "Invalid: misspelled-keyword", + description: + "x-ga4gh-ui-widgte is a misspelled (unknown) x-ga4gh-* keyword.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-ui-widgte": "text", + }, + }, + }, + }, + }, + ], + [ + "not-object-type", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/not-object-type", + title: "Invalid: not-object-type", + description: "The top-level type isn't object.", + type: "array", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "ontology-not-string", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ontology-not-string", + title: "Invalid: ontology-not-string", + description: "x-ga4gh-ontology is a number, not a URI string.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-ontology": 42, + }, + }, + }, + }, + }, + ], + [ + "ontology-not-uri", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ontology-not-uri", + title: "Invalid: ontology-not-uri", + description: "x-ga4gh-ontology is a string, but not a URI.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-ontology": "format_1929", + }, + }, + }, + }, + }, + ], + [ + "output-glob-absolute", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-absolute", + title: "Invalid: output-glob-absolute", + description: + "An output glob is an absolute path, not relative to the output directory.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-output-glob": "/results/*.html", + }, + }, + }, + }, + }, + ], + [ + "output-glob-backslash", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-backslash", + title: "Invalid: output-glob-backslash", + description: + "An output glob has a backslash, which the profile doesn't define.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-output-glob": "results\\*.html", + }, + }, + }, + }, + }, + ], + [ + "output-glob-braces", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-braces", + title: "Invalid: output-glob-braces", + description: + "An output glob uses brace expansion, which the profile doesn't define.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-output-glob": "results/*.{html,htm}", + }, + }, + }, + }, + }, + ], + [ + "output-glob-double-star", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-double-star", + title: "Invalid: output-glob-double-star", + description: "'**' of an output glob is not a whole segment.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-output-glob": "results/**.html", + }, + }, + }, + }, + }, + ], + [ + "output-glob-empty-segment", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-empty-segment", + title: "Invalid: output-glob-empty-segment", + description: "An output glob has an empty segment.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-output-glob": "results//report.html", + }, + }, + }, + }, + }, + ], + [ + "output-glob-items-not-file", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-items-not-file", + title: "Invalid: output-glob-items-not-file", + description: + "An output glob is on a list whose items are not file references.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "array", + items: { + type: "string", + }, + "x-ga4gh-output-glob": "logs/*.txt", + }, + }, + }, + }, + }, + ], + [ + "output-glob-not-file", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-not-file", + title: "Invalid: output-glob-not-file", + description: + "An output glob is on a string output that is not a file reference.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-output-glob": "version.txt", + }, + }, + }, + }, + }, + ], + [ + "output-glob-not-string", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-not-string", + title: "Invalid: output-glob-not-string", + description: "An output glob is not a string.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-output-glob": 3, + }, + }, + }, + }, + }, + ], + [ + "output-glob-on-scalar", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-on-scalar", + title: "Invalid: output-glob-on-scalar", + description: + "An output glob is on an output that is not a file reference or a list of them.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "integer", + "x-ga4gh-output-glob": "count.txt", + }, + }, + }, + }, + }, + ], + [ + "output-glob-parent", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-parent", + title: "Invalid: output-glob-parent", + description: + "An output glob leaves the output directory with a '..' segment.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-output-glob": "../secrets/*.txt", + }, + }, + }, + }, + }, + ], + [ + "output-glob-tuple", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/output-glob-tuple", + title: "Invalid: output-glob-tuple", + description: + "An output glob is on a tuple (prefixItems), whose slots a list of found files can't fill.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "object", + properties: { + report: { + type: "array", + prefixItems: [ + { + type: "integer", + }, + ], + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + "x-ga4gh-output-glob": "*.bam", + }, + }, + }, + }, + }, + ], + [ + "outputs-applicator", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/outputs-applicator", + title: "Invalid: outputs-applicator", + description: + "The outputs hide their properties behind a reference instead of listing them directly.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + $ref: "#/$defs/outputs", + }, + }, + $defs: { + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + ], + [ + "outputs-boolean", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/outputs-boolean", + title: "Invalid: outputs-boolean", + description: "The outputs are a boolean schema, not an object schema.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: true, + }, + }, + ], + [ + "outputs-nested", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/outputs-nested", + title: "Invalid: outputs-nested", + description: "A schema nested in the outputs breaks a keyword rule.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-ui-widget": 3, + }, + }, + }, + }, + }, + ], + [ + "outputs-not-object-type", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/outputs-not-object-type", + title: "Invalid: outputs-not-object-type", + description: "The outputs are not an object.", + type: "object", + properties: { + inputs: { + type: "object", + }, + outputs: { + type: "array", + }, + }, + }, + ], + [ + "parameter-empty", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/parameter-empty", + title: "Invalid: parameter-empty", + description: "x-ga4gh-parameter is empty.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-parameter": {}, + }, + }, + }, + }, + }, + ], + [ + "parameter-name-empty", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/parameter-name-empty", + title: "Invalid: parameter-name-empty", + description: "The engine name of a parameter is an empty string.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-parameter": { + name: "", + }, + }, + }, + }, + }, + }, + ], + [ + "parameter-not-object", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/parameter-not-object", + title: "Invalid: parameter-not-object", + description: "x-ga4gh-parameter is a string, not an object.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-parameter": "wf.sample_id", + }, + }, + }, + }, + }, + ], + [ + "parameter-unknown-field", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/parameter-unknown-field", + title: "Invalid: parameter-unknown-field", + description: "x-ga4gh-parameter has a field it doesn't define.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-parameter": { + name: "sample", + default: "x", + }, + }, + }, + }, + }, + }, + ], + [ + "plain-json-schema", + { + $schema: "https://json-schema.org/draft/2020-12/schema", + properties: { + inputs: {}, + }, + }, + ], + [ + "tabular-schema-nested", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/tabular-schema-nested", + title: "Invalid: tabular-schema-nested", + description: + "A schema nested in x-ga4gh-tabular-schema breaks a keyword rule.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-tabular-schema": { + type: "array", + items: { + type: "object", + properties: { + condition: { + type: "string", + "x-ga4gh-hidden": "no", + }, + }, + }, + }, + }, + }, + }, + }, + }, + ], + [ + "ui-widget-checkbox-string", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-checkbox-string", + title: "Invalid: ui-widget-checkbox-string", + description: "The checkbox widget is on a string.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + paired: { + type: "string", + "x-ga4gh-ui-widget": "checkbox", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-color-picker-integer", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-color-picker-integer", + title: "Invalid: ui-widget-color-picker-integer", + description: "The color-picker widget is on an integer.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + colour: { + type: "integer", + "x-ga4gh-ui-widget": "color-picker", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-custom-newline", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-custom-newline", + title: "Invalid: ui-widget-custom-newline", + description: + "x-ga4gh-ui-widget names a custom widget with a trailing newline, which Python's '$' would otherwise accept.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-ui-widget": "custom:my-widget\n", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-date-picker-no-format", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-date-picker-no-format", + title: "Invalid: ui-widget-date-picker-no-format", + description: "The date-picker widget is on a string without format date.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + date: { + type: "string", + "x-ga4gh-ui-widget": "date-picker", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-datetime-picker-date", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-datetime-picker-date", + title: "Invalid: ui-widget-datetime-picker-date", + description: + "The datetime-picker widget is on a string with format date.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + date: { + type: "string", + format: "date", + "x-ga4gh-ui-widget": "datetime-picker", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-deferred-viewer", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-deferred-viewer", + title: "Invalid: ui-widget-deferred-viewer", + description: + "The genome-browser viewer is deferred: version 0.3.0 has no viewers other than table-viewer and html-viewer.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + outputs: { + type: "object", + properties: { + alignment: { + type: "string", + "x-ga4gh-ui-widget": "genome-browser", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-directory-picker-file", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-directory-picker-file", + title: "Invalid: ui-widget-directory-picker-file", + description: + "The directory-picker widget is on a file reference to a file.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + index: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-ui-widget": "directory-picker", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-directory-picker-no-file", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-directory-picker-no-file", + title: "Invalid: ui-widget-directory-picker-no-file", + description: + "The directory-picker widget is on a string without x-ga4gh-file.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + index: { + type: "string", + "x-ga4gh-ui-widget": "directory-picker", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-dropdown-items-no-enum", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-dropdown-items-no-enum", + title: "Invalid: ui-widget-dropdown-items-no-enum", + description: + "The dropdown widget is on an array whose items have no enum.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + stages: { + type: "array", + items: { + type: "string", + }, + "x-ga4gh-ui-widget": "dropdown", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-dropdown-no-enum", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-dropdown-no-enum", + title: "Invalid: ui-widget-dropdown-no-enum", + description: "The dropdown widget is on a string without enum.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + genome: { + type: "string", + "x-ga4gh-ui-widget": "dropdown", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-file-picker-directory", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-file-picker-directory", + title: "Invalid: ui-widget-file-picker-directory", + description: + "The file-picker widget is on a file reference to a directory.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + "x-ga4gh-ui-widget": "file-picker", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-file-picker-no-file", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-file-picker-no-file", + title: "Invalid: ui-widget-file-picker-no-file", + description: + "The file-picker widget is on a string without x-ga4gh-file.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-ui-widget": "file-picker", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-input-on-output", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-input-on-output", + title: "Invalid: ui-widget-input-on-output", + description: "The file-picker widget, an input widget, is on an output.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-ui-widget": "file-picker", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-no-type", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-no-type", + title: "Invalid: ui-widget-no-type", + description: "The text widget is on a schema without type.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + name: { + "x-ga4gh-ui-widget": "text", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-null-type", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-null-type", + title: "Invalid: ui-widget-null-type", + description: "The text widget is on a schema whose only type is null.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + name: { + type: ["null"], + "x-ga4gh-ui-widget": "text", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-number-string", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-number-string", + title: "Invalid: ui-widget-number-string", + description: "The number widget is on a string.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + threads: { + type: "string", + "x-ga4gh-ui-widget": "number", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-password", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-password", + title: "Invalid: ui-widget-password", + description: "The password widget was removed in version 0.3.0.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-ui-widget": "password", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-radio-no-enum", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-radio-no-enum", + title: "Invalid: ui-widget-radio-no-enum", + description: "The radio widget is on a string without enum.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + strand: { + type: "string", + "x-ga4gh-ui-widget": "radio", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-ref-only", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-ref-only", + title: "Invalid: ui-widget-ref-only", + description: + "The slider widget gets its type and bounds only through $ref, not in the schema that carries it.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + level: { + $ref: "#/$defs/count", + "x-ga4gh-ui-widget": "slider", + }, + }, + }, + }, + $defs: { + count: { + type: "integer", + minimum: 0, + maximum: 9, + }, + }, + }, + ], + [ + "ui-widget-slider-no-maximum", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-slider-no-maximum", + title: "Invalid: ui-widget-slider-no-maximum", + description: "The slider widget is on a number without an upper bound.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + level: { + type: "number", + minimum: 0, + "x-ga4gh-ui-widget": "slider", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-slider-no-minimum", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-slider-no-minimum", + title: "Invalid: ui-widget-slider-no-minimum", + description: "The slider widget is on an integer without a lower bound.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + level: { + type: "integer", + maximum: 9, + "x-ga4gh-ui-widget": "slider", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-slider-string", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-slider-string", + title: "Invalid: ui-widget-slider-string", + description: "The slider widget is on a string.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + level: { + type: "string", + minimum: 0, + maximum: 9, + "x-ga4gh-ui-widget": "slider", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-switch-integer", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-switch-integer", + title: "Invalid: ui-widget-switch-integer", + description: "The switch widget is on an integer.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + verbose: { + type: "integer", + "x-ga4gh-ui-widget": "switch", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-tags-integer-items", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-tags-integer-items", + title: "Invalid: ui-widget-tags-integer-items", + description: "The tags widget is on an array of integers.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + labels: { + type: "array", + items: { + type: "integer", + }, + "x-ga4gh-ui-widget": "tags", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-tags-nullable-items", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-tags-nullable-items", + title: "Invalid: ui-widget-tags-nullable-items", + description: "The tags widget is on an array whose items may be null.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + labels: { + type: "array", + items: { + type: ["string", "null"], + }, + "x-ga4gh-ui-widget": "tags", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-tags-string", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-tags-string", + title: "Invalid: ui-widget-tags-string", + description: + "The tags widget is on a string (a delimited string), not an array of strings.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + labels: { + type: "string", + "x-ga4gh-ui-widget": "tags", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-text-integer", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-text-integer", + title: "Invalid: ui-widget-text-integer", + description: "The text widget is on an integer.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + count: { + type: "integer", + "x-ga4gh-ui-widget": "text", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-textarea-integer", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-textarea-integer", + title: "Invalid: ui-widget-textarea-integer", + description: "The textarea widget is on an integer.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + notes: { + type: "integer", + "x-ga4gh-ui-widget": "textarea", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-time-picker-no-format", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-time-picker-no-format", + title: "Invalid: ui-widget-time-picker-no-format", + description: "The time-picker widget is on a string without format time.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + start: { + type: "string", + "x-ga4gh-ui-widget": "time-picker", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-typeahead-integer", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-typeahead-integer", + title: "Invalid: ui-widget-typeahead-integer", + description: "The typeahead widget is on an integer.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + count: { + type: "integer", + enum: [1, 2], + "x-ga4gh-ui-widget": "typeahead", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-typeahead-no-suggestions", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-typeahead-no-suggestions", + title: "Invalid: ui-widget-typeahead-no-suggestions", + description: + "The typeahead widget is on a string without enum or examples.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + species: { + type: "string", + "x-ga4gh-ui-widget": "typeahead", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-unknown", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-unknown", + title: "Invalid: ui-widget-unknown", + description: + "x-ga4gh-ui-widget names a widget that the vocabulary doesn't define.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-ui-widget": "banana", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-viewer-directory", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-viewer-directory", + title: "Invalid: ui-widget-viewer-directory", + description: + "The html-viewer widget is on a file reference to a directory.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + "x-ga4gh-ui-widget": "html-viewer", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-viewer-no-file", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-viewer-no-file", + title: "Invalid: ui-widget-viewer-no-file", + description: + "The table-viewer widget is on an output that is not a file reference.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + outputs: { + type: "object", + properties: { + summary: { + type: "string", + "x-ga4gh-ui-widget": "table-viewer", + }, + }, + }, + }, + }, + ], + [ + "ui-widget-viewer-on-input", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/ui-widget-viewer-on-input", + title: "Invalid: ui-widget-viewer-on-input", + description: "The html-viewer widget, an output viewer, is on an input.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-ui-widget": "html-viewer", + }, + }, + }, + }, + }, + ], + [ + "workflow-checksum-empty", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-checksum-empty", + title: "Invalid: workflow-checksum-empty", + description: "checksum, if present, lists at least one checksum.", + type: "object", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + entry_point: "align", + checksum: [], + }, + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "workflow-checksum-no-type", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-checksum-no-type", + title: "Invalid: workflow-checksum-no-type", + description: "A checksum lacks its algorithm.", + type: "object", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + entry_point: "align", + checksum: [ + { + checksum: "ab12", + }, + ], + }, + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "workflow-checksum-not-hex", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-checksum-not-hex", + title: "Invalid: workflow-checksum-not-hex", + description: "The checksum of the primary descriptor isn't hex-encoded.", + type: "object", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + entry_point: "align", + checksum: [ + { + type: "sha-256", + checksum: "not-hex", + }, + ], + }, + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "workflow-descriptor-type-missing", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-descriptor-type-missing", + title: "Invalid: workflow-descriptor-type-missing", + description: "x-ga4gh-workflow lacks descriptor_type.", + type: "object", + "x-ga4gh-workflow": { + entry_point: "align", + }, + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "workflow-descriptor-type-unknown", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-descriptor-type-unknown", + title: "Invalid: workflow-descriptor-type-unknown", + description: "descriptor_type isn't a TRS descriptor type.", + type: "object", + "x-ga4gh-workflow": { + descriptor_type: "Nextflow", + }, + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "workflow-entry-point-missing", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-entry-point-missing", + title: "Invalid: workflow-entry-point-missing", + description: "A WDL schema lacks the entry point (the workflow name).", + type: "object", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + }, + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "workflow-misspelled", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-misspelled", + title: "Invalid: workflow-misspelled", + description: + "x-ga4gh-workflw is a misspelled (unknown) top-level keyword.", + type: "object", + "x-ga4gh-workflw": { + descriptor_type: "NFL", + }, + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "workflow-nested-defs", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-nested-defs", + title: "Invalid: workflow-nested-defs", + description: "x-ga4gh-workflow is not allowed in $defs.", + type: "object", + $defs: { + sample: { + type: "string", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + entry_point: "align", + }, + }, + }, + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + $ref: "#/$defs/sample", + }, + }, + }, + }, + }, + ], + [ + "workflow-nested-tabular", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-nested-tabular", + title: "Invalid: workflow-nested-tabular", + description: "x-ga4gh-workflow is not allowed in a tabular schema.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-tabular-schema": { + type: "array", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + entry_point: "align", + }, + }, + }, + }, + }, + }, + }, + ], + [ + "workflow-nested", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-nested", + title: "Invalid: workflow-nested", + description: "x-ga4gh-workflow is allowed only at the top level.", + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + entry_point: "align", + }, + }, + }, + }, + }, + }, + ], + [ + "workflow-not-object", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-not-object", + title: "Invalid: workflow-not-object", + description: "x-ga4gh-workflow is a string, not an object.", + type: "object", + "x-ga4gh-workflow": "WDL", + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "workflow-trs-tool-id-empty", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-trs-tool-id-empty", + title: "Invalid: workflow-trs-tool-id-empty", + description: "trs_tool_id is an empty string.", + type: "object", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + entry_point: "align", + trs_tool_id: "", + }, + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], + [ + "workflow-unknown-field", + { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/invalid/workflow-unknown-field", + title: "Invalid: workflow-unknown-field", + description: + "tool_id is not a field of x-ga4gh-workflow (trs_tool_id is).", + type: "object", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + entry_point: "align", + tool_id: "my-tool", + }, + properties: { + inputs: { + type: "object", + properties: { + sample_id: { + type: "string", + }, + }, + }, + }, + }, + ], +]; diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/examples.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/examples.ts new file mode 100644 index 00000000..247ac21c --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/examples.ts @@ -0,0 +1,1012 @@ +/** + * Example IO schemas of the profile (`tests/data/`, `examples/`). + * + * Generated by `scripts/sync-io-schema.mjs` from https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/2c3dc49ad89f0a556272f160369a2a2d7a21dac3 + * (profile version 0.3.0; Apache-2.0, as this package). Don't edit. + */ +/* eslint-disable */ + +export const EXAMPLES: Record> = { + example_tool: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/bwa-mem/cwl/0.7.17", + title: "BWA MEM Aligner", + description: "Burrows-Wheeler Aligner for short read mapping.", + "x-ga4gh-workflow": { + trs_tool_id: "#tool/example.org/bwa-mem", + trs_version_id: "0.7.17", + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + primary_descriptor_path: "bwa-mem.cwl", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reference_fasta: { + type: "string", + title: "Reference FASTA", + description: + "Reference genome, indexed with bwa index; the five index files lie next to it.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_1929", + secondaryFiles: [".amb", ".ann", ".bwt", ".pac", ".sa"], + }, + }, + read_1: { + type: "string", + title: "Read 1 FASTQ", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_1930", + compression: "gzip", + }, + }, + read_2: { + type: "string", + title: "Read 2 FASTQ", + description: "Mates of read_1, for paired-end reads.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_1930", + compression: "gzip", + }, + }, + threads: { + type: "integer", + minimum: 1, + default: 4, + title: "CPU Threads", + }, + }, + required: ["reference_fasta", "read_1"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + alignment_bam: { + type: "string", + title: "Aligned BAM", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + }, + }, + }, + required: ["alignment_bam"], + additionalProperties: false, + }, + }, + }, + example_wdl: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/variant-calling/wdl/1.2.0", + title: "Germline Variant Calling", + description: "Calls germline variants from aligned reads.", + "x-ga4gh-workflow": { + trs_tool_id: "#workflow/example.org/variant-calling", + trs_version_id: "1.2.0", + descriptor_type: "WDL", + descriptor_type_version: "1.1", + primary_descriptor_path: "workflows/variant_calling.wdl", + checksum: [ + { + type: "sha-256", + checksum: + "9c1e4a7f2b5d8e0a3c6f9b2e5d8a1c4f7b0e3a6d9c2f5b8e1a4d7c0f3b6e9a2d", + }, + ], + entry_point: "variant_calling", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + input_bam: { + type: "string", + title: "Aligned reads (BAM)", + description: "Coordinate-sorted reads; the index lies next to it.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + secondaryFiles: [".bai"], + }, + "x-ga4gh-parameter": { + type: "File", + }, + }, + sample_names: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + title: "Sample names", + "x-ga4gh-parameter": { + type: "Array[String]+", + }, + }, + caller_threads: { + type: "integer", + minimum: 1, + default: 4, + title: "Threads of the variant caller", + "x-ga4gh-parameter": { + name: "call_variants.threads", + type: "Int", + }, + }, + }, + required: ["input_bam", "sample_names"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + variants_vcf: { + type: "string", + title: "Variant calls (VCF)", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_3016", + }, + "x-ga4gh-parameter": { + name: "vcf", + type: "File", + }, + }, + }, + }, + }, + }, + example_workflow: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/nfl/1.0.0", + title: "RNA-Seq Pipeline", + description: "Bulk RNA-Seq alignment and QC workflow.", + "x-ga4gh-workflow": { + trs_tool_id: "#workflow/example.org/rna-seq", + trs_version_id: "1.0.0", + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + primary_descriptor_path: "main.nf", + checksum: [ + { + type: "sha-256", + checksum: + "3f7a2c9e1b4d6f8a0c2e4b6d8f1a3c5e7b9d0f2a4c6e8b1d3f5a7c9e0b2d4f6a", + }, + ], + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_manifest: { + type: "string", + title: "Sample Manifest", + description: + "CSV sample sheet containing biological replicate information.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + schemes: ["drs", "https"], + }, + "x-ga4gh-tabular-schema": { + type: "array", + description: + "Experimental hint: the expected columns of the CSV sample sheet (not a validation rule).", + items: { + type: "object", + properties: { + sample_id: { + type: "string", + title: "Sample ID", + pattern: "^[a-zA-Z0-9_]+$", + }, + fastq_1: { + type: "string", + title: "Read 1 FASTQ", + "x-ga4gh-file": { + kind: "file", + compression: "gzip", + }, + }, + condition: { + type: "string", + title: "Condition", + enum: ["control", "treatment"], + }, + }, + required: ["sample_id", "fastq_1", "condition"], + }, + }, + }, + genome_index: { + type: "string", + title: "Genome Index", + description: + "Directory with the index of the reference genome for the aligner.", + "x-ga4gh-file": { + kind: "directory", + }, + }, + known_variants: { + type: "string", + title: "Known Variants", + description: + "Variants to mask during QC, as a VCF file indexed with tabix.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_3016", + compression: "bgzip", + secondaryFiles: [".tbi"], + }, + }, + }, + required: ["sample_manifest", "genome_index"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + title: "QC HTML Report", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + "x-ga4gh-ui-widget": "html-viewer", + "x-ga4gh-output-glob": "multiqc/multiqc_report.html", + }, + alignments: { + type: "array", + title: "Aligned Reads", + description: + "One BAM file per sample, each with its index next to it.", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + secondaryFiles: [".bai"], + }, + }, + "x-ga4gh-output-glob": "alignments/*.bam", + }, + gene_counts: { + type: "object", + title: "Gene Counts", + description: "Gene counts per sample, keyed by sample ID.", + additionalProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/tab-separated-values", + }, + "x-ga4gh-ui-widget": "table-viewer", + }, + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + title: "Samples Passing QC", + }, + }, + required: ["qc_report", "alignments"], + additionalProperties: false, + }, + }, + }, + demo: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + title: "I/O Schema demo", + description: + "Filters aligned reads by mapping quality and flags, sorts and indexes them, and reports alignment statistics.", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + descriptor_type_version: "1.1", + entry_point: "io_schema_demo", + checksum: [ + { + type: "sha-256", + checksum: + "505fa515d58e09e758a2c131398a26b7e1b9e4243899dce96c005cda4c790a65", + }, + ], + trs_tool_id: "ga4gh-io-schema-demo", + trs_version_id: "1.1.0", + primary_descriptor_path: "demo.wdl", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + schemes: ["https", "s3"], + }, + description: + "Reads aligned to a reference, in BAM format, in any order.", + title: "Aligned reads (BAM)", + "x-ga4gh-parameter": { + type: "File", + }, + examples: [ + "https://raw.githubusercontent.com/nf-core/test-datasets/3e548a3b34994380db1602506e0721fadbad6de1/data/genomics/sarscov2/illumina/bam/test.paired_end.bam", + ], + }, + min_mapq: { + type: "integer", + description: + "Reads with a lower mapping quality are removed (0 keeps all reads).", + title: "Minimum mapping quality", + default: 0, + "x-ga4gh-parameter": { + type: "Int", + }, + minimum: 0, + maximum: 60, + "x-ga4gh-ui-widget": "slider", + "x-ga4gh-error-message": + "The minimum mapping quality is a whole number from 0 to 60", + }, + read_filter: { + type: "string", + description: + "Which reads to keep besides the mapping quality: all, properly paired only, or primary alignments only.", + title: "Read filter", + enum: ["none", "proper_pairs", "primary_only"], + default: "none", + "x-ga4gh-parameter": { + type: "String", + }, + "x-ga4gh-ui-widget": "radio", + }, + }, + required: ["reads"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + filtered_bam: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + }, + description: "The filtered reads, sorted by coordinate.", + title: "Filtered reads (BAM)", + "x-ga4gh-parameter": { + type: "File", + }, + }, + filtered_bam_index: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_3327", + }, + description: "The index of the filtered reads.", + title: "Index of the filtered reads (BAI)", + "x-ga4gh-parameter": { + type: "File", + }, + }, + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + description: "Statistics of the reads before and after filtering.", + title: "Alignment report (HTML)", + "x-ga4gh-parameter": { + type: "File", + }, + "x-ga4gh-ui-widget": "html-viewer", + }, + read_counts: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/tab-separated-values", + }, + description: + "Mapped and unmapped reads per reference sequence, before and after filtering; unmapped reads without a position are counted under *.", + title: "Read counts per reference (TSV)", + "x-ga4gh-parameter": { + type: "File", + }, + "x-ga4gh-ui-widget": "table-viewer", + }, + }, + required: [ + "filtered_bam", + "filtered_bam_index", + "report", + "read_counts", + ], + additionalProperties: false, + }, + }, + }, + "greetings-nextflow": { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + title: "Greetings", + description: "Greets people by name, in one of a few languages.", + "x-ga4gh-workflow": { + trs_tool_id: "io-schema-greetings", + trs_version_id: "1.0.0", + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + primary_descriptor_path: "main.nf", + checksum: [ + { + type: "sha-256", + checksum: + "1d19b64fc8fdadd9dd5b7d599e551d9e32f2447347200b07563403c05455d9de", + }, + ], + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + names: { + type: "array", + title: "Names", + description: "Who to greet, one name per line.", + items: { + type: "string", + pattern: "^[A-Za-z][A-Za-z .-]*$", + "x-ga4gh-error-message": + "A name starts with a letter and has only letters, spaces, dots and dashes", + }, + minItems: 1, + maxItems: 10, + default: ["Ada", "Grace"], + "x-ga4gh-error-message": "Give one to ten names", + }, + language: { + type: "string", + title: "Language", + enum: ["en", "de", "fr", "it"], + default: "en", + "x-ga4gh-ui-widget": "radio", + }, + times: { + type: "integer", + title: "How many times", + description: "How often each greeting is repeated.", + minimum: 1, + maximum: 5, + default: 1, + "x-ga4gh-ui-widget": "slider", + }, + shout: { + type: "boolean", + title: "Shout", + description: "Write the greetings in capitals.", + default: false, + "x-ga4gh-ui-widget": "checkbox", + }, + outdir: { + type: "string", + title: "Output directory", + description: "Where the run writes the greetings.", + default: "results", + "x-ga4gh-hidden": true, + }, + }, + required: ["names"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + greetings: { + type: "array", + title: "Greetings", + description: "One text file per name.", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/plain", + }, + }, + "x-ga4gh-output-glob": "results/*.txt", + }, + }, + additionalProperties: false, + }, + }, + }, + "report-snakemake": { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + title: "Little report", + description: + "Writes a small HTML report with a title, a date, notes and a colour.", + "x-ga4gh-workflow": { + trs_tool_id: "io-schema-report", + trs_version_id: "1.0.0", + descriptor_type: "SMK", + descriptor_type_version: "8", + primary_descriptor_path: "Snakefile", + checksum: [ + { + type: "sha-256", + checksum: + "6a2db7f3a57ee349752f0c98da86936f3cd7b2f05436e1263ff38708ad85a5a6", + }, + ], + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + title: { + type: "string", + title: "Title", + minLength: 1, + maxLength: 80, + "x-ga4gh-error-message": "The title has 1 to 80 characters", + }, + date: { + type: "string", + title: "Date", + format: "date", + "x-ga4gh-ui-widget": "date-picker", + }, + notes: { + type: "string", + title: "Notes", + description: "Free text, on several lines.", + default: "", + "x-ga4gh-ui-widget": "textarea", + }, + colour: { + type: "string", + title: "Colour", + pattern: "^#[0-9a-f]{6}$", + default: "#1f77b4", + "x-ga4gh-ui-widget": "color-picker", + }, + }, + required: ["title", "date"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + title: "Report (HTML)", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + "x-ga4gh-ui-widget": "html-viewer", + "x-ga4gh-output-glob": "results/report.html", + }, + }, + required: ["report"], + additionalProperties: false, + }, + }, + }, + "word-count-cwl": { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + title: "Count words", + description: "Counts the lines, words or characters of a text file.", + "x-ga4gh-workflow": { + trs_tool_id: "io-schema-word-count", + trs_version_id: "1.0.0", + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + primary_descriptor_path: "wc.cwl", + checksum: [ + { + type: "sha-256", + checksum: + "75431e88e519962aa8a2b1109dce230685eba243300c615f1cf6db393d79034f", + }, + ], + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + text: { + type: "string", + title: "Text file", + description: "A plain text file, by its URL.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2330", + schemes: ["https"], + }, + "x-ga4gh-parameter": { + type: "File", + }, + examples: [ + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/README.md", + ], + }, + unit: { + type: "string", + title: "What to count", + enum: ["lines", "words", "characters"], + default: "words", + "x-ga4gh-ui-widget": "dropdown", + }, + }, + required: ["text"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + count: { + type: "string", + title: "Count", + description: + "The count and the name of the file, as wc prints them.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/plain", + }, + "x-ga4gh-parameter": { + type: "File", + }, + }, + }, + required: ["count"], + additionalProperties: false, + }, + }, + }, + "nextflow-fetchngs": { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + }, + type: "object", + properties: { + inputs: { + title: "nf-core/fetchngs pipeline parameters", + description: + "Pipeline to fetch metadata and raw FastQ files from public databases", + type: "object", + allOf: [ + { + $ref: "#/$defs/input_output_options", + }, + { + $ref: "#/$defs/institutional_config_options", + }, + { + $ref: "#/$defs/max_job_request_options", + }, + { + $ref: "#/$defs/generic_options", + }, + { + $ref: "#/$defs/deprecated_options", + }, + ], + }, + outputs: { + type: "object", + properties: {}, + }, + }, + $defs: { + input_output_options: { + title: "Input/output options", + type: "object", + description: + "Define where the pipeline should find input data and save output data.", + required: ["input", "outdir"], + properties: { + input: { + type: "string", + pattern: "^\\S+\\.(csv|tsv|txt)$", + description: + "File containing SRA/ENA/GEO/DDBJ identifiers one per line to download their associated metadata and FastQ files.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + }, + "x-ga4gh-tabular-schema": { + title: "nf-core/fetchngs pipeline - params.input schema", + description: "Schema for the file provided with params.input", + type: "array", + items: { + type: "object", + properties: { + "": { + type: "string", + pattern: + "^(((SR|ER|DR)[APRSX])|(SAM(N|EA|D))|(PRJ(NA|EB|DB))|(GS[EM]))(\\d+)$", + "x-ga4gh-error-message": + "Please provide a valid SRA, ENA, DDBJ or GEO identifier", + }, + }, + }, + }, + }, + ena_metadata_fields: { + type: "string", + description: + "Comma-separated list of ENA metadata fields to fetch before downloading data.\n\nThe default list of fields used by the pipeline can be found at the top of the [`bin/sra_ids_to_runinfo.py`](https://github.com/nf-core/fetchngs/blob/master/bin/sra_ids_to_runinfo.py) script within the pipeline repo. This pipeline requires a minimal set of fields to download FastQ files i.e. `'run_accession,experiment_accession,library_layout,fastq_ftp,fastq_md5'`. Full list of accepted metadata fields can be obtained from the [ENA API](https://www.ebi.ac.uk/ena/portal/api/returnFields?dataPortal=ena&format=tsv&result=read_run).", + "x-ga4gh-description-format": "markdown", + }, + sample_mapping_fields: { + type: "string", + description: + "Comma-separated list of ENA metadata fields used to create a separate 'id_mappings.csv' and 'multiqc_config.yml' with selected fields that can be used to rename samples in general and in MultiQC.", + default: + "experiment_accession,run_accession,sample_accession,experiment_alias,run_alias,sample_alias,experiment_title,sample_title,sample_description", + }, + nf_core_pipeline: { + type: "string", + description: + "Name of supported nf-core pipeline e.g. 'rnaseq'. A samplesheet for direct use with the pipeline will be created with the appropriate columns.", + enum: ["rnaseq", "atacseq", "viralrecon", "taxprofiler"], + }, + nf_core_rnaseq_strandedness: { + type: "string", + description: + "Value for 'strandedness' entry added to samplesheet created when using '--nf_core_pipeline rnaseq'.\n\nThe default is 'auto' which can be used with nf-core/rnaseq v3.10 onwards to auto-detect strandedness during the pipeline execution.", + default: "auto", + "x-ga4gh-description-format": "markdown", + }, + download_method: { + type: "string", + default: "ftp", + enum: ["aspera", "ftp", "sratools"], + description: + "Method to download FastQ files. Available options are 'aspera', 'ftp' or 'sratools'. Default is 'ftp'.\n\nFTP and Aspera CLI download FastQ files directly from the ENA FTP whereas sratools uses sra-tools to download *.sra files and convert to FastQ.", + "x-ga4gh-description-format": "markdown", + }, + skip_fastq_download: { + type: "boolean", + description: + "Only download metadata for public data database ids and don't download the FastQ files.", + }, + dbgap_key: { + type: "string", + description: + "dbGaP repository key.\n\nPath to a JWT cart file used to access protected dbGAP data on SRA using the sra-toolkit. Users with granted access to controlled data can download the JWT cart file for the study from the SRA Run Selector upon logging in. The JWT file can only be used on cloud platforms and is valid for 1 hour upon creation.", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-file": { + kind: "file", + }, + }, + outdir: { + type: "string", + description: + "The output directory where the results will be saved. You have to use absolute paths to storage on Cloud infrastructure.", + "x-ga4gh-file": { + kind: "directory", + }, + }, + email: { + type: "string", + description: + "Email address for completion summary.\n\nSet this parameter to your e-mail address to get a summary e-mail with details of the run sent to you when the workflow exits. If set in your user config file (`~/.nextflow/config`) then you don't need to specify this on the command line for every run.", + pattern: + "^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$", + "x-ga4gh-description-format": "markdown", + }, + }, + }, + institutional_config_options: { + title: "Institutional config options", + type: "object", + description: + "Parameters used to describe centralised config profiles. These should not be edited.\n\nThe centralised nf-core configuration profiles use a handful of pipeline parameters to describe themselves. This information is then printed to the Nextflow log when you run a pipeline. You should not need to change these values when you run a pipeline.", + properties: { + custom_config_version: { + type: "string", + description: "Git commit id for Institutional configs.", + default: "master", + "x-ga4gh-hidden": true, + }, + custom_config_base: { + type: "string", + description: + "Base directory for Institutional configs.\n\nIf you're running offline, Nextflow will not be able to fetch the institutional config files from the internet. If you don't need them, then this is not a problem. If you do need them, you should download the files from the repo and tell Nextflow where to find them with this parameter.", + default: "https://raw.githubusercontent.com/nf-core/configs/master", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-hidden": true, + }, + config_profile_name: { + type: "string", + description: "Institutional config name.", + "x-ga4gh-hidden": true, + }, + config_profile_description: { + type: "string", + description: "Institutional config description.", + "x-ga4gh-hidden": true, + }, + config_profile_contact: { + type: "string", + description: "Institutional config contact information.", + "x-ga4gh-hidden": true, + }, + config_profile_url: { + type: "string", + description: "Institutional config URL link.", + "x-ga4gh-hidden": true, + }, + }, + "x-ga4gh-description-format": "markdown", + }, + max_job_request_options: { + title: "Max job request options", + type: "object", + description: + "Set the top limit for requested resources for any single job.\n\nIf you are running on a smaller system, a pipeline step requesting more resources than are available may cause the Nextflow to stop the run with an error. These options allow you to cap the maximum resources requested by any single job so that the pipeline will run on your system.\n\nNote that you can not _increase_ the resources requested by any job using these options. For that you will need your own configuration file. See [the nf-core website](https://nf-co.re/usage/configuration) for details.", + properties: { + max_cpus: { + type: "integer", + description: + "Maximum number of CPUs that can be requested for any single job.\n\nUse to set an upper-limit for the CPU requirement for each process. Should be an integer e.g. `--max_cpus 1`", + default: 16, + "x-ga4gh-description-format": "markdown", + "x-ga4gh-hidden": true, + }, + max_memory: { + type: "string", + description: + "Maximum amount of memory that can be requested for any single job.\n\nUse to set an upper-limit for the memory requirement for each process. Should be a string in the format integer-unit e.g. `--max_memory '8.GB'`", + default: "128.GB", + pattern: "^\\d+(\\.\\d+)?\\.?\\s*(K|M|G|T)?B$", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-hidden": true, + }, + max_time: { + type: "string", + description: + "Maximum amount of time that can be requested for any single job.\n\nUse to set an upper-limit for the time requirement for each process. Should be a string in the format integer-unit e.g. `--max_time '2.h'`", + default: "240.h", + pattern: "^(\\d+\\.?\\s*(s|m|h|d|day)\\s*)+$", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-hidden": true, + }, + }, + "x-ga4gh-description-format": "markdown", + }, + generic_options: { + title: "Generic options", + type: "object", + description: + "Less common options for the pipeline, typically set in a config file.\n\nThese options are common to all nf-core pipelines and allow you to customise some of the core preferences for how the pipeline runs.\n\nTypically these options would be set in a Nextflow config file loaded for all pipeline runs, such as `~/.nextflow/config`.", + properties: { + help: { + type: "boolean", + description: "Display help text.", + "x-ga4gh-hidden": true, + }, + version: { + type: "boolean", + description: "Display version and exit.", + "x-ga4gh-hidden": true, + }, + publish_dir_mode: { + type: "string", + default: "copy", + description: + "Method used to save pipeline results to output directory.\n\nThe Nextflow `publishDir` option specifies which intermediate files should be saved to the output directory. This option tells the pipeline what method should be used to move these files. See [Nextflow docs](https://www.nextflow.io/docs/latest/process.html#publishdir) for details.", + enum: [ + "symlink", + "rellink", + "link", + "copy", + "copyNoFollow", + "move", + ], + "x-ga4gh-description-format": "markdown", + "x-ga4gh-hidden": true, + }, + email_on_fail: { + type: "string", + description: + "Email address for completion summary, only when pipeline fails.\n\nAn email address to send a summary email to when the pipeline is completed - ONLY sent if the pipeline does not exit successfully.", + pattern: + "^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-hidden": true, + }, + plaintext_email: { + type: "boolean", + description: "Send plain-text email instead of HTML.", + "x-ga4gh-hidden": true, + }, + monochrome_logs: { + type: "boolean", + description: "Do not use coloured log outputs.", + "x-ga4gh-hidden": true, + }, + hook_url: { + type: "string", + description: + "Incoming hook URL for messaging service\n\nIncoming hook URL for messaging service. Currently, MS Teams and Slack are supported.", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-hidden": true, + }, + validate_params: { + type: "boolean", + description: + "Boolean whether to validate parameters against the schema at runtime", + default: true, + "x-ga4gh-hidden": true, + }, + validationShowHiddenParams: { + type: "boolean", + description: + "Show all params when using `--help`\n\nBy default, parameters set as _hidden_ in the schema are not shown on the command line when a user runs with `--help`. Specifying this option will tell the pipeline to show all parameters.", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-hidden": true, + }, + validationFailUnrecognisedParams: { + type: "boolean", + description: + "Validation of parameters fails when an unrecognised parameter is found.\n\nBy default, when an unrecognised parameter is found, it returns a warinig.", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-hidden": true, + }, + validationLenientMode: { + type: "boolean", + description: + "Validation of parameters in lenient more.\n\nAllows string values that are parseable as numbers or booleans. For further information see [JSONSchema docs](https://github.com/everit-org/json-schema#lenient-mode).", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-hidden": true, + }, + }, + "x-ga4gh-description-format": "markdown", + }, + deprecated_options: { + title: "Deprecated options", + type: "object", + description: "List of parameters that have been deprecated.", + default: "", + properties: { + force_sratools_download: { + type: "boolean", + description: + "This parameter has been deprecated. Please use '--download_method sratools' instead.", + enum: [false], + "x-ga4gh-hidden": true, + }, + }, + }, + }, + }, +}; diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/file-values.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/file-values.ts new file mode 100644 index 00000000..0d292658 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/file-values.ts @@ -0,0 +1,293 @@ +/** + * Test vectors of file reference values (`tests/vectors/file-values/cases.json`). + * + * Generated by `scripts/sync-io-schema.mjs` from https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/2c3dc49ad89f0a556272f160369a2a2d7a21dac3 + * (profile version 0.3.0; Apache-2.0, as this package). Don't edit. + */ +/* eslint-disable */ + +export interface FileValueCase { + name: string; + annotation: Record; + value: string; + valid: boolean; + allowedSchemes?: string[]; + allowAbsolutePaths?: boolean; +} + +export const FILE_VALUE_CASES: FileValueCase[] = [ + { + name: "https-uri", + annotation: { + kind: "file", + }, + value: "https://data.example.org/reads_1.fastq.gz", + valid: true, + }, + { + name: "drs-uri-host-name", + annotation: { + kind: "file", + }, + value: "drs://drs.example.org/314159", + valid: true, + }, + { + name: "drs-uri-compact-identifier", + annotation: { + kind: "file", + schemes: ["drs"], + }, + value: "drs://dg.4503:6ca5c2a8", + valid: true, + }, + { + name: "scheme-in-uppercase", + annotation: { + kind: "file", + schemes: ["https"], + }, + value: "HTTPS://data.example.org/reads.fastq.gz", + valid: true, + }, + { + name: "directory-uri-with-slash", + annotation: { + kind: "directory", + }, + value: "https://data.example.org/index/", + valid: true, + }, + { + name: "scheme-not-on-allow-list", + annotation: { + kind: "file", + }, + value: "s3://bucket/reads.fastq.gz", + valid: false, + }, + { + name: "scheme-on-deployment-allow-list", + annotation: { + kind: "file", + }, + value: "s3://bucket/reads.fastq.gz", + allowedSchemes: ["drs", "https", "s3"], + valid: true, + }, + { + name: "scheme-not-in-schemes", + annotation: { + kind: "file", + schemes: ["drs"], + }, + value: "https://data.example.org/reads.fastq.gz", + valid: false, + }, + { + name: "schemes-do-not-extend-allow-list", + annotation: { + kind: "file", + schemes: ["drs", "s3"], + }, + value: "s3://bucket/reads.fastq.gz", + valid: false, + }, + { + name: "relative-path", + annotation: { + kind: "file", + }, + value: "inputs/reads.fastq.gz", + valid: true, + }, + { + name: "relative-path-with-colon-after-dot-slash", + annotation: { + kind: "file", + }, + value: "./sample:1.fastq.gz", + valid: true, + }, + { + name: "relative-path-with-colon-looks-like-scheme", + annotation: { + kind: "file", + }, + value: "sample:1.fastq.gz", + valid: false, + }, + { + name: "path-where-schemes", + annotation: { + kind: "file", + schemes: ["drs", "https"], + }, + value: "inputs/reads.fastq.gz", + valid: false, + }, + { + name: "path-with-dot-dot", + annotation: { + kind: "file", + }, + value: "inputs/../../etc/passwd", + valid: false, + }, + { + name: "path-starting-with-dot-dot", + annotation: { + kind: "file", + }, + value: "../reads.fastq.gz", + valid: false, + }, + { + name: "absolute-path", + annotation: { + kind: "file", + }, + value: "/shared/data/reads.fastq.gz", + valid: false, + }, + { + name: "absolute-path-allowed", + annotation: { + kind: "file", + }, + value: "/shared/data/reads.fastq.gz", + allowAbsolutePaths: true, + valid: true, + }, + { + name: "empty", + annotation: { + kind: "file", + }, + value: "", + valid: false, + }, + { + name: "file-uri", + annotation: { + kind: "file", + }, + value: "file:///etc/passwd", + valid: false, + }, + { + name: "javascript-uri", + annotation: { + kind: "file", + }, + value: "javascript:alert(1)", + valid: false, + }, + { + name: "javascript-uri-in-uppercase", + annotation: { + kind: "file", + }, + value: "JAVASCRIPT:alert(1)", + valid: false, + }, + { + name: "data-uri", + annotation: { + kind: "file", + }, + value: "data:text/plain;base64,SGVsbG8=", + valid: false, + }, + { + name: "leading-space-hides-scheme", + annotation: { + kind: "file", + }, + value: " file:///etc/passwd", + valid: false, + }, + { + name: "trailing-space", + annotation: { + kind: "file", + }, + value: "https://data.example.org/reads.fastq.gz ", + valid: false, + }, + { + name: "newline-splits-scheme", + annotation: { + kind: "file", + }, + value: "fi\nle:///etc/passwd", + valid: false, + }, + { + name: "leading-tab-hides-scheme", + annotation: { + kind: "file", + }, + value: "\tjavascript:alert(1)", + valid: false, + }, + { + name: "percent-encoded-dot-dot", + annotation: { + kind: "file", + }, + value: "%2e%2e/%2e%2e/etc/passwd", + valid: false, + }, + { + name: "percent-encoded-dot-dot-mixed-case", + annotation: { + kind: "file", + }, + value: "inputs/.%2E/secret", + valid: false, + }, + { + name: "home-directory-path", + annotation: { + kind: "file", + }, + value: "~/.ssh/id_rsa", + valid: false, + }, + { + name: "home-directory-path-even-if-absolute-allowed", + annotation: { + kind: "file", + }, + value: "~/.ssh/id_rsa", + allowAbsolutePaths: true, + valid: false, + }, + { + name: "network-path-reference", + annotation: { + kind: "file", + }, + value: "//evil.example/x", + allowAbsolutePaths: true, + valid: false, + }, + { + name: "unc-path", + annotation: { + kind: "file", + }, + value: "\\\\host\\share\\x", + allowAbsolutePaths: true, + valid: false, + }, + { + name: "space-inside-path", + annotation: { + kind: "file", + }, + value: "inputs/my reads.fastq.gz", + valid: true, + }, +]; diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts new file mode 100644 index 00000000..3e84f95c --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts @@ -0,0 +1,245 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import { + checkIoSchema, + getIoSchemaValidator, + IoSchemaValidator, + setIoSchemaValidator, +} from "../validator.js"; +import { PROFILE_SCHEMA } from "../profile.js"; +import { INVALID, VALID } from "./fixtures/conformance.js"; +import { EXAMPLES } from "./fixtures/examples.js"; + +const PROFILE_ID = PROFILE_SCHEMA.$id as string; + +/** An IO schema with the given inputs object and `$defs`. */ +const ioSchema = ( + inputs: Record, + extra: Record = {} +): Record => ({ + $schema: PROFILE_ID, + type: "object", + properties: { inputs: { type: "object", ...inputs } }, + ...extra, +}); + +/** The profile's example for error messages (keywords.md). */ +const SAMPLES = ioSchema( + { + properties: { + samples: { + type: "array", + items: { $ref: "#/$defs/sample_id" }, + minItems: 1, + }, + control: { $ref: "#/$defs/sample_id" }, + threads: { type: "integer", minimum: 1, maximum: 64 }, + when: { type: "string", format: "date" }, + }, + required: ["samples"], + }, + { + $defs: { sample_id: { type: "string", pattern: "^S[0-9]+$" } }, + } +); + +describe("checkIoSchema", () => { + describe("conformance suite (valid)", () => { + for (const [name, document] of VALID) { + it(`accepts ${name}`, async () => { + const result = await checkIoSchema(document); + expect(result.errors, JSON.stringify(result.errors)).to.deep.equal([]); + expect(result.valid).to.equal(true); + }); + } + }); + + describe("conformance suite (invalid)", () => { + for (const [name, document] of INVALID) { + it(`rejects ${name}`, async () => { + const result = await checkIoSchema(document); + expect(result.valid).to.equal(false); + expect(result.errors).to.have.length.above(0); + for (const error of result.errors) { + expect(error.message).to.be.a("string").and.not.equal(""); + expect(error.pointer).to.match(/^(\/.*)?$/); + } + }); + } + }); + + describe("examples of the profile", () => { + for (const [name, document] of Object.entries(EXAMPLES)) { + it(`accepts ${name}`, async () => { + const result = await checkIoSchema(document); + expect(result.errors, JSON.stringify(result.errors)).to.deep.equal([]); + }); + } + }); + + it("checks $schema before the meta-schema", async () => { + const result = await checkIoSchema({ ...SAMPLES, $schema: undefined }); + expect(result.valid).to.equal(false); + expect(result.errors).to.have.length(1); + expect(result.errors[0]).to.include({ pointer: "/$schema" }); + }); + + it("rejects documents that aren't objects", async () => { + for (const document of [null, 1, "x", [], true]) { + // eslint-disable-next-line no-await-in-loop + const result = await checkIoSchema(document); + expect(result.valid).to.equal(false); + expect(result.errors[0].pointer).to.equal(""); + } + }); + + it("names the location and the keyword of meta-schema failures", async () => { + const result = await checkIoSchema( + ioSchema({ + properties: { a: { type: "string", "x-ga4gh-hidden": "yes" } }, + }) + ); + expect(result.valid).to.equal(false); + const pointers = result.errors.map((error) => error.pointer); + expect(pointers).to.include( + "/properties/inputs/properties/a/x-ga4gh-hidden" + ); + }); + + it("rejects a remote $ref without a network request", async () => { + const fetched: string[] = []; + const { fetch } = window; + window.fetch = (input: RequestInfo | URL) => { + fetched.push(String(input)); + return Promise.reject(new Error("no network in this test")); + }; + try { + const result = await checkIoSchema( + ioSchema({ + properties: { a: { $ref: "https://example.org/remote.json" } }, + }) + ); + expect(result.valid).to.equal(false); + expect(result.errors[0].message).to.contain("https://example.org"); + } finally { + window.fetch = fetch; + } + expect(fetched).to.deep.equal([]); + }); + + it("rejects a local $ref to nowhere", async () => { + const result = await checkIoSchema( + ioSchema({ properties: { a: { $ref: "#/$defs/missing" } } }) + ); + expect(result.valid).to.equal(false); + }); + + it("accepts the same schema twice, also with an $id", async () => { + const withId = { ...SAMPLES, $id: "https://example.org/io.schema.json" }; + const first = await checkIoSchema(withId); + const second = await checkIoSchema(withId); + expect(first.valid).to.equal(true); + expect(second.valid).to.equal(true); + }); +}); + +describe("validateInputs", () => { + const validator = async (document: Record) => { + const result = await checkIoSchema(document); + if (!result.valid) throw new Error(JSON.stringify(result.errors)); + return result.validateInputs; + }; + + it("accepts valid values", async () => { + const validate = await validator(SAMPLES); + expect( + validate({ samples: ["S1"], control: "S2", threads: 4 }) + ).to.deep.equal({ valid: true, errors: [] }); + }); + + it("gives JSON Pointers into the values and messages", async () => { + const validate = await validator(SAMPLES); + const result = validate({ samples: ["S1", "x2"], threads: 100 }); + expect(result.valid).to.equal(false); + const byPointer = Object.fromEntries( + result.errors.map((error) => [error.pointer, error]) + ); + expect(byPointer["/samples/1"]).to.include({ keyword: "pattern" }); + expect(byPointer["/samples/1"].schemaPointer).to.equal("/$defs/sample_id"); + expect(byPointer["/threads"]).to.include({ keyword: "maximum" }); + expect(byPointer["/threads"].message).to.contain("64"); + }); + + it("reports missing required inputs at the object", async () => { + const validate = await validator(SAMPLES); + const result = validate({}); + expect(result.errors).to.have.length(1); + expect(result.errors[0]).to.include({ pointer: "", keyword: "required" }); + expect(result.errors[0].message).to.contain("samples"); + }); + + it("asserts formats of values", async () => { + const validate = await validator(SAMPLES); + expect(validate({ samples: ["S1"], when: "2026-12-14" }).valid).to.equal( + true + ); + const result = validate({ samples: ["S1"], when: "14.12.2026" }); + expect(result.errors[0]).to.include({ + pointer: "/when", + keyword: "format", + }); + }); + + it("escapes pointers of property names with / and ~", async () => { + const validate = await validator( + ioSchema({ properties: { "a/b~c": { type: "integer" } } }) + ); + const result = validate({ "a/b~c": "x" }); + expect(result.errors[0].pointer).to.equal("/a~1b~0c"); + }); + + it("validates values against the profile's examples", async () => { + const validate = await validator(EXAMPLES.example_wdl); + expect(validate("not an object").valid).to.equal(false); + }); + + it("validates embedded resources that name the profile", async () => { + const validate = await validator( + ioSchema( + { properties: { a: { $ref: "https://example.org/shared" } } }, + { + $defs: { + shared: { + $id: "https://example.org/shared", + $schema: PROFILE_ID, + type: "integer", + }, + }, + } + ) + ); + expect(validate({ a: 1 }).valid).to.equal(true); + expect(validate({ a: "x" }).valid).to.equal(false); + }); +}); + +describe("setIoSchemaValidator", () => { + it("replaces the validator behind checkIoSchema", async () => { + const original = getIoSchemaValidator(); + const fake: IoSchemaValidator = { + check: async () => ({ + valid: false, + errors: [ + { pointer: "", keyword: "x", schemaPointer: "", message: "m" }, + ], + }), + }; + setIoSchemaValidator(fake); + try { + expect((await checkIoSchema(SAMPLES)).errors[0].message).to.equal("m"); + } finally { + setIoSchemaValidator(original); + } + expect((await checkIoSchema(SAMPLES)).valid).to.equal(true); + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts new file mode 100644 index 00000000..b03bdb6c --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts @@ -0,0 +1,337 @@ +/** + * Checks IO schemas against the GA4GH IO Schema Profile and validates input + * values against them, offline: the meta-schema and its vocabularies are + * bundled (`profile.ts`), and no `$ref` is ever fetched (portals guide, + * "Validate the schema offline"; conformance, "Validator"). + * + * The validator sits behind `IoSchemaValidator`, so that another library + * (e.g. Ajv) can replace @hyperjump/json-schema without changing the + * components. The default needs no `'unsafe-eval'` in a page's Content + * Security Policy. + */ +import { removeUriSchemePlugin } from "@hyperjump/browser"; +import { + hasSchema, + registerSchema, + setShouldValidateFormat, + unregisterSchema, + validate, +} from "@hyperjump/json-schema/draft-2020-12"; +import type { + OutputUnit, + SchemaObject, +} from "@hyperjump/json-schema/draft-2020-12"; +import "@hyperjump/json-schema/formats"; +import { PROFILE_SCHEMA, VOCABULARY_SCHEMAS } from "./profile.js"; +import { keywordMessage } from "./messages.js"; +import { + fragmentPointer, + parsePointer, + toPointer, + valueAt, +} from "./pointer.js"; + +/** One failure of a document or of values. */ +export interface ValidationError { + /** JSON Pointer of the failing value: in the IO schema, or in the values */ + pointer: string; + /** Name of the keyword that failed, e.g. `minimum` */ + keyword: string; + /** + * JSON Pointer of the schema that holds the keyword: in the IO schema for + * values, in the meta-schema (or a vocabulary) for IO schemas + */ + schemaPointer: string; + /** The validator's message, in English */ + message: string; +} + +/** Validates input values against `inputs` of a checked IO schema. */ +export type InputsValidator = (values: unknown) => { + valid: boolean; + errors: ValidationError[]; +}; + +/** The result of checking an IO schema. */ +export type IoSchemaCheck = + | { valid: true; errors: []; validateInputs: InputsValidator } + | { valid: false; errors: ValidationError[] }; + +/** A validator of IO schemas and their input values. */ +export interface IoSchemaValidator { + /** + * Checks a document: `$schema` names the profile, it passes the + * meta-schema with format assertion, and every `$ref` resolves within + * the document. Never fetches anything. + */ + check(document: unknown): Promise; +} + +/** `$id` of the profile's meta-schema, which IO schemas name in `$schema`. */ +export const PROFILE_ID = PROFILE_SCHEMA.$id as string; + +const DRAFT_2020_12 = "https://json-schema.org/draft/2020-12/schema"; + +/** Keywords whose value is a schema, an array of schemas, or a map of them */ +const SCHEMA_KEYWORDS = [ + "additionalProperties", + "contains", + "else", + "if", + "items", + "not", + "propertyNames", + "then", + "unevaluatedItems", + "unevaluatedProperties", +]; +const SCHEMA_ARRAY_KEYWORDS = ["allOf", "anyOf", "oneOf", "prefixItems"]; +const SCHEMA_MAP_KEYWORDS = [ + "$defs", + "definitions", + "dependentSchemas", + "patternProperties", + "properties", +]; +/** Applicators whose branches' own failures are summed up by theirs */ +const SUMMING_KEYWORDS = ["anyOf", "oneOf", "not"]; + +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** + * A copy of an IO schema to register for validating values: the root + * without `$id` (it is registered under a URI of its own), and `$schema` + * naming Draft 2020-12 instead of the profile in the root and in embedded + * resources, as "Dialect and validation of values" allows. Only schemas are + * rewritten, not values of `const`, `enum`, `default` or `examples`. + * + * @param embedded - Receives the JSON Pointer of each embedded resource by + * its `$id`. + */ +function forValues( + document: Record, + embedded: Map +): Record { + const rewrite = (schema: unknown, path: (string | number)[]): unknown => { + if (!isObject(schema)) return schema; + const copy: Record = { ...schema }; + if (copy.$schema === PROFILE_ID) copy.$schema = DRAFT_2020_12; + if (path.length > 0 && typeof copy.$id === "string") { + embedded.set(copy.$id.split("#")[0], toPointer(path)); + } + for (const keyword of SCHEMA_KEYWORDS) { + if (keyword in copy) + copy[keyword] = rewrite(copy[keyword], [...path, keyword]); + } + for (const keyword of SCHEMA_ARRAY_KEYWORDS) { + const value = copy[keyword]; + if (Array.isArray(value)) { + copy[keyword] = value.map((item, i) => + rewrite(item, [...path, keyword, i]) + ); + } + } + for (const keyword of SCHEMA_MAP_KEYWORDS) { + const value = copy[keyword]; + if (isObject(value)) { + copy[keyword] = Object.fromEntries( + Object.entries(value).map(([key, item]) => [ + key, + rewrite(item, [...path, keyword, key]), + ]) + ); + } + } + return copy; + }; + const copy = rewrite(document, []) as Record; + delete copy.$id; + return copy; +} + +let setUp = false; + +/** + * Sets @hyperjump/json-schema up offline, once: no retrieval over HTTP(S), + * format assertion on, and the profile registered from the bundled copies. + * These settings are global to hyperjump on the page. + */ +function setUpHyperjump(): void { + if (setUp) return; + removeUriSchemePlugin("http"); + removeUriSchemePlugin("https"); + setShouldValidateFormat(true); + for (const schema of [...VOCABULARY_SCHEMAS, PROFILE_SCHEMA]) { + if (!hasSchema(schema.$id as string)) { + registerSchema(schema as SchemaObject); + } + } + setUp = true; +} + +let registrations = 0; + +/** Turns hyperjump's output units into errors. */ +function toErrors( + units: OutputUnit[] | undefined, + instance: unknown, + schemaOf: (location: string) => { pointer: string; schema: unknown } +): ValidationError[] { + const all = units ?? []; + const summed = all.filter((unit) => + SUMMING_KEYWORDS.includes(unit.keyword.split("/").pop() ?? "") + ); + return all + .filter( + (unit) => + !summed.some( + (outer) => + outer !== unit && + unit.absoluteKeywordLocation.startsWith( + `${outer.absoluteKeywordLocation}/` + ) + ) + ) + .map((unit) => { + const keyword = unit.keyword.split("/").pop() ?? unit.keyword; + const pointer = fragmentPointer(unit.instanceLocation) ?? ""; + const location = schemaOf(unit.absoluteKeywordLocation); + const segments = parsePointer(location.pointer); + const schemaPointer = toPointer(segments.slice(0, -1)); + return { + pointer, + keyword, + schemaPointer, + message: keywordMessage( + keyword, + location.schema, + valueAt(instance, pointer) + ), + }; + }); +} + +/** Where a keyword location of the meta-schema points, and its value. */ +function metaSchemaLocation(location: string) { + const [uri] = location.split("#"); + const root = [...VOCABULARY_SCHEMAS, PROFILE_SCHEMA].find( + (schema) => schema.$id === uri + ); + const pointer = fragmentPointer(location) ?? ""; + return { pointer, schema: root ? valueAt(root, pointer) : undefined }; +} + +const errorText = (error: unknown) => + error instanceof Error ? error.message : String(error); + +/** The default validator: @hyperjump/json-schema, offline. */ +export const hyperjumpValidator: IoSchemaValidator = { + async check(document) { + if (!isObject(document)) { + return { + valid: false, + errors: [ + { + pointer: "", + keyword: "type", + schemaPointer: "", + message: "An IO schema must be a JSON object.", + }, + ], + }; + } + if (document.$schema !== PROFILE_ID) { + return { + valid: false, + errors: [ + { + pointer: "/$schema", + keyword: "$schema", + schemaPointer: "", + message: keywordMessage("$schema", undefined, document.$schema), + }, + ], + }; + } + setUpHyperjump(); + const output = await validate( + PROFILE_ID, + document as SchemaObject, + "BASIC" + ); + if (!output.valid) { + const errors = toErrors(output.errors, document, metaSchemaLocation); + return { valid: false, errors }; + } + + // Compile the schema of the values, which resolves every `$ref` from + // the document itself, as nothing can be fetched + registrations += 1; + const base = `urn:ecc-io-schema:${registrations}`; + const embedded = new Map(); + const copy = forValues(document, embedded); + const registered = [base, ...embedded.keys()]; + let compiled: Awaited>; + try { + if ([...embedded.keys()].some(hasSchema)) { + throw new Error( + "An embedded schema has the $id of a schema that is checked at the same time." + ); + } + registerSchema(copy as SchemaObject, base); + compiled = await validate(`${base}#/properties/inputs`); + } catch (error) { + return { + valid: false, + errors: [ + { + pointer: "", + keyword: "$ref", + schemaPointer: "", + message: `The schema can't be used: ${errorText(error)}`, + }, + ], + }; + } finally { + for (const uri of registered) { + if (hasSchema(uri)) unregisterSchema(uri); + } + } + + const valuesLocation = (location: string) => { + const [uri] = location.split("#"); + const pointer = + (uri === base ? "" : embedded.get(uri) ?? "") + + (fragmentPointer(location) ?? ""); + return { pointer, schema: valueAt(document, pointer) }; + }; + const validateInputs: InputsValidator = (values) => { + const result = compiled(values as never, "BASIC"); + return result.valid + ? { valid: true, errors: [] } + : { + valid: false, + errors: toErrors(result.errors, values, valuesLocation), + }; + }; + return { valid: true, errors: [], validateInputs }; + }, +}; + +let current: IoSchemaValidator = hyperjumpValidator; + +/** The validator that `checkIoSchema()` uses. */ +export const getIoSchemaValidator = (): IoSchemaValidator => current; + +/** Replaces the validator that `checkIoSchema()` uses. */ +export function setIoSchemaValidator(validator: IoSchemaValidator): void { + current = validator; +} + +/** + * Checks an IO schema against the profile (see `IoSchemaValidator.check`); + * a valid one comes with a validator of its input values. + */ +export const checkIoSchema = (document: unknown): Promise => + current.check(document); diff --git a/packages/ecc-client-ga4gh-wes/tsconfig.prod.json b/packages/ecc-client-ga4gh-wes/tsconfig.prod.json index 16aa85a6..d4c405fe 100644 --- a/packages/ecc-client-ga4gh-wes/tsconfig.prod.json +++ b/packages/ecc-client-ga4gh-wes/tsconfig.prod.json @@ -4,5 +4,5 @@ "rootDir": "./src" }, "include": ["src"], - "exclude": ["src/**/*.test.ts"] + "exclude": ["src/**/*.test.ts", "src/**/tests/**"] } diff --git a/web-test.runner-config.mjs b/web-test.runner-config.mjs index c9b83c82..c99c3bd5 100644 --- a/web-test.runner-config.mjs +++ b/web-test.runner-config.mjs @@ -2,6 +2,48 @@ import { esbuildPlugin } from "@web/dev-server-esbuild"; import fg from "fast-glob"; import { playwrightLauncher } from "@web/test-runner-playwright"; import { a11ySnapshotPlugin } from "@web/test-runner-commands/plugins"; +import { createRequire } from "node:module"; +import { fromRollup } from "@web/dev-server-rollup"; +import rollupCommonjs from "@rollup/plugin-commonjs"; +import rollupJson from "@rollup/plugin-json"; + +// Dependencies that are CommonJS only, or import JSON, which browsers can't +// import as they are (bundlers convert them when packages are built): those +// of @hyperjump/json-schema, the validator of `@elixir-cloud/wes`. The +// CommonJS plugin gives them a default export only, so `cjsNamedExports` +// serves them through a module with their named exports. +const COMMONJS_DEPENDENCIES = ["content-type", "idn-hostname", "punycode"]; +const IMPORTED_BY_ESM = ["content-type", "idn-hostname"]; +const commonjs = fromRollup(rollupCommonjs); +const json = fromRollup(rollupJson); +const require = createRequire(import.meta.url); +const SHIM = "/__cjs-named-exports__/"; +const cjsNamedExports = { + name: "cjs-named-exports", + resolveImport({ source, context }) { + if (IMPORTED_BY_ESM.includes(source) && !context.path.startsWith(SHIM)) { + return `${SHIM}${source}.js`; + } + return undefined; + }, + serve(context) { + if (!context.path.startsWith(SHIM)) return undefined; + const name = context.path.slice(SHIM.length, -".js".length); + if (!IMPORTED_BY_ESM.includes(name)) return undefined; + const names = Object.keys(require(name)).filter((key) => + /^[A-Za-z_$][\w$]*$/.test(key) + ); + return { + body: `import m from "${name}";\nexport default m;\nexport const { ${names.join( + ", " + )} } = m;\n`, + type: "js", + }; + }, +}; +const COMMONJS_FILES = new RegExp( + `node_modules/(${COMMONJS_DEPENDENCIES.join("|")})/` +); // Packages run tests in parallel (at most three at once, as more overload // the browsers on CI runners), so each package's test @@ -9,10 +51,15 @@ import { a11ySnapshotPlugin } from "@web/test-runner-commands/plugins"; // tes 8003, service registry 8004, trs 8005, trs-filer 8006, drs 8007. export default { rootDir: ".", + // JSON files of CommonJS dependencies are served as modules (see `json`) + mimeTypes: { "**/node_modules/idn-hostname/*.json": "js" }, files: "src/**/*.test.ts", // "default" group concurrentBrowsers: 3, nodeResolve: { exportConditions: ["production", "default"], + // Take the browser builds of packages that name them in the `browser` + // field of their package.json (e.g. @hyperjump/browser), as bundlers do + browser: true, }, testFramework: { config: { @@ -38,6 +85,10 @@ export default { tsconfig: "./tsconfig.json", }), a11ySnapshotPlugin(), + cjsNamedExports, + json({ include: COMMONJS_FILES }), + // Without strict requires: their wrappers don't load in the dev server + commonjs({ include: COMMONJS_FILES, strictRequires: false }), ], browsers: [ playwrightLauncher({ product: "chromium" }), From abd7e89bf20d7dd96702f7c8c5cf779d7fc7d528 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 07:26:21 +0100 Subject: [PATCH 02/19] feat(wes): check file reference values Move the URI check of run-output into a shared module (src/io-schema/files.ts) and add the input rules of the profile: paths only where the file reference has no `schemes`, no `..` segments (also percent-encoded), no leading `~` or two slashes, absolute paths only where allowed, and `schemes` narrowing the deployment's allow-list. run-output keeps its behaviour and re-exports the shared helpers. The tests run the profile's file-value vectors (33 cases). Part of #444. Co-Authored-By: Claude Opus 5.5 --- .../pages/docs/wes/io-schema.mdx | 10 ++ .../src/components/run-output/utils.ts | 78 ++-------- .../src/io-schema/files.ts | 145 ++++++++++++++++++ .../src/io-schema/tests/files.test.ts | 63 ++++++++ 4 files changed, 227 insertions(+), 69 deletions(-) create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/files.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/tests/files.test.ts diff --git a/apps/documentation/pages/docs/wes/io-schema.mdx b/apps/documentation/pages/docs/wes/io-schema.mdx index 94764b9f..e5a3266f 100644 --- a/apps/documentation/pages/docs/wes/io-schema.mdx +++ b/apps/documentation/pages/docs/wes/io-schema.mdx @@ -29,3 +29,13 @@ The checks use [@hyperjump/json-schema](https://github.com/hyperjump-io/json-sch The validator sits behind a small internal interface (`IoSchemaValidator`), so that another library could replace it without changing the components. + +## File references + +JSON Schema can't check the values of file references (`x-ga4gh-file`), so the components check them by the profile's rules (see [Values](https://ga4gh-io-schema.readthedocs.io/en/latest/specification/files/#values)) before a value is used: + +- A URI must have a scheme on the deployment's allow-list (`allowedSchemes` of the components, default `drs https`), narrowed by the file reference's own `schemes`, which never extend it. `javascript`, `data`, `file` and other schemes that run code or refer to local data are always refused. +- Inputs may also be relative paths (files attached to the run request), but only where the file reference has no `schemes`: no `..` segments (also not percent-encoded), no leading `~`, `//` or `\\`, and no absolute paths. +- Control characters and leading or trailing whitespace are refused, as they could hide a scheme. + +Outputs must be absolute URIs. The checks pass the profile's test vectors for file reference values (`tests/vectors/file-values`). diff --git a/packages/ecc-client-ga4gh-wes/src/components/run-output/utils.ts b/packages/ecc-client-ga4gh-wes/src/components/run-output/utils.ts index fa4939bb..3f71812d 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/run-output/utils.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/run-output/utils.ts @@ -8,6 +8,8 @@ * "Rendering schemas and outputs" in `docs/security.md`. */ +import { fileOf, isFileReference } from "../../io-schema/files.js"; + /** The schema of one output (a property of `outputs` of an IO schema). */ export type OutputSchema = Record; @@ -26,26 +28,13 @@ export type OutputEntry = } | { type: "value"; value: unknown }; -/** Schemes allowed when the app sets no allow-list. */ -export const DEFAULT_ALLOWED_SCHEMES: readonly string[] = ["drs", "https"]; - -/** - * Schemes that run code in a browser or refer to local data. They are never - * allowed, whatever the allow-list says (the list of the profile's - * meta-schema for `schemes`). - */ -export const FORBIDDEN_SCHEMES: readonly string[] = [ - "javascript", - "vbscript", - "livescript", - "data", - "blob", - "filesystem", - "file", - "jar", - "view-source", - "about", -]; +export { + DEFAULT_ALLOWED_SCHEMES, + FORBIDDEN_SCHEMES, + checkOutputUri, + fileOf, + isFileReference, +} from "../../io-schema/files.js"; /** * Content Security Policy of HTML outputs: no external loads, inline styles @@ -55,59 +44,10 @@ export const HTML_OUTPUT_CSP = "default-src 'none'; img-src data:; style-src 'unsafe-inline'"; const VIEWERS: readonly string[] = ["table-viewer", "html-viewer"]; -const SCHEME = /^([A-Za-z][A-Za-z0-9+.-]*):/; -// eslint-disable-next-line no-control-regex -const CONTROL = /[\u0000-\u001F\u007F]/; const isObject = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); -/** Whether a schema is a file reference (`x-ga4gh-file`). */ -export const isFileReference = (schema: unknown): schema is OutputSchema => - isObject(schema) && - schema.type === "string" && - isObject(schema["x-ga4gh-file"]); - -/** The `x-ga4gh-file` annotation of a file reference. */ -export const fileOf = (schema: OutputSchema): Record => - schema["x-ga4gh-file"] as Record; - -/** - * Checks the URI of an output before it is fetched or offered for - * download. - * - * @param uri - The value of the file reference. - * @param allowedSchemes - The allow-list of the deployment. - * @param fileSchemes - `schemes` of the file reference, which narrows the - * allow-list but never extends it. - * @returns Why the URI is refused, or `null` if it is allowed. - */ -export function checkOutputUri( - uri: unknown, - allowedSchemes: readonly string[], - fileSchemes?: unknown -): string | null { - if (typeof uri !== "string") return "The value isn't a URI."; - if (CONTROL.test(uri) || uri.trim() !== uri) { - return "The URI contains control characters or surrounding whitespace."; - } - const match = SCHEME.exec(uri); - if (!match) return "The value is a path, not an absolute URI."; - const scheme = match[1].toLowerCase(); - const allowed = allowedSchemes.map((s) => s.toLowerCase()); - const narrowed = Array.isArray(fileSchemes) - ? fileSchemes.map((s) => String(s).toLowerCase()) - : null; - if ( - FORBIDDEN_SCHEMES.includes(scheme) || - !allowed.includes(scheme) || - (narrowed !== null && !narrowed.includes(scheme)) - ) { - return `The scheme "${scheme}" is not allowed.`; - } - return null; -} - /** * Whether a URL (absolute, or relative to the page) is an `http:` or * `https:` URL, e.g. one that a provider returns for a download. diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/files.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/files.ts new file mode 100644 index 00000000..84b21be6 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/files.ts @@ -0,0 +1,145 @@ +/** + * File references of the GA4GH IO Schema Profile (`x-ga4gh-file`): the + * checks of their values that JSON Schema can't express, by "Values" in + * `docs/specification/files.md` and "URIs and file references" in + * `docs/security.md` (profile version 0.3.0). + */ + +/** The schema of a file reference, or of any input or output. */ +export type FileSchema = Record; + +/** Schemes allowed when the app sets no allow-list. */ +export const DEFAULT_ALLOWED_SCHEMES: readonly string[] = ["drs", "https"]; + +/** + * Schemes that run code in a browser or refer to local data. They are never + * allowed, whatever the allow-list says (the list of the profile's + * meta-schema for `schemes`). + */ +export const FORBIDDEN_SCHEMES: readonly string[] = [ + "javascript", + "vbscript", + "livescript", + "data", + "blob", + "filesystem", + "file", + "jar", + "view-source", + "about", +]; + +const SCHEME = /^([A-Za-z][A-Za-z0-9+.-]*):/; +// eslint-disable-next-line no-control-regex +const CONTROL = /[\u0000-\u001F\u007F]/; + +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** Whether a schema is a file reference (`x-ga4gh-file`). */ +export const isFileReference = (schema: unknown): schema is FileSchema => + isObject(schema) && + schema.type === "string" && + isObject(schema["x-ga4gh-file"]); + +/** The `x-ga4gh-file` annotation of a file reference. */ +export const fileOf = (schema: FileSchema): Record => + schema["x-ga4gh-file"] as Record; + +/** Why the scheme of a URI is refused, or `null` if it is allowed. */ +function checkScheme( + scheme: string, + allowedSchemes: readonly string[], + fileSchemes: unknown +): string | null { + const allowed = allowedSchemes.map((s) => s.toLowerCase()); + const narrowed = Array.isArray(fileSchemes) + ? fileSchemes.map((s) => String(s).toLowerCase()) + : null; + if ( + FORBIDDEN_SCHEMES.includes(scheme) || + !allowed.includes(scheme) || + (narrowed !== null && !narrowed.includes(scheme)) + ) { + return `The scheme "${scheme}" is not allowed.`; + } + return null; +} + +/** + * Checks the URI of an output before it is fetched or offered for + * download. + * + * @param uri - The value of the file reference. + * @param allowedSchemes - The allow-list of the deployment. + * @param fileSchemes - `schemes` of the file reference, which narrows the + * allow-list but never extends it. + * @returns Why the URI is refused, or `null` if it is allowed. + */ +export function checkOutputUri( + uri: unknown, + allowedSchemes: readonly string[], + fileSchemes?: unknown +): string | null { + if (typeof uri !== "string") return "The value isn't a URI."; + if (CONTROL.test(uri) || uri.trim() !== uri) { + return "The URI contains control characters or surrounding whitespace."; + } + const match = SCHEME.exec(uri); + if (!match) return "The value is a path, not an absolute URI."; + return checkScheme(match[1].toLowerCase(), allowedSchemes, fileSchemes); +} + +/** Decodes `%XX` escapes byte by byte, leaving other `%` signs as they are. */ +const percentDecode = (text: string): string => + text.replace(/%([0-9A-Fa-f]{2})/g, (_, hex: string) => + String.fromCharCode(parseInt(hex, 16)) + ); + +/** + * Checks a value of a file reference of an input: an absolute URI whose + * scheme is on the deployment's allow-list and, if the annotation has + * `schemes`, on that list too; or, without `schemes`, a path without `..` + * segments (also percent-encoded), not starting with `~` or two slashes, + * and absolute only where the deployment allows it. Messages don't repeat + * the value. + * + * @param annotation - The `x-ga4gh-file` annotation of the file reference. + * @param value - The value. + * @param allowedSchemes - The allow-list of the deployment. + * @param allowAbsolutePaths - Whether absolute paths are allowed (only for + * deployments with a shared file system). + * @returns Why the value is refused, or `null` if it is allowed. + */ +export function checkFileValue( + annotation: Record, + value: string, + allowedSchemes: readonly string[] = DEFAULT_ALLOWED_SCHEMES, + allowAbsolutePaths = false +): string | null { + if (typeof value !== "string") return "A file reference must be text."; + if (CONTROL.test(value) || value.trim() !== value) { + return "File references can't contain control characters, or start or end with whitespace."; + } + const declared = Array.isArray(annotation.schemes) + ? annotation.schemes.map(String) + : null; + const match = SCHEME.exec(value); + if (match) + return checkScheme(match[1].toLowerCase(), allowedSchemes, declared); + if (declared) { + return `This input takes only URIs with the schemes ${declared.join( + ", " + )}, not paths.`; + } + if (value === "") return "A file reference can't be empty."; + if (percentDecode(value).split(/[/\\]/).includes("..")) { + return "Paths can't have '..' segments."; + } + if (value.startsWith("~")) return "Paths can't start with '~'."; + if (/^[/\\]{2}/.test(value)) return "Paths can't start with two slashes."; + if (/^[/\\]/.test(value) && !allowAbsolutePaths) { + return "Absolute paths aren't allowed here; use a URI or a relative path."; + } + return null; +} diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/files.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/files.test.ts new file mode 100644 index 00000000..802a14d5 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/files.test.ts @@ -0,0 +1,63 @@ +/* eslint-disable import/no-extraneous-dependencies */ +/* eslint-disable no-script-url -- tests that script URLs are refused */ +import { expect } from "@open-wc/testing"; +import { + DEFAULT_ALLOWED_SCHEMES, + checkFileValue, + checkOutputUri, + isFileReference, +} from "../files.js"; +import * as runOutputUtils from "../../components/run-output/utils.js"; +import { FILE_VALUE_CASES } from "./fixtures/file-values.js"; + +describe("checkFileValue", () => { + describe("file-values vectors of the profile", () => { + for (const testCase of FILE_VALUE_CASES) { + it(`${testCase.valid ? "accepts" : "refuses"} ${testCase.name}`, () => { + const problem = checkFileValue( + testCase.annotation, + testCase.value, + testCase.allowedSchemes ?? DEFAULT_ALLOWED_SCHEMES, + testCase.allowAbsolutePaths ?? false + ); + if (testCase.valid) expect(problem).to.equal(null); + else expect(problem).to.be.a("string"); + }); + } + }); + + it("refuses forbidden schemes even if the allow-list has them", () => { + expect( + checkFileValue({ kind: "file" }, "javascript:alert(1)", ["javascript"]) + ).to.contain("javascript"); + }); + + it("refuses values that aren't strings", () => { + expect(checkFileValue({ kind: "file" }, 1 as unknown as string)).to.be.a( + "string" + ); + }); + + it("doesn't repeat the value in its messages", () => { + const value = "inputs/../secret"; + expect(checkFileValue({ kind: "file" }, value)).to.not.contain(value); + }); + + it("keeps percent signs that don't encode a byte", () => { + expect(checkFileValue({ kind: "file" }, "inputs/100%.txt")).to.equal(null); + }); +}); + +describe("shared with run-output", () => { + it("is the check that run-output uses", () => { + expect(runOutputUtils.checkOutputUri).to.equal(checkOutputUri); + expect(runOutputUtils.isFileReference).to.equal(isFileReference); + }); + + it("refuses paths as outputs, but takes them as inputs", () => { + expect(checkOutputUri("inputs/a.txt", DEFAULT_ALLOWED_SCHEMES)).to.be.a( + "string" + ); + expect(checkFileValue({ kind: "file" }, "inputs/a.txt")).to.equal(null); + }); +}); From 8d981075048691cd1d56644fb5f89c5fe4a5ad4c Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 08:03:28 +0100 Subject: [PATCH 03/19] feat(wes): render Markdown descriptions safely Add one renderer for the profile's Markdown subset, on markdown-it: raw HTML as escaped text, images as their alt text, links only with an allowed scheme (else their text; they open in a new window without referrer), and of GFM only tables, strikethrough and autolinks (www. and bare URLs, not bare host names). It produces the profile's example HTML exactly. Its output is the only HTML that goes through unsafeHTML. Descriptions stay plain text by default, as the proposal's default for open question 4 of #444: setDescriptionFormat("markdown") switches the components to Markdown. run-output takes its descriptions from the same template, unchanged by default. Part of #444. Co-Authored-By: Claude Opus 5.5 --- .../pages/docs/wes/io-schema.mdx | 6 + package-lock.json | 98 ++++++++++- packages/ecc-client-ga4gh-wes/package.json | 3 +- .../src/components/run-output/run-output.ts | 11 +- .../run-output/tests/run-output.test.ts | 39 +++++ .../src/io-schema/descriptions.ts | 132 ++++++++++++++ .../src/io-schema/tests/descriptions.test.ts | 164 ++++++++++++++++++ 7 files changed, 449 insertions(+), 4 deletions(-) create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/descriptions.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/tests/descriptions.test.ts diff --git a/apps/documentation/pages/docs/wes/io-schema.mdx b/apps/documentation/pages/docs/wes/io-schema.mdx index e5a3266f..3f165d90 100644 --- a/apps/documentation/pages/docs/wes/io-schema.mdx +++ b/apps/documentation/pages/docs/wes/io-schema.mdx @@ -39,3 +39,9 @@ JSON Schema can't check the values of file references (`x-ga4gh-file`), so the c - Control characters and leading or trailing whitespace are refused, as they could hide a scheme. Outputs must be absolute URIs. The checks pass the profile's test vectors for file reference values (`tests/vectors/file-values`). + +## Descriptions + +Titles, descriptions and `enum` values of IO schemas are always shown as text, never as markup. + +Descriptions with `"x-ga4gh-description-format": "markdown"` are shown as plain text, which the profile allows. The package also has a renderer for the profile's Markdown subset (raw HTML shown as escaped text, images as their alt text, links only with a scheme from `allowedSchemes`, which open in a new window; of GFM only tables, strikethrough and autolinks), built on [markdown-it](https://github.com/markdown-it/markdown-it). It is switched off until the maintainers decide whether the components render Markdown. diff --git a/package-lock.json b/package-lock.json index 9477b988..45946256 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17461,6 +17461,25 @@ "dev": true, "license": "MIT" }, + "node_modules/linkify-it": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-6.1.0.tgz", + "integrity": "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^3.0.0" + } + }, "node_modules/lit": { "version": "2.8.0", "resolved": "https://registry.npmjs.org/lit/-/lit-2.8.0.tgz", @@ -17694,6 +17713,61 @@ "node": ">=0.10.0" } }, + "node_modules/markdown-it": { + "version": "15.0.3", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.3.tgz", + "integrity": "sha512-+Az7Ojz3iRGu8KYMvJ6xVhvrxP3eE+vEtJX75Ow88XBpcQNV/0lGX5ZynIIBftREo4DC2jsveAMDaeltmm8QvQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^3.0.3", + "entities": "^8.1.0", + "linkify-it": "^6.1.0", + "mdurl": "^2.1.0", + "punycode.js": "^2.3.1", + "uc.micro": "^3.0.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/markdown-it/node_modules/argparse": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.4.tgz", + "integrity": "sha512-fwWK3Zq22l4XJJjx5mcBHGikIk+hJqO+32dPm0Jur7+rtG5x1scOjSfdT9ZKeWHPpsya/l0HHK4tDImBkTrtvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "PSF-2.0" + }, + "node_modules/markdown-it/node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/markdown-table": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz", @@ -18319,6 +18393,12 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/mdurl": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", + "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", + "license": "MIT" + }, "node_modules/media-typer": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", @@ -20856,6 +20936,15 @@ "node": ">=6" } }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/puppeteer-core": { "version": "25.16.0", "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.16.0.tgz", @@ -24338,6 +24427,12 @@ "node": "*" } }, + "node_modules/uc.micro": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-3.0.0.tgz", + "integrity": "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==", + "license": "MIT" + }, "node_modules/ufo": { "version": "1.6.1", "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.1.tgz", @@ -35905,7 +36000,8 @@ "@hyperjump/browser": "^1.6.0", "@hyperjump/json-schema": "^1.18.1", "@lit/react": "^1.0.2", - "lit": "^2.8.0" + "lit": "^2.8.0", + "markdown-it": "^15.0.3" }, "devDependencies": { "@custom-elements-manifest/analyzer": "^0.4.17", diff --git a/packages/ecc-client-ga4gh-wes/package.json b/packages/ecc-client-ga4gh-wes/package.json index 3c7e3747..e3717211 100644 --- a/packages/ecc-client-ga4gh-wes/package.json +++ b/packages/ecc-client-ga4gh-wes/package.json @@ -50,7 +50,8 @@ "@hyperjump/browser": "^1.6.0", "@hyperjump/json-schema": "^1.18.1", "@lit/react": "^1.0.2", - "lit": "^2.8.0" + "lit": "^2.8.0", + "markdown-it": "^15.0.3" }, "devDependencies": { "@custom-elements-manifest/analyzer": "^0.4.17", diff --git a/packages/ecc-client-ga4gh-wes/src/components/run-output/run-output.ts b/packages/ecc-client-ga4gh-wes/src/components/run-output/run-output.ts index 2f0621fc..8e3bf981 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/run-output/run-output.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/run-output/run-output.ts @@ -20,6 +20,7 @@ import { readLimitedText, viewerOf, } from "./utils.js"; +import { descriptionTemplate } from "../../io-schema/descriptions.js"; import "@elixir-cloud/design/components/skeleton/index.js"; const DEFAULT_MAX_ROWS = 1000; @@ -76,6 +77,12 @@ export class ECCClientGa4ghWesRunOutput extends LitElement { display: block; width: 100%; } + + /* Markdown descriptions stay on the row's one line */ + [data-description] p { + display: inline; + margin: 0; + } `, ]; @@ -662,8 +669,8 @@ export class ECCClientGa4ghWesRunOutput extends LitElement { > ${secondary}${secondary && description ? " · " : ""} + >${descriptionTemplate(this.schema, this.allowedSchemes)} ${options.value !== undefined ? options.value : actions} diff --git a/packages/ecc-client-ga4gh-wes/src/components/run-output/tests/run-output.test.ts b/packages/ecc-client-ga4gh-wes/src/components/run-output/tests/run-output.test.ts index c4c668ae..8f496a67 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/run-output/tests/run-output.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/run-output/tests/run-output.test.ts @@ -5,6 +5,7 @@ import sinon from "sinon"; import "../index.js"; import { ECCClientGa4ghWesRunOutput } from "../run-output.js"; import type { WesOutputProvider } from "../../../providers/index.js"; +import { setDescriptionFormat } from "../../../io-schema/descriptions.js"; const REPORT = "s3://bucket/run/report.html"; const COUNTS = "s3://bucket/run/read_counts.tsv"; @@ -108,6 +109,44 @@ describe("ecc-client-ga4gh-wes-run-output", () => { expect(root(el).textContent).to.contain("2"); }); + it("shows Markdown descriptions as text by default", async () => { + const el = await render( + { + type: "integer", + description: "see [docs](https://example.org) *now*", + "x-ga4gh-description-format": "markdown", + }, + 2 + ); + expect(root(el).querySelector("a, em")).to.equal(null); + expect( + root(el).querySelector("[data-description]")?.textContent + ).to.contain("[docs](https://example.org)"); + }); + + it("renders Markdown descriptions once switched on", async () => { + setDescriptionFormat("markdown"); + try { + const el = await render( + { + type: "integer", + description: + "see [docs](https://example.org), [bad](javascript:x) *now*", + "x-ga4gh-description-format": "markdown", + }, + 2 + ); + const description = root(el).querySelector("[data-description]"); + expect(description?.querySelector("em")?.textContent).to.equal("now"); + const links = description?.querySelectorAll("a") ?? []; + expect(links).to.have.length(1); + expect(links[0].getAttribute("href")).to.equal("https://example.org"); + expect(description?.textContent).to.contain("bad"); + } finally { + setDescriptionFormat("plain"); + } + }); + it("falls back to the name of the output as its title", async () => { const el = await render({ type: "integer" }, 2); expect(root(el).querySelector("[data-title]")?.textContent).to.contain( diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/descriptions.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/descriptions.ts new file mode 100644 index 00000000..9777407a --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/descriptions.ts @@ -0,0 +1,132 @@ +/** + * Descriptions of IO schemas. With `"x-ga4gh-description-format": + * "markdown"`, a description is CommonMark with the profile's rules + * ("Markdown descriptions" in `docs/specification/keywords.md`): raw HTML + * is shown as escaped text, images as their alt text, links only with an + * allowed scheme (else their text), and of GFM only tables, strikethrough + * and autolinks. Clients may also show such descriptions as plain text. + * + * Which of the two the components do is one setting + * (`setDescriptionFormat`); plain text is the default. + */ +import { html, nothing, TemplateResult } from "lit"; +import { unsafeHTML } from "lit/directives/unsafe-html.js"; +import MarkdownIt from "markdown-it"; +import { FORBIDDEN_SCHEMES } from "./files.js"; + +/** How descriptions with `"x-ga4gh-description-format": "markdown"` show. */ +export type DescriptionFormat = "plain" | "markdown"; + +let format: DescriptionFormat = "plain"; + +/** How the components show Markdown descriptions. */ +export const getDescriptionFormat = (): DescriptionFormat => format; + +/** Sets how the components show Markdown descriptions. */ +export function setDescriptionFormat(value: DescriptionFormat): void { + format = value; +} + +const SCHEME = /^([A-Za-z][A-Za-z0-9+.-]*):/; + +interface RenderEnv { + [key: string | symbol]: unknown; + allowedSchemes: readonly string[]; + /** Whether each open link is rendered as a link */ + links: boolean[]; +} + +const markdown = new MarkdownIt("commonmark", { + // Raw HTML comes out as escaped text + html: false, + // Extended autolinks of GFM (`www.`, bare URLs) + linkify: true, +}).enable(["table", "strikethrough", "linkify"]); +// GFM links `www.` hosts too; a host without `www.` (`example.org`) stays +// text (see link_open) +markdown.linkify.set({ fuzzyLink: true }); + +// Links are checked by their renderers (against the allow-list), so that a +// refused link still shows its text, which markdown-it's own check doesn't +markdown.validateLink = () => true; + +/** Whether a link destination is an absolute URI with an allowed scheme. */ +function allowedLink(href: string, allowedSchemes: readonly string[]) { + const match = SCHEME.exec(href); + if (!match) return false; + const scheme = match[1].toLowerCase(); + return ( + !FORBIDDEN_SCHEMES.includes(scheme) && + allowedSchemes.some((allowed) => allowed.toLowerCase() === scheme) + ); +} + +markdown.renderer.rules.link_open = (tokens, idx, options, env, self) => { + const { links, allowedSchemes } = env as unknown as RenderEnv; + const token = tokens[idx]; + const text = tokens[idx + 1]?.content ?? ""; + const allowed = + allowedLink(String(token.attrGet("href") ?? ""), allowedSchemes) && + (token.markup !== "linkify" || + /^(www\.|[A-Za-z][A-Za-z0-9+.-]*:)/.test(text)); + links.push(allowed); + if (!allowed) return ""; + token.attrSet("target", "_blank"); + token.attrSet("rel", "noopener noreferrer"); + return self.renderToken(tokens, idx, options); +}; + +markdown.renderer.rules.link_close = (tokens, idx, options, env, self) => + (env as unknown as RenderEnv).links.pop() + ? self.renderToken(tokens, idx, options) + : ""; + +// Images show their alt text and are never loaded +markdown.renderer.rules.image = (tokens, idx, options, env) => + markdown.utils.escapeHtml( + markdown.renderer.renderInlineAsText( + tokens[idx].children ?? [], + options, + env + ) + ); + +/** + * Renders a Markdown description to HTML by the profile's rules. The HTML + * is safe to insert: it has no markup from the source, no images, and only + * links with allowed schemes, which open in a new window. + * + * @param text - The description. + * @param allowedSchemes - Schemes that links may have. + */ +export function renderMarkdown( + text: string, + allowedSchemes: readonly string[] +): string { + const env: RenderEnv = { allowedSchemes, links: [] }; + return markdown.render(text, env); +} + +/** + * The description of a schema, as text, or rendered from Markdown if the + * schema says it is Markdown and the components render Markdown. + * + * @param schema - A schema of an input or output. + * @param allowedSchemes - Schemes that links may have. + */ +export function descriptionTemplate( + schema: Record | undefined, + allowedSchemes: readonly string[] +): TemplateResult | typeof nothing { + const description = schema?.description; + if (typeof description !== "string" || description === "") return nothing; + if ( + format === "markdown" && + schema?.["x-ga4gh-description-format"] === "markdown" + ) { + // The only HTML that is inserted as such: see renderMarkdown() + return html`${unsafeHTML(renderMarkdown(description, allowedSchemes))}`; + } + // The caller's container keeps line breaks (`white-space: pre-line`) + return html`${description}`; +} diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/descriptions.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/descriptions.test.ts new file mode 100644 index 00000000..19f1c4fd --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/descriptions.test.ts @@ -0,0 +1,164 @@ +/* eslint-disable import/no-extraneous-dependencies */ +/* eslint-disable no-script-url -- tests that script URLs are refused */ +import { expect, fixture, html } from "@open-wc/testing"; +import { + DescriptionFormat, + descriptionTemplate, + renderMarkdown, + setDescriptionFormat, + getDescriptionFormat, +} from "../descriptions.js"; + +const ALLOWED = ["drs", "https"]; + +/** The profile's example of a Markdown description (keywords.md). */ +const EXAMPLE = + 'Reads in **FASTQ** format, see [the format](https://en.wikipedia.org/wiki/FASTQ_format).\n\n![Quality plot](https://example.org/plot.png)\n\nPaired-end reads go into two files.'; +const EXAMPLE_HTML = + '

Reads in FASTQ format, see the format.

\n' + + "

Quality plot

\n" + + "

<b onclick="alert(1)">Paired-end</b> reads go into two files.

\n"; + +/** HTML without the attributes that open links in a new window. */ +const withoutTarget = (text: string) => + text.replace(/ target="_blank" rel="noopener noreferrer"/g, ""); + +describe("renderMarkdown", () => { + it("renders the profile's example as the profile shows", () => { + expect(withoutTarget(renderMarkdown(EXAMPLE, ALLOWED))).to.equal( + EXAMPLE_HTML + ); + }); + + it("opens allowed links in a new window, without referrer", () => { + expect(renderMarkdown("[a](https://example.org)", ALLOWED)).to.equal( + '

a

\n' + ); + }); + + it("shows raw HTML blocks as text", () => { + expect( + renderMarkdown("\n\n
x
", ALLOWED) + ).to.equal( + "

<script>alert(1)</script>

\n

<div>x</div>

\n" + ); + }); + + it("decodes entities", () => { + expect(renderMarkdown("a & b <", ALLOWED)).to.equal( + "

a & b <

\n" + ); + }); + + for (const [name, source] of [ + ["javascript:", "[click](javascript:alert(1))"], + ["JavaScript: in other case", "[click](JaVaScRiPt:alert(1))"], + ["data:", "[click](data:text/html,x)"], + ["a scheme not on the allow-list", "[click](ftp://example.org/x)"], + ["a relative link", "[click](docs/readme.md)"], + ["a fragment", "[click](#top)"], + ["a reference link", "[click][r]\n\n[r]: javascript:alert(1)"], + ]) { + it(`shows only the text of a link with ${name}`, () => { + expect(renderMarkdown(source, ALLOWED)).to.equal("

click

\n"); + }); + } + + it("shows images as their alt text, also inside links", () => { + expect( + renderMarkdown( + "[![alt *text*](https://example.org/i.png)](https://example.org)", + ALLOWED + ) + ).to.equal( + '

alt text

\n' + ); + expect( + renderMarkdown('![](x.png)', ALLOWED) + ).to.equal("

<img src=x onerror="x">

\n"); + }); + + it("renders autolinks and extended autolinks", () => { + const out = renderMarkdown( + " and https://example.org/b and www.example.org", + ALLOWED + ); + expect(out).to.contain('href="https://example.org/a"'); + expect(out).to.contain('href="https://example.org/b"'); + expect(out).to.not.contain('href="http://www.example.org"'); + expect(out).to.contain("www.example.org"); + }); + + it("links www. autolinks if http is allowed", () => { + expect( + renderMarkdown("see www.example.org", [...ALLOWED, "http"]) + ).to.contain('href="http://www.example.org"'); + }); + + it("doesn't link host names without www.", () => { + expect(renderMarkdown("see example.org", [...ALLOWED, "http"])).to.equal( + "

see example.org

\n" + ); + }); + + it("renders GFM tables and strikethrough", () => { + const out = renderMarkdown( + "| a | b |\n|---|---|\n| 1 | 2 |\n\n~~old~~", + ALLOWED + ); + expect(out).to.contain(""); + expect(out).to.contain("old"); + }); + + it("doesn't render task lists or footnotes", () => { + const out = renderMarkdown("- [ ] task\n\nx[^1]\n\n[^1]: note", ALLOWED); + expect(out).to.not.contain(" { + afterEach(() => setDescriptionFormat("plain")); + + const render = async (schema: Record) => + fixture( + html`
${descriptionTemplate(schema, ALLOWED)}
` + ); + + it("shows nothing without a description", async () => { + const element = await render({}); + expect(element.textContent?.trim()).to.equal(""); + }); + + it("shows descriptions as plain text by default", async () => { + expect(getDescriptionFormat()).to.equal("plain"); + const element = await render({ + description: EXAMPLE, + "x-ga4gh-description-format": "markdown", + }); + expect(element.querySelector("a, b, img, strong")).to.equal(null); + expect(element.textContent).to.contain("**FASTQ**"); + expect(element.textContent).to.contain(''); + }); + + it("renders Markdown descriptions once switched on", async () => { + setDescriptionFormat("markdown" as DescriptionFormat); + const element = await render({ + description: EXAMPLE, + "x-ga4gh-description-format": "markdown", + }); + expect(element.querySelector("strong")?.textContent).to.equal("FASTQ"); + expect(element.querySelector("a")?.getAttribute("href")).to.equal( + "https://en.wikipedia.org/wiki/FASTQ_format" + ); + expect(element.querySelector("img, b")).to.equal(null); + }); + + it("keeps descriptions of other formats as plain text", async () => { + setDescriptionFormat("markdown"); + const element = await render({ description: "**not** markdown" }); + expect(element.querySelector("strong")).to.equal(null); + expect(element.textContent).to.contain("**not** markdown"); + }); +}); From 21d392a7483c10a8d725d3a22a44885b4b3bcbf8 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 09:13:21 +0100 Subject: [PATCH 04/19] feat(wes): add the I/O Schema input form Add ecc-client-ga4gh-wes-io-form. It checks the IO schema offline, describes its inputs as field descriptors (schema -> descriptors -> controls) and renders them with the design components by type, format and enum: text, number, checkbox, select, date, time, date-time, groups for objects and JSON for the rest. Defaults are prefilled, unset inputs are left out, and every change emits ecc-io-form-changed with {values, valid, errors}. Part of #444. Co-Authored-By: Claude Opus 5.5 --- .changeset/wes-io-form.md | 5 + .../components/packages/wes/IoFormPreview.tsx | 52 ++ .../components/packages/wes/ioFormExamples.ts | 386 +++++++++++ .../pages/docs/wes/components/_meta.json | 5 +- .../pages/docs/wes/components/io-form.mdx | 121 ++++ .../src/components/index.ts | 1 + .../src/components/io-form/index.ts | 13 + .../src/components/io-form/io-form.ts | 615 ++++++++++++++++++ .../components/io-form/tests/io-form.test.ts | 299 +++++++++ .../src/events/ecc-io-form-changed.ts | 9 + .../ecc-client-ga4gh-wes/src/events/index.ts | 1 + .../src/io-schema/fields.ts | 265 ++++++++ .../src/io-schema/tests/fields.test.ts | 167 +++++ .../src/io-schema/tests/values.test.ts | 105 +++ .../src/io-schema/values.ts | 135 ++++ .../ecc-client-ga4gh-wes/src/theming.test.ts | 1 + 16 files changed, 2178 insertions(+), 2 deletions(-) create mode 100644 .changeset/wes-io-form.md create mode 100644 apps/documentation/components/packages/wes/IoFormPreview.tsx create mode 100644 apps/documentation/components/packages/wes/ioFormExamples.ts create mode 100644 apps/documentation/pages/docs/wes/components/io-form.mdx create mode 100644 packages/ecc-client-ga4gh-wes/src/components/io-form/index.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/events/ecc-io-form-changed.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/tests/values.test.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/values.ts diff --git a/.changeset/wes-io-form.md b/.changeset/wes-io-form.md new file mode 100644 index 00000000..a8c777b2 --- /dev/null +++ b/.changeset/wes-io-form.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/wes": minor +--- + +Add `ecc-client-ga4gh-wes-io-form`, which renders the input form of a workflow from its GA4GH IO Schema (profile 0.3.0), checks the schema offline against the profile, validates the values in the browser and emits them with `ecc-io-form-changed` (`{values, valid, errors}`). Output descriptions of `ecc-client-ga4gh-wes-run-output` can be rendered as Markdown (off by default). diff --git a/apps/documentation/components/packages/wes/IoFormPreview.tsx b/apps/documentation/components/packages/wes/IoFormPreview.tsx new file mode 100644 index 00000000..a68b0fc2 --- /dev/null +++ b/apps/documentation/components/packages/wes/IoFormPreview.tsx @@ -0,0 +1,52 @@ +import React, { useState } from 'react'; +import { ECCClientGa4ghWesIoForm } from '@elixir-cloud/wes/react'; +import PreviewLayout from '@/components/common/PreviewLayout'; +import { ioFormExamples } from '@/components/packages/wes/ioFormExamples'; + +const allowedSchemes = ['drs', 'https', 's3']; + +interface Change { + values: Record; + valid: boolean; + errors: { pointer: string; message: string }[]; +} + +export default function IoFormPreview() { + const [example, setExample] = useState('demo'); + const [change, setChange] = useState(null); + + return ( + +
+ + ) => setChange(event.detail)} + /> + {change && ( +
+            {JSON.stringify(change, null, 2)}
+          
+ )} +
+
+ ); +} diff --git a/apps/documentation/components/packages/wes/ioFormExamples.ts b/apps/documentation/components/packages/wes/ioFormExamples.ts new file mode 100644 index 00000000..3004ba5a --- /dev/null +++ b/apps/documentation/components/packages/wes/ioFormExamples.ts @@ -0,0 +1,386 @@ +// Example IO schemas of the GA4GH IO Schema profile, pinned to commit +// 2c3dc49ad89f0a556272f160369a2a2d7a21dac3 of +// https://github.com/elixir-cloud-aai/ga4gh-io-schema (examples/demo and +// examples/workflows), for the preview of ecc-client-ga4gh-wes-io-form. + +export const ioFormExamples: Record }> = { + demo: { + label: 'IO Schema demo (WDL)', + schema: { + $schema: + 'https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json', + title: 'I/O Schema demo', + description: + 'Filters aligned reads by mapping quality and flags, sorts and indexes them, and reports alignment statistics.', + 'x-ga4gh-workflow': { + descriptor_type: 'WDL', + descriptor_type_version: '1.1', + entry_point: 'io_schema_demo', + checksum: [ + { + type: 'sha-256', + checksum: '505fa515d58e09e758a2c131398a26b7e1b9e4243899dce96c005cda4c790a65', + }, + ], + trs_tool_id: 'ga4gh-io-schema-demo', + trs_version_id: '1.1.0', + primary_descriptor_path: 'demo.wdl', + }, + type: 'object', + properties: { + inputs: { + type: 'object', + properties: { + reads: { + type: 'string', + 'x-ga4gh-file': { + kind: 'file', + ontology: 'http://edamontology.org/format_2572', + schemes: ['https', 's3'], + }, + description: 'Reads aligned to a reference, in BAM format, in any order.', + title: 'Aligned reads (BAM)', + 'x-ga4gh-parameter': { + type: 'File', + }, + examples: [ + 'https://raw.githubusercontent.com/nf-core/test-datasets/3e548a3b34994380db1602506e0721fadbad6de1/data/genomics/sarscov2/illumina/bam/test.paired_end.bam', + ], + }, + min_mapq: { + type: 'integer', + description: 'Reads with a lower mapping quality are removed (0 keeps all reads).', + title: 'Minimum mapping quality', + default: 0, + 'x-ga4gh-parameter': { + type: 'Int', + }, + minimum: 0, + maximum: 60, + 'x-ga4gh-ui-widget': 'slider', + 'x-ga4gh-error-message': 'The minimum mapping quality is a whole number from 0 to 60', + }, + read_filter: { + type: 'string', + description: + 'Which reads to keep besides the mapping quality: all, properly paired only, or primary alignments only.', + title: 'Read filter', + enum: ['none', 'proper_pairs', 'primary_only'], + default: 'none', + 'x-ga4gh-parameter': { + type: 'String', + }, + 'x-ga4gh-ui-widget': 'radio', + }, + }, + required: ['reads'], + additionalProperties: false, + }, + outputs: { + type: 'object', + properties: { + filtered_bam: { + type: 'string', + 'x-ga4gh-file': { + kind: 'file', + ontology: 'http://edamontology.org/format_2572', + }, + description: 'The filtered reads, sorted by coordinate.', + title: 'Filtered reads (BAM)', + 'x-ga4gh-parameter': { + type: 'File', + }, + }, + filtered_bam_index: { + type: 'string', + 'x-ga4gh-file': { + kind: 'file', + ontology: 'http://edamontology.org/format_3327', + }, + description: 'The index of the filtered reads.', + title: 'Index of the filtered reads (BAI)', + 'x-ga4gh-parameter': { + type: 'File', + }, + }, + report: { + type: 'string', + 'x-ga4gh-file': { + kind: 'file', + mediaType: 'text/html', + }, + description: 'Statistics of the reads before and after filtering.', + title: 'Alignment report (HTML)', + 'x-ga4gh-parameter': { + type: 'File', + }, + 'x-ga4gh-ui-widget': 'html-viewer', + }, + read_counts: { + type: 'string', + 'x-ga4gh-file': { + kind: 'file', + mediaType: 'text/tab-separated-values', + }, + description: + 'Mapped and unmapped reads per reference sequence, before and after filtering; unmapped reads without a position are counted under *.', + title: 'Read counts per reference (TSV)', + 'x-ga4gh-parameter': { + type: 'File', + }, + 'x-ga4gh-ui-widget': 'table-viewer', + }, + }, + required: ['filtered_bam', 'filtered_bam_index', 'report', 'read_counts'], + additionalProperties: false, + }, + }, + }, + }, + 'word-count-cwl': { + label: 'Word count (CWL)', + schema: { + $schema: + 'https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json', + title: 'Count words', + description: 'Counts the lines, words or characters of a text file.', + 'x-ga4gh-workflow': { + trs_tool_id: 'io-schema-word-count', + trs_version_id: '1.0.0', + descriptor_type: 'CWL', + descriptor_type_version: 'v1.2', + primary_descriptor_path: 'wc.cwl', + checksum: [ + { + type: 'sha-256', + checksum: '75431e88e519962aa8a2b1109dce230685eba243300c615f1cf6db393d79034f', + }, + ], + }, + type: 'object', + properties: { + inputs: { + type: 'object', + properties: { + text: { + type: 'string', + title: 'Text file', + description: 'A plain text file, by its URL.', + 'x-ga4gh-file': { + kind: 'file', + ontology: 'http://edamontology.org/format_2330', + schemes: ['https'], + }, + 'x-ga4gh-parameter': { + type: 'File', + }, + examples: [ + 'https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/README.md', + ], + }, + unit: { + type: 'string', + title: 'What to count', + enum: ['lines', 'words', 'characters'], + default: 'words', + 'x-ga4gh-ui-widget': 'dropdown', + }, + }, + required: ['text'], + additionalProperties: false, + }, + outputs: { + type: 'object', + properties: { + count: { + type: 'string', + title: 'Count', + description: 'The count and the name of the file, as wc prints them.', + 'x-ga4gh-file': { + kind: 'file', + mediaType: 'text/plain', + }, + 'x-ga4gh-parameter': { + type: 'File', + }, + }, + }, + required: ['count'], + additionalProperties: false, + }, + }, + }, + }, + 'greetings-nextflow': { + label: 'Greetings (Nextflow)', + schema: { + $schema: + 'https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json', + title: 'Greetings', + description: 'Greets people by name, in one of a few languages.', + 'x-ga4gh-workflow': { + trs_tool_id: 'io-schema-greetings', + trs_version_id: '1.0.0', + descriptor_type: 'NFL', + descriptor_type_version: 'DSL2', + primary_descriptor_path: 'main.nf', + checksum: [ + { + type: 'sha-256', + checksum: '1d19b64fc8fdadd9dd5b7d599e551d9e32f2447347200b07563403c05455d9de', + }, + ], + }, + type: 'object', + properties: { + inputs: { + type: 'object', + properties: { + names: { + type: 'array', + title: 'Names', + description: 'Who to greet, one name per line.', + items: { + type: 'string', + pattern: '^[A-Za-z][A-Za-z .-]*$', + 'x-ga4gh-error-message': + 'A name starts with a letter and has only letters, spaces, dots and dashes', + }, + minItems: 1, + maxItems: 10, + default: ['Ada', 'Grace'], + 'x-ga4gh-error-message': 'Give one to ten names', + }, + language: { + type: 'string', + title: 'Language', + enum: ['en', 'de', 'fr', 'it'], + default: 'en', + 'x-ga4gh-ui-widget': 'radio', + }, + times: { + type: 'integer', + title: 'How many times', + description: 'How often each greeting is repeated.', + minimum: 1, + maximum: 5, + default: 1, + 'x-ga4gh-ui-widget': 'slider', + }, + shout: { + type: 'boolean', + title: 'Shout', + description: 'Write the greetings in capitals.', + default: false, + 'x-ga4gh-ui-widget': 'checkbox', + }, + outdir: { + type: 'string', + title: 'Output directory', + description: 'Where the run writes the greetings.', + default: 'results', + 'x-ga4gh-hidden': true, + }, + }, + required: ['names'], + additionalProperties: false, + }, + outputs: { + type: 'object', + properties: { + greetings: { + type: 'array', + title: 'Greetings', + description: 'One text file per name.', + items: { + type: 'string', + 'x-ga4gh-file': { + kind: 'file', + mediaType: 'text/plain', + }, + }, + 'x-ga4gh-output-glob': 'results/*.txt', + }, + }, + additionalProperties: false, + }, + }, + }, + }, + 'report-snakemake': { + label: 'Report (Snakemake)', + schema: { + $schema: + 'https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json', + title: 'Little report', + description: 'Writes a small HTML report with a title, a date, notes and a colour.', + 'x-ga4gh-workflow': { + trs_tool_id: 'io-schema-report', + trs_version_id: '1.0.0', + descriptor_type: 'SMK', + descriptor_type_version: '8', + primary_descriptor_path: 'Snakefile', + checksum: [ + { + type: 'sha-256', + checksum: '6a2db7f3a57ee349752f0c98da86936f3cd7b2f05436e1263ff38708ad85a5a6', + }, + ], + }, + type: 'object', + properties: { + inputs: { + type: 'object', + properties: { + title: { + type: 'string', + title: 'Title', + minLength: 1, + maxLength: 80, + 'x-ga4gh-error-message': 'The title has 1 to 80 characters', + }, + date: { + type: 'string', + title: 'Date', + format: 'date', + 'x-ga4gh-ui-widget': 'date-picker', + }, + notes: { + type: 'string', + title: 'Notes', + description: 'Free text, on several lines.', + default: '', + 'x-ga4gh-ui-widget': 'textarea', + }, + colour: { + type: 'string', + title: 'Colour', + pattern: '^#[0-9a-f]{6}$', + default: '#1f77b4', + 'x-ga4gh-ui-widget': 'color-picker', + }, + }, + required: ['title', 'date'], + additionalProperties: false, + }, + outputs: { + type: 'object', + properties: { + report: { + type: 'string', + title: 'Report (HTML)', + 'x-ga4gh-file': { + kind: 'file', + mediaType: 'text/html', + }, + 'x-ga4gh-ui-widget': 'html-viewer', + 'x-ga4gh-output-glob': 'results/report.html', + }, + }, + required: ['report'], + additionalProperties: false, + }, + }, + }, + }, +}; diff --git a/apps/documentation/pages/docs/wes/components/_meta.json b/apps/documentation/pages/docs/wes/components/_meta.json index 3a163c29..ccac9fca 100644 --- a/apps/documentation/pages/docs/wes/components/_meta.json +++ b/apps/documentation/pages/docs/wes/components/_meta.json @@ -2,5 +2,6 @@ "runs": "Runs", "run": "Run", "run-output": "Run Output", - "run-create": "Run Create" -} \ No newline at end of file + "run-create": "Run Create", + "io-form": "I/O Form" +} diff --git a/apps/documentation/pages/docs/wes/components/io-form.mdx b/apps/documentation/pages/docs/wes/components/io-form.mdx new file mode 100644 index 00000000..938d7b58 --- /dev/null +++ b/apps/documentation/pages/docs/wes/components/io-form.mdx @@ -0,0 +1,121 @@ +import { Callout, Tabs } from 'nextra/components' +import ComponentName from '@/components/common/ComponentName' +import IoFormPreview from '@/components/packages/wes/IoFormPreview' + +# EccClientGa4ghWesIoForm Component + + + + + A proposal (cloud-components#444): the element, its event and the libraries behind it may still change. + + +## Overview + +The `ecc-client-ga4gh-wes-io-form` component renders the input form of a workflow from its [GA4GH IO Schema](https://github.com/elixir-cloud-aai/ga4gh-io-schema) (version 0.3.0, commit [`2c3dc49`](https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/2c3dc49ad89f0a556272f160369a2a2d7a21dac3)). It renders the `inputs` of the schema, validates the values in the browser and emits them; the app submits them, e.g. as `workflow_params` of a WES run. + +1. The schema is checked offline against the profile (see [I/O Schemas](../io-schema)). A schema that doesn't conform shows its errors, with the JSON Pointer of each, and no form. +2. Each input gets a control by its `type`, `format` and `enum`: + +| Input | Control | +|-------|---------| +| `string` | Text field | +| `string` with `format` `date`, `time` or `date-time` | Date, time or date-and-time picker | +| `integer`, `number` | Text field that gives a number | +| `boolean` | Checkbox | +| `enum` or `const` (any type) | Dropdown | +| `object` with `properties` | A group with a field per property, at any depth | +| Anything else | JSON text area | + +3. Inputs start from their `default` values; inputs without a value are left out of the values, never sent as `null` or `""`. +4. Errors show at their input once it was changed, and at all inputs after `reportValidity()`. + +Values follow the profile's widget table: a time is an RFC 3339 `full-time` with the offset of the browser's time zone (`14:30:00+01:00`), a date-time is in UTC (`2026-12-14T09:15:00Z`). Text that isn't a number is kept, so that the error says what is wrong. + +## Security + +Schemas are treated as untrusted: titles, descriptions and choices are shown as text, never as markup. Descriptions with `x-ga4gh-description-format: markdown` are shown as plain text unless the app switches Markdown on (see [Descriptions](../io-schema#descriptions)). + +## Usage + +The preview renders example schemas of the IO Schema profile and shows what the form emits. + + + + + + + + ```tsx showLineNumbers copy filename="io-form.tsx" + import React, { useState } from 'react'; + import { ECCClientGa4ghWesIoForm } from '@elixir-cloud/wes/react'; + + export default function IoForm({ schema }: { schema: object }) { + const [inputs, setInputs] = useState({ values: {}, valid: false }); + return ( + <> + setInputs(e.detail)} + /> + + + ); + } + ``` + + + + ```html showLineNumbers copy filename="io-form.html" + + + + + + + + + + + + ``` + + + +## Properties + +| Property | Attribute | Type | Default | Description | +|----------|-----------|------|---------|-------------| +| `schema` | | `object` | `undefined` | The IO schema of the workflow. | +| `values` | | `object` | `undefined` | Values to start from instead of the defaults. | +| `allowedSchemes` | `allowed-schemes` | `string[]` | `["drs", "https"]` | URI schemes that file references and links in descriptions may have. | +| `inputValues` | | `object` | | The current values (read only, a copy). | + +## Methods + +| Method | Description | +|--------|-------------| +| `reportValidity()` | Shows the errors of all inputs and returns whether the values are valid. | + +## Events + +| Event | Detail | Description | +|-------|--------|-------------| +| `ecc-io-form-changed` | `{ values, valid, errors }` | When the schema is loaded and whenever a value changes. `errors` holds `{ pointer, message }`, with JSON Pointers into `values`. | + +## CSS Parts + +| Part | Description | +|------|-------------| +| `base` | The form. | diff --git a/packages/ecc-client-ga4gh-wes/src/components/index.ts b/packages/ecc-client-ga4gh-wes/src/components/index.ts index 508e58ad..a1da31c8 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/index.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/index.ts @@ -2,3 +2,4 @@ import "./run-create/index.js"; import "./runs/index.js"; import "./run/index.js"; import "./run-output/index.js"; +import "./io-form/index.js"; diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/index.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/index.ts new file mode 100644 index 00000000..6efc7c58 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/index.ts @@ -0,0 +1,13 @@ +import ECCClientGa4ghWesIoForm from "./io-form.js"; + +export * from "./io-form.js"; +export default ECCClientGa4ghWesIoForm; + +// Define the custom element +customElements.define("ecc-client-ga4gh-wes-io-form", ECCClientGa4ghWesIoForm); + +declare global { + interface HTMLElementTagNameMap { + "ecc-client-ga4gh-wes-io-form": ECCClientGa4ghWesIoForm; + } +} diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts new file mode 100644 index 00000000..e207c429 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts @@ -0,0 +1,615 @@ +import { LitElement, html, css, nothing, PropertyValues } from "lit"; +import { property, state } from "lit/decorators.js"; +import { ComponentStyles as TailwindStyles } from "./tw-styles.js"; +import { GlobalStyles } from "../../global.js"; +import { + checkIoSchema, + InputsValidator, + ValidationError, +} from "../../io-schema/validator.js"; +import { + allFields, + defaultOf, + describeInputs, + Field, +} from "../../io-schema/fields.js"; +import { + fromDateTimeInput, + fromTimeInput, + getAt, + parseNumber, + setAt, + toDateTimeInput, + toTimeInput, +} from "../../io-schema/values.js"; +import { DEFAULT_ALLOWED_SCHEMES } from "../../io-schema/files.js"; +import { parsePointer } from "../../io-schema/pointer.js"; +import { descriptionTemplate } from "../../io-schema/descriptions.js"; +import "@elixir-cloud/design/components/input/index.js"; +import "@elixir-cloud/design/components/textarea/index.js"; +import "@elixir-cloud/design/components/select/index.js"; +import "@elixir-cloud/design/components/checkbox/index.js"; +import "@elixir-cloud/design/components/label/index.js"; +import "@elixir-cloud/design/components/skeleton/index.js"; + +/** The payload of `ecc-io-form-changed`. */ +export interface IoFormChange { + /** The input values, without unset inputs */ + values: Record; + /** Whether the values pass the IO schema and the form's own checks */ + valid: boolean; + /** The failures, with JSON Pointers into the values */ + errors: { pointer: string; message: string }[]; +} + +type Status = "empty" | "checking" | "invalid" | "ready"; + +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** Compares lists of schemes by content, ignoring case. */ +const sameSchemes = (a: unknown, b: unknown): boolean => + Array.isArray(a) && Array.isArray(b) + ? a.join(" ").toLowerCase() === b.join(" ").toLowerCase() + : a === b; + +/** A choice of `enum` as text. */ +const choiceLabel = (value: unknown) => + typeof value === "string" ? value : JSON.stringify(value); + +/** Whether a pointer is the same as or inside another. */ +const within = (pointer: string, outer: string) => + pointer === outer || pointer.startsWith(`${outer}/`); + +/** A value as the text of a text field. */ +const textOf = (value: unknown): string => { + if (value === undefined) return ""; + return typeof value === "string" ? value : String(value); +}; + +const deepCopy = (value: T): T => + value === undefined ? value : JSON.parse(JSON.stringify(value)); + +/** The error messages of a field. */ +const renderMessages = (messages: string[]) => + messages.length + ? html`` + : nothing; + +/** + * @summary Renders an input form from a GA4GH IO Schema, validates the + * values in the browser and emits them. + * @since 2.0.0 + * + * @property {object} schema - The IO schema (GA4GH IO Schema Profile 0.3.0). + * It is checked offline against the profile; an invalid schema shows its + * errors and no form. + * @property {object} values - Values to start from; without them, the + * defaults of the schema. + * @property {string[]} allowedSchemes - URI schemes that file references + * and links in descriptions may have (attribute `allowed-schemes`, + * separated by spaces or commas); default `drs https`. + * + * @method reportValidity - Shows the errors of all inputs, also of those + * that the user hasn't changed yet, and returns whether the values are + * valid. + * + * @fires ecc-io-form-changed - When the schema is loaded and whenever a + * value changes, with `{values, valid, errors}`. Never `workflow_params`. + * + * @csspart base - The form. + */ +export class ECCClientGa4ghWesIoForm extends LitElement { + static styles = [ + TailwindStyles, + GlobalStyles, + css` + :host { + display: block; + width: 100%; + } + `, + ]; + + @property({ attribute: false }) schema?: unknown; + @property({ attribute: false }) values?: Record; + @property({ + attribute: "allowed-schemes", + hasChanged: (value: unknown, old: unknown) => !sameSchemes(value, old), + converter: { + fromAttribute: (value: string | null) => + value === null + ? [...DEFAULT_ALLOWED_SCHEMES] + : value + .split(/[\s,]+/) + .filter(Boolean) + .map((scheme) => scheme.toLowerCase()), + toAttribute: (value: string[]) => value.join(" "), + }, + }) + allowedSchemes: string[] = [...DEFAULT_ALLOWED_SCHEMES]; + + @state() private status: Status = "empty"; + @state() private schemaErrors: ValidationError[] = []; + @state() private fields: Field[] = []; + @state() private current: Record = {}; + @state() private errors: ValidationError[] = []; + /** Problems found by the form itself (e.g. JSON that doesn't parse) */ + @state() private localErrors = new Map(); + /** Raw text of fields whose value couldn't be parsed */ + @state() private rawText = new Map(); + @state() private touched = new Set(); + @state() private showAll = false; + + private validateInputs?: InputsValidator; + + /** Number of the latest schema check, to drop stale results */ + private checks = 0; + + /** The current input values (a copy). */ + get inputValues(): Record { + return deepCopy(this.current); + } + + protected willUpdate(changed: PropertyValues): void { + if (changed.has("schema")) { + this.load(); + } else if (changed.has("values") && this.status === "ready") { + this.current = deepCopy(this.values) ?? {}; + this.localErrors = new Map(); + this.rawText = new Map(); + this.revalidate(); + } + } + + /** Shows the errors of all inputs and returns whether the values pass. */ + reportValidity(): boolean { + this.showAll = true; + return this.status === "ready" && this.isValid; + } + + private get isValid(): boolean { + return this.errors.length === 0 && this.localErrors.size === 0; + } + + private async load(): Promise { + this.checks += 1; + const check = this.checks; + this.validateInputs = undefined; + this.fields = []; + this.errors = []; + this.localErrors = new Map(); + this.rawText = new Map(); + this.touched = new Set(); + this.showAll = false; + if (this.schema === undefined || this.schema === null) { + this.status = "empty"; + return; + } + this.status = "checking"; + const result = await checkIoSchema(this.schema); + if (check !== this.checks) return; + if (!result.valid) { + this.status = "invalid"; + this.schemaErrors = result.errors; + return; + } + this.schemaErrors = []; + this.validateInputs = result.validateInputs; + this.fields = describeInputs(this.schema as Record); + this.current = this.values ? deepCopy(this.values) : this.defaults(); + this.status = "ready"; + this.revalidate(); + } + + /** The defaults of all inputs. */ + private defaults(): Record { + let values: unknown = {}; + for (const field of this.fields) { + const value = defaultOf(field); + if (value !== undefined) values = setAt(values, field.path, value); + } + return isObject(values) ? values : {}; + } + + private revalidate(): void { + const result = this.validateInputs?.(this.current); + this.errors = result?.errors ?? []; + this.dispatchEvent( + new CustomEvent("ecc-io-form-changed", { + detail: { + values: deepCopy(this.current), + valid: this.isValid, + errors: [ + ...[...this.localErrors].map(([pointer, message]) => ({ + pointer, + message, + })), + ...this.errors.map(({ pointer, message }) => ({ + pointer, + message, + })), + ], + }, + bubbles: true, + composed: true, + }) + ); + } + + /** Sets the value of a field (`undefined` leaves it out). */ + private setValue(field: Field, value: unknown, problem?: string): void { + const next = setAt(this.current, field.path, value); + this.current = isObject(next) ? next : {}; + this.touched = new Set(this.touched).add(field.pointer); + const localErrors = new Map(this.localErrors); + if (problem) localErrors.set(field.pointer, problem); + else localErrors.delete(field.pointer); + this.localErrors = localErrors; + this.revalidate(); + } + + private setRaw(field: Field, text: string | undefined): void { + const rawText = new Map(this.rawText); + if (text === undefined) rawText.delete(field.pointer); + else rawText.set(field.pointer, text); + this.rawText = rawText; + } + + /** The field that shows an error: at its pointer, or the nearest above. */ + private fieldFor(pointer: string): Field | undefined { + let best: Field | undefined; + for (const field of allFields(this.fields)) { + if ( + within(pointer, field.pointer) && + (!best || field.pointer.length > best.pointer.length) + ) { + best = field; + } + } + return best; + } + + /** + * The messages to show, by the pointer of the field that shows them; "" + * for errors of the values as a whole. A missing required input is shown + * at that input. + */ + private messages(): Map { + const messages = new Map(); + const add = (pointer: string, message: string) => { + const list = messages.get(pointer) ?? []; + if (!list.includes(message)) list.push(message); + messages.set(pointer, list); + }; + const pointers = new Set( + [...allFields(this.fields)].map((field) => field.pointer) + ); + for (const error of this.errors) { + let placed = false; + if (error.keyword === "required") { + const object = getAt(this.current, parsePointer(error.pointer)); + for (const field of allFields(this.fields)) { + const parent = field.pointer.slice(0, field.pointer.lastIndexOf("/")); + if ( + parent === error.pointer && + field.required && + !(isObject(object) && field.name in object) && + pointers.has(field.pointer) + ) { + add(field.pointer, "This input is required."); + placed = true; + } + } + } + if (!placed) { + const field = this.fieldFor(error.pointer); + add(field?.pointer ?? "", error.message); + } + } + for (const [pointer, message] of this.localErrors) add(pointer, message); + return messages; + } + + /** Whether the errors of a field are shown. */ + private shows(pointer: string): boolean { + if (this.showAll) return true; + for (const touched of this.touched) { + if (within(touched, pointer) || within(pointer, touched)) return true; + } + return false; + } + + render() { + switch (this.status) { + case "empty": + return nothing; + case "checking": + return html`
+ + +
`; + case "invalid": + return this.renderSchemaErrors(); + default: + return this.renderForm(); + } + } + + private renderSchemaErrors() { + return html``; + } + + private renderForm() { + const messages = this.messages(); + const general = this.shows("") || this.showAll ? messages.get("") : []; + return html`
e.preventDefault()} + > + ${general && general.length + ? html`` + : nothing} + ${this.fields.length === 0 + ? html`

+ This workflow has no inputs to set. +

` + : this.fields.map((field) => this.renderField(field, messages))} + `; + } + + private renderField(field: Field, messages: Map): unknown { + const fieldMessages = this.shows(field.pointer) + ? messages.get(field.pointer) ?? [] + : []; + const id = `input${field.pointer.replace(/[^A-Za-z0-9_-]/g, "_")}`; + if (field.control === "group") { + return html`
+ + ${field.title}${field.required + ? html` *` + : nothing} + + ${this.renderDescription(field)} ${renderMessages(fieldMessages)} + ${field.children.map((child) => this.renderField(child, messages))} +
`; + } + return html`
+ ${field.control === "checkbox" + ? nothing + : html` + ${field.title}${field.required + ? html` *` + : nothing} + `} + ${this.renderControl(field, id, fieldMessages.length > 0)} + ${this.renderDescription(field)} ${renderMessages(fieldMessages)} +
`; + } + + private renderDescription(field: Field) { + const description = descriptionTemplate(field.schema, this.allowedSchemes); + return description === nothing + ? nothing + : html`
+ ${description} +
`; + } + + private renderControl(field: Field, id: string, invalid: boolean) { + const value = getAt(this.current, field.path); + const raw = this.rawText.get(field.pointer); + switch (field.control) { + case "checkbox": + return html``; + case "select": + return this.renderSelect(field, id, value, invalid); + case "number": + return html` { + const text = String(e.detail.value); + this.setRaw(field, text); + this.setValue(field, parseNumber(text)); + }} + >`; + case "date": + return this.renderInput( + field, + id, + "date", + String(value ?? ""), + invalid, + (text) => (text === "" ? undefined : text) + ); + case "time": + return this.renderInput( + field, + id, + "time", + typeof value === "string" ? toTimeInput(value) : "", + invalid, + (text) => fromTimeInput(text, new Date()) + ); + case "datetime": + return this.renderInput( + field, + id, + "datetime-local", + typeof value === "string" ? toDateTimeInput(value) : "", + invalid, + fromDateTimeInput + ); + case "json": + return this.renderJson(field, id, value, raw, invalid); + default: + return this.renderInput( + field, + id, + "text", + textOf(value), + invalid, + (text) => (text === "" ? undefined : text) + ); + } + } + + private renderInput( + field: Field, + id: string, + type: string, + shown: string, + invalid: boolean, + parse: (text: string) => unknown + ) { + return html` + this.setValue(field, parse(String(e.detail.value)))} + >`; + } + + private renderSelect( + field: Field, + id: string, + value: unknown, + invalid: boolean + ) { + const choices = field.choices ?? []; + const index = choices.findIndex( + (choice) => JSON.stringify(choice) === JSON.stringify(value) + ); + return html` { + const chosen = String(e.detail.value); + this.setValue( + field, + chosen === "" ? undefined : choices[Number(chosen)] + ); + }} + > + + + + + ${field.required + ? nothing + : html`(not set)`} + ${choices.map( + (choice, i) => + html`${choiceLabel(choice)}` + )} + + `; + } + + private renderJson( + field: Field, + id: string, + value: unknown, + raw: string | undefined, + invalid: boolean + ) { + return html` { + const text = String(e.detail.value); + this.setRaw(field, text); + if (text.trim() === "") { + this.setValue(field, undefined); + return; + } + try { + this.setValue(field, JSON.parse(text)); + } catch { + this.setValue(field, undefined, "This isn't valid JSON."); + } + }} + >`; + } +} + +export default ECCClientGa4ghWesIoForm; diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts new file mode 100644 index 00000000..dd73ca30 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts @@ -0,0 +1,299 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect, fixture, html, oneEvent, waitUntil } from "@open-wc/testing"; +import "../index.js"; +import type { ECCClientGa4ghWesIoForm, IoFormChange } from "../io-form.js"; +import { PROFILE_ID } from "../../../io-schema/validator.js"; +import { EXAMPLES } from "../../../io-schema/tests/fixtures/examples.js"; + +/** An IO schema with the given inputs object. */ +const ioSchema = ( + inputs: Record, + extra: Record = {} +) => ({ + $schema: PROFILE_ID, + type: "object", + properties: { inputs: { type: "object", ...inputs } }, + ...extra, +}); + +const SCHEMA = ioSchema({ + properties: { + sample: { type: "string", title: "Sample", pattern: "^S[0-9]+$" }, + threads: { + type: "integer", + minimum: 1, + maximum: 64, + default: 4, + description: "CPU threads", + }, + ratio: { type: "number" }, + paired: { type: "boolean", default: true }, + mode: { type: "string", enum: ["fast", "exact"], default: "fast" }, + level: { enum: [1, 2, null] }, + day: { type: "string", format: "date" }, + at: { type: "string", format: "time" }, + when: { type: "string", format: "date-time" }, + options: { + type: "object", + title: "Options", + properties: { seed: { type: "integer" } }, + }, + extra: { type: "object" }, + }, + required: ["sample"], +}); + +const root = (el: ECCClientGa4ghWesIoForm) => el.shadowRoot as ShadowRoot; + +const ready = async (el: ECCClientGa4ghWesIoForm) => { + await waitUntil( + () => root(el).querySelector("form, [data-schema-errors]"), + "the form didn't render", + { timeout: 5000 } + ); + await el.updateComplete; +}; + +const render = async (schema: unknown, values?: Record) => { + const el = await fixture( + html`` + ); + await ready(el); + return el; +}; + +const control = (el: ECCClientGa4ghWesIoForm, pointer: string) => { + const found = root(el).querySelector(`[data-pointer="${pointer}"]`); + if (!found) throw new Error(`no control for ${pointer}`); + return found as HTMLElement & { value?: unknown; checked?: boolean }; +}; + +/** Changes a control as the user would, and returns the emitted change. */ +const change = async ( + el: ECCClientGa4ghWesIoForm, + pointer: string, + detail: Record +): Promise => { + const event = oneEvent(el, "ecc-io-form-changed"); + control(el, pointer).dispatchEvent( + new CustomEvent("ecc-input-changed", { + detail, + bubbles: true, + composed: true, + }) + ); + const { detail: emitted } = await event; + await el.updateComplete; + return emitted as IoFormChange; +}; + +describe("ecc-client-ga4gh-wes-io-form", () => { + it("renders nothing without a schema", async () => { + const el = await fixture( + html`` + ); + expect(root(el).querySelector("form")).to.equal(null); + }); + + it("shows the errors of an invalid schema and no form", async () => { + const el = await render( + ioSchema({ + properties: { a: { type: "string", "x-ga4gh-ui-widget": "slider" } }, + }) + ); + expect(root(el).querySelector("form")).to.equal(null); + const box = root(el).querySelector("[data-schema-errors]"); + expect(box?.textContent).to.contain("/properties/inputs/properties/a"); + }); + + it("refuses schemas that don't name the profile", async () => { + const el = await render({ type: "object" }); + expect(root(el).querySelector("[data-schema-errors]")).to.not.equal(null); + }); + + it("emits the defaults when the schema is loaded", async () => { + const el = await fixture( + html`` + ); + const event = oneEvent(el, "ecc-io-form-changed"); + el.schema = SCHEMA; + const { detail } = await event; + expect(detail.values).to.deep.equal({ + threads: 4, + paired: true, + mode: "fast", + }); + expect(detail.valid).to.equal(false); + expect(detail.errors[0].message).to.contain("sample"); + }); + + it("renders one control per input, at any depth", async () => { + const el = await render(SCHEMA); + for (const pointer of [ + "/sample", + "/threads", + "/ratio", + "/paired", + "/mode", + "/level", + "/day", + "/at", + "/when", + "/options/seed", + "/extra", + ]) { + expect(control(el, pointer).tagName, pointer).to.be.a("string"); + } + expect(control(el, "/sample").tagName).to.equal("ECC-UTILS-DESIGN-INPUT"); + expect(control(el, "/paired").tagName).to.equal( + "ECC-UTILS-DESIGN-CHECKBOX" + ); + expect(control(el, "/mode").tagName).to.equal("ECC-UTILS-DESIGN-SELECT"); + expect(control(el, "/extra").tagName).to.equal("ECC-UTILS-DESIGN-TEXTAREA"); + expect( + root(el).querySelector('fieldset[data-pointer="/options"] legend') + ?.textContent + ).to.contain("Options"); + }); + + it("gives values of the right type", async () => { + const el = await render(SCHEMA); + let result = await change(el, "/sample", { value: "S1" }); + expect(result.values.sample).to.equal("S1"); + expect(result.valid).to.equal(true); + result = await change(el, "/threads", { value: "8" }); + expect(result.values.threads).to.equal(8); + result = await change(el, "/ratio", { value: "0.5" }); + expect(result.values.ratio).to.equal(0.5); + result = await change(el, "/paired", { checked: false }); + expect(result.values.paired).to.equal(false); + result = await change(el, "/mode", { value: "1" }); + expect(result.values.mode).to.equal("exact"); + result = await change(el, "/level", { value: "2" }); + expect(result.values.level).to.equal(null); + result = await change(el, "/day", { value: "2026-12-14" }); + expect(result.values.day).to.equal("2026-12-14"); + result = await change(el, "/at", { value: "14:30" }); + expect(result.values.at).to.match(/^14:30:00([+-]\d\d:\d\d|Z)$/); + result = await change(el, "/when", { value: "2026-12-14T10:00" }); + expect(result.values.when).to.match(/^2026-12-1[34]T\d\d:00:00Z$/); + result = await change(el, "/options/seed", { value: "7" }); + expect(result.values.options).to.deep.equal({ seed: 7 }); + result = await change(el, "/extra", { value: '{"a": [1]}' }); + expect(result.values.extra).to.deep.equal({ a: [1] }); + expect(result.valid).to.equal(true); + }); + + it("leaves cleared inputs out", async () => { + const el = await render(SCHEMA); + await change(el, "/options/seed", { value: "7" }); + const result = await change(el, "/options/seed", { value: "" }); + expect(result.values).to.not.have.property("options"); + const cleared = await change(el, "/mode", { value: "" }); + expect(cleared.values).to.not.have.property("mode"); + expect(Object.values(cleared.values)).to.not.include(null); + }); + + it("reports values that fail, at their input, once changed", async () => { + const el = await render(SCHEMA); + expect(root(el).querySelector("[data-error]")).to.equal(null); + const result = await change(el, "/threads", { value: "100" }); + expect(result.valid).to.equal(false); + expect(result.errors).to.deep.include({ + pointer: "/threads", + message: "Must be at most 64.", + }); + const field = root(el).querySelector('[data-field="/threads"]'); + expect(field?.querySelector("[data-error]")?.textContent).to.contain( + "at most 64" + ); + expect(control(el, "/threads").hasAttribute("invalid")).to.equal(true); + }); + + it("keeps text that isn't a number, and reports it", async () => { + const el = await render(SCHEMA); + const result = await change(el, "/threads", { value: "many" }); + expect(result.values.threads).to.equal("many"); + expect(result.valid).to.equal(false); + expect(control(el, "/threads").value).to.equal("many"); + }); + + it("reports JSON that doesn't parse", async () => { + const el = await render(SCHEMA); + const result = await change(el, "/extra", { value: "{oops" }); + expect(result.valid).to.equal(false); + expect(result.errors).to.deep.include({ + pointer: "/extra", + message: "This isn't valid JSON.", + }); + expect(result.values).to.not.have.property("extra"); + }); + + it("shows missing required inputs at the input on reportValidity()", async () => { + const el = await render(SCHEMA); + expect(el.reportValidity()).to.equal(false); + await el.updateComplete; + const field = root(el).querySelector('[data-field="/sample"]'); + expect(field?.querySelector("[data-error]")?.textContent).to.contain( + "required" + ); + await change(el, "/sample", { value: "S2" }); + expect(el.reportValidity()).to.equal(true); + }); + + it("starts from given values instead of the defaults", async () => { + const el = await render(SCHEMA, { sample: "S9" }); + expect(el.inputValues).to.deep.equal({ sample: "S9" }); + expect(control(el, "/sample").value).to.equal("S9"); + }); + + it("never renders titles, descriptions or choices as HTML", async () => { + const el = await render( + ioSchema({ + properties: { + a: { + type: "string", + title: "bold", + description: "", + enum: ["x"], + }, + }, + }) + ); + expect(root(el).querySelector("b, img, i")).to.equal(null); + expect(root(el).textContent).to.contain("bold"); + expect(root(el).textContent).to.contain(""); + expect(root(el).textContent).to.contain("x"); + }); + + it("drops the result of a schema that was replaced", async () => { + const el = await fixture( + html`` + ); + el.schema = SCHEMA; + el.schema = ioSchema({ properties: { only: { type: "string" } } }); + await ready(el); + await new Promise((resolve) => { + setTimeout(resolve, 100); + }); + expect(root(el).querySelector('[data-pointer="/sample"]')).to.equal(null); + expect(root(el).querySelector('[data-pointer="/only"]')).to.not.equal(null); + }); + + for (const name of [ + "example_tool", + "example_wdl", + "example_workflow", + "demo", + "word-count-cwl", + ]) { + it(`renders the profile's example ${name}`, async () => { + const el = await render(EXAMPLES[name]); + expect(root(el).querySelector("form")).to.not.equal(null); + expect(root(el).querySelector("[data-schema-errors]")).to.equal(null); + }); + } +}); diff --git a/packages/ecc-client-ga4gh-wes/src/events/ecc-io-form-changed.ts b/packages/ecc-client-ga4gh-wes/src/events/ecc-io-form-changed.ts new file mode 100644 index 00000000..f507f07f --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/events/ecc-io-form-changed.ts @@ -0,0 +1,9 @@ +import type { IoFormChange } from "../components/io-form/io-form.js"; + +export type EccIoFormChangedEvent = CustomEvent; + +declare global { + interface GlobalEventHandlersEventMap { + "ecc-io-form-changed": EccIoFormChangedEvent; + } +} diff --git a/packages/ecc-client-ga4gh-wes/src/events/index.ts b/packages/ecc-client-ga4gh-wes/src/events/index.ts index 3615c612..c3080ec4 100644 --- a/packages/ecc-client-ga4gh-wes/src/events/index.ts +++ b/packages/ecc-client-ga4gh-wes/src/events/index.ts @@ -4,3 +4,4 @@ export type { EccRunsChangedEvent } from "./ecc-runs-changed.js"; export type { EccRunsSelectedEvent } from "./ecc-runs-selected.js"; export type { EccRunLogChangedEvent } from "./ecc-run-log-changed.js"; export type { EccRunCreateResetEvent } from "./ecc-run-create-reset.js"; +export type { EccIoFormChangedEvent } from "./ecc-io-form-changed.js"; diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts new file mode 100644 index 00000000..eb18077b --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts @@ -0,0 +1,265 @@ +/** + * Field descriptors of IO schema forms: what to render for each input of + * `inputs`, at any depth, independent of how it is rendered. The form + * element renders descriptors with controls, so that another source of + * descriptors (e.g. a form library) could replace this module without + * changing the element's API. + * + * Controls are chosen as the portals guide says (step 4, "Fallbacks"): by + * `type`, `format` and `enum`. Only local references (`#/...`) are followed; + * the schema has been checked before, so they all resolve. + */ +import { parsePointer, toPointer } from "./pointer.js"; +import type { Path } from "./values.js"; + +/** A JSON Schema of an input, or `true`/`false`. */ +export type Schema = Record; + +/** How an input is edited. */ +export type ControlKind = + | "text" + | "number" + | "checkbox" + | "select" + | "date" + | "time" + | "datetime" + | "group" + | "json"; + +/** One input of the form. */ +export interface Field { + /** Property name, or the item index in a list */ + name: string; + /** Path of the value in the input values */ + path: Path; + /** JSON Pointer of the value in the input values */ + pointer: string; + /** The schema of the input, with local `$ref`s merged in */ + schema: Schema; + /** The schema as written, with the input's own keywords (e.g. widgets) */ + ownSchema: Schema; + title: string; + control: ControlKind; + /** The JSON type of the value, without `null` */ + type?: string; + /** Whether the value may be `null` */ + nullable: boolean; + /** Whether the enclosing object lists the input in `required` */ + required: boolean; + /** The values of `enum` (or `const`), for choices */ + choices?: unknown[]; + /** The fields of an object */ + children: Field[]; +} + +const MAX_DEPTH = 32; + +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** The schema at a local reference (`#/...`) of a document, or `{}`. */ +function target(document: Schema, ref: string): Schema { + if (!ref.startsWith("#")) return {}; + let pointer: string; + try { + pointer = decodeURIComponent(ref.slice(1)); + let value: unknown = document; + for (const segment of parsePointer(pointer)) { + if (!isObject(value) && !Array.isArray(value)) return {}; + value = (value as Record)[segment]; + } + return isObject(value) ? value : {}; + } catch { + return {}; + } +} + +/** + * A schema with its local `$ref`s merged in: the referenced schema's + * keywords, overridden by the schema's own (as both apply in 2020-12). + */ +export function resolve(document: Schema, schema: unknown): Schema { + let current: Schema = isObject(schema) ? schema : {}; + const seen = new Set(); + for (let depth = 0; depth < MAX_DEPTH; depth += 1) { + const ref = current.$ref; + if (typeof ref !== "string" || seen.has(ref)) break; + seen.add(ref); + const own: Schema = { ...current }; + delete own.$ref; + current = { ...target(document, ref), ...own }; + if (current.$ref === ref) delete current.$ref; + } + return current; +} + +/** The JSON type of a schema without `null`, and whether it allows `null`. */ +export function typeOf(schema: Schema): { type?: string; nullable: boolean } { + const { type } = schema; + if (typeof type === "string") return { type, nullable: type === "null" }; + if (Array.isArray(type)) { + const others = type.filter((t) => t !== "null"); + return { + type: others.length === 1 ? String(others[0]) : undefined, + nullable: type.includes("null"), + }; + } + // Without `type`: what the other keywords imply + if (isObject(schema.properties)) return { type: "object", nullable: false }; + if (isObject(schema.items)) return { type: "array", nullable: false }; + if (isObject(schema["x-ga4gh-file"])) { + return { type: "string", nullable: false }; + } + const choices = choicesOf(schema); + if (choices && choices.length > 0) { + const types = new Set(choices.map((c) => jsonType(c))); + types.delete("null"); + return { + type: types.size === 1 ? [...types][0] : undefined, + nullable: choices.includes(null), + }; + } + return { nullable: false }; +} + +/** The JSON type of a value. */ +export function jsonType(value: unknown): string { + if (value === null) return "null"; + if (Array.isArray(value)) return "array"; + if (typeof value === "number") { + return Number.isInteger(value) ? "integer" : "number"; + } + return typeof value; +} + +/** The values of `enum`, or of `const`, if any. */ +export function choicesOf(schema: Schema): unknown[] | undefined { + if (Array.isArray(schema.enum)) return schema.enum; + if ("const" in schema) return [schema.const]; + return undefined; +} + +/** The control for a schema without a widget hint (by type, format, enum). */ +export function controlByType(schema: Schema): ControlKind { + const { type } = typeOf(schema); + if (choicesOf(schema)) return "select"; + switch (type) { + case "boolean": + return "checkbox"; + case "integer": + case "number": + return "number"; + case "string": + if (schema.format === "date") return "date"; + if (schema.format === "time") return "time"; + if (schema.format === "date-time") return "datetime"; + return "text"; + case "object": + return isObject(schema.properties) ? "group" : "json"; + default: + return "json"; + } +} + +/** The title of an input: its `title`, else its name. */ +const titleOf = (schema: Schema, name: string) => + typeof schema.title === "string" && schema.title !== "" ? schema.title : name; + +/** + * Describes one input. + * + * @param document - The IO schema. + * @param ownSchema - The schema of the input as written. + * @param name - Its property name. + * @param path - Path of its value. + * @param required - Whether the enclosing object requires it. + * @param depth - Nesting depth, to stop at cycles. + */ +export function describeField( + document: Schema, + ownSchema: unknown, + name: string, + path: Path, + required: boolean, + depth = 0 +): Field { + const own = isObject(ownSchema) ? ownSchema : {}; + const schema = resolve(document, own); + const { type, nullable } = typeOf(schema); + let control = controlByType(schema); + if (control === "group" && depth >= MAX_DEPTH) control = "json"; + const field: Field = { + name, + path, + pointer: toPointer(path), + schema, + ownSchema: own, + title: titleOf(schema, name), + control, + type, + nullable, + required, + choices: choicesOf(schema), + children: [], + }; + if (control === "group") { + field.children = describeProperties(document, schema, path, depth + 1); + } + return field; +} + +/** Describes the properties of an object schema. */ +export function describeProperties( + document: Schema, + schema: Schema, + path: Path, + depth = 0 +): Field[] { + const properties = isObject(schema.properties) ? schema.properties : {}; + const required = Array.isArray(schema.required) ? schema.required : []; + return Object.entries(properties).map(([name, property]) => + describeField( + document, + property, + name, + [...path, name], + required.includes(name), + depth + ) + ); +} + +/** The schema of `inputs` of an IO schema, resolved. */ +export function inputsSchema(document: Schema): Schema { + const properties = isObject(document.properties) ? document.properties : {}; + return resolve(document, properties.inputs); +} + +/** Describes the inputs of an IO schema. */ +export function describeInputs(document: Schema): Field[] { + return describeProperties(document, inputsSchema(document), []); +} + +/** + * The defaults of a field: its own `default`, else, for an object, the + * defaults of its fields; `undefined` if none. + */ +export function defaultOf(field: Field): unknown { + if ("default" in field.schema) return field.schema.default; + if (field.control !== "group") return undefined; + const value: Record = {}; + for (const child of field.children) { + const childDefault = defaultOf(child); + if (childDefault !== undefined) value[child.name] = childDefault; + } + return Object.keys(value).length > 0 ? value : undefined; +} + +/** The fields at any depth, depth first. */ +export function* allFields(fields: Field[]): Generator { + for (const field of fields) { + yield field; + yield* allFields(field.children); + } +} diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts new file mode 100644 index 00000000..9c50ea87 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts @@ -0,0 +1,167 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import { + allFields, + controlByType, + defaultOf, + describeInputs, + resolve, + typeOf, +} from "../fields.js"; +import { EXAMPLES } from "./fixtures/examples.js"; + +const doc = ( + inputs: Record, + extra: Record = {} +) => ({ + type: "object", + properties: { inputs: { type: "object", ...inputs } }, + ...extra, +}); + +describe("controlByType", () => { + const cases: [Record, string][] = [ + [{ type: "string" }, "text"], + [{ type: "string", format: "date" }, "date"], + [{ type: "string", format: "time" }, "time"], + [{ type: "string", format: "date-time" }, "datetime"], + [{ type: "string", format: "email" }, "text"], + [{ type: "integer" }, "number"], + [{ type: ["number", "null"] }, "number"], + [{ type: "boolean" }, "checkbox"], + [{ type: "string", enum: ["a", "b"] }, "select"], + [{ enum: [1, "a", null] }, "select"], + [{ const: 3 }, "select"], + [{ type: "object", properties: {} }, "group"], + [{ type: "object" }, "json"], + [{ type: ["string", "integer"] }, "json"], + [{}, "json"], + ]; + for (const [schema, control] of cases) { + it(`renders ${JSON.stringify(schema)} as ${control}`, () => { + expect(controlByType(schema)).to.equal(control); + }); + } +}); + +describe("typeOf", () => { + it("separates null from the type", () => { + expect(typeOf({ type: ["string", "null"] })).to.deep.equal({ + type: "string", + nullable: true, + }); + expect(typeOf({ enum: ["a", null] })).to.deep.equal({ + type: "string", + nullable: true, + }); + expect(typeOf({ properties: {} }).type).to.equal("object"); + }); +}); + +describe("resolve", () => { + it("merges local references, the schema's own keywords winning", () => { + const document = { + $defs: { + a: { $ref: "#/$defs/b", title: "A" }, + b: { type: "integer", title: "B", minimum: 1 }, + }, + }; + expect( + resolve(document, { $ref: "#/$defs/a", title: "own" }) + ).to.deep.equal({ type: "integer", title: "own", minimum: 1 }); + }); + + it("stops at cycles and missing targets", () => { + const document = { $defs: { a: { $ref: "#/$defs/a" } } }; + expect(resolve(document, { $ref: "#/$defs/a" })).to.deep.equal({}); + expect(resolve(document, { $ref: "#/nowhere" })).to.deep.equal({}); + expect(resolve(document, { $ref: "https://example.org/x" })).to.deep.equal( + {} + ); + }); + + it("decodes pointers of references", () => { + const document = { + $defs: { "a b": { type: "string" }, "c/d": { type: "integer" } }, + }; + expect(resolve(document, { $ref: "#/$defs/a%20b" }).type).to.equal( + "string" + ); + expect(resolve(document, { $ref: "#/$defs/c~1d" }).type).to.equal( + "integer" + ); + }); +}); + +describe("describeInputs", () => { + it("describes inputs at any depth", () => { + const fields = describeInputs( + doc( + { + properties: { + name: { type: "string", title: "Name" }, + options: { + type: "object", + properties: { threads: { $ref: "#/$defs/threads" } }, + required: ["threads"], + }, + }, + required: ["name"], + }, + { $defs: { threads: { type: "integer", default: 2 } } } + ) + ); + expect(fields.map((f) => [f.name, f.control, f.required])).to.deep.equal([ + ["name", "text", true], + ["options", "group", false], + ]); + const [threads] = fields[1].children; + expect(threads).to.include({ + name: "threads", + pointer: "/options/threads", + control: "number", + required: true, + title: "threads", + }); + expect(defaultOf(fields[1])).to.deep.equal({ threads: 2 }); + }); + + it("escapes pointers", () => { + const [field] = describeInputs(doc({ properties: { "a/b": {} } })); + expect(field.pointer).to.equal("/a~1b"); + }); + + it("stops at recursive objects", () => { + const fields = describeInputs( + doc( + { properties: { node: { $ref: "#/$defs/node" } } }, + { + $defs: { + node: { + type: "object", + properties: { child: { $ref: "#/$defs/node" } }, + }, + }, + } + ) + ); + const depth = [...allFields(fields)].length; + expect(depth).to.be.below(40); + expect([...allFields(fields)].pop()?.control).to.equal("json"); + }); + + it("describes every input of the profile's examples", () => { + for (const [name, example] of Object.entries(EXAMPLES)) { + const inputs = (example.properties as Record) + .inputs as Record; + const properties = Object.keys( + (inputs.properties as Record) ?? {} + ); + const fields = describeInputs(example); + expect( + fields.map((f) => f.name), + name + ).to.deep.equal(properties); + } + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/values.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/values.test.ts new file mode 100644 index 00000000..b5626f20 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/values.test.ts @@ -0,0 +1,105 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import { + fromDateTimeInput, + fromTimeInput, + getAt, + parseNumber, + setAt, + toDateTimeInput, + toTimeInput, +} from "../values.js"; + +describe("setAt", () => { + it("sets nested values, creating objects and arrays", () => { + expect(setAt({}, ["a", "b"], 1)).to.deep.equal({ a: { b: 1 } }); + expect(setAt({}, ["a", 0], "x")).to.deep.equal({ a: ["x"] }); + }); + + it("doesn't change the original", () => { + const original = { a: { b: 1 } }; + setAt(original, ["a", "b"], 2); + expect(original).to.deep.equal({ a: { b: 1 } }); + }); + + it("leaves unset values out, and objects that become empty", () => { + expect(setAt({ a: { b: 1 }, c: 2 }, ["a", "b"], undefined)).to.deep.equal({ + c: 2, + }); + expect(setAt({ a: 1 }, ["a"], undefined)).to.deep.equal({}); + }); + + it("keeps null, which is a value", () => { + expect(setAt({}, ["a"], null)).to.deep.equal({ a: null }); + }); + + it("removes items of arrays", () => { + expect(setAt({ a: [1, 2, 3] }, ["a", 1], undefined)).to.deep.equal({ + a: [1, 3], + }); + }); + + it("ignores prototype keys", () => { + const result = setAt({}, ["__proto__", "polluted"], 1) as Record< + string, + unknown + >; + expect(({} as Record).polluted).to.equal(undefined); + expect(Object.getPrototypeOf(result)).to.equal(Object.prototype); + }); +}); + +describe("getAt", () => { + it("reads nested values", () => { + expect(getAt({ a: [{ b: 1 }] }, ["a", 0, "b"])).to.equal(1); + expect(getAt({ a: 1 }, ["b", "c"])).to.equal(undefined); + }); + + it("doesn't read inherited properties", () => { + expect(getAt({}, ["toString"])).to.equal(undefined); + }); +}); + +describe("parseNumber", () => { + it("parses numbers and leaves other text as it is", () => { + expect(parseNumber("3")).to.equal(3); + expect(parseNumber("-2.5e3")).to.equal(-2500); + expect(parseNumber(" 4 ")).to.equal(4); + expect(parseNumber("")).to.equal(undefined); + expect(parseNumber("4.5")).to.equal(4.5); + expect(parseNumber("abc")).to.equal("abc"); + expect(parseNumber("0x10")).to.equal("0x10"); + expect(parseNumber("Infinity")).to.equal("Infinity"); + }); +}); + +describe("times", () => { + it("gives times with the offset of the local time zone", () => { + const value = fromTimeInput("14:30", new Date(2026, 11, 14)); + expect(value).to.match(/^14:30:00([+-]\d\d:\d\d|Z)$/); + expect(toTimeInput(value as string)).to.equal("14:30"); + }); + + it("shows times of other offsets in local time", () => { + const shown = toTimeInput("12:00:00Z"); + const minutes = (12 * 60 - new Date().getTimezoneOffset() + 1440) % 1440; + const expected = `${String(Math.floor(minutes / 60)).padStart( + 2, + "0" + )}:${String(minutes % 60).padStart(2, "0")}`; + expect(shown).to.equal(expected); + }); + + it("leaves unparsable times empty", () => { + expect(toTimeInput("noon")).to.equal(""); + expect(fromTimeInput("", new Date())).to.equal(undefined); + }); + + it("gives date-times in UTC and shows them in local time", () => { + const value = fromDateTimeInput("2026-12-14T10:15") as string; + expect(value).to.match(/^\d{4}-\d\d-\d\dT\d\d:\d\d:00Z$/); + expect(toDateTimeInput(value)).to.equal("2026-12-14T10:15"); + expect(toDateTimeInput("not a date")).to.equal(""); + expect(fromDateTimeInput("")).to.equal(undefined); + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/values.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/values.ts new file mode 100644 index 00000000..2a834e88 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/values.ts @@ -0,0 +1,135 @@ +/** + * Input values of IO schema forms: reading and writing them by path, and the + * values of controls (numbers, times) as the profile's widget table defines + * them. + */ + +/** A path of property names and array indexes into the values. */ +export type Path = readonly (string | number)[]; + +const UNSAFE_KEYS = ["__proto__", "constructor", "prototype"]; + +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const own = (value: unknown, key: string | number): boolean => + (isObject(value) || Array.isArray(value)) && + Object.prototype.hasOwnProperty.call(value, key); + +/** The value at a path, or `undefined`. */ +export function getAt(values: unknown, path: Path): unknown { + let value = values; + for (const key of path) { + if (!own(value, key)) return undefined; + value = (value as Record)[key]; + } + return value; +} + +/** + * A copy of the values with the value at a path set; `undefined` leaves it + * out (an array item is removed), and objects that become empty on the way + * are left out too. Keys such as `__proto__` are ignored. + */ +export function setAt( + values: unknown, + path: Path, + value: unknown, + nested = false +): unknown { + if (path.length === 0) return value; + const [key, ...rest] = path; + if (typeof key === "string" && UNSAFE_KEYS.includes(key)) return values; + if (typeof key === "number") { + const array = Array.isArray(values) ? [...values] : []; + const item = setAt(array[key], rest, value, true); + if (item === undefined) array.splice(key, 1); + else array[key] = item; + return array; + } + const object: Record = isObject(values) ? { ...values } : {}; + const item = setAt(object[key], rest, value, true); + if (item === undefined) delete object[key]; + else object[key] = item; + if (Object.keys(object).length === 0 && nested && value === undefined) { + return undefined; + } + return object; +} + +/** + * The number that a text field holds, `undefined` if it is empty, or the + * text itself if it isn't a number, so that validation reports it. + */ +export function parseNumber(text: string): number | string | undefined { + const trimmed = text.trim(); + if (trimmed === "") return undefined; + if (!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(trimmed)) return text; + const number = Number(trimmed); + return Number.isFinite(number) ? number : text; +} + +const pad = (n: number) => String(n).padStart(2, "0"); + +/** An offset in minutes east of UTC as `+hh:mm`, or `Z`. */ +const formatOffset = (minutes: number) => + minutes === 0 + ? "Z" + : `${minutes > 0 ? "+" : "-"}${pad( + Math.floor(Math.abs(minutes) / 60) + )}:${pad(Math.abs(minutes) % 60)}`; + +const TIME = /^(\d\d):(\d\d)(?::(\d\d)(?:\.\d+)?)?(Z|[+-]\d\d:\d\d)?$/i; + +/** + * The value of a time widget: an RFC 3339 `full-time` with the offset of + * the local time zone on the given day (the zone that the widget shows). + */ +export function fromTimeInput(text: string, day: Date): string | undefined { + const match = /^(\d\d):(\d\d)(?::(\d\d))?$/.exec(text); + if (!match) return undefined; + const offset = -new Date( + day.getFullYear(), + day.getMonth(), + day.getDate(), + Number(match[1]), + Number(match[2]) + ).getTimezoneOffset(); + return `${match[1]}:${match[2]}:${match[3] ?? "00"}${formatOffset(offset)}`; +} + +/** A `full-time` as the local time of a time input (`HH:MM`), or "". */ +export function toTimeInput(value: string): string { + const match = TIME.exec(value); + if (!match) return ""; + let minutes = Number(match[1]) * 60 + Number(match[2]); + const zone = match[4]; + if (zone) { + const offset = + zone.toUpperCase() === "Z" + ? 0 + : (zone[0] === "-" ? -1 : 1) * + (Number(zone.slice(1, 3)) * 60 + Number(zone.slice(4, 6))); + minutes = minutes - offset - new Date().getTimezoneOffset(); + } + minutes = ((minutes % 1440) + 1440) % 1440; + return `${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}`; +} + +/** The value of a date-time widget: an RFC 3339 `date-time` in UTC. */ +export function fromDateTimeInput(text: string): string | undefined { + if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d(:\d\d)?$/.test(text)) return undefined; + const date = new Date(text); + if (Number.isNaN(date.getTime())) return undefined; + return date.toISOString().replace(/\.\d{3}Z$/, "Z"); +} + +/** A `date-time` as the local value of a `datetime-local` input, or "". */ +export function toDateTimeInput(value: string): string { + if (!/^\d{4}-\d\d-\d\dT/.test(value)) return ""; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return ""; + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad( + date.getDate() + )}T${pad(date.getHours())}:${pad(date.getMinutes())}`; +} diff --git a/packages/ecc-client-ga4gh-wes/src/theming.test.ts b/packages/ecc-client-ga4gh-wes/src/theming.test.ts index dfeee1ad..4f1d6bcd 100644 --- a/packages/ecc-client-ga4gh-wes/src/theming.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/theming.test.ts @@ -11,6 +11,7 @@ const TAGS = [ "ecc-client-ga4gh-wes-run", "ecc-client-ga4gh-wes-run-create", "ecc-client-ga4gh-wes-run-output", + "ecc-client-ga4gh-wes-io-form", ]; describe("WES component theming", () => { From 6a40038e0bfb3934f2d4fd6db3160b7992dc0bff Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 09:29:18 +0100 Subject: [PATCH 05/19] fix(wes): harden I/O Schema checks Review findings on the schema checks: - An embedded $id that collides with a schema in use (e.g. the profile) is refused without unregistering that schema; the profile is registered again if something removed it; checks never reject. - Documents are registered under their own absolute $id, so references by it resolve; embedded $ids are resolved against their resource, so error locations point into embedded resources. - References in outputs and top-level $defs must resolve, too. - Checks run one after the other (hyperjump's registry is global). Also export the checks, the validator switch and the description format from @elixir-cloud/wes/utils, and document them. Part of #444. Co-Authored-By: Claude Opus 5.5 --- .../pages/docs/wes/io-schema.mdx | 19 +- packages/ecc-client-ga4gh-wes/package.json | 6 +- .../src/io-schema/tests/validator.test.ts | 114 +++++++++ .../src/io-schema/validator.ts | 237 +++++++++++------- .../ecc-client-ga4gh-wes/src/utils/index.ts | 28 +++ web-test.runner-config.mjs | 5 + 6 files changed, 319 insertions(+), 90 deletions(-) create mode 100644 packages/ecc-client-ga4gh-wes/src/utils/index.ts diff --git a/apps/documentation/pages/docs/wes/io-schema.mdx b/apps/documentation/pages/docs/wes/io-schema.mdx index 3f165d90..5e6ea006 100644 --- a/apps/documentation/pages/docs/wes/io-schema.mdx +++ b/apps/documentation/pages/docs/wes/io-schema.mdx @@ -10,11 +10,11 @@ The package supports version **0.3.0** of the profile, pinned at commit [`2c3dc4 ## Checks -Before a component uses an IO schema, it checks it **offline**, as the profile asks: +Before [`ecc-client-ga4gh-wes-io-form`](./components/io-form) uses an IO schema, it checks it **offline**, as the profile asks: 1. `$schema` must name the profile's meta-schema. 2. The schema must pass the meta-schema, with formats asserted. -3. Every `$ref` must resolve within the schema. Nothing is fetched over the network: a schema that refers to a remote schema is rejected. +3. Every `$ref` in `inputs`, `outputs` and the top-level `$defs` must resolve within the schema. Nothing is fetched over the network: a schema that refers to a remote schema is rejected. Embedded resources may not reuse the `$id` of a schema in use (such as the profile's meta-schema). Input values are then validated against the schema's `inputs` with the semantics of JSON Schema 2020-12. Failures are reported with the JSON Pointer of the value, the keyword that failed and a message. @@ -28,7 +28,18 @@ The checks use [@hyperjump/json-schema](https://github.com/hyperjump-io/json-sch hyperjump's settings are global to the page: the package turns off its retrieval of schemas over HTTP(S) and turns on format assertion. Pages that use hyperjump themselves get these settings, too. -The validator sits behind a small internal interface (`IoSchemaValidator`), so that another library could replace it without changing the components. +The validator sits behind a small interface (`IoSchemaValidator`), so that another library could replace it without changing the components. Apps can use the checks themselves and replace the validator through `@elixir-cloud/wes/utils`: + +```typescript +import { checkIoSchema, setIoSchemaValidator } from '@elixir-cloud/wes/utils'; + +const result = await checkIoSchema(schema); +if (result.valid) { + const { valid, errors } = result.validateInputs(values); +} +``` + +Checks run one after the other, because hyperjump's registry of schemas is global. ## File references @@ -44,4 +55,4 @@ Outputs must be absolute URIs. The checks pass the profile's test vectors for fi Titles, descriptions and `enum` values of IO schemas are always shown as text, never as markup. -Descriptions with `"x-ga4gh-description-format": "markdown"` are shown as plain text, which the profile allows. The package also has a renderer for the profile's Markdown subset (raw HTML shown as escaped text, images as their alt text, links only with a scheme from `allowedSchemes`, which open in a new window; of GFM only tables, strikethrough and autolinks), built on [markdown-it](https://github.com/markdown-it/markdown-it). It is switched off until the maintainers decide whether the components render Markdown. +Descriptions with `"x-ga4gh-description-format": "markdown"` are shown as plain text, which the profile allows. The package also has a renderer for the profile's Markdown subset (raw HTML shown as escaped text, images as their alt text, links only with a scheme from `allowedSchemes`, which open in a new window; of GFM only tables, strikethrough and autolinks), built on [markdown-it](https://github.com/markdown-it/markdown-it). It is switched off until the maintainers decide whether the components render Markdown; an app can switch it on for all components with `setDescriptionFormat('markdown')` from `@elixir-cloud/wes/utils`. markdown-it is part of the package's bundle either way. diff --git a/packages/ecc-client-ga4gh-wes/package.json b/packages/ecc-client-ga4gh-wes/package.json index e3717211..4c9f41a7 100644 --- a/packages/ecc-client-ga4gh-wes/package.json +++ b/packages/ecc-client-ga4gh-wes/package.json @@ -19,7 +19,11 @@ "./events": "./dist/events/index.js", "./events/*": "./dist/events/*", "./providers": "./dist/providers/index.js", - "./providers/*": "./dist/providers/*" + "./providers/*": "./dist/providers/*", + "./utils": { + "types": "./dist/utils/index.d.ts", + "import": "./dist/utils/index.js" + } }, "repository": { "type": "git", diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts index 3e84f95c..edd0e9cf 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts @@ -143,6 +143,120 @@ describe("checkIoSchema", () => { }); }); +describe("checkIoSchema with $id", () => { + for (const id of [ + PROFILE_ID, + "https://json-schema.org/draft/2020-12/schema", + "https://json-schema.org/draft/2020-12/meta/core", + ]) { + it(`refuses an embedded $id ${id} and keeps working`, async () => { + const result = await checkIoSchema( + ioSchema({ + properties: { a: { $id: id, type: "integer" } }, + }) + ); + expect(result.valid).to.equal(false); + const after = await checkIoSchema(SAMPLES); + expect(after.valid).to.equal(true); + }); + } + + it("refuses a root $id of a schema in use and keeps working", async () => { + const result = await checkIoSchema({ ...SAMPLES, $id: PROFILE_ID }); + expect(result.valid).to.equal(false); + expect((await checkIoSchema(SAMPLES)).valid).to.equal(true); + }); + + it("resolves references by the root $id", async () => { + const id = "https://example.org/io/1.0/schema.json"; + const byRoot = await checkIoSchema( + ioSchema( + { properties: { a: { $ref: `${id}#/$defs/n` } } }, + { $id: id, $defs: { n: { type: "integer" } } } + ) + ); + expect(byRoot.valid).to.equal(true); + const relative = await checkIoSchema( + ioSchema( + { + properties: { a: { $ref: "https://example.org/io/1.0/defs/n.json" } }, + }, + { $id: id, $defs: { n: { $id: "defs/n.json", type: "integer" } } } + ) + ); + expect(relative.valid).to.equal(true); + if (relative.valid) { + expect(relative.validateInputs({ a: "x" }).errors[0]).to.include({ + pointer: "/a", + schemaPointer: "/$defs/n", + message: "Must be of type integer.", + }); + } + }); + + it("points into embedded resources with relative $ids", async () => { + const result = await checkIoSchema( + ioSchema({ + properties: { a: { $ref: "x" }, b: { $id: "x", type: "integer" } }, + }) + ); + expect(result.valid).to.equal(true); + if (result.valid) { + expect(result.validateInputs({ a: "s" }).errors[0]).to.include({ + pointer: "/a", + schemaPointer: "/properties/inputs/properties/b", + message: "Must be of type integer.", + }); + } + }); + + it("checks two schemas with the same $id at the same time", async () => { + const withId = { ...SAMPLES, $id: "https://example.org/same.json" }; + const results = await Promise.all([ + checkIoSchema(withId), + checkIoSchema(withId), + ]); + expect(results.map((r) => r.valid)).to.deep.equal([true, true]); + }); + + const unresolved: [string, Record][] = [ + [ + "a remote $ref in outputs", + { + properties: { + inputs: { type: "object" }, + outputs: { + type: "object", + properties: { o: { $ref: "https://example.org/x.json" } }, + }, + }, + }, + ], + [ + "a local $ref to nowhere in outputs", + { + properties: { + inputs: { type: "object" }, + outputs: { + type: "object", + properties: { o: { $ref: "#/$defs/missing" } }, + }, + }, + }, + ], + [ + "a remote $ref in unused $defs", + { $defs: { u: { $ref: "https://example.org/y.json" } } }, + ], + ]; + for (const [name, extra] of unresolved) { + it(`rejects ${name}`, async () => { + const result = await checkIoSchema({ ...ioSchema({}), ...extra }); + expect(result.valid).to.equal(false); + }); + } +}); + describe("validateInputs", () => { const validator = async (document: Record) => { const result = await checkIoSchema(document); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts index b03bdb6c..1df89d66 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts @@ -99,36 +99,54 @@ const SUMMING_KEYWORDS = ["anyOf", "oneOf", "not"]; const isObject = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); +/** Whether a URI is absolute (has a scheme). */ +const isAbsolute = (uri: string) => /^[a-z][a-z0-9+.-]*:/i.test(uri); + +/** A URI reference resolved against a base, without the fragment. */ +function resolveUri(reference: string, base: string): string { + return new URL(reference, base).href.split("#")[0]; +} + /** - * A copy of an IO schema to register for validating values: the root - * without `$id` (it is registered under a URI of its own), and `$schema` - * naming Draft 2020-12 instead of the profile in the root and in embedded + * A copy of an IO schema to register for validating values: `$schema` + * names Draft 2020-12 instead of the profile in the root and in embedded * resources, as "Dialect and validation of values" allows. Only schemas are * rewritten, not values of `const`, `enum`, `default` or `examples`. * + * @param base - The URI that the root is registered under (its `$id`). * @param embedded - Receives the JSON Pointer of each embedded resource by - * its `$id`. + * its `$id`, resolved against the resource that holds it. */ function forValues( document: Record, + base: string, embedded: Map ): Record { - const rewrite = (schema: unknown, path: (string | number)[]): unknown => { + const rewrite = ( + schema: unknown, + path: (string | number)[], + resource: string + ): unknown => { if (!isObject(schema)) return schema; const copy: Record = { ...schema }; if (copy.$schema === PROFILE_ID) copy.$schema = DRAFT_2020_12; + let inner = resource; if (path.length > 0 && typeof copy.$id === "string") { - embedded.set(copy.$id.split("#")[0], toPointer(path)); + inner = resolveUri(copy.$id, resource); + if (embedded.has(inner) || inner === base) { + throw new Error(`The $id ${inner} is used twice.`); + } + embedded.set(inner, toPointer(path)); } for (const keyword of SCHEMA_KEYWORDS) { if (keyword in copy) - copy[keyword] = rewrite(copy[keyword], [...path, keyword]); + copy[keyword] = rewrite(copy[keyword], [...path, keyword], inner); } for (const keyword of SCHEMA_ARRAY_KEYWORDS) { const value = copy[keyword]; if (Array.isArray(value)) { copy[keyword] = value.map((item, i) => - rewrite(item, [...path, keyword, i]) + rewrite(item, [...path, keyword, i], inner) ); } } @@ -138,36 +156,38 @@ function forValues( copy[keyword] = Object.fromEntries( Object.entries(value).map(([key, item]) => [ key, - rewrite(item, [...path, keyword, key]), + rewrite(item, [...path, keyword, key], inner), ]) ); } } return copy; }; - const copy = rewrite(document, []) as Record; - delete copy.$id; + const copy = rewrite(document, [], base) as Record; + copy.$id = base; return copy; } let setUp = false; /** - * Sets @hyperjump/json-schema up offline, once: no retrieval over HTTP(S), - * format assertion on, and the profile registered from the bundled copies. - * These settings are global to hyperjump on the page. + * Sets @hyperjump/json-schema up offline: no retrieval over HTTP(S) and + * format assertion on (once), and the profile registered from the bundled + * copies (again if something unregistered them). These settings are global + * to hyperjump on the page. */ function setUpHyperjump(): void { - if (setUp) return; - removeUriSchemePlugin("http"); - removeUriSchemePlugin("https"); - setShouldValidateFormat(true); + if (!setUp) { + removeUriSchemePlugin("http"); + removeUriSchemePlugin("https"); + setShouldValidateFormat(true); + setUp = true; + } for (const schema of [...VOCABULARY_SCHEMAS, PROFILE_SCHEMA]) { if (!hasSchema(schema.$id as string)) { registerSchema(schema as SchemaObject); } } - setUp = true; } let registrations = 0; @@ -225,11 +245,115 @@ function metaSchemaLocation(location: string) { const errorText = (error: unknown) => error instanceof Error ? error.message : String(error); +/** An error result with one message about the document as a whole. */ +const unusable = (error: unknown): IoSchemaCheck => ({ + valid: false, + errors: [ + { + pointer: "", + keyword: "$ref", + schemaPointer: "", + message: `The schema can't be used: ${errorText(error)}`, + }, + ], +}); + +/** Locations to compile besides `inputs`, so that all their refs resolve */ +function otherLocations(document: Record): string[] { + const locations: string[] = []; + const properties = isObject(document.properties) ? document.properties : {}; + if ("outputs" in properties) locations.push("/properties/outputs"); + for (const keyword of ["$defs", "definitions"]) { + const value = document[keyword]; + if (isObject(value)) { + for (const key of Object.keys(value)) { + locations.push(toPointer([keyword, key])); + } + } + } + return locations; +} + +/** A JSON Pointer as a URI fragment. */ +const fragment = (pointer: string) => + `#${pointer + .split("/") + .map((segment) => encodeURIComponent(segment)) + .join("/")}`; + +/** Checks a document that names the profile; may throw. */ +async function checkDocument( + document: Record +): Promise { + setUpHyperjump(); + const output = await validate(PROFILE_ID, document as SchemaObject, "BASIC"); + if (!output.valid) { + const errors = toErrors(output.errors, document, metaSchemaLocation); + return { valid: false, errors }; + } + + // Compile the schema of the values, which resolves every `$ref` from + // the document itself, as nothing can be fetched. The document is + // registered under its own `$id` (absolute), else under a URI of its own + registrations += 1; + const ownId = + typeof document.$id === "string" && isAbsolute(document.$id) + ? document.$id.split("#")[0] + : undefined; + const base = + ownId ?? `https://ecc-io-schema.invalid/${registrations}/schema.json`; + const embedded = new Map(); + const copy = forValues(document, base, embedded); + const ids = [base, ...embedded.keys()]; + const taken = ids.find((uri) => hasSchema(uri)); + if (taken !== undefined) { + throw new Error(`The $id ${taken} is the $id of a schema in use.`); + } + let compiled: Awaited>; + let registered = false; + try { + registerSchema(copy as SchemaObject, base); + registered = true; + compiled = await validate(`${base}#/properties/inputs`); + for (const location of otherLocations(document)) { + // eslint-disable-next-line no-await-in-loop + await validate(`${base}${fragment(location)}`); + } + } finally { + if (registered) { + for (const uri of ids) { + if (hasSchema(uri)) unregisterSchema(uri); + } + } + } + + const valuesLocation = (location: string) => { + const [uri] = location.split("#"); + const pointer = + (uri === base ? "" : embedded.get(uri) ?? "") + + (fragmentPointer(location) ?? ""); + return { pointer, schema: valueAt(document, pointer) }; + }; + const validateInputs: InputsValidator = (values) => { + const result = compiled(values as never, "BASIC"); + return result.valid + ? { valid: true, errors: [] } + : { + valid: false, + errors: toErrors(result.errors, values, valuesLocation), + }; + }; + return { valid: true, errors: [], validateInputs }; +} + +/** Checks run one after the other: hyperjump's registry is global */ +let queue: Promise = Promise.resolve(); + /** The default validator: @hyperjump/json-schema, offline. */ export const hyperjumpValidator: IoSchemaValidator = { - async check(document) { + check(document) { if (!isObject(document)) { - return { + return Promise.resolve({ valid: false, errors: [ { @@ -239,10 +363,10 @@ export const hyperjumpValidator: IoSchemaValidator = { message: "An IO schema must be a JSON object.", }, ], - }; + }); } if (document.$schema !== PROFILE_ID) { - return { + return Promise.resolve({ valid: false, errors: [ { @@ -252,70 +376,13 @@ export const hyperjumpValidator: IoSchemaValidator = { message: keywordMessage("$schema", undefined, document.$schema), }, ], - }; + }); } - setUpHyperjump(); - const output = await validate( - PROFILE_ID, - document as SchemaObject, - "BASIC" + const result = queue.then(() => + checkDocument(document).catch((error) => unusable(error)) ); - if (!output.valid) { - const errors = toErrors(output.errors, document, metaSchemaLocation); - return { valid: false, errors }; - } - - // Compile the schema of the values, which resolves every `$ref` from - // the document itself, as nothing can be fetched - registrations += 1; - const base = `urn:ecc-io-schema:${registrations}`; - const embedded = new Map(); - const copy = forValues(document, embedded); - const registered = [base, ...embedded.keys()]; - let compiled: Awaited>; - try { - if ([...embedded.keys()].some(hasSchema)) { - throw new Error( - "An embedded schema has the $id of a schema that is checked at the same time." - ); - } - registerSchema(copy as SchemaObject, base); - compiled = await validate(`${base}#/properties/inputs`); - } catch (error) { - return { - valid: false, - errors: [ - { - pointer: "", - keyword: "$ref", - schemaPointer: "", - message: `The schema can't be used: ${errorText(error)}`, - }, - ], - }; - } finally { - for (const uri of registered) { - if (hasSchema(uri)) unregisterSchema(uri); - } - } - - const valuesLocation = (location: string) => { - const [uri] = location.split("#"); - const pointer = - (uri === base ? "" : embedded.get(uri) ?? "") + - (fragmentPointer(location) ?? ""); - return { pointer, schema: valueAt(document, pointer) }; - }; - const validateInputs: InputsValidator = (values) => { - const result = compiled(values as never, "BASIC"); - return result.valid - ? { valid: true, errors: [] } - : { - valid: false, - errors: toErrors(result.errors, values, valuesLocation), - }; - }; - return { valid: true, errors: [], validateInputs }; + queue = result; + return result; }, }; diff --git a/packages/ecc-client-ga4gh-wes/src/utils/index.ts b/packages/ecc-client-ga4gh-wes/src/utils/index.ts new file mode 100644 index 00000000..a052388c --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/utils/index.ts @@ -0,0 +1,28 @@ +/** + * Public helpers of the GA4GH IO Schema support (`@elixir-cloud/wes/utils`): + * schema checks and their validator, file reference checks, and how + * descriptions are rendered. + */ +export { + checkIoSchema, + getIoSchemaValidator, + setIoSchemaValidator, + PROFILE_ID, +} from "../io-schema/validator.js"; +export type { + InputsValidator, + IoSchemaCheck, + IoSchemaValidator, + ValidationError, +} from "../io-schema/validator.js"; +export { + checkFileValue, + checkOutputUri, + DEFAULT_ALLOWED_SCHEMES, +} from "../io-schema/files.js"; +export { + getDescriptionFormat, + setDescriptionFormat, +} from "../io-schema/descriptions.js"; +export type { DescriptionFormat } from "../io-schema/descriptions.js"; +export { PROFILE_COMMIT, PROFILE_VERSION } from "../io-schema/profile.js"; diff --git a/web-test.runner-config.mjs b/web-test.runner-config.mjs index c99c3bd5..cb0185c4 100644 --- a/web-test.runner-config.mjs +++ b/web-test.runner-config.mjs @@ -12,6 +12,11 @@ import rollupJson from "@rollup/plugin-json"; // of @hyperjump/json-schema, the validator of `@elixir-cloud/wes`. The // CommonJS plugin gives them a default export only, so `cjsNamedExports` // serves them through a module with their named exports. +// IMPORTED_BY_ESM: those of them that ES modules import (and so need the +// named exports); punycode is only required by the others. Verified with +// @hyperjump/json-schema 1.18.1; if a dependency bump breaks it, tests fail +// with "does not provide an export named ...". Drop the shim if the +// validator is replaced. const COMMONJS_DEPENDENCIES = ["content-type", "idn-hostname", "punycode"]; const IMPORTED_BY_ESM = ["content-type", "idn-hostname"]; const commonjs = fromRollup(rollupCommonjs); From 8be98ef5f704b8f401a196122ec0f3a0fd0a7514 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 09:42:19 +0100 Subject: [PATCH 06/19] feat(wes): render the I/O Schema widget hints Choose controls by x-ga4gh-ui-widget where the widget fits the schema that carries it (UI widgets, Rules): textarea, slider with bounds and step, multiple choice for arrays with items.enum, tags one per line, typeahead with examples as suggestions, colour picker. Radio and switch render as dropdown and checkbox, as the profile allows. Misfit, custom and viewer widgets fall back to the type. Nullable inputs get a null toggle. Part of #444. Co-Authored-By: Claude Opus 5.5 --- .../pages/docs/wes/components/io-form.mdx | 15 ++ .../src/components/io-form/io-form.ts | 200 +++++++++++++++++- .../components/io-form/tests/io-form.test.ts | 98 +++++++++ .../src/io-schema/fields.ts | 108 +++++++++- .../src/io-schema/tests/fields.test.ts | 90 ++++++++ 5 files changed, 506 insertions(+), 5 deletions(-) diff --git a/apps/documentation/pages/docs/wes/components/io-form.mdx b/apps/documentation/pages/docs/wes/components/io-form.mdx index 938d7b58..67437c31 100644 --- a/apps/documentation/pages/docs/wes/components/io-form.mdx +++ b/apps/documentation/pages/docs/wes/components/io-form.mdx @@ -31,6 +31,21 @@ The `ecc-client-ga4gh-wes-io-form` component renders the input form of a workflo | `object` with `properties` | A group with a field per property, at any depth | | Anything else | JSON text area | + A widget hint (`x-ga4gh-ui-widget`) chooses the control where it fits its schema, with the keywords it needs next to it, as the profile's [UI widgets](https://ga4gh-io-schema.readthedocs.io/en/latest/specification/widgets/) define: + +| Widget | Control | +|--------|---------| +| `text`, `number`, `checkbox`, `date-picker`, `time-picker`, `datetime-picker` | As above | +| `textarea` | Text area | +| `slider` | Slider within the bounds, in steps of `multipleOf` | +| `dropdown`, `radio` | Dropdown (radio buttons are rendered as a dropdown for now) | +| `dropdown` or `tags` on an array with `items.enum` | Multiple choice | +| `tags` on an array of strings | One tag per line | +| `typeahead` | Text field with the `examples` as suggestions; with `enum`, a dropdown | +| `switch` | Checkbox (for now) | +| `color-picker` | Colour picker, giving `#rrggbb` in lowercase | + + A widget that doesn't fit, a viewer, or a `custom:` widget renders the input by its type. Inputs whose `type` allows `null` get a "No value (null)" checkbox. 3. Inputs start from their `default` values; inputs without a value are left out of the values, never sent as `null` or `""`. 4. Errors show at their input once it was changed, and at all inputs after `reportValidity()`. diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts index e207c429..e66beffb 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts @@ -31,6 +31,7 @@ import "@elixir-cloud/design/components/select/index.js"; import "@elixir-cloud/design/components/checkbox/index.js"; import "@elixir-cloud/design/components/label/index.js"; import "@elixir-cloud/design/components/skeleton/index.js"; +import "@elixir-cloud/design/components/multi-select/index.js"; /** The payload of `ecc-io-form-changed`. */ export interface IoFormChange { @@ -61,6 +62,26 @@ const choiceLabel = (value: unknown) => const within = (pointer: string, outer: string) => pointer === outer || pointer.startsWith(`${outer}/`); +/** The bounds and step of a slider. */ +function sliderRange(field: Field): { min: number; max: number; step: string } { + const { schema } = field; + const num = (value: unknown) => + typeof value === "number" ? value : undefined; + const min = num(schema.minimum) ?? num(schema.exclusiveMinimum) ?? 0; + const max = num(schema.maximum) ?? num(schema.exclusiveMaximum) ?? 100; + const multipleOf = num(schema.multipleOf); + let step = "any"; + if (multipleOf !== undefined) step = String(multipleOf); + else if (field.type === "integer") step = "1"; + return { min, max, step }; +} + +/** The values of `items.enum` of an array input. */ +const itemChoices = (field: Field): unknown[] => { + const { items } = field.schema; + return isObject(items) && Array.isArray(items.enum) ? items.enum : []; +}; + /** A value as the text of a text field. */ const textOf = (value: unknown): string => { if (value === undefined) return ""; @@ -420,7 +441,8 @@ export class ECCClientGa4ghWesIoForm extends LitElement { : nothing} `} ${this.renderControl(field, id, fieldMessages.length > 0)} - ${this.renderDescription(field)} ${renderMessages(fieldMessages)} + ${this.renderNullToggle(field)} ${this.renderDescription(field)} + ${renderMessages(fieldMessages)} `; } @@ -436,6 +458,30 @@ export class ECCClientGa4ghWesIoForm extends LitElement { `; } + /** + * A checkbox that sets a nullable input to `null`, where `null` passes + * its type (choices offer `null` themselves if `enum` has it). + */ + private renderNullToggle(field: Field) { + if (!field.nullable || field.choices || field.control === "group") { + return nothing; + } + const isNull = getAt(this.current, field.path) === null; + return html``; + } + private renderControl(field: Field, id: string, invalid: boolean) { const value = getAt(this.current, field.path); const raw = this.rawText.get(field.pointer); @@ -502,6 +548,64 @@ export class ECCClientGa4ghWesIoForm extends LitElement { ); case "json": return this.renderJson(field, id, value, raw, invalid); + case "textarea": + return html` { + const text = String(e.detail.value); + this.setValue(field, text === "" ? undefined : text); + }} + >`; + case "slider": + return this.renderSlider(field, id, value, invalid); + case "multiselect": + return this.renderMultiSelect(field, id, value, invalid); + case "typeahead": + return this.renderTypeahead(field, id, value, invalid); + case "color": + return html`
+ + this.setValue(field, String(e.detail.value).toLowerCase())} + > + ${typeof value === "string" ? value : "(not set)"} +
`; + case "tags": + return html` String(v)).join("\n") : "")} + ?invalid=${invalid} + @ecc-input-changed=${(e: CustomEvent) => { + const text = String(e.detail.value); + this.setRaw(field, text); + const tags = text + .split("\n") + .map((tag) => tag.trim()) + .filter(Boolean); + this.setValue(field, tags.length ? tags : undefined); + }} + >`; default: return this.renderInput( field, @@ -534,6 +638,100 @@ export class ECCClientGa4ghWesIoForm extends LitElement { >`; } + private renderSlider( + field: Field, + id: string, + value: unknown, + invalid: boolean + ) { + const { min, max, step } = sliderRange(field); + return html`
+ + this.setValue(field, parseNumber(String(e.detail.value)))} + > + ${typeof value === "number" ? value : "(not set)"} +
`; + } + + private renderMultiSelect( + field: Field, + id: string, + value: unknown, + invalid: boolean + ) { + const choices = itemChoices(field); + const chosen = Array.isArray(value) + ? choices + .map((choice, i) => (value.includes(choice) ? String(i) : "")) + .filter(Boolean) + : []; + return html` { + const indexes = (e.detail.value as string[]).map(Number); + const values = choices.filter((_, i) => indexes.includes(i)); + this.setValue(field, values.length ? values : undefined); + }} + > + + + ${choices.map( + (choice, i) => + html`${choiceLabel(choice)}` + )} + + `; + } + + private renderTypeahead( + field: Field, + id: string, + value: unknown, + invalid: boolean + ) { + const examples = ( + Array.isArray(field.schema.examples) ? field.schema.examples : [] + ).filter((example): example is string => typeof example === "string"); + return html`${this.renderInput( + field, + id, + "text", + textOf(value), + invalid, + (text) => (text === "" ? undefined : text) + )} +
+ ${examples.map( + (example) => + html`` + )} +
`; + } + private renderSelect( field: Field, id: string, diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts index dd73ca30..ae7beff1 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts @@ -283,6 +283,104 @@ describe("ecc-client-ga4gh-wes-io-form", () => { expect(root(el).querySelector('[data-pointer="/only"]')).to.not.equal(null); }); + describe("widgets", () => { + const WIDGETS = ioSchema({ + properties: { + notes: { type: "string", "x-ga4gh-ui-widget": "textarea" }, + quality: { + type: "number", + minimum: 0, + maximum: 1, + multipleOf: 0.05, + "x-ga4gh-ui-widget": "slider", + }, + labels: { + type: "array", + items: { type: "string", enum: ["tumour", "normal"] }, + uniqueItems: true, + "x-ga4gh-ui-widget": "tags", + }, + free: { + type: "array", + items: { type: "string" }, + "x-ga4gh-ui-widget": "tags", + }, + genome: { + type: "string", + examples: ["GRCh38", "GRCm39"], + "x-ga4gh-ui-widget": "typeahead", + }, + colour: { + type: "string", + pattern: "^#[0-9a-f]{6}$", + "x-ga4gh-ui-widget": "color-picker", + }, + mode: { enum: ["a", "b"], "x-ga4gh-ui-widget": "radio" }, + on: { type: "boolean", "x-ga4gh-ui-widget": "switch" }, + limit: { type: ["integer", "null"] }, + misfit: { type: "string", "x-ga4gh-ui-widget": "custom:other" }, + }, + }); + + it("renders each widget with a control that fits", async () => { + const el = await render(WIDGETS); + const tag = (pointer: string) => control(el, pointer).tagName; + expect(tag("/notes")).to.equal("ECC-UTILS-DESIGN-TEXTAREA"); + expect(control(el, "/quality").getAttribute("type")).to.equal("range"); + expect(control(el, "/quality").getAttribute("step")).to.equal("0.05"); + expect(tag("/labels")).to.equal("ECC-UTILS-DESIGN-MULTI-SELECT"); + expect(tag("/free")).to.equal("ECC-UTILS-DESIGN-TEXTAREA"); + expect(control(el, "/colour").getAttribute("type")).to.equal("color"); + expect(tag("/mode")).to.equal("ECC-UTILS-DESIGN-SELECT"); + expect(tag("/on")).to.equal("ECC-UTILS-DESIGN-CHECKBOX"); + expect(control(el, "/misfit").getAttribute("type")).to.equal("text"); + }); + + it("gives the values that the widget table defines", async () => { + const el = await render(WIDGETS); + let result = await change(el, "/notes", { value: "a\nb" }); + expect(result.values.notes).to.equal("a\nb"); + result = await change(el, "/quality", { value: "0.35" }); + expect(result.values.quality).to.equal(0.35); + result = await change(el, "/labels", { value: ["1"] }); + expect(result.values.labels).to.deep.equal(["normal"]); + result = await change(el, "/free", { value: " x \n\ny" }); + expect(result.values.free).to.deep.equal(["x", "y"]); + result = await change(el, "/colour", { value: "#1F77B4" }); + expect(result.values.colour).to.equal("#1f77b4"); + expect(result.valid).to.equal(true); + }); + + it("offers examples as suggestions", async () => { + const el = await render(WIDGETS); + const event = oneEvent(el, "ecc-io-form-changed"); + const button = root(el).querySelector( + '[data-field="/genome"] [data-suggestions] button' + ) as HTMLButtonElement; + button.click(); + const { detail } = await event; + expect(detail.values.genome).to.equal("GRCh38"); + }); + + it("sets nullable inputs to null", async () => { + const el = await render(WIDGETS); + const toggle = root(el).querySelector('[data-null="/limit"]'); + expect(toggle).to.not.equal(null); + const event = oneEvent(el, "ecc-io-form-changed"); + toggle?.dispatchEvent( + new CustomEvent("ecc-input-changed", { + detail: { checked: true }, + bubbles: true, + composed: true, + }) + ); + const { detail } = await event; + expect(detail.values.limit).to.equal(null); + expect(detail.valid).to.equal(true); + expect(root(el).querySelector('[data-null="/notes"]')).to.equal(null); + }); + }); + for (const name of [ "example_tool", "example_wdl", diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts index eb18077b..6245b404 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts @@ -5,8 +5,9 @@ * descriptors (e.g. a form library) could replace this module without * changing the element's API. * - * Controls are chosen as the portals guide says (step 4, "Fallbacks"): by - * `type`, `format` and `enum`. Only local references (`#/...`) are followed; + * Controls are chosen by the widget hint (`x-ga4gh-ui-widget`) where it + * fits its schema (UI widgets, "Rules"), else as the portals guide says + * (step 4, "Fallbacks"): by `type`, `format` and `enum`. Only local references (`#/...`) are followed; * the schema has been checked before, so they all resolve. */ import { parsePointer, toPointer } from "./pointer.js"; @@ -25,7 +26,13 @@ export type ControlKind = | "time" | "datetime" | "group" - | "json"; + | "json" + | "textarea" + | "slider" + | "multiselect" + | "typeahead" + | "color" + | "tags"; /** One input of the form. */ export interface Field { @@ -162,6 +169,99 @@ export function controlByType(schema: Schema): ControlKind { } } +const NUMERIC = ["integer", "number"]; + +const hasLower = (schema: Schema) => + typeof schema.minimum === "number" || + typeof schema.exclusiveMinimum === "number"; +const hasUpper = (schema: Schema) => + typeof schema.maximum === "number" || + typeof schema.exclusiveMaximum === "number"; + +/** Whether an array schema's `items` are strings, and their `enum`. */ +function stringItems(schema: Schema): { strings: boolean; choices: boolean } { + const items = isObject(schema.items) ? schema.items : undefined; + if (!items) return { strings: false, choices: false }; + const choices = Array.isArray(items.enum); + const strings = + items.type === "string" || + (choices && (items.enum as unknown[]).every((v) => typeof v === "string")); + return { strings, choices }; +} + +/** + * The control of a widget hint if it fits the schema that carries it, else + * `undefined`. The keywords that a widget needs must be in that schema (not + * behind `$ref`), so the fit is checked on `own`. Radio buttons, switches + * and typeaheads with `enum` render as dropdowns and checkboxes, which the + * profile allows, until the design package has those controls. + */ +function widgetControl(widget: string, own: Schema): ControlKind | undefined { + const { type } = typeOf(own); + const enumOwn = Array.isArray(own.enum) || "const" in own; + switch (widget) { + case "text": + return type === "string" ? "text" : undefined; + case "textarea": + return type === "string" ? "textarea" : undefined; + case "number": + return type && NUMERIC.includes(type) ? "number" : undefined; + case "slider": + return type && NUMERIC.includes(type) && hasLower(own) && hasUpper(own) + ? "slider" + : undefined; + case "dropdown": + if (type === "array") { + const items = stringItems(own); + return items.choices && items.strings ? "multiselect" : undefined; + } + return enumOwn ? "select" : undefined; + case "radio": + return enumOwn ? "select" : undefined; + case "typeahead": + if (type !== "string") return undefined; + if (enumOwn) return "select"; + return Array.isArray(own.examples) ? "typeahead" : undefined; + case "checkbox": + case "switch": + return type === "boolean" ? "checkbox" : undefined; + case "date-picker": + return type === "string" && own.format === "date" ? "date" : undefined; + case "time-picker": + return type === "string" && own.format === "time" ? "time" : undefined; + case "datetime-picker": + return type === "string" && own.format === "date-time" + ? "datetime" + : undefined; + case "color-picker": + return type === "string" ? "color" : undefined; + case "tags": { + if (type !== "array") return undefined; + const items = stringItems(own); + if (!items.strings) return undefined; + return items.choices ? "multiselect" : "tags"; + } + default: + // File pickers come with file references; viewers, custom and unknown + // widgets render by type + return undefined; + } +} + +/** + * The control of an input: by its widget hint where it fits (checked on + * the schema as written), else by `type`, `format` and `enum` of the + * resolved schema. + */ +export function controlOf(own: Schema, schema: Schema): ControlKind { + const widget = own["x-ga4gh-ui-widget"]; + if (typeof widget === "string") { + const control = widgetControl(widget, own); + if (control) return control; + } + return controlByType(schema); +} + /** The title of an input: its `title`, else its name. */ const titleOf = (schema: Schema, name: string) => typeof schema.title === "string" && schema.title !== "" ? schema.title : name; @@ -187,7 +287,7 @@ export function describeField( const own = isObject(ownSchema) ? ownSchema : {}; const schema = resolve(document, own); const { type, nullable } = typeOf(schema); - let control = controlByType(schema); + let control = controlOf(own, schema); if (control === "group" && depth >= MAX_DEPTH) control = "json"; const field: Field = { name, diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts index 9c50ea87..8ee22d0b 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts @@ -3,6 +3,7 @@ import { expect } from "@open-wc/testing"; import { allFields, controlByType, + controlOf, defaultOf, describeInputs, resolve, @@ -165,3 +166,92 @@ describe("describeInputs", () => { } }); }); + +describe("controlOf (widgets)", () => { + const cases: [Record, string][] = [ + [{ type: "string", "x-ga4gh-ui-widget": "text" }, "text"], + [{ type: "string", "x-ga4gh-ui-widget": "textarea" }, "textarea"], + [{ type: "integer", "x-ga4gh-ui-widget": "number" }, "number"], + [ + { + type: "number", + minimum: 0, + maximum: 1, + "x-ga4gh-ui-widget": "slider", + }, + "slider", + ], + [ + { + type: "integer", + exclusiveMinimum: 0, + maximum: 9, + "x-ga4gh-ui-widget": "slider", + }, + "slider", + ], + [{ type: "integer", minimum: 0, "x-ga4gh-ui-widget": "slider" }, "number"], + [{ enum: ["a", "b"], "x-ga4gh-ui-widget": "dropdown" }, "select"], + [ + { + type: "array", + items: { type: "string", enum: ["a", "b"] }, + "x-ga4gh-ui-widget": "dropdown", + }, + "multiselect", + ], + [{ enum: ["a", "b"], "x-ga4gh-ui-widget": "radio" }, "select"], + [{ type: "string", "x-ga4gh-ui-widget": "radio" }, "text"], + [ + { type: "string", enum: ["a"], "x-ga4gh-ui-widget": "typeahead" }, + "select", + ], + [ + { type: "string", examples: ["a"], "x-ga4gh-ui-widget": "typeahead" }, + "typeahead", + ], + [{ type: "boolean", "x-ga4gh-ui-widget": "switch" }, "checkbox"], + [ + { type: "string", format: "date", "x-ga4gh-ui-widget": "date-picker" }, + "date", + ], + [{ type: "string", "x-ga4gh-ui-widget": "date-picker" }, "text"], + [{ type: "string", "x-ga4gh-ui-widget": "color-picker" }, "color"], + [ + { + type: "array", + items: { type: "string" }, + "x-ga4gh-ui-widget": "tags", + }, + "tags", + ], + [ + { + type: "array", + items: { type: "string", enum: ["x", "y"] }, + "x-ga4gh-ui-widget": "tags", + }, + "multiselect", + ], + [{ type: "integer", "x-ga4gh-ui-widget": "tags" }, "number"], + [{ type: "string", "x-ga4gh-ui-widget": "custom:fancy" }, "text"], + [{ type: "string", "x-ga4gh-ui-widget": "table-viewer" }, "text"], + [{ type: ["string", "null"], "x-ga4gh-ui-widget": "textarea" }, "textarea"], + ]; + for (const [schema, control] of cases) { + it(`renders ${JSON.stringify(schema)} as ${control}`, () => { + expect(controlOf(schema, schema)).to.equal(control); + }); + } + + it("needs the keywords next to the widget, not behind $ref", () => { + const own = { $ref: "#/$defs/n", "x-ga4gh-ui-widget": "slider" }; + const resolved = { + type: "integer", + minimum: 0, + maximum: 9, + "x-ga4gh-ui-widget": "slider", + }; + expect(controlOf(own, resolved)).to.equal("number"); + }); +}); From c771794b4ffab662ad79cde718ffc6bd3ea29349 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 09:56:34 +0100 Subject: [PATCH 07/19] fix(wes): bound the I/O form's field walk Review findings on the form: - A schema that refers to itself twice per level expanded to 2^33 fields and froze the tab: references already on the path become JSON inputs, and groups stop expanding at 1000 fields. - References inside embedded resources ($id) aren't followed, as they resolve elsewhere; such inputs are edited as JSON. - Inputs named constructor or prototype can be set; only __proto__ is ignored. Missing required inputs with such names show at the input. - Control ids are unique per pointer. Part of #444. Co-Authored-By: Claude Opus 5.5 --- .../src/components/io-form/io-form.ts | 10 ++- .../components/io-form/tests/io-form.test.ts | 26 +++++++ .../src/io-schema/fields.ts | 74 +++++++++++++++++-- .../src/io-schema/tests/fields.test.ts | 57 ++++++++++++++ .../src/io-schema/tests/values.test.ts | 7 ++ .../src/io-schema/values.ts | 5 +- 6 files changed, 168 insertions(+), 11 deletions(-) diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts index e66beffb..cc2ca597 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts @@ -317,7 +317,10 @@ export class ECCClientGa4ghWesIoForm extends LitElement { if ( parent === error.pointer && field.required && - !(isObject(object) && field.name in object) && + !( + isObject(object) && + Object.prototype.hasOwnProperty.call(object, field.name) + ) && pointers.has(field.pointer) ) { add(field.pointer, "This input is required."); @@ -417,7 +420,10 @@ export class ECCClientGa4ghWesIoForm extends LitElement { const fieldMessages = this.shows(field.pointer) ? messages.get(field.pointer) ?? [] : []; - const id = `input${field.pointer.replace(/[^A-Za-z0-9_-]/g, "_")}`; + const id = `input${field.pointer.replace( + /[^A-Za-z0-9-]/g, + (c) => `_${c.charCodeAt(0).toString(16)}_` + )}`; if (field.control === "group") { return html`
{ expect(root(el).querySelector('[data-pointer="/only"]')).to.not.equal(null); }); + it("shows a missing required input named like a built-in at the input", async () => { + const el = await render( + ioSchema({ + properties: { constructor: { type: "string" } }, + required: ["constructor"], + }) + ); + el.reportValidity(); + await el.updateComplete; + const field = root(el).querySelector('[data-field="/constructor"]'); + expect(field?.querySelector("[data-error]")?.textContent).to.contain( + "required" + ); + const result = await change(el, "/constructor", { value: "v" }); + expect(result.valid).to.equal(true); + }); + + it("gives every control its own id", async () => { + const el = await render( + ioSchema({ + properties: { "a b": { type: "string" }, a_b: { type: "string" } }, + }) + ); + expect(control(el, "/a b").id).to.not.equal(control(el, "/a_b").id); + }); + describe("widgets", () => { const WIDGETS = ioSchema({ properties: { diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts index 6245b404..be9e13db 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts @@ -62,6 +62,15 @@ export interface Field { const MAX_DEPTH = 32; +/** Fields that a form describes at most; deeper inputs become JSON */ +const MAX_FIELDS = 1000; + +/** State of one walk over the inputs */ +interface Walk { + /** Fields described so far */ + count: number; +} + const isObject = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); @@ -275,6 +284,9 @@ const titleOf = (schema: Schema, name: string) => * @param path - Path of its value. * @param required - Whether the enclosing object requires it. * @param depth - Nesting depth, to stop at cycles. + * @param refs - References followed on the way, to stop at cycles. + * @param inResource - Whether the input is in an embedded resource. + * @param walk - State of the walk. */ export function describeField( document: Schema, @@ -282,13 +294,39 @@ export function describeField( name: string, path: Path, required: boolean, - depth = 0 + depth = 0, + refs: readonly string[] = [], + inResource = false, + walk: Walk = { count: 0 } ): Field { + // eslint-disable-next-line no-param-reassign + walk.count += 1; const own = isObject(ownSchema) ? ownSchema : {}; - const schema = resolve(document, own); + const inner = inResource || typeof own.$id === "string"; + const ref = typeof own.$ref === "string" ? own.$ref : undefined; + const cyclic = ref !== undefined && refs.includes(ref); + const followed = ref !== undefined && !inner && !cyclic; + let schema: Schema = own; + if (followed) schema = resolve(document, own); + else if (ref !== undefined) { + schema = { ...own }; + delete schema.$ref; + } const { type, nullable } = typeOf(schema); - let control = controlOf(own, schema); - if (control === "group" && depth >= MAX_DEPTH) control = "json"; + let control = + cyclic || (ref !== undefined && !followed) + ? "json" + : controlOf(own, schema); + if ( + control === "group" && + (depth >= MAX_DEPTH || + walk.count + + Object.keys(isObject(schema.properties) ? schema.properties : {}) + .length > + MAX_FIELDS) + ) { + control = "json"; + } const field: Field = { name, path, @@ -304,7 +342,15 @@ export function describeField( children: [], }; if (control === "group") { - field.children = describeProperties(document, schema, path, depth + 1); + field.children = describeProperties( + document, + schema, + path, + depth + 1, + ref === undefined ? refs : [...refs, ref], + inner, + walk + ); } return field; } @@ -314,7 +360,10 @@ export function describeProperties( document: Schema, schema: Schema, path: Path, - depth = 0 + depth = 0, + refs: readonly string[] = [], + inResource = false, + walk: Walk = { count: 0 } ): Field[] { const properties = isObject(schema.properties) ? schema.properties : {}; const required = Array.isArray(schema.required) ? schema.required : []; @@ -325,7 +374,10 @@ export function describeProperties( name, [...path, name], required.includes(name), - depth + depth, + refs, + inResource, + walk ) ); } @@ -338,6 +390,14 @@ export function inputsSchema(document: Schema): Schema { /** Describes the inputs of an IO schema. */ export function describeInputs(document: Schema): Field[] { + const properties = isObject(document.properties) ? document.properties : {}; + const inputs = isObject(properties.inputs) ? properties.inputs : {}; + if (typeof inputs.$id === "string") { + // An embedded resource: its references resolve against its own $id + const own = { ...inputs }; + delete own.$ref; + return describeProperties(document, own, [], 0, [], true); + } return describeProperties(document, inputsSchema(document), []); } diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts index 8ee22d0b..e19a120c 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts @@ -255,3 +255,60 @@ describe("controlOf (widgets)", () => { expect(controlOf(own, resolved)).to.equal("number"); }); }); + +describe("describeInputs (limits)", () => { + it("stops at a schema that refers to itself twice", () => { + const fields = describeInputs( + doc( + { properties: { tree: { $ref: "#/$defs/n" } } }, + { + $defs: { + n: { + type: "object", + properties: { + l: { $ref: "#/$defs/n" }, + r: { $ref: "#/$defs/n" }, + }, + }, + }, + } + ) + ); + const all = [...allFields(fields)]; + expect(all.length).to.equal(3); + expect(all.slice(1).map((f) => f.control)).to.deep.equal(["json", "json"]); + }); + + it("caps the number of fields", () => { + const wide = Object.fromEntries( + Array.from({ length: 60 }, (_, i) => [`p${i}`, { $ref: "#/$defs/row" }]) + ); + const row = Object.fromEntries( + Array.from({ length: 60 }, (_, i) => [`c${i}`, { type: "string" }]) + ); + const fields = describeInputs( + doc( + { properties: wide }, + { $defs: { row: { type: "object", properties: row } } } + ) + ); + // Expanded groups stop at 1000 fields; the 60 inputs are always listed + expect([...allFields(fields)].length).to.be.at.most(1060); + }); + + it("doesn't follow references inside embedded resources", () => { + const fields = describeInputs({ + type: "object", + $defs: { t: { type: "string", enum: ["x", "y"] } }, + properties: { + inputs: { + $id: "https://e.example/inputs", + type: "object", + $defs: { t: { type: "integer" } }, + properties: { n: { $ref: "#/$defs/t" } }, + }, + }, + }); + expect(fields[0].control).to.equal("json"); + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/values.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/values.test.ts index b5626f20..a5b15ebb 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/values.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/values.test.ts @@ -39,6 +39,13 @@ describe("setAt", () => { }); }); + it("sets inputs named constructor or prototype", () => { + expect(setAt({}, ["constructor"], "v")).to.deep.equal({ constructor: "v" }); + expect(setAt({}, ["prototype", "a"], 1)).to.deep.equal({ + prototype: { a: 1 }, + }); + }); + it("ignores prototype keys", () => { const result = setAt({}, ["__proto__", "polluted"], 1) as Record< string, diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/values.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/values.ts index 2a834e88..b1bf7d1d 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/values.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/values.ts @@ -7,7 +7,8 @@ /** A path of property names and array indexes into the values. */ export type Path = readonly (string | number)[]; -const UNSAFE_KEYS = ["__proto__", "constructor", "prototype"]; +/** Keys that would set the prototype of the plain objects built here */ +const UNSAFE_KEYS = ["__proto__"]; const isObject = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); @@ -29,7 +30,7 @@ export function getAt(values: unknown, path: Path): unknown { /** * A copy of the values with the value at a path set; `undefined` leaves it * out (an array item is removed), and objects that become empty on the way - * are left out too. Keys such as `__proto__` are ignored. + * are left out too. `__proto__` is ignored. */ export function setAt( values: unknown, From 2bba81ede5b8a51b7adc24611105fae582dc1df0 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 10:09:52 +0100 Subject: [PATCH 08/19] feat(wes): check file reference inputs File references (x-ga4gh-file, also as a branch of anyOf/oneOf such as CWL's [File, string]) get a text field for a URI or relative path. Values are checked by the profile's file rules against allowedSchemes, narrowed by the reference's schemes, and make the form invalid when refused; refused defaults aren't prefilled. Changing allowedSchemes re-validates. Part of #444. Co-Authored-By: Claude Opus 5.5 --- .../pages/docs/wes/components/io-form.mdx | 2 + .../src/components/io-form/io-form.ts | 85 ++++++++++++++++++- .../components/io-form/tests/io-form.test.ts | 70 +++++++++++++++ .../src/io-schema/fields.ts | 50 ++++++++++- 4 files changed, 202 insertions(+), 5 deletions(-) diff --git a/apps/documentation/pages/docs/wes/components/io-form.mdx b/apps/documentation/pages/docs/wes/components/io-form.mdx index 67437c31..3a7e8e86 100644 --- a/apps/documentation/pages/docs/wes/components/io-form.mdx +++ b/apps/documentation/pages/docs/wes/components/io-form.mdx @@ -45,6 +45,8 @@ The `ecc-client-ga4gh-wes-io-form` component renders the input form of a workflo | `switch` | Checkbox (for now) | | `color-picker` | Colour picker, giving `#rrggbb` in lowercase | + File references (`x-ga4gh-file`, also as a branch of `anyOf` or `oneOf`) get a text field for a URI or a relative path. Their values are checked by the profile's rules (see [File references](../io-schema#file-references)) against `allowedSchemes`, narrowed by the reference's `schemes`; refused values make the form invalid, and refused defaults aren't prefilled. A picker for DRS or storage is up to the app for now. + A widget that doesn't fit, a viewer, or a `custom:` widget renders the input by its type. Inputs whose `type` allows `null` get a "No value (null)" checkbox. 3. Inputs start from their `default` values; inputs without a value are left out of the values, never sent as `null` or `""`. 4. Errors show at their input once it was changed, and at all inputs after `reportValidity()`. diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts index cc2ca597..c24107d6 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts @@ -22,7 +22,10 @@ import { toDateTimeInput, toTimeInput, } from "../../io-schema/values.js"; -import { DEFAULT_ALLOWED_SCHEMES } from "../../io-schema/files.js"; +import { + checkFileValue, + DEFAULT_ALLOWED_SCHEMES, +} from "../../io-schema/files.js"; import { parsePointer } from "../../io-schema/pointer.js"; import { descriptionTemplate } from "../../io-schema/descriptions.js"; import "@elixir-cloud/design/components/input/index.js"; @@ -177,6 +180,12 @@ export class ECCClientGa4ghWesIoForm extends LitElement { protected willUpdate(changed: PropertyValues): void { if (changed.has("schema")) { this.load(); + } else if ( + changed.has("allowedSchemes") && + !changed.has("values") && + this.status === "ready" + ) { + this.revalidate(); } else if (changed.has("values") && this.status === "ready") { this.current = deepCopy(this.values) ?? {}; this.localErrors = new Map(); @@ -232,12 +241,48 @@ export class ECCClientGa4ghWesIoForm extends LitElement { const value = defaultOf(field); if (value !== undefined) values = setAt(values, field.path, value); } + // Defaults of file references that the checks refuse aren't prefilled + for (const field of this.fileFields()) { + const value = getAt(values, field.path); + if (typeof value === "string" && this.fileProblem(field, value)) { + values = setAt(values, field.path, undefined); + } + } return isObject(values) ? values : {}; } + private fileFields(): Field[] { + return [...allFields(this.fields)].filter((field) => field.file); + } + + /** Why a file reference value is refused, or `null`. */ + private fileProblem(field: Field, value: string): string | null { + return checkFileValue(field.file ?? {}, value, this.allowedSchemes); + } + + /** Failures of file reference values, which JSON Schema can't check. */ + private fileErrors(): ValidationError[] { + const errors: ValidationError[] = []; + for (const field of this.fileFields()) { + const value = getAt(this.current, field.path); + if (typeof value === "string") { + const problem = this.fileProblem(field, value); + if (problem) { + errors.push({ + pointer: field.pointer, + keyword: "x-ga4gh-file", + schemaPointer: "", + message: problem, + }); + } + } + } + return errors; + } + private revalidate(): void { const result = this.validateInputs?.(this.current); - this.errors = result?.errors ?? []; + this.errors = [...(result?.errors ?? []), ...this.fileErrors()]; this.dispatchEvent( new CustomEvent("ecc-io-form-changed", { detail: { @@ -570,6 +615,8 @@ export class ECCClientGa4ghWesIoForm extends LitElement { >`; case "slider": return this.renderSlider(field, id, value, invalid); + case "file": + return this.renderFile(field, id, value, invalid); case "multiselect": return this.renderMultiSelect(field, id, value, invalid); case "typeahead": @@ -644,6 +691,40 @@ export class ECCClientGa4ghWesIoForm extends LitElement { >`; } + private renderFile( + field: Field, + id: string, + value: unknown, + invalid: boolean + ) { + const declared = Array.isArray(field.file?.schemes) + ? (field.file?.schemes as unknown[]).map(String) + : undefined; + const schemes = this.allowedSchemes.filter( + (scheme) => !declared || declared.includes(scheme) + ); + const kind = field.file?.kind === "directory" ? "directory" : "file"; + const placeholder = [ + ...schemes.map((scheme) => `${scheme}://...`), + ...(declared ? [] : ["relative/path"]), + ].join(" or "); + return html` { + const text = String(e.detail.value).trim(); + this.setValue(field, text === "" ? undefined : text); + }} + >`; + } + private renderSlider( field: Field, id: string, diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts index 06f96b5e..ada4b634 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts @@ -309,6 +309,76 @@ describe("ecc-client-ga4gh-wes-io-form", () => { expect(control(el, "/a b").id).to.not.equal(control(el, "/a_b").id); }); + describe("file references", () => { + const FILES = ioSchema({ + properties: { + reads: { + type: "string", + "x-ga4gh-file": { kind: "file", schemes: ["drs", "https"] }, + default: "drs://example.org/abc", + }, + any: { type: "string", "x-ga4gh-file": { kind: "file" } }, + bad: { + type: "string", + "x-ga4gh-file": { kind: "file" }, + default: "file:///etc/passwd", + }, + dir: { + type: "string", + "x-ga4gh-file": { kind: "directory" }, + "x-ga4gh-ui-widget": "directory-picker", + }, + union: { + anyOf: [ + { type: "string", "x-ga4gh-file": { kind: "file" } }, + { type: "string" }, + ], + }, + }, + }); + + it("renders file references and unions with a file as file fields", async () => { + const el = await render(FILES); + expect(control(el, "/reads").dataset.file).to.equal("file"); + expect(control(el, "/dir").dataset.file).to.equal("directory"); + expect(control(el, "/union").dataset.file).to.equal("file"); + }); + + it("prefills allowed defaults only", async () => { + const el = await render(FILES); + expect(el.inputValues).to.deep.equal({ reads: "drs://example.org/abc" }); + }); + + it("refuses values by the file reference rules", async () => { + const el = await render(FILES); + let result = await change(el, "/any", { + value: ["javascript", "alert(1)"].join(":"), + }); + expect(result.valid).to.equal(false); + expect(result.errors.map((e) => e.pointer)).to.include("/any"); + result = await change(el, "/any", { value: "data/../../etc" }); + expect(result.valid).to.equal(false); + result = await change(el, "/any", { value: "data/reads.fq" }); + expect(result.valid).to.equal(true); + result = await change(el, "/reads", { value: "data/reads.fq" }); + expect(result.valid).to.equal(false); + result = await change(el, "/reads", { value: "s3://bucket/x" }); + expect(result.valid).to.equal(false); + result = await change(el, "/union", { value: "~/x" }); + expect(result.valid).to.equal(false); + }); + + it("follows the deployment's allow-list", async () => { + const el = await render(FILES); + let result = await change(el, "/any", { value: "s3://bucket/x" }); + expect(result.valid).to.equal(false); + const event = oneEvent(el, "ecc-io-form-changed"); + el.allowedSchemes = ["drs", "https", "s3"]; + result = (await event).detail; + expect(result.valid).to.equal(true); + }); + }); + describe("widgets", () => { const WIDGETS = ioSchema({ properties: { diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts index be9e13db..afdea0a6 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts @@ -32,7 +32,8 @@ export type ControlKind = | "multiselect" | "typeahead" | "color" - | "tags"; + | "tags" + | "file"; /** One input of the form. */ export interface Field { @@ -58,6 +59,11 @@ export interface Field { choices?: unknown[]; /** The fields of an object */ children: Field[]; + /** + * The `x-ga4gh-file` annotation of a file reference, also of the file + * branch of an `anyOf`/`oneOf` union (e.g. CWL's `[File, string]`) + */ + file?: Record; } const MAX_DEPTH = 32; @@ -167,6 +173,7 @@ export function controlByType(schema: Schema): ControlKind { case "number": return "number"; case "string": + if (isObject(schema["x-ga4gh-file"])) return "file"; if (schema.format === "date") return "date"; if (schema.format === "time") return "time"; if (schema.format === "date-time") return "datetime"; @@ -250,9 +257,11 @@ function widgetControl(widget: string, own: Schema): ControlKind | undefined { if (!items.strings) return undefined; return items.choices ? "multiselect" : "tags"; } + case "file-picker": + case "directory-picker": + return isObject(own["x-ga4gh-file"]) ? "file" : undefined; default: - // File pickers come with file references; viewers, custom and unknown - // widgets render by type + // Viewers, custom and unknown widgets render by type return undefined; } } @@ -271,6 +280,29 @@ export function controlOf(own: Schema, schema: Schema): ControlKind { return controlByType(schema); } +/** + * The file reference annotation of a schema: its own `x-ga4gh-file`, or + * that of a branch of `anyOf`/`oneOf` (after local references). + */ +export function fileAnnotation( + document: Schema, + schema: Schema +): Record | undefined { + if (isObject(schema["x-ga4gh-file"])) return schema["x-ga4gh-file"]; + for (const keyword of ["anyOf", "oneOf"]) { + const branches = schema[keyword]; + if (Array.isArray(branches)) { + for (const branch of branches) { + const resolved = resolve(document, branch); + if (isObject(resolved["x-ga4gh-file"])) { + return resolved["x-ga4gh-file"]; + } + } + } + } + return undefined; +} + /** The title of an input: its `title`, else its name. */ const titleOf = (schema: Schema, name: string) => typeof schema.title === "string" && schema.title !== "" ? schema.title : name; @@ -327,10 +359,22 @@ export function describeField( ) { control = "json"; } + // File references are edited as files, whatever widget they carry; + // unions with a file branch too + let file: Record | undefined; + if (!cyclic && (ref === undefined || followed)) { + file = fileAnnotation(document, schema); + if (file && (isObject(schema["x-ga4gh-file"]) || control === "json")) { + control = "file"; + } else { + file = undefined; + } + } const field: Field = { name, path, pointer: toPointer(path), + file, schema, ownSchema: own, title: titleOf(schema, name), From 70ca407a5ba27d36e2180fc0626102acfbb3d2cf Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 10:18:19 +0100 Subject: [PATCH 09/19] feat(wes): add error messages, hidden inputs x-ga4gh-error-message replaces the validator's messages of the failures at the value its schema applies to, once per location; the outermost message wins (the input's own over its $ref target's). Hidden inputs go under a collapsed Advanced section, except inputs that must be set and inputs whose values fail. Part of #444. Co-Authored-By: Claude Opus 5.5 --- .../pages/docs/wes/components/io-form.mdx | 2 + .../src/components/io-form/io-form.ts | 72 ++++++++++++++++- .../components/io-form/tests/io-form.test.ts | 72 +++++++++++++++++ .../src/io-schema/error-messages.ts | 51 ++++++++++++ .../io-schema/tests/error-messages.test.ts | 77 +++++++++++++++++++ 5 files changed, 270 insertions(+), 4 deletions(-) create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/error-messages.ts create mode 100644 packages/ecc-client-ga4gh-wes/src/io-schema/tests/error-messages.test.ts diff --git a/apps/documentation/pages/docs/wes/components/io-form.mdx b/apps/documentation/pages/docs/wes/components/io-form.mdx index 3a7e8e86..aabbd24f 100644 --- a/apps/documentation/pages/docs/wes/components/io-form.mdx +++ b/apps/documentation/pages/docs/wes/components/io-form.mdx @@ -50,6 +50,8 @@ The `ecc-client-ga4gh-wes-io-form` component renders the input form of a workflo A widget that doesn't fit, a viewer, or a `custom:` widget renders the input by its type. Inputs whose `type` allows `null` get a "No value (null)" checkbox. 3. Inputs start from their `default` values; inputs without a value are left out of the values, never sent as `null` or `""`. 4. Errors show at their input once it was changed, and at all inputs after `reportValidity()`. +5. A schema's `x-ga4gh-error-message` replaces the validator's messages for failures at its value, once per value; of several, the outermost wins (the input's own over that of a shared definition it refers to). Failures of a property's value use the property's message; a missing property uses the message of its object. +6. Inputs with `x-ga4gh-hidden: true` are listed under a collapsed "Advanced" section, except inputs that must be set (required, without a default) and inputs whose values fail. Values follow the profile's widget table: a time is an RFC 3339 `full-time` with the offset of the browser's time zone (`14:30:00+01:00`), a date-time is in UTC (`2026-12-14T09:15:00Z`). Text that isn't a number is kept, so that the error says what is wrong. diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts index c24107d6..76a98b49 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts @@ -27,6 +27,7 @@ import { DEFAULT_ALLOWED_SCHEMES, } from "../../io-schema/files.js"; import { parsePointer } from "../../io-schema/pointer.js"; +import { withErrorMessages } from "../../io-schema/error-messages.js"; import { descriptionTemplate } from "../../io-schema/descriptions.js"; import "@elixir-cloud/design/components/input/index.js"; import "@elixir-cloud/design/components/textarea/index.js"; @@ -35,6 +36,7 @@ import "@elixir-cloud/design/components/checkbox/index.js"; import "@elixir-cloud/design/components/label/index.js"; import "@elixir-cloud/design/components/skeleton/index.js"; import "@elixir-cloud/design/components/multi-select/index.js"; +import "@elixir-cloud/design/components/collapsible/index.js"; /** The payload of `ecc-io-form-changed`. */ export interface IoFormChange { @@ -169,6 +171,9 @@ export class ECCClientGa4ghWesIoForm extends LitElement { private validateInputs?: InputsValidator; + /** The defaults of the inputs, to tell which inputs must be set */ + private defaultValues: Record = {}; + /** Number of the latest schema check, to drop stale results */ private checks = 0; @@ -229,7 +234,10 @@ export class ECCClientGa4ghWesIoForm extends LitElement { this.schemaErrors = []; this.validateInputs = result.validateInputs; this.fields = describeInputs(this.schema as Record); - this.current = this.values ? deepCopy(this.values) : this.defaults(); + this.defaultValues = this.defaults(); + this.current = this.values + ? deepCopy(this.values) + : deepCopy(this.defaultValues); this.status = "ready"; this.revalidate(); } @@ -282,7 +290,14 @@ export class ECCClientGa4ghWesIoForm extends LitElement { private revalidate(): void { const result = this.validateInputs?.(this.current); - this.errors = [...(result?.errors ?? []), ...this.fileErrors()]; + const fields = new Map( + [...allFields(this.fields)].map((field) => [field.pointer, field]) + ); + this.errors = withErrorMessages( + [...(result?.errors ?? []), ...this.fileErrors()], + this.schema, + (pointer) => fields.get(pointer)?.schema + ); this.dispatchEvent( new CustomEvent("ecc-io-form-changed", { detail: { @@ -457,10 +472,59 @@ export class ECCClientGa4ghWesIoForm extends LitElement { ? html`

This workflow has no inputs to set.

` - : this.fields.map((field) => this.renderField(field, messages))} + : this.renderFields(this.fields, messages)} `; } + /** + * Whether users must set an input: it is required, no default gives it a + * value, and its object is set (keywords, "Hidden inputs"). + */ + private mustSet(field: Field): boolean { + if (!field.required) return false; + if (getAt(this.defaultValues, field.path) !== undefined) return false; + const parent = field.path.slice(0, -1); + return parent.length === 0 || getAt(this.current, parent) !== undefined; + } + + /** Whether a value at or inside an input fails validation. */ + private failing(field: Field): boolean { + return [ + ...this.errors, + ...[...this.localErrors.keys()].map((pointer) => ({ pointer })), + ].some((error) => within(error.pointer, field.pointer)); + } + + /** + * Renders inputs; hidden ones (`x-ga4gh-hidden`) go under "Advanced", + * except those that users must set or whose values fail. + */ + private renderFields(fields: Field[], messages: Map) { + const advanced = fields.filter( + (field) => + field.schema["x-ga4gh-hidden"] === true && + !this.mustSet(field) && + !this.failing(field) + ); + const shown = fields.filter((field) => !advanced.includes(field)); + return html`${shown.map((field) => this.renderField(field, messages))} + ${advanced.length + ? html` + + Advanced (${advanced.length}) + + +
+ ${advanced.map((field) => this.renderField(field, messages))} +
+
+
` + : nothing}`; + } + private renderField(field: Field, messages: Map): unknown { const fieldMessages = this.shows(field.pointer) ? messages.get(field.pointer) ?? [] @@ -480,7 +544,7 @@ export class ECCClientGa4ghWesIoForm extends LitElement { : nothing} ${this.renderDescription(field)} ${renderMessages(fieldMessages)} - ${field.children.map((child) => this.renderField(child, messages))} + ${this.renderFields(field.children, messages)}
`; } return html`
diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts index ada4b634..a208c511 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts @@ -379,6 +379,78 @@ describe("ecc-client-ga4gh-wes-io-form", () => { }); }); + describe("error messages and hidden inputs", () => { + const SCHEMA7 = ioSchema( + { + properties: { + control: { + $ref: "#/$defs/sample_id", + "x-ga4gh-error-message": "The control is a sample ID such as S1", + }, + case: { $ref: "#/$defs/sample_id" }, + tuning: { + type: "integer", + default: 3, + minimum: 1, + "x-ga4gh-hidden": true, + }, + seed: { type: "integer", "x-ga4gh-hidden": true }, + key: { type: "string", "x-ga4gh-hidden": true }, + }, + required: ["key"], + }, + { + $defs: { + sample_id: { + type: "string", + pattern: "^S[0-9]+$", + "x-ga4gh-error-message": "A sample ID is S followed by digits", + }, + }, + } + ); + + it("shows the outermost custom message", async () => { + const el = await render(SCHEMA7); + let result = await change(el, "/control", { value: "x" }); + expect(result.errors).to.deep.include({ + pointer: "/control", + message: "The control is a sample ID such as S1", + }); + result = await change(el, "/case", { value: "x" }); + expect(result.errors).to.deep.include({ + pointer: "/case", + message: "A sample ID is S followed by digits", + }); + const field = root(el).querySelector('[data-field="/control"]'); + expect(field?.querySelector("[data-error]")?.textContent).to.contain( + "such as S1" + ); + }); + + it("puts hidden inputs under Advanced, except those to set", async () => { + const el = await render(SCHEMA7); + const advanced = root(el).querySelector("[data-advanced]"); + expect(advanced?.querySelector('[data-field="/tuning"]')).to.not.equal( + null + ); + expect(advanced?.querySelector('[data-field="/seed"]')).to.not.equal( + null + ); + expect(advanced?.querySelector('[data-field="/key"]')).to.equal(null); + expect(root(el).querySelector('[data-field="/key"]')).to.not.equal(null); + }); + + it("shows hidden inputs whose values fail", async () => { + const el = await render(SCHEMA7, { key: "k", tuning: 0 }); + const advanced = root(el).querySelector("[data-advanced]"); + expect(advanced?.querySelector('[data-field="/tuning"]')).to.equal(null); + expect(root(el).querySelector('[data-field="/tuning"]')).to.not.equal( + null + ); + }); + }); + describe("widgets", () => { const WIDGETS = ioSchema({ properties: { diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/error-messages.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/error-messages.ts new file mode 100644 index 00000000..6e423784 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/error-messages.ts @@ -0,0 +1,51 @@ +/** + * Custom error messages of IO schemas (`x-ga4gh-error-message`, keywords, + * "Error messages"): the message of a schema replaces the validator's + * messages of the failures at the location of the value it applies to, once + * per location. Of several schemas with a message at a location, the + * outermost on the evaluation path wins: the schema of the input as written + * (whose own keywords override those of its `$ref`), else the schema that + * holds the failing keyword. + */ +import type { ValidationError } from "./validator.js"; +import { valueAt } from "./pointer.js"; + +const KEYWORD = "x-ga4gh-error-message"; + +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const messageOf = (schema: unknown): string | undefined => + isObject(schema) && typeof schema[KEYWORD] === "string" + ? (schema[KEYWORD] as string) + : undefined; + +/** + * Errors with the schemas' own messages in place of the validator's. + * + * @param errors - Failures of the values, with `schemaPointer` into the + * IO schema. + * @param document - The IO schema. + * @param schemaAt - The schema of the input at a location of the values + * (with local references merged in), if the form has one there. + */ +export function withErrorMessages( + errors: ValidationError[], + document: unknown, + schemaAt: (pointer: string) => unknown +): ValidationError[] { + const result: ValidationError[] = []; + const given = new Set(); + for (const error of errors) { + const message = + messageOf(schemaAt(error.pointer)) ?? + messageOf(valueAt(document, error.schemaPointer)); + if (message === undefined) { + result.push(error); + } else if (!given.has(error.pointer)) { + given.add(error.pointer); + result.push({ ...error, keyword: KEYWORD, message }); + } + } + return result; +} diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/error-messages.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/error-messages.test.ts new file mode 100644 index 00000000..c0755ae7 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/error-messages.test.ts @@ -0,0 +1,77 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import { withErrorMessages } from "../error-messages.js"; +import { checkIoSchema } from "../validator.js"; +import { describeInputs, allFields } from "../fields.js"; +import { PROFILE_SCHEMA } from "../profile.js"; + +/** The profile's example for error messages (keywords.md). */ +const SCHEMA = { + $schema: PROFILE_SCHEMA.$id, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + samples: { + type: "array", + items: { $ref: "#/$defs/sample_id" }, + minItems: 1, + "x-ga4gh-error-message": "Give at least one sample", + }, + control: { + $ref: "#/$defs/sample_id", + "x-ga4gh-error-message": "The control is a sample ID such as S1", + }, + threads: { type: "integer", minimum: 1, maximum: 64 }, + }, + required: ["samples"], + }, + }, + $defs: { + sample_id: { + type: "string", + pattern: "^S[0-9]+$", + "x-ga4gh-error-message": "A sample ID is S followed by digits", + }, + }, +}; + +const check = async (values: unknown) => { + const result = await checkIoSchema(SCHEMA); + if (!result.valid) throw new Error("schema refused"); + const fields = [...allFields(describeInputs(SCHEMA))]; + const schemaAt = (pointer: string) => + fields.find((field) => field.pointer === pointer)?.schema; + return withErrorMessages( + result.validateInputs(values).errors, + SCHEMA, + schemaAt + ).map(({ pointer, message }) => ({ pointer, message })); +}; + +describe("withErrorMessages", () => { + it("gives the profile's example messages", async () => { + expect( + await check({ samples: ["S1", "x"], control: "y", threads: 0 }) + ).to.deep.equal([ + { pointer: "/samples/1", message: "A sample ID is S followed by digits" }, + { pointer: "/control", message: "The control is a sample ID such as S1" }, + { pointer: "/threads", message: "Must be at least 1." }, + ]); + }); + + it("gives a message once per location", async () => { + const errors = await check({ samples: [] }); + expect(errors).to.deep.equal([ + { pointer: "/samples", message: "Give at least one sample" }, + ]); + }); + + it("keeps the message of a missing property at the object", async () => { + const errors = await check({}); + expect(errors).to.have.length(1); + expect(errors[0].pointer).to.equal(""); + expect(errors[0].message).to.contain("samples"); + }); +}); From e3408953f6c4330ad66d90666fb578d39def531f Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 10:27:26 +0100 Subject: [PATCH 10/19] feat(wes): edit lists and unions in the I/O form Arrays with items get a list editor: a field per item (objects, file references and widgets included), Add and Remove within minItems and maxItems; a cleared item stays in the list, empty. Unions (anyOf or oneOf without a type) get a branch chooser, by title or type, that renders the chosen branch; the branch is guessed from the value's type at first. Other arrays (prefixItems) stay JSON. Part of #444. Co-Authored-By: Claude Opus 5.5 --- .../pages/docs/wes/components/io-form.mdx | 4 +- .../src/components/io-form/io-form.ts | 176 +++++++++++++++++- .../components/io-form/tests/io-form.test.ts | 103 ++++++++++ .../src/io-schema/fields.ts | 90 ++++++++- .../src/io-schema/tests/fields.test.ts | 3 + 5 files changed, 365 insertions(+), 11 deletions(-) diff --git a/apps/documentation/pages/docs/wes/components/io-form.mdx b/apps/documentation/pages/docs/wes/components/io-form.mdx index aabbd24f..638d1f28 100644 --- a/apps/documentation/pages/docs/wes/components/io-form.mdx +++ b/apps/documentation/pages/docs/wes/components/io-form.mdx @@ -29,7 +29,9 @@ The `ecc-client-ga4gh-wes-io-form` component renders the input form of a workflo | `boolean` | Checkbox | | `enum` or `const` (any type) | Dropdown | | `object` with `properties` | A group with a field per property, at any depth | -| Anything else | JSON text area | +| `array` with `items` | A list with a field per item, "Add" and "Remove" within `minItems` and `maxItems` | +| `anyOf` or `oneOf` without a `type` | A choice of the branch (by its `title`, else its type), then the branch's control | +| Anything else (e.g. `prefixItems`, objects without `properties`) | JSON text area | A widget hint (`x-ga4gh-ui-widget`) chooses the control where it fits its schema, with the keywords it needs next to it, as the profile's [UI widgets](https://ga4gh-io-schema.readthedocs.io/en/latest/specification/widgets/) define: diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts index 76a98b49..6c3be22e 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts @@ -8,10 +8,17 @@ import { ValidationError, } from "../../io-schema/validator.js"; import { - allFields, + branchesOf, + branchLabel, defaultOf, + describeBranch, describeInputs, + describeItem, + emptyValue, Field, + jsonType, + resolve, + typeOf, } from "../../io-schema/fields.js"; import { fromDateTimeInput, @@ -168,6 +175,8 @@ export class ECCClientGa4ghWesIoForm extends LitElement { @state() private rawText = new Map(); @state() private touched = new Set(); @state() private showAll = false; + /** The chosen branch of each union input, by pointer */ + @state() private branches = new Map(); private validateInputs?: InputsValidator; @@ -218,6 +227,7 @@ export class ECCClientGa4ghWesIoForm extends LitElement { this.localErrors = new Map(); this.rawText = new Map(); this.touched = new Set(); + this.branches = new Map(); this.showAll = false; if (this.schema === undefined || this.schema === null) { this.status = "empty"; @@ -259,8 +269,57 @@ export class ECCClientGa4ghWesIoForm extends LitElement { return isObject(values) ? values : {}; } + private get document(): Record { + return isObject(this.schema) ? this.schema : {}; + } + + /** The items of a list input, by the current value. */ + private itemsOf(field: Field): Field[] { + const value = getAt(this.current, field.path); + const count = Array.isArray(value) ? value.length : 0; + return Array.from({ length: count }, (_, i) => + describeItem(this.document, field, i) + ); + } + + /** The branch of a union input: as chosen, else by the value's type. */ + private branchOf(field: Field): number { + const chosen = this.branches.get(field.pointer); + if (chosen !== undefined) return chosen; + const value = getAt(this.current, field.path); + if (value === undefined) return 0; + const type = jsonType(value); + const index = branchesOf(field).findIndex((branch) => { + const branchType = typeOf(resolve(this.document, branch)).type; + return ( + branchType === type || (branchType === "number" && type === "integer") + ); + }); + return index === -1 ? 0 : index; + } + + /** The fields with the items of lists and the branches of unions. */ + private *liveFields(fields: Field[] = this.fields): Generator { + for (const field of fields) { + yield field; + if (field.control === "list") { + yield* this.liveFields(this.itemsOf(field)); + } else if (field.control === "union") { + const branch = describeBranch( + this.document, + field, + this.branchOf(field) + ); + yield* this.liveFields(branch.children.length ? [branch] : []); + if (branch.file) yield branch; + } else { + yield* this.liveFields(field.children); + } + } + } + private fileFields(): Field[] { - return [...allFields(this.fields)].filter((field) => field.file); + return [...this.liveFields()].filter((field) => field.file); } /** Why a file reference value is refused, or `null`. */ @@ -291,7 +350,7 @@ export class ECCClientGa4ghWesIoForm extends LitElement { private revalidate(): void { const result = this.validateInputs?.(this.current); const fields = new Map( - [...allFields(this.fields)].map((field) => [field.pointer, field]) + [...this.liveFields()].map((field) => [field.pointer, field]) ); this.errors = withErrorMessages( [...(result?.errors ?? []), ...this.fileErrors()], @@ -322,7 +381,13 @@ export class ECCClientGa4ghWesIoForm extends LitElement { /** Sets the value of a field (`undefined` leaves it out). */ private setValue(field: Field, value: unknown, problem?: string): void { - const next = setAt(this.current, field.path, value); + // A cleared list item stays in the list, empty + const item = typeof field.path[field.path.length - 1] === "number"; + const next = setAt( + this.current, + field.path, + item && value === undefined ? emptyValue(field) : value + ); this.current = isObject(next) ? next : {}; this.touched = new Set(this.touched).add(field.pointer); const localErrors = new Map(this.localErrors); @@ -342,7 +407,7 @@ export class ECCClientGa4ghWesIoForm extends LitElement { /** The field that shows an error: at its pointer, or the nearest above. */ private fieldFor(pointer: string): Field | undefined { let best: Field | undefined; - for (const field of allFields(this.fields)) { + for (const field of this.liveFields()) { if ( within(pointer, field.pointer) && (!best || field.pointer.length > best.pointer.length) @@ -366,13 +431,13 @@ export class ECCClientGa4ghWesIoForm extends LitElement { messages.set(pointer, list); }; const pointers = new Set( - [...allFields(this.fields)].map((field) => field.pointer) + [...this.liveFields()].map((field) => field.pointer) ); for (const error of this.errors) { let placed = false; if (error.keyword === "required") { const object = getAt(this.current, parsePointer(error.pointer)); - for (const field of allFields(this.fields)) { + for (const field of this.liveFields()) { const parent = field.pointer.slice(0, field.pointer.lastIndexOf("/")); if ( parent === error.pointer && @@ -555,7 +620,7 @@ export class ECCClientGa4ghWesIoForm extends LitElement { ? html` *` : nothing} `} - ${this.renderControl(field, id, fieldMessages.length > 0)} + ${this.renderControl(field, id, fieldMessages.length > 0, messages)} ${this.renderNullToggle(field)} ${this.renderDescription(field)} ${renderMessages(fieldMessages)}
`; @@ -597,7 +662,12 @@ export class ECCClientGa4ghWesIoForm extends LitElement { `; } - private renderControl(field: Field, id: string, invalid: boolean) { + private renderControl( + field: Field, + id: string, + invalid: boolean, + messages: Map + ): unknown { const value = getAt(this.current, field.path); const raw = this.rawText.get(field.pointer); switch (field.control) { @@ -663,6 +733,10 @@ export class ECCClientGa4ghWesIoForm extends LitElement { ); case "json": return this.renderJson(field, id, value, raw, invalid); + case "list": + return this.renderList(field, messages); + case "union": + return this.renderUnion(field, id, messages); case "textarea": return html``; } + private renderList(field: Field, messages: Map) { + const items = this.itemsOf(field); + const { minItems, maxItems } = field.schema; + const canAdd = typeof maxItems !== "number" || items.length < maxItems; + const canRemove = typeof minItems !== "number" || items.length > minItems; + const list = getAt(this.current, field.path); + return html`
+ ${items.map( + (item, i) => html`
+
${this.renderField(item, messages)}
+ +
` + )} + +
`; + } + + private renderUnion( + field: Field, + id: string, + messages: Map + ): unknown { + const branches = branchesOf(field); + const index = this.branchOf(field); + const branch = describeBranch(this.document, field, index); + return html`
+ + ${branch.control === "group" + ? branch.children.map((child) => this.renderField(child, messages)) + : this.renderControl( + { ...branch, pointer: field.pointer }, + `${id}-value`, + (messages.get(field.pointer) ?? []).length > 0, + messages + )} +
`; + } + private renderSlider( field: Field, id: string, diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts index a208c511..66300f23 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/tests/io-form.test.ts @@ -451,6 +451,109 @@ describe("ecc-client-ga4gh-wes-io-form", () => { }); }); + describe("lists and unions", () => { + const LISTS = ioSchema({ + properties: { + samples: { + type: "array", + items: { type: "string", pattern: "^S[0-9]+$" }, + minItems: 1, + maxItems: 2, + default: ["S1"], + }, + reads: { + type: "array", + items: { type: "string", "x-ga4gh-file": { kind: "file" } }, + }, + pairs: { + type: "array", + items: { + type: "object", + properties: { id: { type: "string" }, n: { type: "integer" } }, + required: ["id"], + }, + }, + size: { + anyOf: [ + { type: "integer", title: "Count" }, + { + type: "object", + title: "Range", + properties: { min: { type: "integer" } }, + }, + ], + }, + tuple: { type: "array", prefixItems: [{ type: "string" }] }, + }, + }); + + const click = async (el: ECCClientGa4ghWesIoForm, selector: string) => { + const event = oneEvent(el, "ecc-io-form-changed"); + (root(el).querySelector(selector) as HTMLButtonElement).click(); + const { detail } = await event; + await el.updateComplete; + return detail as IoFormChange; + }; + + it("edits lists item by item within minItems and maxItems", async () => { + const el = await render(LISTS); + const add = '[data-list="/samples"] > [data-add]'; + const remove = '[data-list="/samples"] [data-remove]'; + expect( + (root(el).querySelector(remove) as HTMLButtonElement).disabled + ).to.equal(true); + let result = await click(el, add); + expect(result.values.samples).to.deep.equal(["S1", ""]); + expect( + (root(el).querySelector(add) as HTMLButtonElement).disabled + ).to.equal(true); + result = await change(el, "/samples/1", { value: "S2" }); + expect(result.values.samples).to.deep.equal(["S1", "S2"]); + result = await change(el, "/samples/1", { value: "" }); + expect(result.values.samples).to.deep.equal(["S1", ""]); + result = await change(el, "/samples/1", { value: "x" }); + expect(result.errors.map((e) => e.pointer)).to.include("/samples/1"); + const field = root(el).querySelector('[data-field="/samples/1"]'); + expect(field?.querySelector("[data-error]")).to.not.equal(null); + }); + + it("lists objects and file references", async () => { + const el = await render(LISTS); + let result = await click(el, '[data-list="/pairs"] > [data-add]'); + expect(result.values.pairs).to.deep.equal([{}]); + result = await change(el, "/pairs/0/id", { value: "a" }); + expect(result.values.pairs).to.deep.equal([{ id: "a" }]); + await click(el, '[data-list="/reads"] > [data-add]'); + result = await change(el, "/reads/0", { value: "file:///etc/passwd" }); + expect(result.valid).to.equal(false); + expect(result.errors.map((e) => e.pointer)).to.include("/reads/0"); + }); + + it("chooses a branch of a union", async () => { + const el = await render(LISTS); + let result = await change(el, "/size", { value: "5" }); + expect(result.values.size).to.equal(5); + const select = root(el).querySelector( + '[data-union="/size"] [data-branch]' + ) as HTMLSelectElement; + const event = oneEvent(el, "ecc-io-form-changed"); + select.value = "1"; + select.dispatchEvent(new Event("change")); + await event; + await el.updateComplete; + result = await change(el, "/size/min", { value: "2" }); + expect(result.values.size).to.deep.equal({ min: 2 }); + expect(result.valid).to.equal(true); + }); + + it("edits other arrays as JSON", async () => { + const el = await render(LISTS); + expect(control(el, "/tuple").tagName).to.equal( + "ECC-UTILS-DESIGN-TEXTAREA" + ); + }); + }); + describe("widgets", () => { const WIDGETS = ioSchema({ properties: { diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts index afdea0a6..7a564c28 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts @@ -33,7 +33,9 @@ export type ControlKind = | "typeahead" | "color" | "tags" - | "file"; + | "file" + | "list" + | "union"; /** One input of the form. */ export interface Field { @@ -166,6 +168,12 @@ export function choicesOf(schema: Schema): unknown[] | undefined { export function controlByType(schema: Schema): ControlKind { const { type } = typeOf(schema); if (choicesOf(schema)) return "select"; + if ( + type === undefined && + (Array.isArray(schema.anyOf) || Array.isArray(schema.oneOf)) + ) { + return "union"; + } switch (type) { case "boolean": return "checkbox"; @@ -180,6 +188,10 @@ export function controlByType(schema: Schema): ControlKind { return "text"; case "object": return isObject(schema.properties) ? "group" : "json"; + case "array": + return isObject(schema.items) && !("prefixItems" in schema) + ? "list" + : "json"; default: return "json"; } @@ -467,3 +479,79 @@ export function* allFields(fields: Field[]): Generator { yield* allFields(field.children); } } + +/** The JSON value that a new list item or a chosen branch starts from. */ +export function emptyValue(field: Field): unknown { + const fallback = defaultOf(field); + if (fallback !== undefined) return fallback; + if (field.choices && field.choices.length > 0) return field.choices[0]; + switch (field.type) { + case "string": + return ""; + case "boolean": + return false; + case "object": + return {}; + case "array": + return []; + default: + return null; + } +} + +/** Describes item `index` of a list input. */ +export function describeItem( + document: Schema, + list: Field, + index: number +): Field { + return describeField( + document, + list.schema.items, + `Item ${index + 1}`, + [...list.path, index], + true, + list.path.length + 1 + ); +} + +/** The branches of a union input (`anyOf` or `oneOf`). */ +export function branchesOf(field: Field): unknown[] { + const { anyOf, oneOf } = field.schema; + if (Array.isArray(anyOf)) return anyOf; + if (Array.isArray(oneOf)) return oneOf; + return []; +} + +/** Describes branch `index` of a union input, at the union's location. */ +export function describeBranch( + document: Schema, + union: Field, + index: number +): Field { + const branch = branchesOf(union)[index]; + const field = describeField( + document, + branch, + union.name, + union.path, + union.required, + union.path.length + 1 + ); + return { ...field, title: union.title }; +} + +/** A label of a union branch: its title, else its type, else its number. */ +export function branchLabel( + document: Schema, + branch: unknown, + index: number +): string { + const schema = resolve(document, branch); + if (typeof schema.title === "string" && schema.title !== "") { + return schema.title; + } + const { type } = typeOf(schema); + if (isObject(schema["x-ga4gh-file"])) return "File"; + return type ? type[0].toUpperCase() + type.slice(1) : `Option ${index + 1}`; +} diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts index e19a120c..39544101 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts @@ -36,6 +36,9 @@ describe("controlByType", () => { [{ type: "object", properties: {} }, "group"], [{ type: "object" }, "json"], [{ type: ["string", "integer"] }, "json"], + [{ type: "array", items: { type: "string" } }, "list"], + [{ type: "array", prefixItems: [{}], items: {} }, "json"], + [{ anyOf: [{ type: "string" }, { type: "integer" }] }, "union"], [{}, "json"], ]; for (const [schema, control] of cases) { From 48d818cc1efd490b05cde99d660d7305eb704d76 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 10:50:43 +0100 Subject: [PATCH 11/19] feat(wes): show allOf groups as form sections Branches of allOf with properties (after a local $ref), such as nf-core's parameter groups, become sections of their object with the branch's title and description; their required lists apply to their fields, and their defaults are prefilled. The docs demo gets the profile's nf-core/fetchngs schema. Part of #444. Co-Authored-By: Claude Opus 5.5 --- .../components/packages/wes/ioFormExamples.ts | 316 +++++++++++++++++- .../pages/docs/wes/components/io-form.mdx | 1 + .../src/components/io-form/io-form.ts | 21 +- .../components/io-form/tests/io-form.test.ts | 18 + .../src/io-schema/fields.ts | 47 ++- .../src/io-schema/tests/fields.test.ts | 44 ++- 6 files changed, 440 insertions(+), 7 deletions(-) diff --git a/apps/documentation/components/packages/wes/ioFormExamples.ts b/apps/documentation/components/packages/wes/ioFormExamples.ts index 3004ba5a..97215256 100644 --- a/apps/documentation/components/packages/wes/ioFormExamples.ts +++ b/apps/documentation/components/packages/wes/ioFormExamples.ts @@ -1,9 +1,321 @@ // Example IO schemas of the GA4GH IO Schema profile, pinned to commit // 2c3dc49ad89f0a556272f160369a2a2d7a21dac3 of -// https://github.com/elixir-cloud-aai/ga4gh-io-schema (examples/demo and -// examples/workflows), for the preview of ecc-client-ga4gh-wes-io-form. +// https://github.com/elixir-cloud-aai/ga4gh-io-schema (examples/demo, +// examples/workflows and tests/data/nextflow/fetchngs/expected.json), for the preview of ecc-client-ga4gh-wes-io-form. export const ioFormExamples: Record }> = { + 'nextflow-fetchngs': { + label: 'nf-core/fetchngs (Nextflow, sections)', + schema: { + $schema: + 'https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json', + 'x-ga4gh-workflow': { + descriptor_type: 'NFL', + }, + type: 'object', + properties: { + inputs: { + title: 'nf-core/fetchngs pipeline parameters', + description: 'Pipeline to fetch metadata and raw FastQ files from public databases', + type: 'object', + allOf: [ + { + $ref: '#/$defs/input_output_options', + }, + { + $ref: '#/$defs/institutional_config_options', + }, + { + $ref: '#/$defs/max_job_request_options', + }, + { + $ref: '#/$defs/generic_options', + }, + { + $ref: '#/$defs/deprecated_options', + }, + ], + }, + outputs: { + type: 'object', + properties: {}, + }, + }, + $defs: { + input_output_options: { + title: 'Input/output options', + type: 'object', + description: 'Define where the pipeline should find input data and save output data.', + required: ['input', 'outdir'], + properties: { + input: { + type: 'string', + pattern: '^\\S+\\.(csv|tsv|txt)$', + description: + 'File containing SRA/ENA/GEO/DDBJ identifiers one per line to download their associated metadata and FastQ files.', + 'x-ga4gh-file': { + kind: 'file', + mediaType: 'text/csv', + }, + 'x-ga4gh-tabular-schema': { + title: 'nf-core/fetchngs pipeline - params.input schema', + description: 'Schema for the file provided with params.input', + type: 'array', + items: { + type: 'object', + properties: { + '': { + type: 'string', + pattern: + '^(((SR|ER|DR)[APRSX])|(SAM(N|EA|D))|(PRJ(NA|EB|DB))|(GS[EM]))(\\d+)$', + 'x-ga4gh-error-message': + 'Please provide a valid SRA, ENA, DDBJ or GEO identifier', + }, + }, + }, + }, + }, + ena_metadata_fields: { + type: 'string', + description: + "Comma-separated list of ENA metadata fields to fetch before downloading data.\n\nThe default list of fields used by the pipeline can be found at the top of the [`bin/sra_ids_to_runinfo.py`](https://github.com/nf-core/fetchngs/blob/master/bin/sra_ids_to_runinfo.py) script within the pipeline repo. This pipeline requires a minimal set of fields to download FastQ files i.e. `'run_accession,experiment_accession,library_layout,fastq_ftp,fastq_md5'`. Full list of accepted metadata fields can be obtained from the [ENA API](https://www.ebi.ac.uk/ena/portal/api/returnFields?dataPortal=ena&format=tsv&result=read_run).", + 'x-ga4gh-description-format': 'markdown', + }, + sample_mapping_fields: { + type: 'string', + description: + "Comma-separated list of ENA metadata fields used to create a separate 'id_mappings.csv' and 'multiqc_config.yml' with selected fields that can be used to rename samples in general and in MultiQC.", + default: + 'experiment_accession,run_accession,sample_accession,experiment_alias,run_alias,sample_alias,experiment_title,sample_title,sample_description', + }, + nf_core_pipeline: { + type: 'string', + description: + "Name of supported nf-core pipeline e.g. 'rnaseq'. A samplesheet for direct use with the pipeline will be created with the appropriate columns.", + enum: ['rnaseq', 'atacseq', 'viralrecon', 'taxprofiler'], + }, + nf_core_rnaseq_strandedness: { + type: 'string', + description: + "Value for 'strandedness' entry added to samplesheet created when using '--nf_core_pipeline rnaseq'.\n\nThe default is 'auto' which can be used with nf-core/rnaseq v3.10 onwards to auto-detect strandedness during the pipeline execution.", + default: 'auto', + 'x-ga4gh-description-format': 'markdown', + }, + download_method: { + type: 'string', + default: 'ftp', + enum: ['aspera', 'ftp', 'sratools'], + description: + "Method to download FastQ files. Available options are 'aspera', 'ftp' or 'sratools'. Default is 'ftp'.\n\nFTP and Aspera CLI download FastQ files directly from the ENA FTP whereas sratools uses sra-tools to download *.sra files and convert to FastQ.", + 'x-ga4gh-description-format': 'markdown', + }, + skip_fastq_download: { + type: 'boolean', + description: + "Only download metadata for public data database ids and don't download the FastQ files.", + }, + dbgap_key: { + type: 'string', + description: + 'dbGaP repository key.\n\nPath to a JWT cart file used to access protected dbGAP data on SRA using the sra-toolkit. Users with granted access to controlled data can download the JWT cart file for the study from the SRA Run Selector upon logging in. The JWT file can only be used on cloud platforms and is valid for 1 hour upon creation.', + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-file': { + kind: 'file', + }, + }, + outdir: { + type: 'string', + description: + 'The output directory where the results will be saved. You have to use absolute paths to storage on Cloud infrastructure.', + 'x-ga4gh-file': { + kind: 'directory', + }, + }, + email: { + type: 'string', + description: + "Email address for completion summary.\n\nSet this parameter to your e-mail address to get a summary e-mail with details of the run sent to you when the workflow exits. If set in your user config file (`~/.nextflow/config`) then you don't need to specify this on the command line for every run.", + pattern: '^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$', + 'x-ga4gh-description-format': 'markdown', + }, + }, + }, + institutional_config_options: { + title: 'Institutional config options', + type: 'object', + description: + 'Parameters used to describe centralised config profiles. These should not be edited.\n\nThe centralised nf-core configuration profiles use a handful of pipeline parameters to describe themselves. This information is then printed to the Nextflow log when you run a pipeline. You should not need to change these values when you run a pipeline.', + properties: { + custom_config_version: { + type: 'string', + description: 'Git commit id for Institutional configs.', + default: 'master', + 'x-ga4gh-hidden': true, + }, + custom_config_base: { + type: 'string', + description: + "Base directory for Institutional configs.\n\nIf you're running offline, Nextflow will not be able to fetch the institutional config files from the internet. If you don't need them, then this is not a problem. If you do need them, you should download the files from the repo and tell Nextflow where to find them with this parameter.", + default: 'https://raw.githubusercontent.com/nf-core/configs/master', + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-hidden': true, + }, + config_profile_name: { + type: 'string', + description: 'Institutional config name.', + 'x-ga4gh-hidden': true, + }, + config_profile_description: { + type: 'string', + description: 'Institutional config description.', + 'x-ga4gh-hidden': true, + }, + config_profile_contact: { + type: 'string', + description: 'Institutional config contact information.', + 'x-ga4gh-hidden': true, + }, + config_profile_url: { + type: 'string', + description: 'Institutional config URL link.', + 'x-ga4gh-hidden': true, + }, + }, + 'x-ga4gh-description-format': 'markdown', + }, + max_job_request_options: { + title: 'Max job request options', + type: 'object', + description: + 'Set the top limit for requested resources for any single job.\n\nIf you are running on a smaller system, a pipeline step requesting more resources than are available may cause the Nextflow to stop the run with an error. These options allow you to cap the maximum resources requested by any single job so that the pipeline will run on your system.\n\nNote that you can not _increase_ the resources requested by any job using these options. For that you will need your own configuration file. See [the nf-core website](https://nf-co.re/usage/configuration) for details.', + properties: { + max_cpus: { + type: 'integer', + description: + 'Maximum number of CPUs that can be requested for any single job.\n\nUse to set an upper-limit for the CPU requirement for each process. Should be an integer e.g. `--max_cpus 1`', + default: 16, + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-hidden': true, + }, + max_memory: { + type: 'string', + description: + "Maximum amount of memory that can be requested for any single job.\n\nUse to set an upper-limit for the memory requirement for each process. Should be a string in the format integer-unit e.g. `--max_memory '8.GB'`", + default: '128.GB', + pattern: '^\\d+(\\.\\d+)?\\.?\\s*(K|M|G|T)?B$', + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-hidden': true, + }, + max_time: { + type: 'string', + description: + "Maximum amount of time that can be requested for any single job.\n\nUse to set an upper-limit for the time requirement for each process. Should be a string in the format integer-unit e.g. `--max_time '2.h'`", + default: '240.h', + pattern: '^(\\d+\\.?\\s*(s|m|h|d|day)\\s*)+$', + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-hidden': true, + }, + }, + 'x-ga4gh-description-format': 'markdown', + }, + generic_options: { + title: 'Generic options', + type: 'object', + description: + 'Less common options for the pipeline, typically set in a config file.\n\nThese options are common to all nf-core pipelines and allow you to customise some of the core preferences for how the pipeline runs.\n\nTypically these options would be set in a Nextflow config file loaded for all pipeline runs, such as `~/.nextflow/config`.', + properties: { + help: { + type: 'boolean', + description: 'Display help text.', + 'x-ga4gh-hidden': true, + }, + version: { + type: 'boolean', + description: 'Display version and exit.', + 'x-ga4gh-hidden': true, + }, + publish_dir_mode: { + type: 'string', + default: 'copy', + description: + 'Method used to save pipeline results to output directory.\n\nThe Nextflow `publishDir` option specifies which intermediate files should be saved to the output directory. This option tells the pipeline what method should be used to move these files. See [Nextflow docs](https://www.nextflow.io/docs/latest/process.html#publishdir) for details.', + enum: ['symlink', 'rellink', 'link', 'copy', 'copyNoFollow', 'move'], + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-hidden': true, + }, + email_on_fail: { + type: 'string', + description: + 'Email address for completion summary, only when pipeline fails.\n\nAn email address to send a summary email to when the pipeline is completed - ONLY sent if the pipeline does not exit successfully.', + pattern: '^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$', + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-hidden': true, + }, + plaintext_email: { + type: 'boolean', + description: 'Send plain-text email instead of HTML.', + 'x-ga4gh-hidden': true, + }, + monochrome_logs: { + type: 'boolean', + description: 'Do not use coloured log outputs.', + 'x-ga4gh-hidden': true, + }, + hook_url: { + type: 'string', + description: + 'Incoming hook URL for messaging service\n\nIncoming hook URL for messaging service. Currently, MS Teams and Slack are supported.', + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-hidden': true, + }, + validate_params: { + type: 'boolean', + description: 'Boolean whether to validate parameters against the schema at runtime', + default: true, + 'x-ga4gh-hidden': true, + }, + validationShowHiddenParams: { + type: 'boolean', + description: + 'Show all params when using `--help`\n\nBy default, parameters set as _hidden_ in the schema are not shown on the command line when a user runs with `--help`. Specifying this option will tell the pipeline to show all parameters.', + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-hidden': true, + }, + validationFailUnrecognisedParams: { + type: 'boolean', + description: + 'Validation of parameters fails when an unrecognised parameter is found.\n\nBy default, when an unrecognised parameter is found, it returns a warinig.', + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-hidden': true, + }, + validationLenientMode: { + type: 'boolean', + description: + 'Validation of parameters in lenient more.\n\nAllows string values that are parseable as numbers or booleans. For further information see [JSONSchema docs](https://github.com/everit-org/json-schema#lenient-mode).', + 'x-ga4gh-description-format': 'markdown', + 'x-ga4gh-hidden': true, + }, + }, + 'x-ga4gh-description-format': 'markdown', + }, + deprecated_options: { + title: 'Deprecated options', + type: 'object', + description: 'List of parameters that have been deprecated.', + default: '', + properties: { + force_sratools_download: { + type: 'boolean', + description: + "This parameter has been deprecated. Please use '--download_method sratools' instead.", + enum: [false], + 'x-ga4gh-hidden': true, + }, + }, + }, + }, + }, + }, demo: { label: 'IO Schema demo (WDL)', schema: { diff --git a/apps/documentation/pages/docs/wes/components/io-form.mdx b/apps/documentation/pages/docs/wes/components/io-form.mdx index 638d1f28..69222a25 100644 --- a/apps/documentation/pages/docs/wes/components/io-form.mdx +++ b/apps/documentation/pages/docs/wes/components/io-form.mdx @@ -30,6 +30,7 @@ The `ecc-client-ga4gh-wes-io-form` component renders the input form of a workflo | `enum` or `const` (any type) | Dropdown | | `object` with `properties` | A group with a field per property, at any depth | | `array` with `items` | A list with a field per item, "Add" and "Remove" within `minItems` and `maxItems` | +| Branches of `allOf` with `properties` (e.g. nf-core parameter groups) | Sections of the object, with the branch's `title` and `description` | | `anyOf` or `oneOf` without a `type` | A choice of the branch (by its `title`, else its type), then the branch's control | | Anything else (e.g. `prefixItems`, objects without `properties`) | JSON text area | diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts index 6c3be22e..43c324fc 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts @@ -19,6 +19,7 @@ import { jsonType, resolve, typeOf, + withoutSections, } from "../../io-schema/fields.js"; import { fromDateTimeInput, @@ -255,7 +256,7 @@ export class ECCClientGa4ghWesIoForm extends LitElement { /** The defaults of all inputs. */ private defaults(): Record { let values: unknown = {}; - for (const field of this.fields) { + for (const field of withoutSections(this.fields)) { const value = defaultOf(field); if (value !== undefined) values = setAt(values, field.path, value); } @@ -301,6 +302,12 @@ export class ECCClientGa4ghWesIoForm extends LitElement { /** The fields with the items of lists and the branches of unions. */ private *liveFields(fields: Field[] = this.fields): Generator { for (const field of fields) { + // Sections share the location of their object: only their fields count + if (field.control === "section") { + yield* this.liveFields(field.children); + // eslint-disable-next-line no-continue + continue; + } yield field; if (field.control === "list") { yield* this.liveFields(this.itemsOf(field)); @@ -598,6 +605,18 @@ export class ECCClientGa4ghWesIoForm extends LitElement { /[^A-Za-z0-9-]/g, (c) => `_${c.charCodeAt(0).toString(16)}_` )}`; + if (field.control === "section") { + return html`
+ ${field.title + ? html`

${field.title}

` + : nothing} + ${this.renderDescription(field)} + ${this.renderFields(field.children, messages)} +
`; + } if (field.control === "group") { return html`
{ }); }); + it("renders allOf groups as sections (nf-core fetchngs)", async () => { + const el = await render(EXAMPLES["nextflow-fetchngs"]); + const sections = [...root(el).querySelectorAll("[data-section]")].map( + (section) => section.getAttribute("data-section") + ); + expect(sections).to.include("Input/output options"); + expect(sections.length).to.be.at.least(4); + const io = root(el).querySelector('[data-section="Input/output options"]'); + expect(io?.querySelector('[data-field="/outdir"]')).to.not.equal(null); + expect(el.inputValues).to.have.property("sample_mapping_fields"); + expect(el.reportValidity()).to.equal(false); + await el.updateComplete; + const outdir = root(el).querySelector('[data-field="/outdir"]'); + expect(outdir?.querySelector("[data-error]")?.textContent).to.contain( + "required" + ); + }); + describe("widgets", () => { const WIDGETS = ioSchema({ properties: { diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts index 7a564c28..f01ca83c 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/fields.ts @@ -35,7 +35,8 @@ export type ControlKind = | "tags" | "file" | "list" - | "union"; + | "union" + | "section"; /** One input of the form. */ export interface Field { @@ -423,7 +424,7 @@ export function describeProperties( ): Field[] { const properties = isObject(schema.properties) ? schema.properties : {}; const required = Array.isArray(schema.required) ? schema.required : []; - return Object.entries(properties).map(([name, property]) => + const fields = Object.entries(properties).map(([name, property]) => describeField( document, property, @@ -436,6 +437,46 @@ export function describeProperties( walk ) ); + // Branches of `allOf` with properties (e.g. nf-core's parameter groups) + // become sections of the same object + const allOf = Array.isArray(schema.allOf) ? schema.allOf : []; + allOf.forEach((branch, i) => { + if (depth >= MAX_DEPTH || !isObject(branch)) return; + const ref = typeof branch.$ref === "string" ? branch.$ref : undefined; + if (ref && (inResource || refs.includes(ref))) return; + const section = ref ? resolve(document, branch) : branch; + if (!isObject(section.properties)) return; + // eslint-disable-next-line no-param-reassign + walk.count += 1; + fields.push({ + name: `section-${i}`, + path, + pointer: toPointer(path), + schema: section, + ownSchema: branch, + title: typeof section.title === "string" ? section.title : "", + control: "section", + nullable: false, + required: false, + children: describeProperties( + document, + section, + path, + depth + 1, + ref ? [...refs, ref] : refs, + inResource || typeof section.$id === "string", + walk + ), + }); + }); + return fields; +} + +/** The fields of an object with the fields of its sections in place. */ +export function withoutSections(fields: Field[]): Field[] { + return fields.flatMap((field) => + field.control === "section" ? withoutSections(field.children) : [field] + ); } /** The schema of `inputs` of an IO schema, resolved. */ @@ -465,7 +506,7 @@ export function defaultOf(field: Field): unknown { if ("default" in field.schema) return field.schema.default; if (field.control !== "group") return undefined; const value: Record = {}; - for (const child of field.children) { + for (const child of withoutSections(field.children)) { const childDefault = defaultOf(child); if (childDefault !== undefined) value[child.name] = childDefault; } diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts index 39544101..e6bbc47a 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fields.test.ts @@ -8,6 +8,7 @@ import { describeInputs, resolve, typeOf, + withoutSections, } from "../fields.js"; import { EXAMPLES } from "./fixtures/examples.js"; @@ -163,7 +164,7 @@ describe("describeInputs", () => { ); const fields = describeInputs(example); expect( - fields.map((f) => f.name), + fields.filter((f) => f.control !== "section").map((f) => f.name), name ).to.deep.equal(properties); } @@ -315,3 +316,44 @@ describe("describeInputs (limits)", () => { expect(fields[0].control).to.equal("json"); }); }); + +describe("describeInputs (allOf sections)", () => { + it("describes allOf branches with properties as sections", () => { + const fields = describeInputs( + doc( + { + properties: { top: { type: "string" } }, + allOf: [ + { $ref: "#/$defs/a" }, + { required: ["top"] }, + { title: "B", properties: { b: { type: "integer", default: 1 } } }, + ], + }, + { + $defs: { + a: { + title: "A", + type: "object", + properties: { a: { type: "string" } }, + required: ["a"], + }, + }, + } + ) + ); + expect(fields.map((f) => [f.control, f.title])).to.deep.equal([ + ["text", "top"], + ["section", "A"], + ["section", "B"], + ]); + expect(fields[1].children[0]).to.include({ + pointer: "/a", + required: true, + }); + expect(withoutSections(fields).map((f) => f.pointer)).to.deep.equal([ + "/top", + "/a", + "/b", + ]); + }); +}); From cedf572c9e67d1606272f23eb8ad7d1c893fc300 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Thu, 3 Dec 2026 11:28:17 +0100 Subject: [PATCH 12/19] fix(wes): name I/O form controls and buttons Quality review: aria-labels on selects, multi-selects, checkboxes and the null toggle; list buttons name their list; suggestions form a labelled group; the slider value is announced. Tests for the allowed-schemes attribute and for new values. Docs: slider steps, null toggle, required marker, attribute format. Part of #444. Co-Authored-By: Claude Opus 5.5 --- .../pages/docs/wes/components/io-form.mdx | 6 +-- .../src/components/io-form/io-form.ts | 19 ++++++++-- .../components/io-form/tests/io-form.test.ts | 38 +++++++++++++++++++ 3 files changed, 57 insertions(+), 6 deletions(-) diff --git a/apps/documentation/pages/docs/wes/components/io-form.mdx b/apps/documentation/pages/docs/wes/components/io-form.mdx index 69222a25..cb0c162d 100644 --- a/apps/documentation/pages/docs/wes/components/io-form.mdx +++ b/apps/documentation/pages/docs/wes/components/io-form.mdx @@ -40,7 +40,7 @@ The `ecc-client-ga4gh-wes-io-form` component renders the input form of a workflo |--------|---------| | `text`, `number`, `checkbox`, `date-picker`, `time-picker`, `datetime-picker` | As above | | `textarea` | Text area | -| `slider` | Slider within the bounds, in steps of `multipleOf` | +| `slider` | Slider within the bounds, in steps of `multipleOf` (else 1 for integers, any step for numbers) | | `dropdown`, `radio` | Dropdown (radio buttons are rendered as a dropdown for now) | | `dropdown` or `tags` on an array with `items.enum` | Multiple choice | | `tags` on an array of strings | One tag per line | @@ -50,7 +50,7 @@ The `ecc-client-ga4gh-wes-io-form` component renders the input form of a workflo File references (`x-ga4gh-file`, also as a branch of `anyOf` or `oneOf`) get a text field for a URI or a relative path. Their values are checked by the profile's rules (see [File references](../io-schema#file-references)) against `allowedSchemes`, narrowed by the reference's `schemes`; refused values make the form invalid, and refused defaults aren't prefilled. A picker for DRS or storage is up to the app for now. - A widget that doesn't fit, a viewer, or a `custom:` widget renders the input by its type. Inputs whose `type` allows `null` get a "No value (null)" checkbox. + A widget that doesn't fit, a viewer, or a `custom:` widget renders the input by its type. Inputs whose `type` allows `null` get a "No value (null)" checkbox, which disables the control while it is checked. Required inputs are marked with `*`. 3. Inputs start from their `default` values; inputs without a value are left out of the values, never sent as `null` or `""`. 4. Errors show at their input once it was changed, and at all inputs after `reportValidity()`. 5. A schema's `x-ga4gh-error-message` replaces the validator's messages for failures at its value, once per value; of several, the outermost wins (the input's own over that of a shared definition it refers to). Failures of a property's value use the property's message; a missing property uses the message of its object. @@ -121,7 +121,7 @@ The preview renders example schemas of the IO Schema profile and shows what the |----------|-----------|------|---------|-------------| | `schema` | | `object` | `undefined` | The IO schema of the workflow. | | `values` | | `object` | `undefined` | Values to start from instead of the defaults. | -| `allowedSchemes` | `allowed-schemes` | `string[]` | `["drs", "https"]` | URI schemes that file references and links in descriptions may have. | +| `allowedSchemes` | `allowed-schemes` | `string[]` | `["drs", "https"]` | URI schemes that file references and links in descriptions may have; the attribute takes them separated by spaces or commas, in any case. Changing it checks the values again (defaults refused at load stay out). | | `inputValues` | | `object` | | The current values (read only, a copy). | ## Methods diff --git a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts index 43c324fc..87ea97ff 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/io-form/io-form.ts @@ -670,6 +670,7 @@ export class ECCClientGa4ghWesIoForm extends LitElement { class="flex items-center gap-2 text-xs text-muted-foreground" > { @@ -694,6 +695,7 @@ export class ECCClientGa4ghWesIoForm extends LitElement { return html`