From 79bbf7515a9eeb803a683aa70d257bed15862f52 Mon Sep 17 00:00:00 2001 From: Greg Smith Date: Wed, 18 Nov 2026 22:33:54 +0000 Subject: [PATCH] feat(models): add ucp-lock.json provenance and draft channel on main --- .github/workflows/linter.yml | 8 +- .github/workflows/tests.yml | 43 +- README.md | 64 +- generate_models.sh | 220 +-- pyproject.toml | 2 +- scripts/generate_models.py | 283 ++++ src/ucp_sdk/__init__.py | 7 +- src/ucp_sdk/models/schemas/__init__.py | 58 + src/ucp_sdk/models/schemas/_generated.py | 1806 ++++++++++++++++------ tests/test_models.py | 156 +- ucp-lock.json | 7 + 11 files changed, 1907 insertions(+), 747 deletions(-) create mode 100644 scripts/generate_models.py create mode 100644 ucp-lock.json diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 99a5613..47828fd 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -16,9 +16,9 @@ name: Lint on: push: - branches: [main] + branches: [main, "release/**"] pull_request: - branches: [main] + branches: [main, "release/**"] permissions: contents: read @@ -27,10 +27,10 @@ jobs: pre-commit: runs-on: ubuntu-latest steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: '3.x' - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index e057df5..6b937e3 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -16,9 +16,9 @@ name: Tests on: push: - branches: [main] + branches: [main, "release/**"] pull_request: - branches: [main] + branches: [main, "release/**"] permissions: contents: read @@ -40,7 +40,7 @@ jobs: uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.python-version }} - - name: Install package (generated-model tests import it) + - name: Install package run: pip install -e . - name: Run unit tests run: python -m unittest discover -s tests -p "test_*.py" @@ -56,12 +56,17 @@ jobs: - name: Install uv uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 with: - enable-cache: true - - name: Install ucp-schema CLI - env: - UCP_SCHEMA_VERSION: "2.0.0" + enable-cache: false + - name: Regenerate models from ucp-lock.json and verify zero drift run: | set -euo pipefail + LOCK_FIELDS="$(jq -er ' + (.ucp_sha | select(type == "string" and test("^[0-9a-f]{40}$"))) as $sha | + (.ucp_schema_version | select(type == "string" and test("^[0-9]+\\.[0-9]+\\.[0-9]+$"))) as $ver | + "\($sha) \($ver)" + ' ucp-lock.json)" + read -r UCP_SHA UCP_SCHEMA_VERSION <<< "$LOCK_FIELDS" + tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT base_url="https://github.com/Universal-Commerce-Protocol/ucp-schema/releases/download/v${UCP_SCHEMA_VERSION}" @@ -70,18 +75,16 @@ jobs: (cd "$tmp_dir" && sha256sum -c --ignore-missing SHA256SUMS) mkdir -p "$HOME/.local/bin" install -m 0755 "$tmp_dir/ucp-schema-linux-x86_64" "$HOME/.local/bin/ucp-schema" - echo "$HOME/.local/bin" >> "$GITHUB_PATH" - - name: Regenerate models from the pinned spec version - # SDK 0.6.x targets UCP 2026-08-25 (see the README compatibility - # table). Bump this pin together with the SDK version line. - run: ./generate_models.sh 2026-08-25 - - name: Fail if regeneration does not reproduce the committed models - run: | - git add -A -- src/ucp_sdk/models/schemas - if ! git diff --cached --quiet -- src/ucp_sdk/models/schemas; then - echo "::error::Committed models differ from regeneration against the pinned UCP spec. Either the generation pipeline is broken, or the models were edited without regenerating. Run ./generate_models.sh 2026-08-25 and commit the result." - git --no-pager diff --cached --stat -- src/ucp_sdk/models/schemas - git --no-pager diff --cached -- src/ucp_sdk/models/schemas + export PATH="$HOME/.local/bin:$PATH" + + rm -rf "$RUNNER_TEMP/ucp-spec" + git clone --filter=blob:none --no-checkout https://github.com/Universal-Commerce-Protocol/ucp.git "$RUNNER_TEMP/ucp-spec" + git -C "$RUNNER_TEMP/ucp-spec" checkout --detach "$UCP_SHA" + ./generate_models.sh --from-lock --spec-dir "$RUNNER_TEMP/ucp-spec" + + if [ -n "$(git status --porcelain -- src/ucp_sdk pyproject.toml ucp-lock.json)" ]; then + echo "::error::Committed models differ from regeneration against ucp-lock.json. Run ./generate_models.sh --from-lock and commit the result." + git status --short -- src/ucp_sdk pyproject.toml ucp-lock.json + git --no-pager diff -- src/ucp_sdk pyproject.toml ucp-lock.json exit 1 fi - echo "Committed models match regeneration." diff --git a/README.md b/README.md index 9dfb528..f42cf3c 100644 --- a/README.md +++ b/README.md @@ -37,31 +37,51 @@ Python. ### UCP Version Compatibility -Each version of the Python SDK is generated against a specific version of the -UCP schema: - -| SDK Version | UCP Schema Version | -| ----------------- | ------------------ | -| **`0.6.x`** | **`2026-08-25`** | -| `0.5.x` | `2026-08-25` | -| `0.4.x` | `2026-04-08` | -| `0.3.x` | `2026-01-23` | -| `0.2.x` / `0.1.x` | `2026-01-11` | +Starting with the `2026-08-25` UCP specification release, PyPI releases use +spec-aligned `YYYYMMDD.MINOR.PATCH` versioning (for example, `20260825.0.0` for +UCP `2026-08-25`), while `main` tracks the `draft` UCP schema (`0.0.0.dev0`) +pinned in [`ucp-lock.json`](ucp-lock.json): + +| SDK Version | UCP Schema Version | Channel | +| -------------------------------- | ---------------------------------- | ------------------- | +| **`YYYYMMDD.MINOR.PATCH`** | **`YYYY-MM-DD`** (`>= 2026-08-25`) | PyPI | +| `0.0.0.dev0` (`main` git commit) | `draft` (`ucp@main` in `ucp-lock`) | Git (`main`) | +| `0.5.x` | `2026-08-25` | PyPI (legacy `0.x`) | +| `0.4.x` | `2026-04-08` | PyPI | +| `0.3.x` | `2026-01-23` | PyPI | +| `0.2.x` / `0.1.x` | `2026-01-11` | PyPI | ## Installation -To use this SDK in your own project, install it from PyPI: +### Published Releases (PyPI) + +Install the latest published UCP release from PyPI: ```bash pip install ucp-sdk ``` -Or, if you are managing your project with [uv](https://docs.astral.sh/uv/): +Or with [uv](https://docs.astral.sh/uv/): ```bash uv add ucp-sdk ``` +To pin a specific UCP specification release epoch (for example, `2026-08-25`): + +```bash +uv add "ucp-sdk>=20260825.0.0,<20260826.0.0" +``` + +### Unreleased `draft` Schemas (Git-Native) + +To build against unreleased `draft` schemas on `main`, install directly from a +commit SHA on `Universal-Commerce-Protocol/python-sdk`: + +```bash +uv add "ucp-sdk @ git+https://github.com/Universal-Commerce-Protocol/python-sdk.git@" +``` + ## Usage The example below parses a UCP checkout response and reads typed fields: @@ -175,20 +195,26 @@ uv sync ### Generating Pydantic Models The models are automatically generated from the JSON schemas in the UCP -Specification using `ucp-schema generate-types` and `datamodel-codegen`. +Specification using `ucp-schema generate-types` and `datamodel-codegen`, with +provenance recorded in [`ucp-lock.json`](ucp-lock.json). To regenerate the models: ```bash uv sync -./generate_models.sh -``` -Where `` is a UCP release version (for example, `2026-08-25`), -a branch or commit SHA, or a path to a local UCP repository checkout. +# Reproduce committed models from the exact commit pinned in ucp-lock.json +./generate_models.sh -If no argument is specified, the `main` branch of the -[UCP repo](https://github.com/Universal-Commerce-Protocol/ucp) will be used. +# Advance ucp-lock.json and regenerate models from ucp@main (draft channel) +./generate_models.sh --ref main --write-lock + +# Pin ucp-lock.json to a release branch +./generate_models.sh --ref release/2026-08-25 --write-lock + +# Regenerate models from a local UCP checkout without modifying ucp-lock.json +./generate_models.sh --spec-dir /path/to/ucp +``` The generated code is automatically formatted using `ruff`. diff --git a/generate_models.sh b/generate_models.sh index b43bb6a..581eedc 100755 --- a/generate_models.sh +++ b/generate_models.sh @@ -13,225 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Generate Pydantic models from UCP JSON Schemas using ucp-schema generate-types. - set -euo pipefail - -# Ensure we are in the script's directory cd "$(dirname "$0")" - -# Add ~/.local/bin to PATH for uv export PATH="$HOME/.local/bin:$PATH" - -if ! command -v git &> /dev/null; then - echo "Error: git not found. Please install git." - exit 1 -fi - -if ! command -v uv &> /dev/null; then - echo "Error: uv not found." - echo "Please install uv: curl -LsSf https://astral.sh/uv/install.sh | sh" - exit 1 -fi - -# Resolve ucp-schema binary -if [ -n "${UCP_SCHEMA_BIN:-}" ] && [ ! -x "$UCP_SCHEMA_BIN" ]; then - echo "Error: UCP_SCHEMA_BIN='$UCP_SCHEMA_BIN' is not executable." - exit 1 -elif [ -n "${UCP_SCHEMA_BIN:-}" ]; then - if ! "$UCP_SCHEMA_BIN" generate-types --help &> /dev/null; then - echo "Error: UCP_SCHEMA_BIN='$UCP_SCHEMA_BIN' does not support 'generate-types'." - exit 1 - fi -elif command -v ucp-schema &> /dev/null && ucp-schema generate-types --help &> /dev/null; then - UCP_SCHEMA_BIN="$(command -v ucp-schema)" -elif [ -x "../ucp-schema/target/release/ucp-schema" ] && "../ucp-schema/target/release/ucp-schema" generate-types --help &> /dev/null; then - UCP_SCHEMA_BIN="../ucp-schema/target/release/ucp-schema" -elif [ -x "../ucp-schema/target/debug/ucp-schema" ] && "../ucp-schema/target/debug/ucp-schema" generate-types --help &> /dev/null; then - UCP_SCHEMA_BIN="../ucp-schema/target/debug/ucp-schema" -elif [ -f "../ucp-schema/Cargo.toml" ] && command -v cargo &> /dev/null; then - echo "Building ucp-schema from ../ucp-schema..." - cargo build --release --manifest-path "../ucp-schema/Cargo.toml" - UCP_SCHEMA_BIN="../ucp-schema/target/release/ucp-schema" - if ! "$UCP_SCHEMA_BIN" generate-types --help &> /dev/null; then - echo "Error: ../ucp-schema checkout does not support 'generate-types'." - exit 1 - fi -else - echo "Error: ucp-schema binary (with generate-types) not found. Set UCP_SCHEMA_BIN, install ucp-schema on PATH, or build ../ucp-schema." - exit 1 -fi - -TMP_CLONE_DIR="" -SCOPED_SCHEMA_DIR="" -TMP_TYPES_JSON="$(mktemp "${TMPDIR:-/tmp}/ucp-types.XXXXXX.json")" -cleanup() { - rm -f "$TMP_TYPES_JSON" - if [ -n "$SCOPED_SCHEMA_DIR" ] && [ -d "$SCOPED_SCHEMA_DIR" ]; then - rm -rf "$SCOPED_SCHEMA_DIR" - fi - if [ -n "$TMP_CLONE_DIR" ] && [ -d "$TMP_CLONE_DIR" ]; then - rm -rf "$TMP_CLONE_DIR" - fi -} -trap cleanup EXIT - -INPUT_ARG="${1:-}" -if [ -n "$INPUT_ARG" ] && [ -d "$INPUT_ARG" ]; then - INPUT_DIR="$INPUT_ARG" - echo "Using local UCP directory: $INPUT_DIR" -elif [[ "$INPUT_ARG" == /* || "$INPUT_ARG" == ./* || "$INPUT_ARG" == ../* ]]; then - echo "Error: Local UCP directory not found at '$INPUT_ARG'." - exit 1 -elif [ -z "$INPUT_ARG" ]; then - TMP_CLONE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/ucp-clone.XXXXXX")" - echo "No version specified, cloning main branch..." - git clone -b main --depth 1 https://github.com/Universal-Commerce-Protocol/ucp "$TMP_CLONE_DIR" - INPUT_DIR="$TMP_CLONE_DIR" -elif [[ "$INPUT_ARG" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then - TMP_CLONE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/ucp-clone.XXXXXX")" - BRANCH="release/$INPUT_ARG" - echo "Cloning version $INPUT_ARG (branch: $BRANCH)..." - git clone -b "$BRANCH" --depth 1 https://github.com/Universal-Commerce-Protocol/ucp "$TMP_CLONE_DIR" - INPUT_DIR="$TMP_CLONE_DIR" -elif [[ "$INPUT_ARG" =~ ^[0-9a-fA-F]{7,40}$ ]]; then - TMP_CLONE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/ucp-clone.XXXXXX")" - echo "Cloning UCP repository at commit $INPUT_ARG..." - git clone https://github.com/Universal-Commerce-Protocol/ucp "$TMP_CLONE_DIR" - git -C "$TMP_CLONE_DIR" checkout "$INPUT_ARG" - INPUT_DIR="$TMP_CLONE_DIR" -else - TMP_CLONE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/ucp-clone.XXXXXX")" - echo "Cloning branch/ref $INPUT_ARG..." - git clone -b "$INPUT_ARG" --depth 1 https://github.com/Universal-Commerce-Protocol/ucp "$TMP_CLONE_DIR" - INPUT_DIR="$TMP_CLONE_DIR" -fi - -if [ -d "$INPUT_DIR/source/schemas" ]; then - SCHEMA_DIR="$INPUT_DIR/source/schemas" -elif [ -d "$INPUT_DIR/spec/schemas" ]; then - SCHEMA_DIR="$INPUT_DIR/spec/schemas" -elif [ -d "$INPUT_DIR/schemas" ]; then - SCHEMA_DIR="$INPUT_DIR/schemas" -elif [ -f "$INPUT_DIR/ucp.json" ]; then - SCHEMA_DIR="$INPUT_DIR" -else - echo "Error: Could not locate schema directory under '$INPUT_DIR'." - exit 1 -fi - -OUTPUT_DIR="src/ucp_sdk/models/schemas" - -# Scope compilation to Shopping + Common + Transports so other verticals do not bleed in. -SCOPED_SCHEMA_DIR="$(mktemp -d "${TMPDIR:-/tmp}/ucp-schemas.XXXXXX")" -if compgen -G "$SCHEMA_DIR/*.json" > /dev/null; then - cp "$SCHEMA_DIR"/*.json "$SCOPED_SCHEMA_DIR"/ -fi -for dir in common transports shopping; do - if [ -d "$SCHEMA_DIR/$dir" ]; then - cp -R "$SCHEMA_DIR/$dir" "$SCOPED_SCHEMA_DIR/$dir" - fi -done - -echo "Compiling type bundle with ucp-schema generate-types..." -"$UCP_SCHEMA_BIN" generate-types --schema-dir "$SCOPED_SCHEMA_DIR" --output "$TMP_TYPES_JSON" - -echo "Generating Pydantic models from compiled type bundle..." -mkdir -p "$OUTPUT_DIR" && rm -f "$OUTPUT_DIR/_generated.py" - -uv run \ - --link-mode=copy \ - --extra-index-url https://pypi.org/simple python \ - -m datamodel_code_generator \ - --input "$TMP_TYPES_JSON" \ - --input-file-type jsonschema \ - --output "$OUTPUT_DIR/_generated.py" \ - --output-model-type pydantic_v2.BaseModel \ - --use-schema-description \ - --field-constraints \ - --use-field-description \ - --enum-field-as-literal all \ - --disable-timestamp \ - --use-double-quotes \ - --extra-fields=allow \ - --use-type-alias \ - --use-standard-collections \ - --reuse-model \ - --use-title-as-name \ - --additional-imports pydantic.ConfigDict - -echo "Generating lazy package index in $OUTPUT_DIR/__init__.py..." -python3 - <<'PY' -import ast -from pathlib import Path - -_SYNTHETIC_WRAPPERS = {"UCPSchemaTypes", "UcpSchemaTypes"} -schemas_dir = Path("src/ucp_sdk/models/schemas") -tree = ast.parse((schemas_dir / "_generated.py").read_text(encoding="utf-8")) -type_alias_cls = getattr(ast, "TypeAlias", ()) -names: set[str] = set() -for node in tree.body: - if isinstance(node, ast.ClassDef): - names.add(node.name) - elif isinstance(node, ast.Assign): - names.update(t.id for t in node.targets if isinstance(t, ast.Name)) - elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): - names.add(node.target.id) - elif isinstance(node, type_alias_cls) and isinstance(getattr(node, "name", None), ast.Name): - names.add(node.name.id) -exports = sorted(n for n in names if not n.startswith("_") and n not in _SYNTHETIC_WRAPPERS) -imports = ", ".join(exports) -all_items = ", ".join(f'"{n}"' for n in exports) -(schemas_dir / "__init__.py").write_text( - '# Copyright 2026 UCP Authors\n' - '#\n' - '# Licensed under the Apache License, Version 2.0 (the "License");\n' - '# you may not use this file except in compliance with the License.\n' - '# You may obtain a copy of the License at\n' - '#\n' - '# http://www.apache.org/licenses/LICENSE-2.0\n' - '#\n' - '# Unless required by applicable law or agreed to in writing, software\n' - '# distributed under the License is distributed on an "AS IS" BASIS,\n' - '# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' - '# See the License for the specific language governing permissions and\n' - '# limitations under the License.\n\n' - '# generated by generate_models.sh\n\n' - '"""Generated UCP schema models."""\n\n' - 'from __future__ import annotations\n\n' - 'import importlib\n' - 'from typing import TYPE_CHECKING, Any\n\n' - f'if TYPE_CHECKING:\n from ._generated import ({imports},)\n\n' - f'__all__ = [{all_items},]\n\n\n' - 'def __getattr__(name: str) -> Any:\n' - ' """Import public schema models and type aliases on first access."""\n' - ' if name not in __all__:\n' - ' msg = f"module {__name__!r} has no attribute {name!r}"\n' - ' raise AttributeError(msg)\n' - ' module = importlib.import_module("._generated", __name__)\n' - ' value = getattr(module, name)\n' - ' globals()[name] = value\n' - ' return value\n\n\n' - 'def __dir__() -> list[str]:\n' - ' """Return module attributes including lazily re-exported schema names."""\n' - ' return sorted({*globals(), *__all__})\n', - encoding="utf-8", -) -PY - -echo "Formatting generated models..." -uv run ruff check --fix src/ucp_sdk/models -uv run ruff format src/ucp_sdk/models - -# Normalize file endings (as pre-commit's end-of-file-fixer does) -python3 - <<'PY' -from pathlib import Path - -for path in Path("src/ucp_sdk/models").rglob("*.py"): - text = path.read_text(encoding="utf-8") - fixed = text.rstrip("\n") + "\n" if text.strip() else "" - if fixed != text: - path.write_text(fixed, encoding="utf-8") -PY - -echo "Done. Models generated in $OUTPUT_DIR/_generated.py" +exec uv run --link-mode=copy python scripts/generate_models.py "$@" diff --git a/pyproject.toml b/pyproject.toml index 49ab086..449e250 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ucp-sdk" -version = "0.6.0" +version = "0.0.0.dev0" description = "UCP Python SDK" readme = "README.md" license = {file = "LICENSE"} diff --git a/scripts/generate_models.py b/scripts/generate_models.py new file mode 100644 index 0000000..5395308 --- /dev/null +++ b/scripts/generate_models.py @@ -0,0 +1,283 @@ +# Copyright 2026 UCP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Generate Pydantic v2 models from UCP JSON Schemas.""" + +from __future__ import annotations + +import argparse +import ast +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +from typing import NoReturn + +_REPO_ROOT = Path(__file__).resolve().parents[1] +_UCP_URL = "https://github.com/Universal-Commerce-Protocol/ucp.git" +_WRAPPERS = {"UCPSchemaTypes", "UcpSchemaTypes"} +_SEMVER_RE = re.compile(r"[0-9]+\.[0-9]+\.[0-9]+") +_CODEGEN_FLAGS = ( + "--input-file-type=jsonschema", + "--output-model-type=pydantic_v2.BaseModel", + "--use-schema-description", + "--field-constraints", + "--use-field-description", + "--enum-field-as-literal=all", + "--disable-timestamp", + "--use-double-quotes", + "--extra-fields=allow", + "--use-type-alias", + "--use-standard-collections", + "--reuse-model", + "--use-title-as-name", + "--additional-imports=pydantic.ConfigDict", +) + + +def _die(msg: str) -> NoReturn: + sys.stderr.write(f"Error: {msg}\n") + raise SystemExit(1) + + +def _run(*cmd: str | Path, capture: bool = False) -> str: + args = [str(c) for c in cmd] + res = subprocess.run(args, check=True, text=True, capture_output=capture) + return res.stdout.strip() if capture else "" + + +def _git_head(repo: Path) -> str: + return _run( + "git", "-C", repo, "rev-parse", "--verify", "HEAD", capture=True + ).lower() + + +def _resolve_ucp_schema() -> tuple[str, str]: + env_bin = os.environ.get("UCP_SCHEMA_BIN") + if env_bin: + if not (Path(env_bin).is_file() and os.access(env_bin, os.X_OK)): + _die(f"UCP_SCHEMA_BIN={env_bin!r} is missing or not executable.") + bin_path = env_bin + else: + path_env = f"{Path.home() / '.local/bin'}:{os.environ.get('PATH', '')}" + bin_path = shutil.which("ucp-schema", path=path_env) or "" + if not bin_path: + _die("ucp-schema binary not found (set UCP_SCHEMA_BIN or PATH).") + if subprocess.run( + [bin_path, "generate-types", "--help"], capture_output=True + ).returncode: + _die(f"'{bin_path}' lacks 'generate-types'.") + ver = _run(bin_path, "--version", capture=True).split()[-1] + if not _SEMVER_RE.fullmatch(ver): + _die(f"Invalid semver from '{bin_path} --version': {ver!r}.") + env_ver = os.environ.get("UCP_SCHEMA_VERSION") + if ( + env_ver + and os.environ.get("UCP_SKIP_VERSION_CHECK") != "1" + and ver != env_ver + ): + _die(f"ucp-schema {ver} != UCP_SCHEMA_VERSION={env_ver}.") + return bin_path, ver + + +def _write_lazy_index(schemas_dir: Path) -> None: + header = "\n".join(Path(__file__).read_text("utf-8").splitlines()[:13]) + tree = ast.parse((schemas_dir / "_generated.py").read_text("utf-8")) + alias_cls = getattr(ast, "TypeAlias", ()) + names: set[str] = set() + for node in tree.body: + if isinstance(node, ast.ClassDef): + names.add(node.name) + elif isinstance(node, ast.Assign): + names.update(t.id for t in node.targets if isinstance(t, ast.Name)) + elif isinstance(node, ast.AnnAssign) and isinstance( + node.target, ast.Name + ): + names.add(node.target.id) + elif isinstance(node, alias_cls) and isinstance( + getattr(node, "name", None), ast.Name + ): + names.add(node.name.id) + exports = sorted( + n for n in names if not n.startswith("_") and n not in _WRAPPERS + ) + imports = ", ".join(exports) + items = ", ".join(f'"{n}"' for n in exports) + (schemas_dir / "__init__.py").write_text( + f"{header}\n\n# generated by generate_models.sh\n\n" + '"""Generated UCP schema models."""\n\n' + "from __future__ import annotations\n\nimport importlib\n" + "from typing import TYPE_CHECKING, Any\n\n" + f"if TYPE_CHECKING:\n from ._generated import ({imports},)\n\n" + f"__all__ = [{items},]\n\n\n" + "def __getattr__(name: str) -> Any:\n" + ' """Import public schema models and type aliases on ' + 'first access."""\n' + " if name not in __all__:\n" + ' msg = f"module {__name__!r} has no attribute {name!r}"\n' + " raise AttributeError(msg)\n" + ' module = importlib.import_module("._generated", __name__)\n' + " value = getattr(module, name)\n" + " globals()[name] = value\n return value\n\n\n" + "def __dir__() -> list[str]:\n" + ' """Return module attributes including lazily re-exported ' + 'schema names."""\n' + " return sorted({*globals(), *__all__})\n", + encoding="utf-8", + ) + + +def main(argv: list[str] | None = None) -> None: + """Parse CLI flags, synthesize UCP IR bundle, and emit Pydantic DTOs.""" + os.chdir(_REPO_ROOT) + p = argparse.ArgumentParser(prog="./generate_models.sh") + p.add_argument("--from-lock", action="store_true") + p.add_argument("--ref", metavar="") + p.add_argument("--channel", choices=("draft", "release")) + p.add_argument("--spec-dir", type=Path, metavar="") + p.add_argument("--write-lock", action="store_true") + args = p.parse_args(argv) + + from_lock = args.from_lock or (args.ref is None and args.spec_dir is None) + if args.from_lock and args.ref is not None: + p.error("--from-lock cannot be combined with --ref.") + if from_lock and (args.channel is not None or args.write_lock): + p.error( + "--from-lock cannot be combined with --channel or --write-lock." + ) + if args.ref is None and (args.channel is not None or args.write_lock): + p.error("--channel and --write-lock require --ref.") + if args.ref is not None and not args.ref.strip(): + p.error("--ref must be non-empty.") + if args.spec_dir is not None and not args.spec_dir.is_dir(): + _die(f"--spec-dir '{args.spec_dir}' does not exist.") + + bin_path, bin_ver = _resolve_ucp_schema() + url = os.environ.get("UCP_REMOTE_URL", _UCP_URL) + lock_path = Path("ucp-lock.json") + vertical = "shopping" + + with tempfile.TemporaryDirectory(prefix="ucp-codegen-") as tmp_str: + tmp = Path(tmp_str) + if from_lock: + if not lock_path.is_file(): + _die("ucp-lock.json not found.") + try: + lock = json.loads(lock_path.read_text("utf-8")) + except json.JSONDecodeError as exc: + _die(f"Invalid ucp-lock.json: {exc}") + if not isinstance(lock, dict): + _die("Invalid ucp-lock.json: expected JSON object.") + chan, ref = lock.get("channel"), lock.get("ucp_ref") + sha, ver = lock.get("ucp_sha"), lock.get("ucp_schema_version") + vertical = str(lock.get("vertical") or "shopping") + ref_re = ( + r"main" if chan == "draft" else r"release/\d{4}-\d{2}-\d{2}" + ) + valid = ( + chan in ("draft", "release") + and isinstance(ref, str) + and bool(re.fullmatch(ref_re, ref)) + and isinstance(sha, str) + and bool(re.fullmatch(r"[0-9a-f]{40}", sha)) + and isinstance(ver, str) + and bool(_SEMVER_RE.fullmatch(ver)) + and bool(re.fullmatch(r"[a-z0-9_-]+", vertical)) + ) + if not valid: + _die("Invalid ucp-lock.json fields.") + if ( + os.environ.get("UCP_SKIP_VERSION_CHECK") != "1" + and bin_ver != ver + ): + _die(f"ucp-schema {bin_ver} != ucp-lock.json {ver}.") + spec = args.spec_dir or (tmp / "ucp-spec") + if args.spec_dir is not None: + if _git_head(spec) != sha: + _die(f"--spec-dir HEAD != {sha}.") + else: + _run( + "git", + "clone", + "--filter=blob:none", + "--no-checkout", + url, + spec, + ) + _run("git", "-C", spec, "checkout", "--detach", sha) + elif args.ref is not None: + spec = args.spec_dir or (tmp / "ucp-spec") + if args.spec_dir is None: + _run("git", "clone", "-b", args.ref, "--depth=1", url, spec) + sha = _git_head(spec) + else: + spec = args.spec_dir + + sub_dirs = ("source/schemas", "spec/schemas", "schemas") + schema_dir = next( + (spec / s for s in sub_dirs if (spec / s).is_dir()), + spec if (spec / "ucp.json").is_file() else None, + ) + if schema_dir is None: + _die(f"Could not locate schema directory under '{spec}'.") + + scoped = tmp / "scoped-schemas" + scoped.mkdir() + for jf in schema_dir.glob("*.json"): + shutil.copy2(jf, scoped / jf.name) + for sub in ("common", "transports", vertical): + if (schema_dir / sub).is_dir(): + shutil.copytree(schema_dir / sub, scoped / sub) + + types = tmp / "ucp-types.json" + _run(bin_path, "generate-types", "--schema-dir", scoped, "-o", types) + + out_dir = Path("src/ucp_sdk/models/schemas") + out_dir.mkdir(parents=True, exist_ok=True) + (out_dir / "_generated.py").unlink(missing_ok=True) + _run( + sys.executable, + "-m", + "datamodel_code_generator", + "--input", + types, + "--output", + out_dir / "_generated.py", + *_CODEGEN_FLAGS, + ) + _write_lazy_index(out_dir) + models_dir = Path("src/ucp_sdk/models") + _run(sys.executable, "-m", "ruff", "check", "--fix", models_dir) + _run(sys.executable, "-m", "ruff", "format", models_dir) + + if args.write_lock: + chan = args.channel or ( + "release" if args.ref.startswith("release/") else "draft" + ) + data = { + "channel": chan, + "ucp_ref": args.ref, + "ucp_sha": sha, + "ucp_schema_version": bin_ver, + "vertical": vertical, + } + lock_path.write_text(json.dumps(data, indent=2) + "\n", "utf-8") + + +if __name__ == "__main__": + main() diff --git a/src/ucp_sdk/__init__.py b/src/ucp_sdk/__init__.py index dea1684..01a3ff7 100644 --- a/src/ucp_sdk/__init__.py +++ b/src/ucp_sdk/__init__.py @@ -14,4 +14,9 @@ """UCP Python SDK.""" -__version__ = "0.6.0" +from importlib.metadata import PackageNotFoundError, version + +try: + __version__: str = version("ucp-sdk") +except PackageNotFoundError: + __version__ = "0.0.0.dev0" diff --git a/src/ucp_sdk/models/schemas/__init__.py b/src/ucp_sdk/models/schemas/__init__.py index 2d8ca11..005d3ef 100644 --- a/src/ucp_sdk/models/schemas/__init__.py +++ b/src/ucp_sdk/models/schemas/__init__.py @@ -41,6 +41,8 @@ Amenity, AmenityType, Amount, + Amount1, + Amount2, Ap2, Ap2WithCheckoutMandate, Ap2WithCheckoutMandateCompleteRequest, @@ -80,6 +82,8 @@ Checkout, CheckoutCompleteRequest, CheckoutCreateRequest, + CheckoutCreateRequestCartId, + CheckoutCreateRequestLineItems, CheckoutMandate, CheckoutUpdateRequest, Consent, @@ -92,6 +96,7 @@ ContextPayment, Conversation, DailyHour, + DateInterval, Description, DetailOptionValue, DetailProduct, @@ -99,6 +104,7 @@ DiscountsObject, DiscountsObjectCreateRequest, DiscountsObjectUpdateRequest, + Duration, EarningBreakdown, EarningForecast, EmbeddedConfig, @@ -113,6 +119,7 @@ ExpectationLineItem, Extends, Extension, + Fee, Fulfillment, FulfillmentAvailableMethod, FulfillmentBusinessSchema, @@ -260,6 +267,8 @@ PickupMethodUpdateRequest, PlatformFulfillmentConfig, Policy, + PolicyReturnPoliciesItem, + PolicyReturnPoliciesItemBase, PostalAddress, Price, PriceFilter, @@ -272,16 +281,33 @@ ProfilePlatformSchema, Provider, ProviderBase, + PurchaseOption, + PurchaseOptionsDetailProduct, + PurchaseOptionsDetailProductOption, + PurchaseOptionsLookupProduct, + PurchaseOptionsLookupVariant, + PurchaseOptionsLookupVariantBarcode, + PurchaseOptionsLookupVariantSeller, + PurchaseOptionsPoliciesItem, + PurchaseOptionsPoliciesItemBase, + PurchaseOptionsProduct, + PurchaseOptionsVariant, + PurchaseOptionsVariantBarcode, + PurchaseOptionsVariantSeller, QuantityUnit, Rating, RequestConstraints, Requires, ResponseAskSchema, + ResponseBookingSchema, ResponseCartSchema, ResponseCatalogSchema, ResponseCheckoutSchema, ResponseLocationSchema, ResponseOrderSchema, + ReturnBody, + ReturnEligibility, + ReturnPolicy, ReverseDomainName, RewardAmount, RewardCurrency, @@ -314,6 +340,8 @@ ShippingMethodUpdateRequest, Signals, SignedAmount, + SubscriptionPolicy, + SubscriptionSchedule, Success, TimeInterval, TokenCredential, @@ -336,6 +364,7 @@ ValueConstraintEnum, Variant, VariantBarcode, + VariantPurchaseOptions, VariantSeller, Version, VersionConstraint, @@ -361,6 +390,8 @@ "Amenity", "AmenityType", "Amount", + "Amount1", + "Amount2", "Ap2", "Ap2WithCheckoutMandate", "Ap2WithCheckoutMandateCompleteRequest", @@ -400,6 +431,8 @@ "Checkout", "CheckoutCompleteRequest", "CheckoutCreateRequest", + "CheckoutCreateRequestCartId", + "CheckoutCreateRequestLineItems", "CheckoutMandate", "CheckoutUpdateRequest", "Consent", @@ -412,6 +445,7 @@ "ContextPayment", "Conversation", "DailyHour", + "DateInterval", "Description", "DetailOptionValue", "DetailProduct", @@ -419,6 +453,7 @@ "DiscountsObject", "DiscountsObjectCreateRequest", "DiscountsObjectUpdateRequest", + "Duration", "EarningBreakdown", "EarningForecast", "EmbeddedConfig", @@ -433,6 +468,7 @@ "ExpectationLineItem", "Extends", "Extension", + "Fee", "Fulfillment", "FulfillmentAvailableMethod", "FulfillmentBusinessSchema", @@ -580,6 +616,8 @@ "PickupMethodUpdateRequest", "PlatformFulfillmentConfig", "Policy", + "PolicyReturnPoliciesItem", + "PolicyReturnPoliciesItemBase", "PostalAddress", "Price", "PriceFilter", @@ -592,16 +630,33 @@ "ProfilePlatformSchema", "Provider", "ProviderBase", + "PurchaseOption", + "PurchaseOptionsDetailProduct", + "PurchaseOptionsDetailProductOption", + "PurchaseOptionsLookupProduct", + "PurchaseOptionsLookupVariant", + "PurchaseOptionsLookupVariantBarcode", + "PurchaseOptionsLookupVariantSeller", + "PurchaseOptionsPoliciesItem", + "PurchaseOptionsPoliciesItemBase", + "PurchaseOptionsProduct", + "PurchaseOptionsVariant", + "PurchaseOptionsVariantBarcode", + "PurchaseOptionsVariantSeller", "QuantityUnit", "Rating", "RequestConstraints", "Requires", "ResponseAskSchema", + "ResponseBookingSchema", "ResponseCartSchema", "ResponseCatalogSchema", "ResponseCheckoutSchema", "ResponseLocationSchema", "ResponseOrderSchema", + "ReturnBody", + "ReturnEligibility", + "ReturnPolicy", "ReverseDomainName", "RewardAmount", "RewardCurrency", @@ -634,6 +689,8 @@ "ShippingMethodUpdateRequest", "Signals", "SignedAmount", + "SubscriptionPolicy", + "SubscriptionSchedule", "Success", "TimeInterval", "TokenCredential", @@ -656,6 +713,7 @@ "ValueConstraintEnum", "Variant", "VariantBarcode", + "VariantPurchaseOptions", "VariantSeller", "Version", "VersionConstraint", diff --git a/src/ucp_sdk/models/schemas/_generated.py b/src/ucp_sdk/models/schemas/_generated.py index a8ef3d7..aa60962 100644 --- a/src/ucp_sdk/models/schemas/_generated.py +++ b/src/ucp_sdk/models/schemas/_generated.py @@ -20,7 +20,7 @@ from __future__ import annotations -from datetime import date +from datetime import date, timedelta from typing import Annotated, Any, Literal from pydantic import AnyUrl, AwareDatetime, BaseModel, ConfigDict, Field @@ -362,6 +362,24 @@ class DailyHour(BaseModel): """ +class DateInterval(BaseModel): + """ + Represents a closed date range defined by start and end dates. + """ + + model_config = ConfigDict( + extra="allow", + ) + start_date: date + """ + Start date of the interval in ISO 8601 format. + """ + end_date: date + """ + End date of the interval in ISO 8601 format. MUST be on or after `start_date`. + """ + + class Description(BaseModel): """ Description content in one or more formats. At least one format must be provided. @@ -446,6 +464,14 @@ class DiscountsObjectUpdateRequest(BaseModel): """ +Duration = TypeAliasType( + "Duration", Annotated[timedelta, Field(..., title="Duration")] +) +""" +A length of time as an ISO 8601 duration (RFC 3339 Appendix A grammar) with whole-number components greater than zero: weeks alone, or years, months, and days in that order, optionally followed by `T` and hours, minutes, and seconds in that order, each at most once (e.g., `P30D` is 30 days, `PT30M` is 30 minutes, `P1M` is one month; `T` separates date units from time units, so `M` before it means months and after it minutes). It states a length, not an instant; resolving it to a calendar time is up to the schema that uses it. +""" + + class EmbeddedConfig(BaseModel): """ Per-session configuration for embedded transport binding. Allows businesses to vary EP availability and delegations based on cart contents, agent authorization, or policy. @@ -479,6 +505,7 @@ class EmbeddedConfig(BaseModel): "eligibility_invalid", "identity_required", "insufficient_scope", + "purchase_option_unavailable", ], title="ErrorCode", ), @@ -552,6 +579,24 @@ class Extension(BaseModel): """ +Amount1 = TypeAliasType( + "Amount1", + Annotated[int, Field(..., ge=0, le=9007199254740991, title="Amount")], +) +""" +Estimated maximum flat charge, in ISO 4217 minor units of the currency the covered items are priced in, charged per the unit of the fee `type`. `0` states that nothing is charged. Mutually exclusive with `basis_points`. +""" + + +Amount2 = TypeAliasType( + "Amount2", + Annotated[int, Field(..., ge=1, le=9007199254740991, title="Amount")], +) +""" +Cap on a `basis_points` charge: the charge is at most this amount, in ISO 4217 minor units of the currency the covered items are priced in, per the unit of the fee `type`. Requires `basis_points`. +""" + + class FulfillmentAvailableMethod(BaseModel): """ Inventory availability hint for a fulfillment method type. @@ -1932,6 +1977,44 @@ class PlatformFulfillmentConfig(BaseModel): """ +class PolicyReturnPoliciesItemBase(BaseModel): + """ + A `policies[]` entry; validates against `return_policy` when `type` is `dev.ucp.shopping.policy.return`. + """ + + model_config = ConfigDict( + extra="allow", + ) + type: str = Field( + ..., + examples=[ + "dev.ucp.shopping.checkout", + "dev.ucp.common.identity_linking", + "com.example.loyalty_gold", + "com.example-shop.checkout", + "com.2example.cart", + "uk.co.example-shop.checkout", + "xn--p1ai.example.checkout", + ], + pattern="^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9_-]*[a-z0-9_])?)+$", + ) + """ + Policy type discriminator. Open reverse-DNS vocabulary. See specification documentation for the registry of well-known policy types. Businesses MAY define custom types in their own domain (e.g., `com.example.policy.price_match`). Platforms MUST tolerate unknown values. + """ + description: Description + """ + Human-readable policy summary in one or more formats (plain, markdown, html). Required on every policy so a platform can present it without understanding any type-specific fields. This is not the buyer-facing disclosure — display is compelled by a `messages[]` warning (see the Policies section). + """ + applies_to: list[str] | None = None + """ + RFC 9535 JSONPath expressions identifying the nodes this policy applies to, relative to the embedding response root (e.g., `$.line_items[0]` in cart/checkout, `$.products[2]` in catalog). Each target covers the node it names and everything nested under it, so a target on a product also covers its variants. A singular query (RFC 9535 Section 2.3.5.1; name and index selectors only) names a single node; filters, wildcards, and slices match a set. When omitted, the policy applies to the entire response. When policies of the same `type` contest a node, the narrowest target wins and overrides the rest. See the Policies section for how specificity resolves. + """ + url: AnyUrl | None = None + """ + Optional link to the full policy document. + """ + + class PostalAddress(BaseModel): model_config = ConfigDict( extra="allow", @@ -2060,6 +2143,68 @@ class ProviderBase(BaseModel): """ +class PurchaseOptionsDetailProductOption(DetailProductOption): + pass + + +class PurchaseOptionsLookupVariantBarcode(FulfillmentLookupVariantBarcode): + pass + + +class PurchaseOptionsLookupVariantSeller(LookupVariantSeller): + """ + Optional seller context for this variant. + """ + + +class PurchaseOptionsPoliciesItemBase(BaseModel): + """ + A `policies[]` entry; validates against `subscription_policy` when `type` is `dev.ucp.shopping.policy.subscription`. + """ + + model_config = ConfigDict( + extra="allow", + ) + type: str = Field( + ..., + examples=[ + "dev.ucp.shopping.checkout", + "dev.ucp.common.identity_linking", + "com.example.loyalty_gold", + "com.example-shop.checkout", + "com.2example.cart", + "uk.co.example-shop.checkout", + "xn--p1ai.example.checkout", + ], + pattern="^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9_-]*[a-z0-9_])?)+$", + ) + """ + Policy type discriminator. Open reverse-DNS vocabulary. See specification documentation for the registry of well-known policy types. Businesses MAY define custom types in their own domain (e.g., `com.example.policy.price_match`). Platforms MUST tolerate unknown values. + """ + description: Description + """ + Human-readable policy summary in one or more formats (plain, markdown, html). Required on every policy so a platform can present it without understanding any type-specific fields. This is not the buyer-facing disclosure — display is compelled by a `messages[]` warning (see the Policies section). + """ + applies_to: list[str] | None = None + """ + RFC 9535 JSONPath expressions identifying the nodes this policy applies to, relative to the embedding response root (e.g., `$.line_items[0]` in cart/checkout, `$.products[2]` in catalog). Each target covers the node it names and everything nested under it, so a target on a product also covers its variants. A singular query (RFC 9535 Section 2.3.5.1; name and index selectors only) names a single node; filters, wildcards, and slices match a set. When omitted, the policy applies to the entire response. When policies of the same `type` contest a node, the narrowest target wins and overrides the rest. See the Policies section for how specificity resolves. + """ + url: AnyUrl | None = None + """ + Optional link to the full policy document. + """ + + +class PurchaseOptionsVariantBarcode(FulfillmentLookupVariantBarcode): + pass + + +class PurchaseOptionsVariantSeller(LookupVariantSeller): + """ + Optional seller context for this variant. + """ + + class QuantityUnit(BaseModel): """ Sale-basis descriptor for quantities: the shared unit descriptor plus the Business's ordering policy. Its unit-descriptor machine identity remains (`unit`, effective `scale`); `display_text` and `increment` are excluded from identity and mismatch comparison. @@ -2112,6 +2257,32 @@ class Rating(BaseModel): """ +class ReturnEligibility(BaseModel): + """ + An open return eligibility statement. `window` states a guaranteed minimum period after an anchor event and, once resolved, the instant it ends; expiration does not signal non-returnability. `unlimited` states no time restriction, not unconditional eligibility. `not_accepted` states that the business's return policy does not accept returns of the covered items; it does not describe remedies under applicable law or third-party guarantees. Unknown types establish no eligibility inference; consumers may use the base policy's `description`. + """ + + model_config = ConfigDict( + extra="allow", + ) + type: str + """ + Eligibility kind. Well-known values: `window`, `unlimited`, `not_accepted`. Unknown values establish no eligibility inference. + """ + duration: Duration | None = None + """ + Length of the return window after the `anchor` event. It states the term for presentation; the Business resolves the deadline as `expires_at`. + """ + anchor: str | None = None + """ + Event the window is measured from. Well-known values: `purchased`, `fulfilled`, `delivered`. + """ + expires_at: AwareDatetime | None = None + """ + RFC 3339 instant at which the window ends, resolved by the Business once the `anchor` event has occurred (e.g., on an order after delivery). When covered quantities reach the anchor at different times, it states the earliest of their deadlines. An otherwise eligible return requested no later than this instant is accepted. + """ + + ReverseDomainName = TypeAliasType( "ReverseDomainName", Annotated[ @@ -2527,6 +2698,32 @@ class Signals(BaseModel): """ +class SubscriptionPolicy(BaseModel): + """ + A policy of type `dev.ucp.shopping.policy.subscription`: the terms of the recurring orders a line results in — until when, how the buyer cancels, and where they manage it. Targets the line items it governs. Adds no fields to the base policy. + """ + + model_config = ConfigDict( + extra="allow", + ) + type: Literal["dev.ucp.shopping.policy.subscription"] + """ + Policy discriminator for subscription terms. + """ + description: Description + """ + Human-readable policy summary in one or more formats (plain, markdown, html). Required on every policy so a platform can present it without understanding any type-specific fields. This is not the buyer-facing disclosure — display is compelled by a `messages[]` warning (see the Policies section). + """ + applies_to: list[str] | None = None + """ + RFC 9535 JSONPath expressions identifying the nodes this policy applies to, relative to the embedding response root (e.g., `$.line_items[0]` in cart/checkout, `$.products[2]` in catalog). Each target covers the node it names and everything nested under it, so a target on a product also covers its variants. A singular query (RFC 9535 Section 2.3.5.1; name and index selectors only) names a single node; filters, wildcards, and slices match a set. When omitted, the policy applies to the entire response. When policies of the same `type` contest a node, the narrowest target wins and overrides the rest. See the Policies section for how specificity resolves. + """ + url: AnyUrl | None = None + """ + Optional link to the full policy document. + """ + + class TimeInterval(BaseModel): """ Reusable opening and closing time fields for a containing schedule schema. Containing schemas determine whether the `opens` and `closes` pair is required; this fragment's standalone `{}` is not an interval. @@ -2826,6 +3023,8 @@ class VersionConstraint(BaseModel): "prop65", "fulfillment_changed", "payment_term_changed", + "purchase_option_changed", + "totals_changed", "age_restricted", ], title="WarningCode", @@ -3642,6 +3841,44 @@ class Expectation(BaseModel): """ +class Fee(BaseModel): + """ + A charge on a return, typed by what it is for, as an estimated maximum. `amount` states a flat charge, where `0` means nothing is charged; `basis_points` states a percentage, optionally capped by `max_amount`; with neither, the fee is charged at its actual cost and no maximum is stated. + """ + + model_config = ConfigDict( + extra="allow", + ) + type: ReverseDomainName | None = None + """ + Fee kind, as a reverse-domain name. Well-known values: `dev.ucp.shopping.fee.restocking` (a deduction from the refund, charged per one whole `quantity_unit.unit` returned, for example per lb, or per `each` when `quantity_unit` is absent), `dev.ucp.shopping.fee.return_shipping` (the cost of shipping the return, charged per return shipment), `dev.ucp.shopping.fee.handling` (charged per return request). Vendor kinds use the vendor's own namespace (e.g., `com.example.fee.eco`) and are charged per return request. A vendor fee charged on another basis, such as per item, omits `amount` and states its terms in `display_text`. A fee with an unknown `type` MUST carry `display_text`. Omitted only on an entry with `amount: 0`, which states that the business charges no fee of any kind in its scope, including vendor kinds and kinds defined later. + """ + methods: list[str] | None = Field(None, min_length=1) + """ + Return channels this fee applies to; omitted means every channel. A channel need not be listed in the policy's `methods`. When more than one entry applies to a fee on a channel, an entry that lists the channel takes precedence over one that does not; among entries that both list the channel or both do not, an entry with a `type` takes precedence over one without. + """ + amount: Amount1 | None = Field( + None, ge=0, le=9007199254740991, title="Amount" + ) + """ + Estimated maximum flat charge, in ISO 4217 minor units of the currency the covered items are priced in, charged per the unit of the fee `type`. `0` states that nothing is charged. Mutually exclusive with `basis_points`. + """ + basis_points: int | None = Field(None, ge=1, le=10000) + """ + Estimated maximum charge in basis points (hundredths of a percent; `1250` = 12.5%) of the amount paid for the returned quantity, after item-level discounts and excluding tax, shipping, and other fees. On catalog surfaces, where no amount has been paid, it applies to the covered product's price. Mutually exclusive with `amount`. + """ + max_amount: Amount2 | None = Field( + None, ge=1, le=9007199254740991, title="Amount" + ) + """ + Cap on a `basis_points` charge: the charge is at most this amount, in ISO 4217 minor units of the currency the covered items are priced in, per the unit of the fee `type`. Requires `basis_points`. + """ + display_text: str | None = None + """ + Human-readable fee label, naming any condition under which the fee applies (e.g., '15% restocking fee on opened items'). Required when `type` is not a well-known fee kind, and when the fee has neither `amount` nor `basis_points`. + """ + + class FulfillmentBusinessSchema(BaseModel): """ Business-level fulfillment capability configuration @@ -3875,6 +4112,10 @@ class Item(BaseModel): """ Unit price in ISO 4217 minor units. Price is the amount per one whole `quantity_unit.unit` (for example, per lb or per hour); when `quantity_unit` is absent, it is per `each`. """ + list_price: Amount | None = None + """ + Reference price for comparison display, typically shown as a strikethrough next to `price`, and denominated like `price`. It is not charged and is never part of `totals`; the gap against `price` is a comparison, not a discount. The Business chooses what it is measured against (for example, the price typically charged over a preceding period, or the manufacturer's suggested retail price); what is permitted varies by jurisdiction. On an Order, this is the value captured at Checkout. + """ quantity_unit: QuantityUnit | None = None """ Sale basis this item's `quantity` is denominated in. On an authoritative Business response, absence encodes the default `each` machine identity (`C62`, 0); the Business MUST include this descriptor for every non-`each` response. On Platform requests, omission makes no assertion: the Business interprets `quantity` using the item's authoritative sale basis. If the Platform includes this descriptor, it asserts the unit-descriptor machine identity. The Business MUST compare that machine identity (`unit`, effective `scale`), ignore `display_text` and `increment`, and resolve a mismatch by conversion surfaced as a visible line revision with a warning, or by rejection with a recoverable business outcome; silent reinterpretation is forbidden. An explicit `C62` descriptor at effective scale 0 matches an authoritative basis represented by an absent descriptor. @@ -3937,30 +4178,6 @@ class ItemUpdateRequest(BaseModel): """ -class LineItem(BaseModel): - """ - Line item object. Expected to use the currency of the parent object. - """ - - model_config = ConfigDict( - extra="allow", - ) - id: str - item: Item - quantity: int = Field(..., ge=1, le=9007199254740991) - """ - Always an integer step count. On Platform requests, steps use the item's Business-authoritative sale basis; omitting `item.quantity_unit` makes no assertion and does not imply `each`. On Business responses, `item.quantity_unit` describes the basis; if absent, it encodes the `each` machine identity (`C62`, 0) and `quantity` counts whole items. - """ - totals: list[Total] - """ - Line item totals breakdown. - """ - parent_id: str | None = None - """ - Parent line item identifier for any nested structures. - """ - - class LineItemCreateRequest(BaseModel): """ Request payload to create a new LineItem. Line item object. Expected to use the currency of the parent object. @@ -3974,6 +4191,10 @@ class LineItemCreateRequest(BaseModel): """ Always an integer step count. On Platform requests, steps use the item's Business-authoritative sale basis; omitting `item.quantity_unit` makes no assertion and does not imply `each`. On Business responses, `item.quantity_unit` describes the basis; if absent, it encodes the `each` machine identity (`C62`, 0) and `quantity` counts whole items. """ + selected_purchase_option_id: str | None = None + """ + ID of the selected purchase option, one of `purchase_options[].id`. The Business selects the default where the Platform made no choice, and reports any change it makes with a `purchase_option_changed` warning. + """ class LineItemUpdateRequest(BaseModel): @@ -3994,73 +4215,9 @@ class LineItemUpdateRequest(BaseModel): """ Parent line item identifier for any nested structures. """ - - -class Location(BaseModel): - """ - The full, rich representation of a physical business location. Builds on the Location Summary schema with discovery-centric details such as geographic coordinates, operating hours, timezone, and amenities. - """ - - model_config = ConfigDict( - extra="allow", - ) - id: str - """ - Stable, opaque, Business-scoped Location identifier. - """ - name: str - """ - Buyer-facing, Business-owned display name. - """ - address: PostalAddress | None = None - """ - Physical address of the location. - """ - geo: Geo | None = None - """ - Geographic coordinates for the location. - """ - amenities: dict[AmenityType, Amenity] | None = None - """ - Static features, services, or capabilities of the Location, keyed by reverse-domain amenity identifier. Each value provides a buyer-facing description; the key alone defines amenity identity and filter matching. - """ - hours: list[DailyHour] | None = None - """ - Regular weekly operating hours whose day and time values use this Location's canonical local civil-time frame. Multiple entries for the same day support split shifts. An omitted day has no regular interval beginning that day; an interval beginning on the preceding day can carry into it. Omission of the entire `hours` property means the regular schedule is unknown. - """ - exception_hours: list[ExceptionHour] | None = None - """ - Date-specific operating-hour exceptions, including full closures, whose date and time values use this Location's canonical local civil-time frame. - """ - timezone: str | None = None - """ - The Business-owned IANA Time Zone Database identifier (e.g., 'America/New_York') defining this Location's canonical local civil-time frame for all returned schedule day, time, and date fields. The Business does not vary this canonical framing by the requesting Platform's or Buyer's timezone. Required when hours or exception_hours is present. - """ - - -class LocationDestination(BaseModel): - """ - A business location fulfillment destination. Business-authored and response-only: the Platform selects a location via `selected_destination_id` rather than writing destinations. - """ - - model_config = ConfigDict( - extra="allow", - ) - type: Literal["business_location"] - """ - Destination type discriminator. Response-only. - """ - id: str - """ - Stable, opaque, Business-scoped Location identifier. - """ - name: str - """ - Buyer-facing, Business-owned display name. - """ - address: PostalAddress | None = None + selected_purchase_option_id: str | None = None """ - Physical address of the location. + ID of the selected purchase option, one of `purchase_options[].id`. The Business selects the default where the Platform made no choice, and reports any change it makes with a `purchase_option_changed` warning. """ @@ -4137,77 +4294,9 @@ class LocationSearchRequest(BaseModel): pagination: PaginationRequest | None = None -class LocationSummary(BaseModel): +class MediaBase(BaseModel): """ - A summary of a physical business location. - """ - - model_config = ConfigDict( - extra="allow", - ) - id: str - """ - Stable, opaque, Business-scoped Location identifier. - """ - name: str - """ - Buyer-facing, Business-owned display name. - """ - address: PostalAddress | None = None - """ - Physical address of the location. - """ - - -class LookupLocation(BaseModel): - """ - Location with required correlation metadata for lookup responses. - """ - - model_config = ConfigDict( - extra="allow", - ) - id: str - """ - Stable, opaque, Business-scoped Location identifier. - """ - name: str - """ - Buyer-facing, Business-owned display name. - """ - address: PostalAddress | None = None - """ - Physical address of the location. - """ - geo: Geo | None = None - """ - Geographic coordinates for the location. - """ - amenities: dict[AmenityType, Amenity] | None = None - """ - Static features, services, or capabilities of the Location, keyed by reverse-domain amenity identifier. Each value provides a buyer-facing description; the key alone defines amenity identity and filter matching. - """ - hours: list[DailyHour] | None = None - """ - Regular weekly operating hours whose day and time values use this Location's canonical local civil-time frame. Multiple entries for the same day support split shifts. An omitted day has no regular interval beginning that day; an interval beginning on the preceding day can carry into it. Omission of the entire `hours` property means the regular schedule is unknown. - """ - exception_hours: list[ExceptionHour] | None = None - """ - Date-specific operating-hour exceptions, including full closures, whose date and time values use this Location's canonical local civil-time frame. - """ - timezone: str | None = None - """ - The Business-owned IANA Time Zone Database identifier (e.g., 'America/New_York') defining this Location's canonical local civil-time frame for all returned schedule day, time, and date fields. The Business does not vary this canonical framing by the requesting Platform's or Buyer's timezone. Required when hours or exception_hours is present. - """ - inputs: list[LookupLocationInput] = Field(..., min_length=1) - """ - Which request identifiers resolved to this Location. Each entry preserves one identifier exactly as supplied in the request. - """ - - -class MediaBase(BaseModel): - """ - One logical media item — such as an image, a video, or a 3D model. `url` identifies the resource the Platform renders; `sources` lists alternate renditions; `preview` is a still. + One logical media item — such as an image, a video, or a 3D model. `url` identifies the resource the Platform renders; `sources` lists alternate renditions; `preview` is a still. """ model_config = ConfigDict( @@ -4501,36 +4590,6 @@ class OrderFulfillment(BaseModel): """ -class OrderLineItem(BaseModel): - model_config = ConfigDict( - extra="allow", - ) - id: str - """ - Line item identifier. - """ - item: Item - """ - Purchased item data, including identity, price, and sale basis. - """ - quantity: OrderLineItemQuantity = Field(..., title="OrderLineItemQuantity") - """ - Tracks the line item's original, current active, and fulfilled quantities. All three values use the same inherited `item.quantity_unit`. When `item.quantity_unit` is absent on an authoritative order response, each step is one whole item (`each`) under the shared default. - """ - totals: list[Total] - """ - Line item totals breakdown. - """ - status: Literal["processing", "partial", "fulfilled", "removed"] - """ - Derived status: removed if quantity.total == 0, fulfilled if quantity.total > 0 and quantity.fulfilled == quantity.total, partial if quantity.total > 0 and quantity.fulfilled > 0, otherwise processing. - """ - parent_id: str | None = None - """ - Parent line item identifier for any nested structures. - """ - - class OrderPayment(BaseModel): """ Order payment details carrying the term the Buyer accepted at checkout. @@ -4771,7 +4830,7 @@ class Policy(BaseModel): ) type: ReverseDomainName """ - Policy type discriminator. Open reverse-DNS vocabulary. Well-known values: `dev.ucp.shopping.policy.return` (return terms), `dev.ucp.shopping.policy.warranty` (warranty terms). Businesses MAY define custom types in their own domain (e.g., `com.example.policy.price_match`). Platforms MUST tolerate unknown values. + Policy type discriminator. Open reverse-DNS vocabulary. See specification documentation for the registry of well-known policy types. Businesses MAY define custom types in their own domain (e.g., `com.example.policy.price_match`). Platforms MUST tolerate unknown values. """ description: Description """ @@ -4796,6 +4855,18 @@ class Policy(BaseModel): """ +PurchaseOptionsPoliciesItem = TypeAliasType( + "PurchaseOptionsPoliciesItem", + Annotated[ + SubscriptionPolicy | PurchaseOptionsPoliciesItemBase, + Field(..., title="PurchaseOptionsPoliciesItem"), + ], +) +""" +A `policies[]` entry; validates against `subscription_policy` when `type` is `dev.ucp.shopping.policy.subscription`. +""" + + class RequestConstraints(BaseModel): """ Binds the shared Constraint Expression grammar to data in the next UCP request to the same resource. @@ -4842,6 +4913,74 @@ class Requires(BaseModel): """ +class ReturnBody(BaseModel): + """ + Return terms for a `dev.ucp.shopping.policy.return` policy. + """ + + model_config = ConfigDict( + extra="allow", + ) + eligibility: ReturnEligibility | None = None + """ + Structured return eligibility statement. Omitted means eligibility is not stated structurally, not that returns are unlimited or not accepted. When `type` is `not_accepted`, the business's return policy does not accept returns of the covered items, and `supported_resolutions`, `methods`, and `fees` MUST be omitted. + """ + supported_resolutions: list[str] | None = Field(None, min_length=1) + """ + Return outcomes guaranteed for every eligible return, as an unordered set; not an exhaustive list. Well-known values: `original_payment_method`, `store_credit`, `gift_card`, `exchange`, `replacement`. + """ + methods: list[str] | None = Field(None, min_length=1) + """ + Return channels guaranteed for every eligible return, as an unordered set; not an exhaustive list. Well-known values: `in_store`, `by_mail`, `kiosk`. Omit when channels are not stated structurally. + """ + fees: list[Fee] | None = Field(None, min_length=1) + """ + Estimated maximum charges on a return, each typed by what it is for and optionally scoped to channels; not an exhaustive list. Omitted means fees are not stated structurally, not that none are charged. + """ + + +class ReturnPolicy(BaseModel): + """ + A return policy statement with type `dev.ucp.shopping.policy.return`. + """ + + model_config = ConfigDict( + extra="allow", + ) + type: Literal["dev.ucp.shopping.policy.return"] + """ + Policy type discriminator. Open reverse-DNS vocabulary. See specification documentation for the registry of well-known policy types. Businesses MAY define custom types in their own domain (e.g., `com.example.policy.price_match`). Platforms MUST tolerate unknown values. + """ + description: Description + """ + Human-readable policy summary in one or more formats (plain, markdown, html). Required on every policy so a platform can present it without understanding any type-specific fields. This is not the buyer-facing disclosure — display is compelled by a `messages[]` warning (see the Policies section). + """ + applies_to: list[str] | None = None + """ + RFC 9535 JSONPath expressions identifying the nodes this policy applies to, relative to the embedding response root (e.g., `$.line_items[0]` in cart/checkout, `$.products[2]` in catalog). Each target covers the node it names and everything nested under it, so a target on a product also covers its variants. A singular query (RFC 9535 Section 2.3.5.1; name and index selectors only) names a single node; filters, wildcards, and slices match a set. When omitted, the policy applies to the entire response. When policies of the same `type` contest a node, the narrowest target wins and overrides the rest. See the Policies section for how specificity resolves. + """ + url: AnyUrl | None = None + """ + Optional link to the full policy document. + """ + eligibility: ReturnEligibility | None = None + """ + Structured return eligibility statement. Omitted means eligibility is not stated structurally, not that returns are unlimited or not accepted. When `type` is `not_accepted`, the business's return policy does not accept returns of the covered items, and `supported_resolutions`, `methods`, and `fees` MUST be omitted. + """ + supported_resolutions: list[str] | None = Field(None, min_length=1) + """ + Return outcomes guaranteed for every eligible return, as an unordered set; not an exhaustive list. Well-known values: `original_payment_method`, `store_credit`, `gift_card`, `exchange`, `replacement`. + """ + methods: list[str] | None = Field(None, min_length=1) + """ + Return channels guaranteed for every eligible return, as an unordered set; not an exhaustive list. Well-known values: `in_store`, `by_mail`, `kiosk`. Omit when channels are not stated structurally. + """ + fees: list[Fee] | None = Field(None, min_length=1) + """ + Estimated maximum charges on a return, each typed by what it is for and optionally scoped to channels; not an exhaustive list. Omitted means fees are not stated structurally, not that none are charged. + """ + + class ServiceBase(BaseModel): model_config = ConfigDict( extra="allow", @@ -5377,6 +5516,36 @@ class ServiceResponseSchemaEmbedded(BaseModel): """ +class SubscriptionSchedule(BaseModel): + """ + One run of recurring orders on one set of terms: a buyer-facing `description`, each order's `totals`, an optional stated regular `interval`, and when the run starts and ends. + """ + + model_config = ConfigDict( + extra="allow", + ) + description: Description + """ + Complete buyer-facing statement of this run: what each order costs, how often, from when, and until when. Sufficient on its own; a Platform can render it verbatim. + """ + totals: list[Total] = Field(..., min_length=1) + """ + Breakdown of each recurring order, as a line item's `totals`, with exactly one `total` entry. Per unit on a catalog variant; for the line at its quantity on a cart or checkout. Before taxes, fulfillment, and fees unless the Business can state them. + """ + interval: Duration | None = None + """ + Stated regular cadence of recurring orders in this run (e.g., `P30D`, `P1M`, `P2W`), agreeing with `description`. Omitted when cadence is not structurally stated; omission does not mean no recurrence. This is not an execution rule or a generator of order dates; the Business owns calendar arithmetic. + """ + starts_at: AwareDatetime | None = None + """ + RFC 3339 date-time when the first order under this schedule is placed. Supplementary to `description`; omitted where the Business cannot yet determine it. + """ + ends_at: AwareDatetime | None = None + """ + RFC 3339 date-time after which no order is placed under this schedule, before the next schedule's `starts_at`. On the last schedule it marks a subscription that ends on its own; omitted there, the orders continue until the buyer cancels. + """ + + class UcpEntity(BaseModel): """ Shared foundation for all UCP entities. @@ -5605,18 +5774,6 @@ class FulfillmentCreateRequest(BaseModel): """ -FulfillmentDestination = TypeAliasType( - "FulfillmentDestination", - Annotated[ - LocationDestination | ShippingDestination | FulfillmentDestinationBase, - Field(..., title="FulfillmentDestination"), - ], -) -""" -A destination for fulfillment. -""" - - class FulfillmentGroup(BaseModel): """ A merchant-generated package/group of line items with fulfillment options. @@ -5643,40 +5800,6 @@ class FulfillmentGroup(BaseModel): """ -class FulfillmentMethodBase(BaseModel): - """ - A fulfillment method with destinations and groups. - """ - - model_config = ConfigDict( - extra="allow", - ) - id: str - """ - Unique fulfillment method identifier. - """ - type: str - """ - Fulfillment method type. Well-known values: `shipping`, `pickup`. Businesses MAY use additional values. - """ - line_item_ids: list[str] - """ - Line item IDs fulfilled via this method. - """ - destinations: list[FulfillmentDestination] | None = None - """ - Available destinations for this method. In Business responses, each destination carries a `type` and `id`. - """ - selected_destination_id: str | None = None - """ - ID of the selected destination. Accepts any stable, Business-scoped ID the Business recognizes for this method, including Location IDs not yet enumerated in `destinations`. - """ - groups: list[FulfillmentGroup] | None = None - """ - Fulfillment groups for selecting options. Agent sets selected_option_id on groups to choose shipping method. - """ - - class IdentityLinkingBusinessSchemaConfig(BaseModel): """ Entity-specific configuration. Structure defined by each entity's schema. @@ -6014,9 +6137,21 @@ class PermalinkBusinessSchema(BaseModel): """ -class PickupMethod(BaseModel): +PolicyReturnPoliciesItem = TypeAliasType( + "PolicyReturnPoliciesItem", + Annotated[ + ReturnPolicy | PolicyReturnPoliciesItemBase, + Field(..., title="PolicyReturnPoliciesItem"), + ], +) +""" +A `policies[]` entry; validates against `return_policy` when `type` is `dev.ucp.shopping.policy.return`. +""" + + +class PurchaseOption(BaseModel): """ - A fulfillment method with destinations and groups. + One way to buy a variant: once, or as a subscription. The Business lists the options it sells; the Platform selects one by `id`. """ model_config = ConfigDict( @@ -6024,52 +6159,236 @@ class PickupMethod(BaseModel): ) id: str """ - Unique fulfillment method identifier. - """ - type: Literal["pickup"] - """ - Fulfillment method type. Well-known values: `shipping`, `pickup`. Businesses MAY use additional values. + Opaque identifier, sent back as `selected_purchase_option_id`. """ - line_item_ids: list[str] + title: str """ - Line item IDs fulfilled via this method. + Short label distinguishing this option from its siblings (e.g. 'One-time', 'Subscribe & save 15%'). """ - destinations: list[LocationDestination] | None = None + description: Description | None = None """ - Business-authored business locations able to fulfill this method. Response-only: the Platform selects one via `selected_destination_id`, never writes one. + Supplementary buyer-facing context for the title, describing the way of buying (e.g. 'A fresh bag every month, 15% off'). Terms belong to the policy and amounts to `schedules`. """ - selected_destination_id: str | None = None + price: Price """ - ID of the selected destination. Accepts any stable, Business-scoped ID the Business recognizes for this method, including Location IDs not yet enumerated in `destinations`. + What one unit costs in the current purchase under this option, before quantity, taxes, fees, and fulfillment. `0` means genuinely free. Recurring orders are stated in `schedules`. """ - groups: list[FulfillmentGroup] | None = None + schedules: list[SubscriptionSchedule] | None = Field(None, min_length=1) """ - Fulfillment groups for selecting options. Agent sets selected_option_id on groups to choose shipping method. + The recurring orders that follow the current purchase, as consecutive schedules in the order they take effect. Present only on an option that results in recurring orders; binding once selected on a cart or checkout line. """ -class ResponseAskSchema(BaseModel): +class PurchaseOptionsLookupVariant(BaseModel): """ - UCP metadata for ask responses. + A lookup variant (carrying input correlation) carrying purchase options. """ model_config = ConfigDict( extra="allow", ) - version: Version - map_order: MapOrder | None = None + id: str """ - Preferred key-traversal order for sibling registry fields inside the root `ucp` envelope (`services`, `capabilities`, and `payment_handlers`). + Global ID (GID) uniquely identifying this variant. Used as item.id in checkout. """ - status: Literal["success", "error"] | None = "success" + sku: str | None = None """ - Application-level status of the UCP operation. + Business-assigned identifier for inventory and fulfillment. """ - services: dict[ReverseDomainName, list[ServiceBase]] | None = None + barcodes: list[PurchaseOptionsLookupVariantBarcode] | None = None """ - Service registry keyed by reverse-domain name. + Industry-standard product identifiers for cross-reference and correlation. """ - capabilities: ( + handle: str | None = None + """ + URL-safe variant handle/slug. + """ + title: str + """ + Variant display title (e.g., 'Blue / Large'). + """ + description: Description + """ + Variant description in one or more formats. + """ + url: AnyUrl | None = None + """ + Canonical variant page URL. + """ + categories: list[Category] | None = None + """ + Variant categories with optional taxonomy identifiers. + """ + price: Price + """ + Current selling price. Price is the amount per one whole `quantity_unit.unit` (for example, per lb or per hour); when `quantity_unit` is absent, it is per `each`. Line total is `price × quantity × 10^-scale`, computed and rounded once by the Business; `totals` remain authoritative. + """ + quantity_unit: QuantityUnit | None = None + """ + Sale basis this variant's `quantity` is denominated in. The default sale basis is `each`, whose machine identity is (`C62`, 0); `C62` is the UN/CEFACT Rec20 code for one/each. An absent catalog descriptor encodes that default. An `increment` advertises the ordering granularity in steps (for example, `scale` 2 with `increment` 25 sells in 0.25-unit multiples). + """ + list_price: Price | None = None + """ + Reference price for comparison display, typically shown as a strikethrough next to `price`, and denominated like `price`. It is not charged and is never part of `totals`; the gap against `price` is a comparison, not a discount. The Business chooses what it is measured against (for example, the price typically charged over a preceding period, or the manufacturer's suggested retail price); what is permitted varies by jurisdiction. `list_price.currency` MUST equal `price.currency`. + """ + unit_price: UnitPrice | None = None + """ + Price per standard unit of measurement, for shelf-style comparison display. MAY be omitted when unit pricing does not apply. + """ + availability: Availability | None = None + """ + Variant availability for purchase. + """ + options: list[SelectedOption] | None = None + """ + Option values that define this variant (e.g., Color: Blue, Size: Large). + """ + media: list[Media] | None = None + """ + Variant media (images, videos, 3D models). First item is the featured media for listings. + """ + rating: Rating | None = None + """ + Variant rating. + """ + tags: list[str] | None = None + """ + Variant tags for categorization and search. + """ + metadata: dict[str, Any] | None = None + """ + Business-defined custom data extending the standard variant model. + """ + seller: PurchaseOptionsLookupVariantSeller | None = Field( + None, title="PurchaseOptionsLookupVariantSeller" + ) + """ + Optional seller context for this variant. + """ + inputs: list[InputCorrelation] = Field(..., min_length=1) + """ + Which request identifiers resolved to this variant, and how. Each entry maps a request ID to its match type. + """ + purchase_options: list[PurchaseOption] | None = Field(None, min_length=1) + """ + The ways this variant can be bought, in the Business's order of preference. The first is the default, and the variant's `price` is its `price`. Absent when the variant is bought the ordinary way. + """ + + +class PurchaseOptionsVariant(BaseModel): + """ + A catalog variant carrying purchase options. + """ + + model_config = ConfigDict( + extra="allow", + ) + id: str + """ + Global ID (GID) uniquely identifying this variant. Used as item.id in checkout. + """ + sku: str | None = None + """ + Business-assigned identifier for inventory and fulfillment. + """ + barcodes: list[PurchaseOptionsVariantBarcode] | None = None + """ + Industry-standard product identifiers for cross-reference and correlation. + """ + handle: str | None = None + """ + URL-safe variant handle/slug. + """ + title: str + """ + Variant display title (e.g., 'Blue / Large'). + """ + description: Description + """ + Variant description in one or more formats. + """ + url: AnyUrl | None = None + """ + Canonical variant page URL. + """ + categories: list[Category] | None = None + """ + Variant categories with optional taxonomy identifiers. + """ + price: Price + """ + Current selling price. Price is the amount per one whole `quantity_unit.unit` (for example, per lb or per hour); when `quantity_unit` is absent, it is per `each`. Line total is `price × quantity × 10^-scale`, computed and rounded once by the Business; `totals` remain authoritative. + """ + quantity_unit: QuantityUnit | None = None + """ + Sale basis this variant's `quantity` is denominated in. The default sale basis is `each`, whose machine identity is (`C62`, 0); `C62` is the UN/CEFACT Rec20 code for one/each. An absent catalog descriptor encodes that default. An `increment` advertises the ordering granularity in steps (for example, `scale` 2 with `increment` 25 sells in 0.25-unit multiples). + """ + list_price: Price | None = None + """ + Reference price for comparison display, typically shown as a strikethrough next to `price`, and denominated like `price`. It is not charged and is never part of `totals`; the gap against `price` is a comparison, not a discount. The Business chooses what it is measured against (for example, the price typically charged over a preceding period, or the manufacturer's suggested retail price); what is permitted varies by jurisdiction. `list_price.currency` MUST equal `price.currency`. + """ + unit_price: UnitPrice | None = None + """ + Price per standard unit of measurement, for shelf-style comparison display. MAY be omitted when unit pricing does not apply. + """ + availability: Availability | None = None + """ + Variant availability for purchase. + """ + options: list[SelectedOption] | None = None + """ + Option values that define this variant (e.g., Color: Blue, Size: Large). + """ + media: list[Media] | None = None + """ + Variant media (images, videos, 3D models). First item is the featured media for listings. + """ + rating: Rating | None = None + """ + Variant rating. + """ + tags: list[str] | None = None + """ + Variant tags for categorization and search. + """ + metadata: dict[str, Any] | None = None + """ + Business-defined custom data extending the standard variant model. + """ + seller: PurchaseOptionsVariantSeller | None = Field( + None, title="PurchaseOptionsVariantSeller" + ) + """ + Optional seller context for this variant. + """ + purchase_options: list[PurchaseOption] | None = Field(None, min_length=1) + """ + The ways this variant can be bought, in the Business's order of preference. The first is the default, and the variant's `price` is its `price`. Absent when the variant is bought the ordinary way. + """ + + +class ResponseAskSchema(BaseModel): + """ + UCP metadata for ask responses. + """ + + model_config = ConfigDict( + extra="allow", + ) + version: Version + map_order: MapOrder | None = None + """ + Preferred key-traversal order for sibling registry fields inside the root `ucp` envelope (`services`, `capabilities`, and `payment_handlers`). + """ + status: Literal["success", "error"] | None = "success" + """ + Application-level status of the UCP operation. + """ + services: dict[ReverseDomainName, list[ServiceBase]] | None = None + """ + Service registry keyed by reverse-domain name. + """ + capabilities: ( dict[ReverseDomainName, list[CapabilityResponseSchema]] | None ) = None """ @@ -6083,6 +6402,41 @@ class ResponseAskSchema(BaseModel): """ +class ResponseBookingSchema(BaseModel): + """ + UCP metadata for booking responses. + """ + + model_config = ConfigDict( + extra="allow", + ) + version: Version + map_order: MapOrder | None = None + """ + Preferred key-traversal order for sibling registry fields inside the root `ucp` envelope (`services`, `capabilities`, and `payment_handlers`). + """ + status: Literal["success", "error"] | None = "success" + """ + Application-level status of the UCP operation. + """ + services: dict[ReverseDomainName, list[ServiceResponseSchema]] | None = None + """ + Service registry keyed by reverse-domain name. + """ + capabilities: ( + dict[ReverseDomainName, list[CapabilityResponseSchema]] | None + ) = None + """ + Capability registry keyed by reverse-domain name. + """ + payment_handlers: dict[ + ReverseDomainName, list[PaymentHandlerResponseSchema] + ] + """ + Payment handler registry keyed by reverse-domain name. + """ + + class ResponseCartSchema(BaseModel): """ UCP metadata for cart responses. No payment handlers needed pre-checkout. @@ -6515,7 +6869,7 @@ class Variant(BaseModel): """ list_price: Price | None = None """ - List price before discounts (for strikethrough display). + Reference price for comparison display, typically shown as a strikethrough next to `price`, and denominated like `price`. It is not charged and is never part of `totals`; the gap against `price` is a comparison, not a discount. The Business chooses what it is measured against (for example, the price typically charged over a preceding period, or the manufacturer's suggested retail price); what is permitted varies by jurisdiction. `list_price.currency` MUST equal `price.currency`. """ unit_price: UnitPrice | None = None """ @@ -6551,6 +6905,20 @@ class Variant(BaseModel): """ +class VariantPurchaseOptions(BaseModel): + """ + The purchase option fields added to a catalog variant. + """ + + model_config = ConfigDict( + extra="allow", + ) + purchase_options: list[PurchaseOption] | None = Field(None, min_length=1) + """ + The ways this variant can be bought, in the Business's order of preference. The first is the default, and the variant's `price` is its `price`. Absent when the variant is bought the ordinary way. + """ + + class AskResponse(BaseModel): model_config = ConfigDict( extra="allow", @@ -6623,7 +6991,7 @@ class DetailProduct(BaseModel): """ list_price_range: PriceRange | None = None """ - List price range before discounts (for strikethrough display). + Range of variant `list_price` values across all variants; see `variant.list_price`. The range MUST use the same currency as `price_range`. """ media: list[Media] | None = None """ @@ -6727,7 +7095,7 @@ class FulfillmentLookupVariant(BaseModel): """ list_price: Price | None = None """ - List price before discounts (for strikethrough display). + Reference price for comparison display, typically shown as a strikethrough next to `price`, and denominated like `price`. It is not charged and is never part of `totals`; the gap against `price` is a comparison, not a discount. The Business chooses what it is measured against (for example, the price typically charged over a preceding period, or the manufacturer's suggested retail price); what is permitted varies by jurisdiction. `list_price.currency` MUST equal `price.currency`. """ unit_price: UnitPrice | None = None """ @@ -6770,18 +7138,6 @@ class FulfillmentLookupVariant(BaseModel): fulfillment: CatalogFulfillment | None = None -FulfillmentMethod = TypeAliasType( - "FulfillmentMethod", - Annotated[ - PickupMethod | ShippingMethod | FulfillmentMethodBase, - Field(..., title="FulfillmentMethod"), - ], -) -""" -A fulfillment method with destinations and groups. -""" - - class FulfillmentVariant(BaseModel): """ A catalog variant with fulfillment. @@ -6832,7 +7188,7 @@ class FulfillmentVariant(BaseModel): """ list_price: Price | None = None """ - List price before discounts (for strikethrough display). + Reference price for comparison display, typically shown as a strikethrough next to `price`, and denominated like `price`. It is not charged and is never part of `totals`; the gap against `price` is a comparison, not a discount. The Business chooses what it is measured against (for example, the price typically charged over a preceding period, or the manufacturer's suggested retail price); what is permitted varies by jurisdiction. `list_price.currency` MUST equal `price.currency`. """ unit_price: UnitPrice | None = None """ @@ -6871,37 +7227,206 @@ class FulfillmentVariant(BaseModel): fulfillment: CatalogFulfillment | None = None -class LocationLookupResponse(BaseModel): - model_config = ConfigDict( - extra="allow", - ) - ucp: ResponseLocationSchema - locations: list[LookupLocation] - """ - Locations matching the requested identifiers and refinements. May contain fewer Locations if some identifiers do not resolve or their resolved Locations are filtered out, or more if one identifier resolves to multiple Locations. When multiple identifiers resolve to the same Location, one returned Location carries all corresponding `inputs` entries. - """ - messages: list[Message] | None = None +class LineItem(BaseModel): """ - Errors, warnings, or informational messages about the requested Locations, including `batch_limit_applied` when the Business processes only its configured maximum number of identifiers. + Line item object. Expected to use the currency of the parent object. """ - -class LocationSearchResponse(BaseModel): model_config = ConfigDict( extra="allow", ) - ucp: ResponseLocationSchema - locations: list[Location] + id: str + item: Item + quantity: int = Field(..., ge=1, le=9007199254740991) """ - Locations matching the search criteria. + Always an integer step count. On Platform requests, steps use the item's Business-authoritative sale basis; omitting `item.quantity_unit` makes no assertion and does not imply `each`. On Business responses, `item.quantity_unit` describes the basis; if absent, it encodes the `each` machine identity (`C62`, 0) and `quantity` counts whole items. """ - pagination: PaginationResponse | None = None - messages: list[Message] | None = None + totals: list[Total] + """ + Line item totals breakdown. + """ + parent_id: str | None = None + """ + Parent line item identifier for any nested structures. + """ + purchase_options: list[PurchaseOption] | None = Field(None, min_length=1) + """ + The ways this line's variant can be bought, priced for this cart or checkout. The selected option's price is the line's `item.price`; the others are indicative. + """ + selected_purchase_option_id: str | None = None + """ + ID of the selected purchase option, one of `purchase_options[].id`. The Business selects the default where the Platform made no choice, and reports any change it makes with a `purchase_option_changed` warning. + """ + + +class Location(BaseModel): + """ + The full, rich representation of a physical business location. Builds on the Location Summary schema with discovery-centric details such as geographic coordinates, operating hours, timezone, and amenities. + """ + + model_config = ConfigDict( + extra="allow", + ) + id: str + """ + Stable, opaque, Business-scoped Location identifier. + """ + name: str + """ + Buyer-facing, Business-owned display name. + """ + address: PostalAddress | None = None + """ + Physical address of the location. + """ + media: list[Media] | None = None + """ + Location media assets (e.g., images, logos, hero banners). First item is the featured media for presentation. + """ + geo: Geo | None = None + """ + Geographic coordinates for the location. + """ + amenities: dict[AmenityType, Amenity] | None = None + """ + Static features, services, or capabilities of the Location, keyed by reverse-domain amenity identifier. Each value provides a buyer-facing description; the key alone defines amenity identity and filter matching. + """ + hours: list[DailyHour] | None = None + """ + Regular weekly operating hours whose day and time values use this Location's canonical local civil-time frame. Multiple entries for the same day support split shifts. An omitted day has no regular interval beginning that day; an interval beginning on the preceding day can carry into it. Omission of the entire `hours` property means the regular schedule is unknown. + """ + exception_hours: list[ExceptionHour] | None = None + """ + Date-specific operating-hour exceptions, including full closures, whose date and time values use this Location's canonical local civil-time frame. + """ + timezone: str | None = None + """ + The Business-owned IANA Time Zone Database identifier (e.g., 'America/New_York') defining this Location's canonical local civil-time frame for all returned schedule day, time, and date fields. The Business does not vary this canonical framing by the requesting Platform's or Buyer's timezone. Required when hours or exception_hours is present. + """ + + +class LocationDestination(BaseModel): + """ + A business location fulfillment destination. Business-authored and response-only: the Platform selects a location via `selected_destination_id` rather than writing destinations. + """ + + model_config = ConfigDict( + extra="allow", + ) + type: Literal["business_location"] + """ + Destination type discriminator. Response-only. + """ + id: str + """ + Stable, opaque, Business-scoped Location identifier. + """ + name: str + """ + Buyer-facing, Business-owned display name. + """ + address: PostalAddress | None = None + """ + Physical address of the location. + """ + media: list[Media] | None = None + """ + Location media assets (e.g., images, logos, hero banners). First item is the featured media for presentation. + """ + + +class LocationSearchResponse(BaseModel): + model_config = ConfigDict( + extra="allow", + ) + ucp: ResponseLocationSchema + locations: list[Location] + """ + Locations matching the search criteria. + """ + pagination: PaginationResponse | None = None + messages: list[Message] | None = None """ Errors, warnings, or informational messages about the search results. """ +class LocationSummary(BaseModel): + """ + A summary of a physical business location. + """ + + model_config = ConfigDict( + extra="allow", + ) + id: str + """ + Stable, opaque, Business-scoped Location identifier. + """ + name: str + """ + Buyer-facing, Business-owned display name. + """ + address: PostalAddress | None = None + """ + Physical address of the location. + """ + media: list[Media] | None = None + """ + Location media assets (e.g., images, logos, hero banners). First item is the featured media for presentation. + """ + + +class LookupLocation(BaseModel): + """ + Location with required correlation metadata for lookup responses. + """ + + model_config = ConfigDict( + extra="allow", + ) + id: str + """ + Stable, opaque, Business-scoped Location identifier. + """ + name: str + """ + Buyer-facing, Business-owned display name. + """ + address: PostalAddress | None = None + """ + Physical address of the location. + """ + media: list[Media] | None = None + """ + Location media assets (e.g., images, logos, hero banners). First item is the featured media for presentation. + """ + geo: Geo | None = None + """ + Geographic coordinates for the location. + """ + amenities: dict[AmenityType, Amenity] | None = None + """ + Static features, services, or capabilities of the Location, keyed by reverse-domain amenity identifier. Each value provides a buyer-facing description; the key alone defines amenity identity and filter matching. + """ + hours: list[DailyHour] | None = None + """ + Regular weekly operating hours whose day and time values use this Location's canonical local civil-time frame. Multiple entries for the same day support split shifts. An omitted day has no regular interval beginning that day; an interval beginning on the preceding day can carry into it. Omission of the entire `hours` property means the regular schedule is unknown. + """ + exception_hours: list[ExceptionHour] | None = None + """ + Date-specific operating-hour exceptions, including full closures, whose date and time values use this Location's canonical local civil-time frame. + """ + timezone: str | None = None + """ + The Business-owned IANA Time Zone Database identifier (e.g., 'America/New_York') defining this Location's canonical local civil-time frame for all returned schedule day, time, and date fields. The Business does not vary this canonical framing by the requesting Platform's or Buyer's timezone. Required when hours or exception_hours is present. + """ + inputs: list[LookupLocationInput] = Field(..., min_length=1) + """ + Which request identifiers resolved to this Location. Each entry preserves one identifier exactly as supplied in the request. + """ + + class LookupVariant(BaseModel): """ Variant with required correlation metadata for lookup responses. @@ -6952,7 +7477,7 @@ class LookupVariant(BaseModel): """ list_price: Price | None = None """ - List price before discounts (for strikethrough display). + Reference price for comparison display, typically shown as a strikethrough next to `price`, and denominated like `price`. It is not charged and is never part of `totals`; the gap against `price` is a comparison, not a discount. The Business chooses what it is measured against (for example, the price typically charged over a preceding period, or the manufacturer's suggested retail price); what is permitted varies by jurisdiction. `list_price.currency` MUST equal `price.currency`. """ unit_price: UnitPrice | None = None """ @@ -7017,66 +7542,71 @@ class LookupVariant(BaseModel): """ -class Order(BaseModel): - """ - Order schema with line items, buyer-facing fulfillment expectations, and event logs. - """ - +class OrderLineItem(BaseModel): model_config = ConfigDict( extra="allow", ) - ucp: ResponseOrderSchema id: str """ - Unique order identifier. + Line item identifier. """ - label: str | None = None + item: Item """ - Human-readable label for identifying the order. MUST only be provided by the business. + Purchased item data, including identity, price, and sale basis. """ - checkout_id: str + quantity: OrderLineItemQuantity = Field(..., title="OrderLineItemQuantity") """ - Associated checkout ID for reconciliation. + Tracks the line item's original, current active, and fulfilled quantities. All three values use the same inherited `item.quantity_unit`. When `item.quantity_unit` is absent on an authoritative order response, each step is one whole item (`each`) under the shared default. """ - permalink_url: AnyUrl + totals: list[Total] """ - Permalink to access the order on merchant site. + Line item totals breakdown. """ - line_items: list[OrderLineItem] + status: Literal["processing", "partial", "fulfilled", "removed"] """ - Line items representing what was purchased — can change post-order via edits or exchanges. + Derived status: removed if quantity.total == 0, fulfilled if quantity.total > 0 and quantity.fulfilled == quantity.total, partial if quantity.total > 0 and quantity.fulfilled > 0, otherwise processing. """ - fulfillment: OrderFulfillment = Field(..., title="OrderFulfillment") + parent_id: str | None = None """ - Fulfillment data: buyer expectations and what actually happened. + Parent line item identifier for any nested structures. """ - adjustments: list[Adjustment] | None = None + purchase_option: PurchaseOption | None = None """ - Post-order events (refunds, returns, credits, disputes, cancellations, etc.) that exist independently of fulfillment. + The purchase option selected for this line, as it stood at checkout: a historical record, unchanged if the catalog option later changes, whose `id` need not still resolve. Its `price` is the line's `item.price`; its `schedules` are the recurring orders agreed to. Absent when the variant carried none. """ - currency: str + + +class PickupMethod(BaseModel): """ - ISO 4217 currency code. MUST match the currency from the originating checkout session. + A fulfillment method with destinations and groups. """ - totals: Totals + + model_config = ConfigDict( + extra="allow", + ) + id: str """ - Different totals for the order. + Unique fulfillment method identifier. """ - policies: list[Policy] | None = None + type: Literal["pickup"] """ - Snapshot of the policies that applied to the items at checkout, captured on the order as a durable record. `applies_to` targets are relative to the response root. + Fulfillment method type. Well-known values: `shipping`, `pickup`. Businesses MAY use additional values. """ - messages: list[Message] | None = None + line_item_ids: list[str] """ - Business outcome messages (errors, warnings, informational). Present when the business needs to communicate status or issues to the platform. + Line item IDs fulfilled via this method. """ - attribution: Attribution | None = None + destinations: list[LocationDestination] | None = None """ - Snapshot of the attribution associated with the originating checkout. Read-only on the order. + Business-authored business locations able to fulfill this method. Response-only: the Platform selects one via `selected_destination_id`, never writes one. """ - payment: OrderPayment | None = None + selected_destination_id: str | None = None """ - Payment details for the Order, including the accepted payment term. + ID of the selected destination. Accepts any stable, Business-scoped ID the Business recognizes for this method, including Location IDs not yet enumerated in `destinations`. + """ + groups: list[FulfillmentGroup] | None = None + """ + Fulfillment groups for selecting options. Agent sets selected_option_id on groups to choose shipping method. """ @@ -7118,7 +7648,7 @@ class Product(BaseModel): """ list_price_range: PriceRange | None = None """ - List price range before discounts (for strikethrough display). + Range of variant `list_price` values across all variants; see `variant.list_price`. The range MUST use the same currency as `price_range`. """ media: list[Media] | None = None """ @@ -7218,25 +7748,227 @@ class ProfilePlatformSchema(BaseModel): """ -class Buyer(BaseModel): +class PurchaseOptionsDetailProduct(BaseModel): + """ + A get_product detail product whose variants carry purchase options. Used by get_product. + """ + model_config = ConfigDict( extra="allow", ) - first_name: str | None = None + id: str """ - First name of the buyer. + Global ID (GID) uniquely identifying this product. """ - last_name: str | None = None + handle: str | None = None """ - Last name of the buyer. + URL-safe slug for SEO-friendly URLs (e.g., 'blue-runner-pro'). Use id for stable API references. """ - email: str | None = None + title: str """ - Email of the buyer. + Product title. """ - phone_number: str | None = None + description: Description """ - E.164 standard. + Product description in one or more formats. + """ + url: AnyUrl | None = None + """ + Canonical product page URL. + """ + categories: list[Category] | None = None + """ + Product categories with optional taxonomy identifiers. + """ + price_range: PriceRange + """ + Price range across all variants. + """ + list_price_range: PriceRange | None = None + """ + Range of variant `list_price` values across all variants; see `variant.list_price`. The range MUST use the same currency as `price_range`. + """ + media: list[Media] | None = None + """ + Product media (images, videos, 3D models). First item is the featured media for listings. + """ + options: list[PurchaseOptionsDetailProductOption] | None = None + """ + Product options with availability signals relative to the effective selections. + """ + variants: list[PurchaseOptionsVariant] = Field(..., min_length=1) + """ + Purchasable variants of this product. First item is the featured variant for listings. + """ + rating: Rating | None = None + """ + Aggregate product rating. + """ + tags: list[str] | None = None + """ + Product tags for categorization and search. + """ + metadata: dict[str, Any] | None = None + """ + Business-defined custom data extending the standard product model. + """ + selected: list[SelectedOption] | None = None + """ + Effective option selections that anchor the featured variant and availability signals. Required when the product has configurable options; may be empty or omitted for products with no option axes. + """ + + +class PurchaseOptionsLookupProduct(BaseModel): + """ + A lookup product whose variants carry purchase options, preserving input correlation. Used by lookup. + """ + + model_config = ConfigDict( + extra="allow", + ) + id: str + """ + Global ID (GID) uniquely identifying this product. + """ + handle: str | None = None + """ + URL-safe slug for SEO-friendly URLs (e.g., 'blue-runner-pro'). Use id for stable API references. + """ + title: str + """ + Product title. + """ + description: Description + """ + Product description in one or more formats. + """ + url: AnyUrl | None = None + """ + Canonical product page URL. + """ + categories: list[Category] | None = None + """ + Product categories with optional taxonomy identifiers. + """ + price_range: PriceRange + """ + Price range across all variants. + """ + list_price_range: PriceRange | None = None + """ + Range of variant `list_price` values across all variants; see `variant.list_price`. The range MUST use the same currency as `price_range`. + """ + media: list[Media] | None = None + """ + Product media (images, videos, 3D models). First item is the featured media for listings. + """ + options: list[ProductOption] | None = None + """ + Product options (Size, Color, etc.). + """ + variants: list[PurchaseOptionsLookupVariant] = Field(..., min_length=1) + """ + Purchasable variants of this product. First item is the featured variant for listings. + """ + rating: Rating | None = None + """ + Aggregate product rating. + """ + tags: list[str] | None = None + """ + Product tags for categorization and search. + """ + metadata: dict[str, Any] | None = None + """ + Business-defined custom data extending the standard product model. + """ + + +class PurchaseOptionsProduct(BaseModel): + """ + A catalog product whose variants carry purchase options. Used by search. + """ + + model_config = ConfigDict( + extra="allow", + ) + id: str + """ + Global ID (GID) uniquely identifying this product. + """ + handle: str | None = None + """ + URL-safe slug for SEO-friendly URLs (e.g., 'blue-runner-pro'). Use id for stable API references. + """ + title: str + """ + Product title. + """ + description: Description + """ + Product description in one or more formats. + """ + url: AnyUrl | None = None + """ + Canonical product page URL. + """ + categories: list[Category] | None = None + """ + Product categories with optional taxonomy identifiers. + """ + price_range: PriceRange + """ + Price range across all variants. + """ + list_price_range: PriceRange | None = None + """ + Range of variant `list_price` values across all variants; see `variant.list_price`. The range MUST use the same currency as `price_range`. + """ + media: list[Media] | None = None + """ + Product media (images, videos, 3D models). First item is the featured media for listings. + """ + options: list[ProductOption] | None = None + """ + Product options (Size, Color, etc.). + """ + variants: list[PurchaseOptionsVariant] = Field(..., min_length=1) + """ + Purchasable variants of this product. First item is the featured variant for listings. + """ + rating: Rating | None = None + """ + Aggregate product rating. + """ + tags: list[str] | None = None + """ + Product tags for categorization and search. + """ + metadata: dict[str, Any] | None = None + """ + Business-defined custom data extending the standard product model. + """ + + +class Buyer(BaseModel): + model_config = ConfigDict( + extra="allow", + ) + first_name: str | None = None + """ + First name of the buyer. + """ + last_name: str | None = None + """ + Last name of the buyer. + """ + email: str | None = None + """ + Email of the buyer. + """ + phone_number: str | None = None + """ + E.164 standard. """ consent: Consent | None = None """ @@ -7289,100 +8021,203 @@ class Cart(BaseModel): """ links: list[Link] | None = None """ - Optional merchant links (policies, FAQs). + Optional merchant links (policies, FAQs). + """ + policies: list[PurchaseOptionsPoliciesItem] | None = None + """ + Policies (e.g., return/refund terms) that apply to the items in this cart. `applies_to` targets are relative to the response root; when absent or empty, refer to the URLs in `links[]`. + """ + continue_url: AnyUrl | None = None + """ + URL for cart handoff and session recovery. Enables sharing and human-in-the-loop flows. + """ + expires_at: AwareDatetime | None = None + """ + Cart expiry timestamp (RFC 3339). Optional. + """ + loyalty: Loyalty | None = None + discounts: DiscountsObject | None = None + + +class CartCreateRequest(BaseModel): + """ + Request payload to create a new Cart. Shopping cart with estimated pricing before checkout. Lightweight pre-purchase exploration with no payment info or complex status states. + """ + + model_config = ConfigDict( + extra="allow", + ) + line_items: list[LineItemCreateRequest] + """ + Cart line items. Same structure as checkout. Full replacement on update. + """ + context: Context | None = None + """ + Buyer signals for localization (country, region, postal_code). Merchant uses for pricing, availability, currency. Falls back to geo-IP if omitted. + """ + signals: Signals | None = None + attribution: Attribution | None = None + buyer: Buyer | None = None + """ + Buyer with consent tracking. + """ + discounts: DiscountsObjectCreateRequest | None = None + + +class CartUpdateRequest(BaseModel): + """ + Request payload to update an existing Cart. Shopping cart with estimated pricing before checkout. Lightweight pre-purchase exploration with no payment info or complex status states. + """ + + model_config = ConfigDict( + extra="allow", + ) + line_items: list[LineItemUpdateRequest] + """ + Cart line items. Same structure as checkout. Full replacement on update. + """ + context: Context | None = None + """ + Buyer signals for localization (country, region, postal_code). Merchant uses for pricing, availability, currency. Falls back to geo-IP if omitted. + """ + signals: Signals | None = None + attribution: Attribution | None = None + buyer: Buyer | None = None + """ + Buyer with consent tracking. + """ + discounts: DiscountsObjectUpdateRequest | None = None + + +class CatalogGetProductResponse(BaseModel): + model_config = ConfigDict( + extra="allow", + ) + ucp: ResponseCatalogSchema + product: PurchaseOptionsDetailProduct + """ + The requested product with full detail. Singular — this is a single-resource operation. + """ + actions: Actions | None = None + """ + Outstanding extension-defined Actions for this product response. + """ + messages: list[Message] | None = None + """ + Warnings or informational messages about the product (e.g., price recently changed, limited availability). + """ + policies: list[PurchaseOptionsPoliciesItem] | None = None + """ + Policies (e.g., return/refund terms) that apply to this product. `applies_to` targets are relative to the response root; when absent or empty, refer to the URLs in `links[]`. + """ + loyalty: Loyalty | None = None + + +class CatalogLookupResponse(BaseModel): + model_config = ConfigDict( + extra="allow", + ) + ucp: ResponseCatalogSchema + products: list[PurchaseOptionsLookupProduct] + """ + Products matching the requested identifiers. May contain fewer items if some identifiers not found, or more if identifiers match multiple products. """ - policies: list[Policy] | None = None + actions: Actions | None = None """ - Policies (e.g., return/refund terms) that apply to the items in this cart. `applies_to` targets are relative to the response root; when absent or empty, refer to the URLs in `links[]`. + Outstanding extension-defined Actions for this catalog lookup response. """ - continue_url: AnyUrl | None = None + messages: list[Message] | None = None """ - URL for cart handoff and session recovery. Enables sharing and human-in-the-loop flows. + Errors, warnings, or informational messages about the requested items. """ - expires_at: AwareDatetime | None = None + policies: list[PurchaseOptionsPoliciesItem] | None = None """ - Cart expiry timestamp (RFC 3339). Optional. + Policies (e.g., return/refund terms) that apply to the products in this response. `applies_to` targets are relative to the response root; when absent or empty, refer to the URLs in `links[]`. """ loyalty: Loyalty | None = None - discounts: DiscountsObject | None = None -class CartCreateRequest(BaseModel): - """ - Request payload to create a new Cart. Shopping cart with estimated pricing before checkout. Lightweight pre-purchase exploration with no payment info or complex status states. - """ - +class CatalogSearchResponse(BaseModel): model_config = ConfigDict( extra="allow", ) - line_items: list[LineItemCreateRequest] + ucp: ResponseCatalogSchema + products: list[PurchaseOptionsProduct] """ - Cart line items. Same structure as checkout. Full replacement on update. + Products matching the search criteria. """ - context: Context | None = None + pagination: PaginationResponse | None = None + actions: Actions | None = None """ - Buyer signals for localization (country, region, postal_code). Merchant uses for pricing, availability, currency. Falls back to geo-IP if omitted. + Outstanding extension-defined Actions for this catalog search response. """ - signals: Signals | None = None - attribution: Attribution | None = None - buyer: Buyer | None = None + messages: list[Message] | None = None """ - Buyer with consent tracking. + Errors, warnings, or informational messages about the search results. """ - discounts: DiscountsObjectCreateRequest | None = None + policies: list[PurchaseOptionsPoliciesItem] | None = None + """ + Policies (e.g., return/refund terms) that apply to the products in these search results. `applies_to` targets are relative to the response root; when absent or empty, refer to the URLs in `links[]`. + """ + loyalty: Loyalty | None = None -class CartUpdateRequest(BaseModel): +class CheckoutCompleteRequest(BaseModel): """ - Request payload to update an existing Cart. Shopping cart with estimated pricing before checkout. Lightweight pre-purchase exploration with no payment info or complex status states. + Request payload to complete a Checkout. Base checkout schema. Extensions compose onto this using allOf. """ model_config = ConfigDict( extra="allow", ) - line_items: list[LineItemUpdateRequest] - """ - Cart line items. Same structure as checkout. Full replacement on update. - """ - context: Context | None = None + buyer: Buyer | None = None """ - Buyer signals for localization (country, region, postal_code). Merchant uses for pricing, availability, currency. Falls back to geo-IP if omitted. + Buyer with consent tracking. """ signals: Signals | None = None attribution: Attribution | None = None - buyer: Buyer | None = None + payment: PaymentCompleteRequest """ - Buyer with consent tracking. + Payment details with available and selected payment terms. """ - discounts: DiscountsObjectUpdateRequest | None = None + ap2: Ap2WithCheckoutMandateCompleteRequest | None = None -class CheckoutCompleteRequest(BaseModel): +class CheckoutCreateRequestLineItems(BaseModel): """ - Request payload to complete a Checkout. Base checkout schema. Extensions compose onto this using allOf. + Request payload to create a new Checkout. Base checkout schema. Extensions compose onto this using allOf. """ model_config = ConfigDict( extra="allow", ) + line_items: list[LineItemCreateRequest] + """ + List of line items being checked out. In create requests, the Platform MUST include line_items or cart_id and MAY include both. The Platform MUST include line_items in update requests and omits it from complete requests. The Business MUST include line_items in checkout responses. + """ + cart_id: str | None = None + """ + Cart ID for checkout initialization. The Business MUST reject requests using it without negotiated Cart support. Cart contents take precedence over overlapping checkout fields; line_items may be omitted or empty. + """ buyer: Buyer | None = None """ Buyer with consent tracking. """ + context: Context | None = None signals: Signals | None = None attribution: Attribution | None = None - payment: PaymentCompleteRequest + payment: PaymentCreateRequest | None = None """ Payment details with available and selected payment terms. """ - cart_id: str | None = Field(None, deprecated=True) + discounts: DiscountsObjectCreateRequest | None = None + fulfillment: FulfillmentCreateRequest | None = None """ - Cart ID to convert to checkout. Business MUST use cart contents (line_items, context, buyer) and MUST ignore overlapping fields in checkout payload. + Fulfillment details. """ - ap2: Ap2WithCheckoutMandateCompleteRequest | None = None -class CheckoutCreateRequest(BaseModel): +class CheckoutCreateRequestCartId(BaseModel): """ Request payload to create a new Checkout. Base checkout schema. Extensions compose onto this using allOf. """ @@ -7390,9 +8225,13 @@ class CheckoutCreateRequest(BaseModel): model_config = ConfigDict( extra="allow", ) - line_items: list[LineItemCreateRequest] + line_items: list[LineItemCreateRequest] | None = None + """ + List of line items being checked out. In create requests, the Platform MUST include line_items or cart_id and MAY include both. The Platform MUST include line_items in update requests and omits it from complete requests. The Business MUST include line_items in checkout responses. """ - List of line items being checked out. + cart_id: str + """ + Cart ID for checkout initialization. The Business MUST reject requests using it without negotiated Cart support. Cart contents take precedence over overlapping checkout fields; line_items may be omitted or empty. """ buyer: Buyer | None = None """ @@ -7405,10 +8244,6 @@ class CheckoutCreateRequest(BaseModel): """ Payment details with available and selected payment terms. """ - cart_id: str | None = None - """ - Cart ID to convert to checkout. Business MUST use cart contents (line_items, context, buyer) and MUST ignore overlapping fields in checkout payload. - """ discounts: DiscountsObjectCreateRequest | None = None fulfillment: FulfillmentCreateRequest | None = None """ @@ -7416,6 +8251,18 @@ class CheckoutCreateRequest(BaseModel): """ +CheckoutCreateRequest = TypeAliasType( + "CheckoutCreateRequest", + Annotated[ + CheckoutCreateRequestLineItems | CheckoutCreateRequestCartId, + Field(..., title="CheckoutCreateRequest"), + ], +) +""" +Request payload to create a new Checkout. Base checkout schema. Extensions compose onto this using allOf. +""" + + class CheckoutUpdateRequest(BaseModel): """ Request payload to update an existing Checkout. Base checkout schema. Extensions compose onto this using allOf. @@ -7426,7 +8273,7 @@ class CheckoutUpdateRequest(BaseModel): ) line_items: list[LineItemUpdateRequest] """ - List of line items being checked out. + List of line items being checked out. In create requests, the Platform MUST include line_items or cart_id and MAY include both. The Platform MUST include line_items in update requests and omits it from complete requests. The Business MUST include line_items in checkout responses. """ buyer: Buyer | None = None """ @@ -7446,22 +8293,16 @@ class CheckoutUpdateRequest(BaseModel): """ -class Fulfillment(BaseModel): - """ - Container for fulfillment methods and availability. - """ - - model_config = ConfigDict( - extra="allow", - ) - methods: list[FulfillmentMethod] | None = None - """ - Fulfillment methods for cart items. - """ - available_methods: list[FulfillmentAvailableMethod] | None = None - """ - Inventory availability hints. - """ +FulfillmentDestination = TypeAliasType( + "FulfillmentDestination", + Annotated[ + LocationDestination | ShippingDestination | FulfillmentDestinationBase, + Field(..., title="FulfillmentDestination"), + ], +) +""" +A destination for fulfillment. +""" class FulfillmentDetailProduct(BaseModel): @@ -7502,7 +8343,7 @@ class FulfillmentDetailProduct(BaseModel): """ list_price_range: PriceRange | None = None """ - List price range before discounts (for strikethrough display). + Range of variant `list_price` values across all variants; see `variant.list_price`. The range MUST use the same currency as `price_range`. """ media: list[Media] | None = None """ @@ -7572,7 +8413,7 @@ class FulfillmentLookupProduct(BaseModel): """ list_price_range: PriceRange | None = None """ - List price range before discounts (for strikethrough display). + Range of variant `list_price` values across all variants; see `variant.list_price`. The range MUST use the same currency as `price_range`. """ media: list[Media] | None = None """ @@ -7600,6 +8441,40 @@ class FulfillmentLookupProduct(BaseModel): """ +class FulfillmentMethodBase(BaseModel): + """ + A fulfillment method with destinations and groups. + """ + + model_config = ConfigDict( + extra="allow", + ) + id: str + """ + Unique fulfillment method identifier. + """ + type: str + """ + Fulfillment method type. Well-known values: `shipping`, `pickup`. Businesses MAY use additional values. + """ + line_item_ids: list[str] + """ + Line item IDs fulfilled via this method. + """ + destinations: list[FulfillmentDestination] | None = None + """ + Available destinations for this method. In Business responses, each destination carries a `type` and `id`. + """ + selected_destination_id: str | None = None + """ + ID of the selected destination. Accepts any stable, Business-scoped ID the Business recognizes for this method, including Location IDs not yet enumerated in `destinations`. + """ + groups: list[FulfillmentGroup] | None = None + """ + Fulfillment groups for selecting options. Agent sets selected_option_id on groups to choose shipping method. + """ + + class FulfillmentProduct(BaseModel): """ A catalog product whose variants are fulfillment-enriched. Used by search. @@ -7638,7 +8513,7 @@ class FulfillmentProduct(BaseModel): """ list_price_range: PriceRange | None = None """ - List price range before discounts (for strikethrough display). + Range of variant `list_price` values across all variants; see `variant.list_price`. The range MUST use the same currency as `price_range`. """ media: list[Media] | None = None """ @@ -7666,77 +8541,112 @@ class FulfillmentProduct(BaseModel): """ -class CatalogGetProductResponse(BaseModel): +class LocationLookupResponse(BaseModel): model_config = ConfigDict( extra="allow", ) - ucp: ResponseCatalogSchema - product: FulfillmentDetailProduct - """ - The requested product with full detail. Singular — this is a single-resource operation. - """ - actions: Actions | None = None + ucp: ResponseLocationSchema + locations: list[LookupLocation] """ - Outstanding extension-defined Actions for this product response. + Locations matching the requested identifiers and refinements. May contain fewer Locations if some identifiers do not resolve or their resolved Locations are filtered out, or more if one identifier resolves to multiple Locations. When multiple identifiers resolve to the same Location, one returned Location carries all corresponding `inputs` entries. """ messages: list[Message] | None = None """ - Warnings or informational messages about the product (e.g., price recently changed, limited availability). + Errors, warnings, or informational messages about the requested Locations, including `batch_limit_applied` when the Business processes only its configured maximum number of identifiers. """ - policies: list[Policy] | None = None + + +class Order(BaseModel): """ - Policies (e.g., return/refund terms) that apply to this product. `applies_to` targets are relative to the response root; when absent or empty, refer to the URLs in `links[]`. + Order schema with line items, buyer-facing fulfillment expectations, and event logs. """ - loyalty: Loyalty | None = None - -class CatalogLookupResponse(BaseModel): model_config = ConfigDict( extra="allow", ) - ucp: ResponseCatalogSchema - products: list[FulfillmentLookupProduct] + ucp: ResponseOrderSchema + id: str """ - Products matching the requested identifiers. May contain fewer items if some identifiers not found, or more if identifiers match multiple products. + Unique order identifier. """ - actions: Actions | None = None + label: str | None = None """ - Outstanding extension-defined Actions for this catalog lookup response. + Human-readable label for identifying the order. MUST only be provided by the business. + """ + checkout_id: str + """ + Associated checkout ID for reconciliation. + """ + permalink_url: AnyUrl + """ + Permalink to access the order on merchant site. + """ + line_items: list[OrderLineItem] + """ + Line items representing what was purchased — can change post-order via edits or exchanges. + """ + fulfillment: OrderFulfillment = Field(..., title="OrderFulfillment") + """ + Fulfillment data: buyer expectations and what actually happened. + """ + adjustments: list[Adjustment] | None = None + """ + Post-order events (refunds, returns, credits, disputes, cancellations, etc.) that exist independently of fulfillment. + """ + currency: str + """ + ISO 4217 currency code. MUST match the currency from the originating checkout session. + """ + totals: Totals + """ + Different totals for the order. + """ + policies: list[PurchaseOptionsPoliciesItem] | None = None + """ + Snapshot of the policies that applied to the items at checkout, captured on the order as a durable record. `applies_to` targets are relative to the response root. """ messages: list[Message] | None = None """ - Errors, warnings, or informational messages about the requested items. + Business outcome messages (errors, warnings, informational). Present when the business needs to communicate status or issues to the platform. """ - policies: list[Policy] | None = None + attribution: Attribution | None = None """ - Policies (e.g., return/refund terms) that apply to the products in this response. `applies_to` targets are relative to the response root; when absent or empty, refer to the URLs in `links[]`. + Snapshot of the attribution associated with the originating checkout. Read-only on the order. + """ + payment: OrderPayment | None = None + """ + Payment details for the Order, including the accepted payment term. """ - loyalty: Loyalty | None = None -class CatalogSearchResponse(BaseModel): +FulfillmentMethod = TypeAliasType( + "FulfillmentMethod", + Annotated[ + PickupMethod | ShippingMethod | FulfillmentMethodBase, + Field(..., title="FulfillmentMethod"), + ], +) +""" +A fulfillment method with destinations and groups. +""" + + +class Fulfillment(BaseModel): + """ + Container for fulfillment methods and availability. + """ + model_config = ConfigDict( extra="allow", ) - ucp: ResponseCatalogSchema - products: list[FulfillmentProduct] - """ - Products matching the search criteria. - """ - pagination: PaginationResponse | None = None - actions: Actions | None = None - """ - Outstanding extension-defined Actions for this catalog search response. - """ - messages: list[Message] | None = None + methods: list[FulfillmentMethod] | None = None """ - Errors, warnings, or informational messages about the search results. + Fulfillment methods for cart items. """ - policies: list[Policy] | None = None + available_methods: list[FulfillmentAvailableMethod] | None = None """ - Policies (e.g., return/refund terms) that apply to the products in these search results. `applies_to` targets are relative to the response root; when absent or empty, refer to the URLs in `links[]`. + Inventory availability hints. """ - loyalty: Loyalty | None = None class Checkout(BaseModel): @@ -7754,7 +8664,7 @@ class Checkout(BaseModel): """ line_items: list[LineItem] """ - List of line items being checked out. + List of line items being checked out. In create requests, the Platform MUST include line_items or cart_id and MAY include both. The Platform MUST include line_items in update requests and omits it from complete requests. The Business MUST include line_items in checkout responses. """ buyer: Buyer | None = None """ @@ -7794,7 +8704,7 @@ class Checkout(BaseModel): """ Links to be displayed by the platform (Privacy Policy, TOS). Mandatory for legal compliance. """ - policies: list[Policy] | None = None + policies: list[PurchaseOptionsPoliciesItem] | None = None """ Policies (e.g., return/refund terms) that apply to the items in this checkout. `applies_to` targets are relative to the response root; when absent or empty, refer to the URLs in `links[]`. """ @@ -7814,10 +8724,6 @@ class Checkout(BaseModel): """ Details about an order created for this checkout session. """ - cart_id: str | None = None - """ - Cart ID to convert to checkout. Business MUST use cart contents (line_items, context, buyer) and MUST ignore overlapping fields in checkout payload. - """ loyalty: Loyalty | None = None ap2: Ap2 | None = None discounts: DiscountsObject | None = None diff --git a/tests/test_models.py b/tests/test_models.py index b3dc009..6c24406 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -16,14 +16,19 @@ from __future__ import annotations +import importlib +from importlib.metadata import PackageNotFoundError +import json import os from pathlib import Path import subprocess import sys from typing import Any import unittest +from unittest.mock import patch from pydantic import TypeAdapter, ValidationError +import ucp_sdk import ucp_sdk.models as models_module from ucp_sdk.models import ( Ap2WithCheckoutMandateCompleteRequest, @@ -176,75 +181,88 @@ def test_complete_request_requires_valid_checkout_mandate_when_ap2_present( assert isinstance(req.ap2, Ap2WithCheckoutMandateCompleteRequest) self.assertEqual(req.ap2.checkout_mandate, mandate) - def test_complete_request_buyer_optional_and_cart_id_deprecated( + def test_complete_request_buyer_optional_and_cart_id_channel_behavior( self, ) -> None: + lock = json.loads( + (Path(__file__).resolve().parents[1] / "ucp-lock.json").read_text( + encoding="utf-8" + ) + ) req = CheckoutCompleteRequest.model_validate( { "payment": self.PAYMENT_PAYLOAD, "buyer": {"email": "buyer@example.com"}, } ) - self.assertIsNotNone(req.buyer) assert req.buyer is not None self.assertEqual(str(req.buyer.email), "buyer@example.com") - self.assertTrue( - CheckoutCompleteRequest.model_fields["cart_id"].deprecated - ) - with self.assertWarns(DeprecationWarning): - self.assertIsNone(req.cart_id) + if lock.get("ucp_ref") == "release/2026-08-25": + field = CheckoutCompleteRequest.model_fields["cart_id"] + self.assertIsNone(field.default) + self.assertTrue(bool(field.deprecated)) + with self.assertRaises(ValidationError): + CheckoutCompleteRequest.model_validate( + {"payment": self.PAYMENT_PAYLOAD, "cart_id": 123} + ) + else: + self.assertNotIn("cart_id", CheckoutCompleteRequest.model_fields) - def test_complete_request_explicit_cart_id_and_extra_fields(self) -> None: + def test_complete_request_preserves_extra_fields(self) -> None: req = CheckoutCompleteRequest.model_validate( { "payment": self.PAYMENT_PAYLOAD, - "cart_id": "cart_123", "com.example.trace_id": "trace_abc", } ) - with self.assertWarns(DeprecationWarning): - self.assertEqual(req.cart_id, "cart_123") dumped = req.model_dump(exclude_none=True) - self.assertEqual(dumped["cart_id"], "cart_123") self.assertEqual(dumped["com.example.trace_id"], "trace_abc") + def test_create_request_validation_and_line_items_or_cart_id_variants( + self, + ) -> None: + create_adapter: TypeAdapter[Any] = TypeAdapter(CheckoutCreateRequest) with self.assertRaises(ValidationError): - CheckoutCompleteRequest.model_validate( - {"payment": self.PAYMENT_PAYLOAD, "cart_id": 12345} - ) - - def test_create_request_validation_and_non_deprecated_cart_id(self) -> None: - with self.assertRaises(ValidationError) as ctx: - CheckoutCreateRequest.model_validate({}) - error_locs = [err["loc"] for err in ctx.exception.errors()] - self.assertIn(("line_items",), error_locs) + create_adapter.validate_python({}) for bad_line_item in ( {"item": {"id": "sku_1"}, "quantity": 0}, {"quantity": 1}, ): with self.assertRaises(ValidationError): - CheckoutCreateRequest.model_validate( - {"line_items": [bad_line_item]} - ) + create_adapter.validate_python({"line_items": [bad_line_item]}) - self.assertFalse( - bool(CheckoutCreateRequest.model_fields["cart_id"].deprecated) - ) - req = CheckoutCreateRequest.model_validate( + req_both = create_adapter.validate_python( { "line_items": [{"item": {"id": "sku_1"}, "quantity": 2}], "cart_id": "cart_live_1", "com.example.channel": "mobile_web", } ) - self.assertEqual(req.cart_id, "cart_live_1") - self.assertEqual(len(req.line_items), 1) - self.assertEqual(req.line_items[0].item.id, "sku_1") - self.assertEqual(req.line_items[0].quantity, 2) - dumped = req.model_dump(exclude_none=True) + self.assertEqual(req_both.cart_id, "cart_live_1") + assert req_both.line_items is not None + self.assertEqual(len(req_both.line_items), 1) + self.assertEqual(req_both.line_items[0].item.id, "sku_1") + self.assertEqual(req_both.line_items[0].quantity, 2) + dumped = req_both.model_dump(exclude_none=True) self.assertEqual(dumped["com.example.channel"], "mobile_web") + if hasattr(models_module, "CheckoutCreateRequestLineItems"): + self.assertIsInstance( + req_both, models_module.CheckoutCreateRequestLineItems + ) + req_cart = create_adapter.validate_python( + {"cart_id": "cart_only_1"} + ) + self.assertIsInstance( + req_cart, models_module.CheckoutCreateRequestCartId + ) + self.assertEqual(req_cart.cart_id, "cart_only_1") + self.assertIsNone(req_cart.line_items) + else: + with self.assertRaises(ValidationError): + create_adapter.validate_python({"cart_id": "cart_only_1"}) + class MediaModelTest(unittest.TestCase): """Tests for consolidated Media open discriminated union and variants.""" @@ -965,5 +983,77 @@ def test_dto_openness_preserves_extra_fields(self) -> None: ) +class LockfileAndVersionContractTest(unittest.TestCase): + """Tests for ucp-lock.json provenance invariants and ucp_sdk.__version__.""" + + def test_ucp_lock_json_schema_and_formatting_invariants(self) -> None: + lock_path = Path(__file__).resolve().parents[1] / "ucp-lock.json" + raw = lock_path.read_text(encoding="utf-8") + data = json.loads(raw) + self.assertEqual(raw, json.dumps(data, indent=2) + "\n") + self.assertEqual( + list(data.keys()), + [ + "channel", + "ucp_ref", + "ucp_sha", + "ucp_schema_version", + "vertical", + ], + ) + self.assertIn(data["channel"], ("draft", "release")) + expected_ref = ( + r"^main$" + if data["channel"] == "draft" + else r"^release/[0-9]{4}-[0-9]{2}-[0-9]{2}$" + ) + self.assertRegex(data["ucp_ref"], expected_ref) + self.assertRegex(data["ucp_sha"], r"^[0-9a-f]{40}$") + self.assertRegex( + data["ucp_schema_version"], r"^[0-9]+\.[0-9]+\.[0-9]+$" + ) + self.assertEqual(data["vertical"], "shopping") + + def test_package_version_resolution_and_fallback(self) -> None: + self.assertTrue(ucp_sdk.__version__) + with patch( + "importlib.metadata.version", + side_effect=PackageNotFoundError("ucp-sdk"), + ): + importlib.reload(ucp_sdk) + self.assertEqual(ucp_sdk.__version__, "0.0.0.dev0") + importlib.reload(ucp_sdk) + + def test_generate_models_cli_rejects_positionals_and_invalid_flag_combos( + self, + ) -> None: + script = ( + Path(__file__).resolve().parents[1] / "scripts/generate_models.py" + ) + for bad_args in ( + ["draft"], + ["--unknown-flag"], + ["--from-lock", "--ref", "main"], + ["--from-lock", "--write-lock"], + ["--write-lock"], + ["--spec-dir", ".", "--write-lock"], + ["--channel", "draft"], + ): + proc = subprocess.run( + [sys.executable, str(script), *bad_args], + capture_output=True, + text=True, + ) + self.assertNotEqual(proc.returncode, 0, msg=f"args={bad_args}") + + bad_bin = subprocess.run( + [sys.executable, str(script), "--from-lock"], + env={**os.environ, "UCP_SCHEMA_BIN": "/nonexistent/ucp-schema"}, + capture_output=True, + text=True, + ) + self.assertNotEqual(bad_bin.returncode, 0) + + if __name__ == "__main__": unittest.main() diff --git a/ucp-lock.json b/ucp-lock.json new file mode 100644 index 0000000..682cb23 --- /dev/null +++ b/ucp-lock.json @@ -0,0 +1,7 @@ +{ + "channel": "draft", + "ucp_ref": "main", + "ucp_sha": "1be6f778131e732646046b19fa689c2834df2636", + "ucp_schema_version": "2.0.0", + "vertical": "shopping" +}