From 4cf232c48a8af1d314a591e5f289574c8e558e9e Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 08:59:54 +0200 Subject: [PATCH 001/135] feat!: shopify_api 1.0, operations checked against Shopify's schema at compile time A rewrite around a `graphql!` macro that checks each query or mutation against the bundled Admin schema (2026-10) and generates the types of its variables and result. See MIGRATION.md for the move from 0.10. - Workspace of three crates released together: shopify_api, shopify_api_macros and shopify_api_graphql (schema, analyzer, codegen). - Deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason; directives come from the schema. - Operations go to the version of the schema they were checked against; `shopify-api schema download` stores another version, `check` validates .graphql files. - Tokens: static, client credentials, expiring with refresh; renewed in a task of its own, once for all clones, saved through a TokenStore. - Retries: throttling waits for its cost, 429 for Retry-After, queries after 5xx or network failures, never a mutation. - Pagination, bulk operations, webhooks (verification, subscription sync), OAuth and session tokens, MockTransport for tests. - Errors never hold secrets or signed query strings. - mise.toml for the toolchain and tasks; CI runs `mise run check`. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 108 +- .github/workflows/publish.yml | 29 +- CHANGELOG.md | 23 + Cargo.lock | 522 +-- Cargo.toml | 96 +- MIGRATION.md | 145 + README.md | 367 +- crates/shopify_api/Cargo.toml | 75 + crates/shopify_api/docs/graphql.md | 229 + crates/shopify_api/examples/bulk_export.rs | 58 + crates/shopify_api/examples/products.rs | 47 + crates/shopify_api/src/auth.rs | 667 +++ crates/shopify_api/src/bin/shopify-api.rs | 298 ++ crates/shopify_api/src/bulk.rs | 760 ++++ crates/shopify_api/src/client.rs | 465 +++ crates/shopify_api/src/error.rs | 276 ++ crates/shopify_api/src/graphql.rs | 219 + crates/shopify_api/src/graphql/operation.rs | 538 +++ crates/shopify_api/src/graphql/response.rs | 222 + crates/shopify_api/src/lib.rs | 101 + crates/shopify_api/src/oauth.rs | 884 ++++ crates/shopify_api/src/pagination.rs | 97 + crates/shopify_api/src/schema.rs | 134 + crates/shopify_api/src/shop.rs | 171 + crates/shopify_api/src/testing.rs | 212 + crates/shopify_api/src/transport.rs | 372 ++ crates/shopify_api/src/version.rs | 220 + crates/shopify_api/src/webhooks.rs | 739 ++++ crates/shopify_api/tests/auth.rs | 430 ++ crates/shopify_api/tests/bulk.rs | 266 ++ crates/shopify_api/tests/compile_fail.rs | 8 + crates/shopify_api/tests/graphql.rs | 368 ++ .../shopify_api/tests/graphql/order.graphql | 7 + crates/shopify_api/tests/live.rs | 85 + crates/shopify_api/tests/oauth.rs | 127 + crates/shopify_api/tests/pagination.rs | 99 + crates/shopify_api/tests/retry.rs | 149 + .../tests/ui/deprecated_field_denied.rs | 5 + .../tests/ui/deprecated_field_denied.stderr | 11 + .../tests/ui/integer_out_of_range.rs | 3 + .../tests/ui/integer_out_of_range.stderr | 6 + crates/shopify_api/tests/ui/missing_file.rs | 5 + .../shopify_api/tests/ui/missing_file.stderr | 5 + .../shopify_api/tests/ui/missing_variable.rs | 3 + .../tests/ui/missing_variable.stderr | 5 + crates/shopify_api/tests/ui/subscription.rs | 3 + .../shopify_api/tests/ui/subscription.stderr | 6 + crates/shopify_api/tests/ui/syntax_error.rs | 3 + .../shopify_api/tests/ui/syntax_error.stderr | 6 + .../tests/ui/unknown_enum_value.rs | 3 + .../tests/ui/unknown_enum_value.stderr | 6 + crates/shopify_api/tests/ui/unknown_field.rs | 3 + .../shopify_api/tests/ui/unknown_field.stderr | 6 + .../shopify_api/tests/ui/unknown_variable.rs | 3 + .../tests/ui/unknown_variable.stderr | 5 + .../shopify_api/tests/ui/unselected_field.rs | 6 + .../tests/ui/unselected_field.stderr | 7 + .../shopify_api/tests/ui/wrong_value_type.rs | 3 + .../tests/ui/wrong_value_type.stderr | 29 + crates/shopify_api/tests/webhooks.rs | 128 + crates/shopify_api_graphql/Cargo.toml | 24 + crates/shopify_api_graphql/README.md | 11 + .../schema/admin-2026-10.json | 3711 +++++++++++++++++ crates/shopify_api_graphql/src/analyze.rs | 1134 +++++ crates/shopify_api_graphql/src/codegen.rs | 449 ++ crates/shopify_api_graphql/src/lib.rs | 49 + crates/shopify_api_graphql/src/schema.rs | 1140 +++++ crates/shopify_api_graphql/tests/analyze.rs | 695 +++ crates/shopify_api_macros/Cargo.toml | 27 + crates/shopify_api_macros/README.md | 5 + crates/shopify_api_macros/src/lib.rs | 751 ++++ deny.toml | 31 + mise.toml | 59 + schema_dl.graphql | 107 - src/auth.rs | 293 -- src/bin/shopify-api.rs | 97 - src/graphql/bulk_query.rs | 562 --- src/graphql/mod.rs | 146 - src/graphql/types.rs | 12 - src/lib.rs | 284 -- src/schema.rs | 42 - src/utils.rs | 228 - src/webhooks/frameworks/mod.rs | 325 -- src/webhooks/frameworks/warp.rs | 129 - src/webhooks/mod.rs | 13 - src/webhooks/verify.rs | 27 - src/webhooks/webhook.rs | 217 - tests/live.rs | 213 - 88 files changed, 17316 insertions(+), 3338 deletions(-) create mode 100644 MIGRATION.md create mode 100644 crates/shopify_api/Cargo.toml create mode 100644 crates/shopify_api/docs/graphql.md create mode 100644 crates/shopify_api/examples/bulk_export.rs create mode 100644 crates/shopify_api/examples/products.rs create mode 100644 crates/shopify_api/src/auth.rs create mode 100644 crates/shopify_api/src/bin/shopify-api.rs create mode 100644 crates/shopify_api/src/bulk.rs create mode 100644 crates/shopify_api/src/client.rs create mode 100644 crates/shopify_api/src/error.rs create mode 100644 crates/shopify_api/src/graphql.rs create mode 100644 crates/shopify_api/src/graphql/operation.rs create mode 100644 crates/shopify_api/src/graphql/response.rs create mode 100644 crates/shopify_api/src/lib.rs create mode 100644 crates/shopify_api/src/oauth.rs create mode 100644 crates/shopify_api/src/pagination.rs create mode 100644 crates/shopify_api/src/schema.rs create mode 100644 crates/shopify_api/src/shop.rs create mode 100644 crates/shopify_api/src/testing.rs create mode 100644 crates/shopify_api/src/transport.rs create mode 100644 crates/shopify_api/src/version.rs create mode 100644 crates/shopify_api/src/webhooks.rs create mode 100644 crates/shopify_api/tests/auth.rs create mode 100644 crates/shopify_api/tests/bulk.rs create mode 100644 crates/shopify_api/tests/compile_fail.rs create mode 100644 crates/shopify_api/tests/graphql.rs create mode 100644 crates/shopify_api/tests/graphql/order.graphql create mode 100644 crates/shopify_api/tests/live.rs create mode 100644 crates/shopify_api/tests/oauth.rs create mode 100644 crates/shopify_api/tests/pagination.rs create mode 100644 crates/shopify_api/tests/retry.rs create mode 100644 crates/shopify_api/tests/ui/deprecated_field_denied.rs create mode 100644 crates/shopify_api/tests/ui/deprecated_field_denied.stderr create mode 100644 crates/shopify_api/tests/ui/integer_out_of_range.rs create mode 100644 crates/shopify_api/tests/ui/integer_out_of_range.stderr create mode 100644 crates/shopify_api/tests/ui/missing_file.rs create mode 100644 crates/shopify_api/tests/ui/missing_file.stderr create mode 100644 crates/shopify_api/tests/ui/missing_variable.rs create mode 100644 crates/shopify_api/tests/ui/missing_variable.stderr create mode 100644 crates/shopify_api/tests/ui/subscription.rs create mode 100644 crates/shopify_api/tests/ui/subscription.stderr create mode 100644 crates/shopify_api/tests/ui/syntax_error.rs create mode 100644 crates/shopify_api/tests/ui/syntax_error.stderr create mode 100644 crates/shopify_api/tests/ui/unknown_enum_value.rs create mode 100644 crates/shopify_api/tests/ui/unknown_enum_value.stderr create mode 100644 crates/shopify_api/tests/ui/unknown_field.rs create mode 100644 crates/shopify_api/tests/ui/unknown_field.stderr create mode 100644 crates/shopify_api/tests/ui/unknown_variable.rs create mode 100644 crates/shopify_api/tests/ui/unknown_variable.stderr create mode 100644 crates/shopify_api/tests/ui/unselected_field.rs create mode 100644 crates/shopify_api/tests/ui/unselected_field.stderr create mode 100644 crates/shopify_api/tests/ui/wrong_value_type.rs create mode 100644 crates/shopify_api/tests/ui/wrong_value_type.stderr create mode 100644 crates/shopify_api/tests/webhooks.rs create mode 100644 crates/shopify_api_graphql/Cargo.toml create mode 100644 crates/shopify_api_graphql/README.md create mode 100644 crates/shopify_api_graphql/schema/admin-2026-10.json create mode 100644 crates/shopify_api_graphql/src/analyze.rs create mode 100644 crates/shopify_api_graphql/src/codegen.rs create mode 100644 crates/shopify_api_graphql/src/lib.rs create mode 100644 crates/shopify_api_graphql/src/schema.rs create mode 100644 crates/shopify_api_graphql/tests/analyze.rs create mode 100644 crates/shopify_api_macros/Cargo.toml create mode 100644 crates/shopify_api_macros/README.md create mode 100644 crates/shopify_api_macros/src/lib.rs create mode 100644 deny.toml create mode 100644 mise.toml delete mode 100644 schema_dl.graphql delete mode 100644 src/auth.rs delete mode 100644 src/bin/shopify-api.rs delete mode 100644 src/graphql/bulk_query.rs delete mode 100644 src/graphql/mod.rs delete mode 100644 src/graphql/types.rs delete mode 100644 src/lib.rs delete mode 100644 src/schema.rs delete mode 100644 src/utils.rs delete mode 100644 src/webhooks/frameworks/mod.rs delete mode 100644 src/webhooks/frameworks/warp.rs delete mode 100644 src/webhooks/mod.rs delete mode 100644 src/webhooks/verify.rs delete mode 100644 src/webhooks/webhook.rs delete mode 100644 tests/live.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f5e16c5..97f8fc0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,109 +7,37 @@ on: branches: - master +permissions: + contents: read + env: + CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - TEST_SHOP_NAME: "${{ secrets.TEST_SHOP_NAME }}" - TEST_KEY: "${{ secrets.TEST_KEY }}" - RUST_LOG: "debug" jobs: ci-pass: name: CI is green runs-on: ubuntu-latest needs: - - style - - test - - docs + - check + - msrv steps: - run: exit 0 - style: - name: Check Style - + check: + name: fmt, clippy, tests, docs runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v1 - - - name: Install rust - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - components: rustfmt - profile: minimal - override: true - - - name: cargo fmt -- --check - uses: actions-rs/cargo@v1 - with: - command: fmt - args: -- --check - - - name: temporary workaround - fmt all files under src - run: cargo fmt -- --check $(find . -name '*.rs' -print) - - test: - name: ${{ matrix.name }} - needs: [style] - - runs-on: ${{ matrix.os || 'ubuntu-latest' }} - - strategy: - matrix: - name: - - linux / stable - # - macOS / stable - - include: - - name: linux / stable - # - name: macOS / stable - # os: macOS-latest - steps: - - name: Checkout - uses: actions/checkout@v1 - - - name: Install rust - uses: actions-rs/toolchain@v1 - with: - toolchain: ${{ matrix.rust || 'stable' }} - target: ${{ matrix.target }} - profile: minimal - override: true - - - name: Build - uses: actions-rs/cargo@v1 - with: - command: build - args: ${{ matrix.features }} + - uses: actions/checkout@v4 + - uses: jdx/mise-action@v2 + - uses: Swatinem/rust-cache@v2 + - run: mise run check - - name: Test - uses: actions-rs/cargo@v1 - with: - command: test - args: ${{ matrix.features }} ${{ matrix.test-features }} -- --test-threads=1 - - docs: - name: Docs + msrv: + name: Rust 1.88 runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v2 - - - name: Install Rust - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - profile: minimal - override: true - - - name: Check documentation - env: - RUSTDOCFLAGS: -D warnings - uses: actions-rs/cargo@v1 - with: - command: doc - args: --no-deps --document-private-items --all-features + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@1.88 + - uses: Swatinem/rust-cache@v2 + - run: cargo check --workspace --all-features --locked diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 06e2908..e0dcd48 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -3,7 +3,11 @@ name: Release on: push: tags: - - "*" + - "v*" + - "[0-9]*" + +permissions: + contents: read jobs: call-ci: @@ -16,16 +20,15 @@ jobs: needs: - call-ci steps: - - name: Checkout sources - uses: actions/checkout@v2 - - - name: Install stable toolchain - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true - - - run: cargo publish --token ${CRATES_TOKEN} + - uses: actions/checkout@v4 + - uses: jdx/mise-action@v2 + # In dependency order: the schema and checker, the macro, then the client. + - run: cargo publish --locked -p shopify_api_graphql + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} + - run: cargo publish --locked -p shopify_api_macros + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} + - run: cargo publish --locked -p shopify_api env: - CRATES_TOKEN: ${{ secrets.CRATES_TOKEN }} + CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 967882e..9dc0420 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog +## 1.0.0 + +A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATION.md). + +- Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`, with typed input objects) or read from a file (`file("…graphql")`). +- Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. +- Add: the Admin schema 2026-10 is bundled (`shopify_api_graphql`); `shopify-api schema download` stores the schema of another version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. +- Add: `shopify-api check` checks `.graphql` files against the schema. +- Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`; queries are retried after a `5xx` or a network failure, mutations never. `RetryPolicy`. +- Add: tokens are renewed once for all the clones of a client, before they expire and when Shopify refuses one with a `401`. `Auth::expiring_token` with a `TokenStore`. +- Add: `Shopify::paginate`, `Page`. +- Add: bulk operations: `bulk_query_rows`, `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, typed `BulkOperation` and statuses, adaptive polling. +- Add: `webhooks`: `Webhook::verify` (headers, signature with secret rotation, payload), subscriptions with `sync_webhook_subscriptions`, which updates in place and creates before it deletes. +- Add: `oauth`: `ShopifyApp` with install links, callback and admin launch verification, code exchange, session tokens and token exchange, app proxies. +- Add: `Transport` trait, `ReqwestTransport` (redirections always off, `from_builder` for your own settings), and `testing::MockTransport`. +- Add: token renewals run in a task of their own: a cancelled request does not lose a rotated refresh token. A failed renewal answers the requests waiting for it. +- Add: errors never hold a query string (signed bulk result addresses stay out of logs); `Error::Http` carries Shopify's `X-Request-Id`. +- Add: `ShopDomain` refuses anything but `` or `.myshopify.com`. +- Breaking: `Shopify::new(shop, auth)` and `Shopify::builder`; `ShopifyAuth` is `Auth`; `ShopifyConfig` is gone; `ShopifyAPIError` is `Error`. +- Breaking: `graphql` returns `data` as a `Value` and `graphql_as` reads it as a type; `post_graphql` and the `graphql-client` feature are gone. +- Breaking: the warp wrapper, the webhook payload structs, `utils` (`retry_async`, `read_json_tree`) and `graphql_at_path` are gone. +- Breaking: Rust 1.88, edition 2024. + ## 0.10.1 - Security: refresh `Cargo.lock` to pick up fixes for RUSTSEC-2026-0185, -0285, -0338, -0339, -0340, -0342, -0346, -0348, -0349, -0382 and -0383 (`quinn-proto`, `rustls`, `rustls-webpki`, `webpki-root-certs`). diff --git a/Cargo.lock b/Cargo.lock index 335f123..8cd2a1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -114,15 +114,6 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - [[package]] name = "block-buffer" version = "0.12.1" @@ -175,7 +166,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cpufeatures 0.3.1", + "cpufeatures", "rand_core", ] @@ -186,10 +177,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", - "js-sys", "num-traits", "serde", - "wasm-bindgen", "windows-link", ] @@ -254,15 +243,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" -[[package]] -name = "colored" -version = "3.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "combine" version = "4.6.9" @@ -295,15 +275,6 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - [[package]] name = "cpufeatures" version = "0.3.1" @@ -313,16 +284,6 @@ dependencies = [ "libc", ] -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - [[package]] name = "crypto-common" version = "0.2.2" @@ -341,31 +302,15 @@ dependencies = [ "cmov", ] -[[package]] -name = "deranged" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "crypto-common 0.1.7", -] - [[package]] name = "digest" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer 0.12.1", + "block-buffer", "const-oid", - "crypto-common 0.2.2", + "crypto-common", "ctutils", ] @@ -386,6 +331,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.14" @@ -453,12 +404,6 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - [[package]] name = "futures-task" version = "0.3.34" @@ -472,22 +417,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", - "futures-sink", "futures-task", "pin-project-lite", "slab", ] -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - [[package]] name = "getrandom" version = "0.2.17" @@ -516,13 +450,10 @@ dependencies = [ ] [[package]] -name = "graphql-introspection-query" -version = "0.3.0" +name = "glob" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e063446242093b0acecc78a2313801e6c4faafa3501277b409a2b1972eff5d85" -dependencies = [ - "serde", -] +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] name = "graphql-parser" @@ -535,66 +466,10 @@ dependencies = [ ] [[package]] -name = "graphql_client" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0f04840854efa7b06377d86fab117f598f5f5c95727067463417ccaf8aa7635" -dependencies = [ - "graphql_query_derive", - "serde", - "serde_json", -] - -[[package]] -name = "graphql_client_codegen" -version = "0.16.0" +name = "hashbrown" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa0141e66c8d0302f8a586df12ad5d0cf87c0fa8c391f2f5b5dc296312dce569" -dependencies = [ - "graphql-introspection-query", - "graphql-parser", - "heck", - "proc-macro2", - "quote", - "serde", - "serde_json", - "syn 2.0.119", -] - -[[package]] -name = "graphql_query_derive" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e16ecf9bb87a6760cf5227f66cbe48bad7b89505aeb002aa9439ea090e6038a3" -dependencies = [ - "graphql_client_codegen", - "proc-macro2", - "syn 2.0.119", -] - -[[package]] -name = "headers" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc2700e3fe555c3310aa7286cac6167449f2c87e0eb58769c9208a1c58a1d106" -dependencies = [ - "base64 0.22.1", - "bytes", - "headers-core", - "http", - "httpdate", - "mime", - "sha1", -] - -[[package]] -name = "headers-core" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" -dependencies = [ - "http", -] +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" [[package]] name = "heck" @@ -602,13 +477,19 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "hmac" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest 0.11.3", + "digest", ] [[package]] @@ -650,12 +531,6 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - [[package]] name = "hybrid-array" version = "0.4.15" @@ -867,6 +742,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -973,15 +858,6 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - [[package]] name = "log" version = "0.4.34" @@ -1000,22 +876,6 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "mime_guess" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" -dependencies = [ - "mime", - "unicase", -] - [[package]] name = "mio" version = "1.2.4" @@ -1044,12 +904,6 @@ dependencies = [ "tempfile", ] -[[package]] -name = "num-conv" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" - [[package]] name = "num-traits" version = "0.2.19" @@ -1059,15 +913,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "num_threads" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" -dependencies = [ - "libc", -] - [[package]] name = "once_cell" version = "1.21.4" @@ -1123,55 +968,12 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link", -] - [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" -[[package]] -name = "pin-project" -version = "1.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "pin-project-lite" version = "0.2.17" @@ -1193,12 +995,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "powerfmt" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" - [[package]] name = "proc-macro2" version = "1.0.107" @@ -1306,15 +1102,6 @@ dependencies = [ "rand_core", ] -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags", -] - [[package]] name = "reqwest" version = "0.13.5" @@ -1324,7 +1111,6 @@ dependencies = [ "base64 0.23.1", "bytes", "futures-core", - "futures-util", "http", "http-body", "http-body-util", @@ -1334,7 +1120,6 @@ dependencies = [ "hyper-util", "js-sys", "log", - "mime_guess", "native-tls", "percent-encoding", "pin-project-lite", @@ -1342,9 +1127,6 @@ dependencies = [ "rustls", "rustls-pki-types", "rustls-platform-verifier", - "serde", - "serde_json", - "serde_urlencoded", "sync_wrapper", "tokio", "tokio-native-tls", @@ -1505,18 +1287,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "scoped-tls" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - [[package]] name = "security-framework" version = "3.7.0" @@ -1600,6 +1370,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -1612,17 +1391,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sha1" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - [[package]] name = "sha2" version = "0.11.1" @@ -1630,8 +1398,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", - "cpufeatures 0.3.1", - "digest 0.11.3", + "cpufeatures", + "digest", ] [[package]] @@ -1642,34 +1410,46 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "shopify_api" -version = "0.10.1" +version = "1.0.0" dependencies = [ "base64 0.22.1", - "bytes", "chrono", "clap", - "graphql_client", + "hex", "hmac", - "log", "reqwest", "serde", "serde_json", "serde_path_to_error", + "serde_urlencoded", "sha2", - "simple_logger", + "shopify_api_graphql", + "shopify_api_macros", "thiserror 2.0.21", "tokio", - "warp", + "tracing", + "trybuild", ] [[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +name = "shopify_api_graphql" +version = "1.0.0" dependencies = [ - "errno", - "libc", + "graphql-parser", + "proc-macro2", + "quote", + "serde", + "serde_json", +] + +[[package]] +name = "shopify_api_macros" +version = "1.0.0" +dependencies = [ + "proc-macro2", + "quote", + "shopify_api_graphql", + "syn 2.0.119", ] [[package]] @@ -1688,18 +1468,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" -[[package]] -name = "simple_logger" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7038d0e96661bf9ce647e1a6f6ef6d6f3663f66d9bf741abf14ba4876071c17" -dependencies = [ - "colored", - "log", - "time", - "windows-sys 0.61.2", -] - [[package]] name = "slab" version = "0.4.12" @@ -1782,6 +1550,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "target-tuple" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "876fef147edbcbddc8ac5cbbba92c7b86519e314e86638596c09673b2ed01e7f" + [[package]] name = "tempfile" version = "3.27.0" @@ -1795,6 +1569,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -1835,38 +1618,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "time" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" -dependencies = [ - "deranged", - "libc", - "num-conv", - "num_threads", - "powerfmt", - "serde_core", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" - -[[package]] -name = "time-macros" -version = "0.2.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" -dependencies = [ - "num-conv", - "time-core", -] - [[package]] name = "tinystr" version = "0.8.4" @@ -1885,16 +1636,14 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.54.0" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", "mio", - "parking_lot", "pin-project-lite", - "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.61.2", @@ -1932,18 +1681,44 @@ dependencies = [ ] [[package]] -name = "tokio-util" -version = "0.7.20" +name = "toml" +version = "1.1.8+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", ] +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + [[package]] name = "tower" version = "0.5.3" @@ -1995,7 +1770,6 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ - "log", "pin-project-lite", "tracing-core", ] @@ -2016,16 +1790,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] -name = "typenum" -version = "1.20.1" +name = "trybuild" +version = "1.0.122" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +checksum = "62db9c92d704393fbf2132041720cc80b689f2d3f28521015c2ac866223c11b8" +dependencies = [ + "glob", + "serde", + "serde_derive", + "serde_json", + "target-tuple", + "termcolor", + "toml", +] [[package]] -name = "unicase" -version = "2.10.0" +name = "typenum" +version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "unicode-ident" @@ -2069,12 +1852,6 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - [[package]] name = "walkdir" version = "2.5.0" @@ -2094,33 +1871,6 @@ dependencies = [ "try-lock", ] -[[package]] -name = "warp" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0a808122a8a77eecdabaefd88ddb1913c4be5ea1465399f63ba64c7aa705fea" -dependencies = [ - "bytes", - "futures-util", - "headers", - "http", - "http-body", - "http-body-util", - "log", - "mime", - "mime_guess", - "percent-encoding", - "pin-project", - "scoped-tls", - "serde", - "serde_json", - "serde_urlencoded", - "tokio", - "tokio-util", - "tower-service", - "tracing", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2362,6 +2112,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + [[package]] name = "writeable" version = "0.6.4" diff --git a/Cargo.toml b/Cargo.toml index 41a1cba..ee78e6e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,56 +1,54 @@ -[package] -name = "shopify_api" -description = "Shopify API client" -documentation = "https://docs.rs/shopify_api" -readme = "README.md" -repository = "https://github.com/0xtlt/shopify_api" -version = "0.10.1" -edition = "2021" -rust-version = "1.85" -keywords = ["shopify", "api", "client"] -categories = ["api-bindings", "web-programming"] +[workspace] +resolver = "3" +members = [ + "crates/shopify_api", + "crates/shopify_api_graphql", + "crates/shopify_api_macros", +] + +[workspace.package] +version = "1.0.0" +edition = "2024" +rust-version = "1.88" license = "MIT" +repository = "https://github.com/0xtlt/shopify_api" authors = ["Thomas Tastet"] -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[workspace.dependencies] +# The three crates are released together: each one requires the exact +# version of the others, since the macro emits code for that runtime. +shopify_api = { path = "crates/shopify_api", version = "=1.0.0" } +shopify_api_graphql = { path = "crates/shopify_api_graphql", version = "=1.0.0" } +shopify_api_macros = { path = "crates/shopify_api_macros", version = "=1.0.0" } -[dependencies] -reqwest = { version = "0.13.5", default-features = false, features = ["form", "json", "multipart"] } -serde_json = { version = "1", default-features = false } -serde = { version = "1", default-features = false, features = ["derive"] } -chrono = { version = "0.4", features = ["serde"] } -tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] } -log = "0.4" -simple_logger = "5.2.0" +base64 = "0.22" +chrono = { version = "0.4", default-features = false, features = ["clock", "serde", "std"] } +clap = { version = "4.6", features = ["derive", "env"] } +graphql-parser = "0.4" +hex = "0.4" +hmac = "0.13" +proc-macro2 = "1" +quote = "1" +reqwest = { version = "0.13.5", default-features = false } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +serde_path_to_error = "0.1" +serde_urlencoded = "0.7" +sha2 = "0.11" +subtle = "2.6" +syn = { version = "2", features = ["full"] } thiserror = "2.0.21" -hmac = { version = "0.13.0", optional = true } -sha2 = { version = "0.11.0", optional = true } -base64 = { version = "0.22", optional = true } -warp = { version = "0.4.3", optional = true, default-features = false, features = [] } -bytes = { version = "1.12", optional = true } -graphql_client = { version = "0.16.0", optional = true } -serde_path_to_error = { version = "0.1", optional = true } -clap = { version = "4.6.7", features = ["derive"], optional = true } - -[[bin]] -name = "shopify-api" -path = "src/bin/shopify-api.rs" -required-features = ["cli"] +tokio = { version = "1", default-features = false } +tracing = { version = "0.1", default-features = false, features = ["std"] } +trybuild = "1" -[dev-dependencies] -tokio = { version = "1", features = ["full"] } +[workspace.lints.rust] +unsafe_code = "forbid" +unused_must_use = "deny" +missing_debug_implementations = "warn" -[features] -default = ["rustls"] -warp-wrapper = ["warp", "bytes"] -graphql-client = ["graphql_client"] -full = ["webhooks", "graphql-client", "debug", "cli"] -rustls = ["reqwest/rustls"] -native-tls = ["reqwest/native-tls"] -webhooks = ["hmac", "sha2", "base64"] -debug = ["serde_path_to_error"] -cli = ["dep:clap"] -hmac = ["dep:hmac"] -sha2 = ["dep:sha2"] -warp = ["dep:warp"] -graphql_client = ["dep:graphql_client"] +[workspace.lints.clippy] +dbg_macro = "deny" +todo = "deny" +unimplemented = "deny" +mod_module_files = "deny" diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 0000000..17b173f --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,145 @@ +# Upgrading from 0.10 to 1.0 + +1.0 keeps what 0.10 did, under new names, and adds operations checked at +compile time. Most code changes in three places: building the client, the +error type, and GraphQL calls. + +## Building the client + +```rust,ignore +// 0.10 +let shopify = Shopify::new("my-shop", ShopifyAuth::AccessToken(token), ShopifyConfig::default())?; + +// 1.0 +let shopify = Shopify::new("my-shop", Auth::access_token(token))?; +``` + +| 0.10 | 1.0 | +| --- | --- | +| `ShopifyAuth::AccessToken(token)` | `Auth::access_token(token)` | +| `ShopifyAuth::client_credentials(id, secret)` | `Auth::client_credentials(id, secret)` | +| `ShopifyAuth::expiring_offline_token(id, secret, token)` | `Auth::expiring_token(id, secret, token)` | +| `ShopifyConfig { api_version, .. }` | `Shopify::builder(shop).api_version(ApiVersion::V2026_07)` | +| `ShopifyConfig { token_store, .. }` | `.token_store(store)` | +| `ShopifyConfig { token_refresh_leeway, .. }` | `.refresh_leeway(duration)` (a `std::time::Duration`) | +| `ShopifyConfig { user_agent, .. }` | `.user_agent(text)` | +| `ShopifyConfig { shared_secret, .. }` | Gone: pass the secret to `webhooks::Webhook::verify` | +| `ApiVersion::new("2026-07")` | The same, or `ApiVersion::V2026_07` | +| `shopify.replace_auth(auth)` | Build another client | +| `shopify.get_shop()`, `shop_domain()` | `shopify.shop()`, a `ShopDomain` | +| `shopify.get_query_url()` | `shopify.graphql_url(version)` | + +`TokenStore::save_token(shop: &str, token: TokenData)` is +`TokenStore::save(shop: &ShopDomain, token: &TokenData)`, and returns a boxed +error of yours. `TokenData` has the same fields, and two more for online +tokens; build it with `TokenData::new(token)`. + +The shop must now be `` or `.myshopify.com` (with or without +`https://`): 0.10 accepted any text and appended `.myshopify.com`. + +Without a pinned version, an operation of `graphql!` goes to the version its +schema was checked against (2026-10, or the version of your +`graphql/admin.schema.json`), and an untyped call to 2026-10. 0.10 sent +everything to 2026-04 by default: pin it with `.api_version(ApiVersion::V2026_04)` +to keep that. + +## Errors + +`ShopifyAPIError` is `Error`, and `shopify_api::Result` is available. + +| 0.10 | 1.0 | +| --- | --- | +| `ConnectionFailed(reqwest::Error)` | `Transport { url, source }` | +| An `error_for_status` failure | `Http { status, url, body }`; `error.status()`, `error.is_unauthorized()` | +| `Throttled` | `Throttled { retries, cost }`, once the retries are spent | +| `GraphqlErrors(Vec)` | `Graphql(GraphqlErrors { errors, data })` | +| `JsonParseError` | `Json`, or `Decode { path, message }` when `data` does not fit its type | +| `NotWantedJsonFormat`, `NotJson`, `ResponseBroken` | `Decode` | +| `Authentication(text)` | `Auth(text)` | +| `MissingGraphqlData`, `InvalidHeaderValue`, `Other` | Gone | + +## GraphQL calls + +```rust,ignore +// 0.10: a struct per answer, written by hand, and a json! of variables. +#[derive(Deserialize)] +struct ShopQuery { shop: Shop } +#[derive(Deserialize)] +struct Shop { name: String } +let data: ShopQuery = shopify.graphql("query { shop { name } }", &json!({})).await?; + +// 1.0: checked when the crate compiles, typed from the selection. +let data = shopify.execute(graphql!("query { shop { name } }")).await?; +println!("{}", data.shop.name); + +// 1.0, still untyped: `graphql_as` reads `data` as your type. +let data: ShopQuery = shopify.graphql_as("query { shop { name } }", ()).await?; +``` + +| 0.10 | 1.0 | +| --- | --- | +| `graphql::(query, &variables)` | `graphql_as::(query, variables)`, or `execute(graphql!(…))` | +| `graphql_raw(query, &variables)` | `graphql_raw(query, variables)`, a `RawResponse` | +| `graphql_at_path(query, &variables, &[Key("a"), Key("b")])` | `graphql(…)` then `value.pointer("/a/b")`, or a typed operation | +| `post_graphql::(variables)` (`graphql-client` feature) | `execute(graphql!(…))`: no schema file or build step to keep | +| `types::{Decimal, DateTime, JSON, UnsignedInt64}` | Gone: `graphql!` maps every scalar | + +Variables are now anything that serializes to an object, by value or by +reference, or `()` for none. + +## Bulk operations + +| 0.10 | 1.0 | +| --- | --- | +| `run_bulk_query(query)` → `BulkOperationPayload` | `run_bulk_query(query)` → `BulkOperation`; user errors are `Error::UserErrors` | +| `run_bulk_query_with_grouping(query, group)` | `run_bulk_query_grouped(query, group)` | +| `run_bulk_mutation(mutation, staged_upload_path)` | `run_bulk_mutation_staged(mutation, path, None)`, or `run_bulk_mutation(mutation, &rows)`, which uploads the rows | +| `stage_upload_jsonl(&rows)` | `stage_bulk_variables(&rows)` | +| `get_bulk_operation(id)` | `bulk_operation(id)` | +| `list_bulk_operations(BulkOperationsFilter { .. })` | `bulk_operations(BulkOperationsFilter::new().first(10))`, a `Page` | +| `wait_for_bulk(id, BulkWaitOptions { .. })` | `wait_for_bulk_operation(id, BulkWaitOptions::new().timeout(…))` | +| `Shopify::download_bulk_jsonl(url)` | `shopify.download_bulk_results(url)`, or `bulk_query_rows` for the whole cycle | +| `run_bulk_queries`, `run_bulk_mutations`, `BulkConcurrencyOptions` | Gone: call the single versions in a loop | +| `ShopifyBulkOperation`, `ShopifyBulkStatus` | `bulk::BulkOperation`, `bulk::BulkOperationStatus` | + +`object_count`, `root_object_count` and `file_size` are numbers. + +## Webhooks + +The `webhooks` feature verifies and reads webhooks without a web framework, so +the `warp-wrapper` feature, `Shopify::warp_wrapper` and the `ShopifyWebhook` +payload structs are gone. In your handler, with the raw body: + +```rust,ignore +let webhook = shopify_api::webhooks::Webhook::verify(headers, body, client_secret)?; +let order: MyOrder = webhook.payload()?; +``` + +| 0.10 | 1.0 | +| --- | --- | +| `shopify.verify_hmac(data, header)` | `webhooks::verify_hmac(secret, data, header)` | +| `list_webhooks()` | `webhook_subscriptions()`, every page | +| `add_webhook(address, topic, format)` | `create_webhook_subscription(&WebhookSubscriptionSpec::new(topic, address))` | +| `delete_webhook(id)` | `delete_webhook_subscription(id)` | +| `webhook_auto_config(vec![(address, topic, format)])` | `sync_webhook_subscriptions(&[WebhookSubscriptionSpec::new(topic, address)])`, which returns what it did | +| `edit_webhook` | Delete and create, or `sync_webhook_subscriptions` | + +Topics are accepted as `orders/create` or `ORDERS_CREATE`. + +## Schema download + +| 0.10 | 1.0 | +| --- | --- | +| `download_public_admin_schema("2026-04")` | `schema::download_public_admin_schema(ApiVersion::V2026_04)` | +| `shopify.download_admin_schema()` | The same | +| `shopify-api schema download --public --out file` | `shopify-api schema download` (public by default), `--introspection` for the raw result | + +`graphql!` reads the compact form the command writes by default, in +`graphql/admin.schema.json`. + +## Removed + +- `utils::retry_async` and `retry_sync`: the client retries what can be. +- `utils::read_json_tree`: `serde_json::Value::pointer`. +- `utils::deserialize_from_value` and `deserialize_from_str`: errors name the path of a mismatch. +- The `debug` and `graphql-client` features, and the `simple_logger` dependency: logs go through `tracing`. diff --git a/README.md b/README.md index b61875d..59d136e 100644 --- a/README.md +++ b/README.md @@ -5,160 +5,311 @@ [![MIT licensed](https://img.shields.io/crates/l/shopify_api.svg)](./LICENSE.txt) [![CI](https://github.com/0xtlt/shopify_api/actions/workflows/ci.yml/badge.svg)](https://github.com/0xtlt/shopify_api/actions/workflows/ci.yml) -An ergonomic Shopify Admin GraphQL API client for Rust. +A Shopify Admin GraphQL client for Rust, whose operations are checked against +Shopify's schema while your crate compiles. -Version `0.10` is a breaking refactor for Shopify Admin API `2026-04` and newer: +```rust,no_run +use shopify_api::{Auth, Shopify, graphql}; + +#[tokio::main] +async fn main() -> shopify_api::Result<()> { + let shopify = Shopify::new("my-shop", Auth::access_token("shpat_…"))?; + + let data = shopify + .execute(graphql!( + "query Products($first: Int!) { + products(first: $first) { nodes { id title totalInventory } } + }", + first = 10, + )) + .await?; + + for product in data.products.nodes { + println!("{}: {:?} in stock", product.title, product.total_inventory); + } + Ok(()) +} +``` -- GraphQL-first client -- `2026-04` minimum API version -- static access tokens, client credentials tokens, and expiring offline tokens -- dynamic GraphQL schema download -- Bulk operations using the 2026 `bulkOperation(id:)` and `bulkOperations` APIs +`data.products.nodes` is a `Vec` of structs generated from the selection, and +`total_inventory` an `Option` because the schema says it may be null. + +- **Checked operations.** A field, argument, enum value or variable that does + not exist is a compile error, with a suggestion. A deprecated one is a + compiler warning with Shopify's reason. +- **Typed variables and results**, input objects included, generated with no + build script and no generated file. +- **Tokens handled**: static tokens, the client credentials grant, expiring + offline tokens. Obtained, renewed before they expire, renewed once when + Shopify refuses one, and saved where you say. +- **Throttling handled**: a throttled request waits for what its cost needs, + then goes again. Queries are retried after a server error; mutations never + run twice. +- **The rest of an app's Admin API work**: pagination, bulk operations, + webhooks, OAuth and session tokens, a mock transport for tests, and a + command that downloads the schema of any API version. ## Install ```toml [dependencies] -shopify_api = "0.10" -tokio = { version = "1", features = ["full"] } -serde = { version = "1", features = ["derive"] } -serde_json = "1" +shopify_api = "1" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` -## Basic GraphQL +Rust 1.88 or newer. The bundled schema is the Admin API **2026-10**. -```rust,no_run -use serde::Deserialize; -use shopify_api::{Shopify, ShopifyAuth, ShopifyConfig}; +## Operations -#[derive(Deserialize)] -struct ShopQuery { - shop: Shop, -} +### Inline -#[derive(Deserialize)] -struct Shop { - name: String, -} +`graphql!("…", name = value, …)` is an operation whose types are inferred: -#[tokio::main] -async fn main() -> Result<(), shopify_api::ShopifyAPIError> { - let shopify = Shopify::new( - "my-shop", - ShopifyAuth::AccessToken("shpat_...".to_string()), - ShopifyConfig::default(), - )?; - - let data: ShopQuery = shopify - .graphql( - "query { shop { name } }", - &serde_json::json!({}), - ) - .await?; +```rust,ignore +let data = shopify + .execute(graphql!( + "query($id: ID!) { order(id: $id) { name displayFinancialStatus totalPriceSet { shopMoney { amount currencyCode } } } }", + id = "gid://shopify/Order/1", + )) + .await?; - println!("{}", data.shop.name); - Ok(()) -} +let order = data.order.expect("an order"); +println!("{} {:?} {}", order.name, order.display_financial_status, order.total_price_set.shop_money.amount); ``` -## Client Credentials +Values are converted to the variable's type: any integer for an `Int`, `&str` +or `String` for an `ID`, a bare value or an `Option` for a nullable variable, +a slice or an array for a list. A value of the wrong type does not compile. + +### Named + +`graphql! { pub mod name = "…"; }` names the types, for functions, sharing and +typed input objects: ```rust,ignore -use shopify_api::{Shopify, ShopifyAuth, ShopifyConfig}; +graphql! { + pub mod metafields_set = "mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { + metafields { id key } + userErrors { field message code } + } + }"; +} -let shopify = Shopify::new( - "my-shop", - ShopifyAuth::client_credentials("client_id", "client_secret"), - ShopifyConfig::default(), -)?; +let variables = metafields_set::Variables { + metafields: vec![metafields_set::MetafieldsSetInput { + owner_id: product_id.to_string(), + namespace: Some("custom".to_string()), + key: "color".to_string(), + value: "blue".to_string(), + ..Default::default() + }], +}; +let data: metafields_set::Data = shopify.execute(metafields_set::operation(variables)).await?; ``` -The crate acquires and refreshes 24-hour client-credentials tokens automatically. Add a `TokenStore` in `ShopifyConfig` when your app needs to persist refreshed token data. +### From a file -## Dynamic GraphQL Schema +```rust,ignore +graphql! { + pub mod order = file("graphql/order.graphql"); +} +``` -Public Shopify schema: +### Untyped -```rust,no_run -# async fn example() -> Result<(), shopify_api::ShopifyAPIError> { -let schema = shopify_api::download_public_admin_schema("2026-04").await?; -# Ok(()) -# } -``` +For an operation built at run time, `shopify.graphql(query, variables)` +returns `data` as a `serde_json::Value`, `graphql_as::` reads it as your +type, and `graphql_raw` returns the whole answer, `errors` included. + +The full reference of `graphql!`, with the mapping of every GraphQL type, is +[on docs.rs](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html). + +## API versions + +Every operation is checked against a schema, and **sent to the version of that +schema**. Out of the box that is the bundled 2026-10. To work with another +version, download its schema into your crate: ```bash cargo install shopify_api --features cli -shopify-api schema download \ - --public \ - --api-version 2026-04 \ - --out graphql.schema.json +shopify-api schema download --api-version 2026-07 # writes graphql/admin.schema.json ``` -This uses Shopify's public schema proxy: +`graphql!` then checks your operations against 2026-07, and the client sends +them to the 2026-07 endpoint: nothing else to change. Commit the file. +`ShopifyBuilder::api_version` pins every request to one version instead. -```txt -https://shopify.dev/admin-graphql-direct-proxy/2026-04 -``` +`shopify-api check graphql/*.graphql` checks `.graphql` files the same way, +for CI or for operations used by other tools. + +## Tokens -The proxy is a GraphQL endpoint for introspection requests, not a static `GET` file. +```rust,ignore +use shopify_api::{Auth, Shopify, TokenData}; -Runtime: +// A custom app's Admin API token, or an offline token stored at installation. +let shopify = Shopify::new("my-shop", Auth::access_token("shpat_…"))?; -```rust,no_run -use shopify_api::{Shopify, ShopifyAuth, ShopifyConfig}; - -# async fn example() -> Result<(), shopify_api::ShopifyAPIError> { -let shopify = Shopify::new( - "my-shop", - ShopifyAuth::AccessToken("shpat_...".to_string()), - ShopifyConfig::default(), -)?; -let schema = shopify.download_admin_schema().await?; -# Ok(()) -# } +// The client credentials grant: tokens of 24 hours for a store of the +// organization that owns the app, asked for and renewed by the client. +let shopify = Shopify::new("my-shop", Auth::client_credentials(client_id, client_secret))?; + +// An expiring offline token, renewed with its refresh token and saved. +let shopify = Shopify::builder("my-shop") + .auth(Auth::expiring_token(client_id, client_secret, stored_token)) + .token_store(MyDatabase) + .build()?; ``` -CLI: +Clones of a client share its token: one renewal serves them all, however many +requests wait for it. -```bash -cargo install shopify_api --features cli -shopify-api schema download \ - --shop my-shop \ - --access-token "$SHOPIFY_ACCESS_TOKEN" \ - --out shop.graphql.schema.json -``` +## Rate limits and retries -The crate no longer ships built-in Shopify schema JSON files. Use the CLI output as the `schema_path` for `graphql_client`. +A request Shopify throttles is sent again when the bucket holds its cost again, +computed from `extensions.cost`. A `429` waits for its `Retry-After`. A query +is also retried after a `5xx` or a network failure, with exponential backoff; +a mutation is not, since it may have run. -## Bulk Operations +```rust,ignore +use std::time::Duration; +use shopify_api::RetryPolicy; -```rust,no_run -use shopify_api::{BulkWaitOptions, Shopify, ShopifyAuth, ShopifyConfig}; +let shopify = Shopify::builder("my-shop") + .access_token(token) + .retry(RetryPolicy::new(6).with_max_delay(Duration::from_secs(10))) + .build()?; + +let response = shopify.execute_response(operation).await?; +println!("{:?}", response.cost()); // requested and actual cost, what is left +``` -# async fn example() -> Result<(), shopify_api::ShopifyAPIError> { -let shopify = Shopify::new( - "my-shop", - ShopifyAuth::AccessToken("shpat_...".to_string()), - ShopifyConfig::default(), -)?; +## Pagination -let payload = shopify - .run_bulk_query("{ products { edges { node { id title } } } }") +```rust,ignore +use shopify_api::Page; + +let products = shopify + .paginate( + |after| graphql!( + "query($after: String) { products(first: 250, after: $after) { nodes { id title } pageInfo { hasNextPage endCursor } } }", + after = after, + ), + |data| Page::new(data.products.nodes, data.products.page_info.has_next_page, data.products.page_info.end_cursor), + ) .await?; +``` + +## Bulk operations + +```rust,ignore +use shopify_api::bulk::BulkWaitOptions; -let operation = payload.bulk_operation.unwrap(); -let operation = shopify - .wait_for_bulk(&operation.id, BulkWaitOptions::default()) +// Start, wait, download, read each line. +let rows: Vec = shopify + .bulk_query_rows("{ products { edges { node { id title } } } }", BulkWaitOptions::default()) .await?; -if let Some(url) = operation.url { - let rows: Vec = Shopify::download_bulk_jsonl(&url).await?; - println!("{} rows", rows.len()); +// One mutation per item, uploaded as JSONL first. +let operation = shopify.run_bulk_mutation( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + &inputs, +).await?; +``` + +`run_bulk_query`, `wait_for_bulk_operation`, `bulk_operations`, +`cancel_bulk_operation` and `download_bulk_results` give each step on its own. + +## Webhooks + +Feature `webhooks`: + +```rust,ignore +use shopify_api::webhooks::{Webhook, WebhookSubscriptionSpec}; + +// In your HTTP handler, on the raw body. +let webhook = Webhook::verify(headers, body, client_secret)?; +if webhook.topic() == "orders/create" { + let order: MyOrder = webhook.payload()?; } -# Ok(()) -# } + +// Make the shop's subscriptions exactly these. +shopify.sync_webhook_subscriptions(&[ + WebhookSubscriptionSpec::new("orders/create", "https://example.com/webhooks"), + WebhookSubscriptionSpec::new("app/uninstalled", "https://example.com/webhooks"), +]).await?; ``` -## Changelog +## OAuth and embedded apps + +Feature `oauth`: + +```rust,ignore +use shopify_api::oauth::{RequestedToken, ShopifyApp}; + +let app = ShopifyApp::new(client_id, client_secret); + +// Embedded app: the session token of each request, exchanged for a token. +let session = app.verify_session_token(bearer)?; +let token = app.exchange_session_token(&session, RequestedToken::ExpiringOffline).await?; +let shopify = app.client(session.shop(), token)?; + +// Install link and callback, admin launches, app proxies. +let link = app.authorization_url(&shop, &request); +let callback = app.verify_query(query_string)?; +let token = app.exchange_code(&callback).await?; +let proxied = app.verify_app_proxy(query_string)?; +``` + +## Testing your code + +Feature `testing`: a `MockTransport` records what the client sends and answers +what the test says, with no network. + +```rust,ignore +use shopify_api::testing::{MockTransport, client}; + +let mock = MockTransport::new(); +mock.push_data(serde_json::json!({ "shop": { "name": "Test shop" } })); +let shopify = client(&mock); + +assert_eq!(my_code_under_test(&shopify).await?, "Test shop"); +assert_eq!(mock.graphql_requests()[0].operation_name.as_deref(), Some("Shop")); +``` + +## Features + +| Feature | | +| --- | --- | +| `rustls` (default) | The default transport over rustls. | +| `native-tls` | The same over the platform's TLS. | +| `webhooks` | Webhook verification, parsing and subscriptions. | +| `oauth` | Install links, callbacks, token exchange, session tokens, app proxies. | +| `testing` | `MockTransport`. | +| `cli` | The `shopify-api` command. | +| `full` | All of the above. | + +Without `rustls` or `native-tls`, give the client your own `Transport`. + +## Upgrading from 0.10 + +See [MIGRATION.md](MIGRATION.md). + +## Development + +The toolchain and the tasks are in `mise.toml`: + +```bash +mise install +mise run check # what CI runs: fmt, clippy, tests, docs +mise run schema:bundle # download the bundled schema again (another version as argument) +mise tasks # every task +``` + +The tests never reach Shopify: they script it with `MockTransport`. +`mise run test:live` runs a few against a real development store. + +## License -See [CHANGELOG.md](CHANGELOG.md). +MIT diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml new file mode 100644 index 0000000..e5976b6 --- /dev/null +++ b/crates/shopify_api/Cargo.toml @@ -0,0 +1,75 @@ +[package] +name = "shopify_api" +description = "Shopify Admin GraphQL client: operations checked against Shopify's schema at compile time, typed results, automatic tokens and throttling, bulk operations, webhooks and OAuth." +documentation = "https://docs.rs/shopify_api" +readme = "../../README.md" +keywords = ["shopify", "graphql", "api", "client", "ecommerce"] +categories = ["api-bindings", "web-programming::http-client"] +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +include = ["src/**", "docs/**", "tests/**", "examples/**", "Cargo.toml"] + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] + +[dependencies] +shopify_api_macros.workspace = true + +chrono.workspace = true +reqwest = { workspace = true, optional = true } +serde.workspace = true +serde_json.workspace = true +serde_path_to_error.workspace = true +serde_urlencoded.workspace = true +thiserror.workspace = true +tokio = { workspace = true, features = ["sync", "time"] } +tracing.workspace = true + +base64 = { workspace = true, optional = true } +hex = { workspace = true, optional = true } +hmac = { workspace = true, optional = true } +sha2 = { workspace = true, optional = true } + +clap = { workspace = true, optional = true } +shopify_api_graphql = { workspace = true, optional = true } + +[dev-dependencies] +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time", "test-util"] } +trybuild.workspace = true + +[features] +default = ["rustls"] +## The default transport, `ReqwestTransport`, with rustls. +rustls = ["dep:reqwest", "reqwest/rustls"] +## The default transport, `ReqwestTransport`, with the platform's TLS. +native-tls = ["dep:reqwest", "reqwest/native-tls"] +## Webhook verification and parsing, webhook subscriptions. +webhooks = ["dep:hmac", "dep:sha2", "dep:base64"] +## OAuth: install links, callbacks, token exchange, session tokens, app proxies. +oauth = ["dep:hmac", "dep:sha2", "dep:base64", "dep:hex"] +## `MockTransport`, to test code that calls Shopify without the network. +testing = [] +## The `shopify-api` command: downloads Admin schemas, checks `.graphql` files. +cli = ["dep:clap", "dep:shopify_api_graphql", "rustls", "tokio/macros", "tokio/rt-multi-thread", "tokio/fs"] +full = ["webhooks", "oauth", "testing", "cli"] + +[[bin]] +name = "shopify-api" +path = "src/bin/shopify-api.rs" +required-features = ["cli"] + +[[example]] +name = "products" +required-features = ["rustls"] + +[[example]] +name = "bulk_export" +required-features = ["rustls"] + +[lints] +workspace = true diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md new file mode 100644 index 0000000..330e830 --- /dev/null +++ b/crates/shopify_api/docs/graphql.md @@ -0,0 +1,229 @@ + +The operation is checked while the crate compiles: a field, an argument, a +fragment, a directive or an enum value that does not exist, a missing required +argument or input field, a variable that is not declared, unused or of the +wrong type, the same response key selected with other arguments, are compile +errors on the operation, with a suggestion when a name is close to an +existing one: + +```text +error: Type `Order` has no field `nam` (did you mean `name`?) (line 1, column 58) + (checked against the Shopify Admin API 2026-10) + --> src/orders.rs:12:13 +``` + +What the schema deprecates is a compiler warning that gives Shopify's reason +(an error under `-D warnings`; silence it with `#[allow(deprecated)]`): + +```text +warning: use of deprecated constant `…::SHOPIFY_DEPRECATION`: `Product.bodyHtml` is deprecated + in the Shopify Admin API 2026-10: Use `descriptionHtml` instead. (line 1, column 38 of the operation) +``` + +# Inline operations + +```rust,no_run +use shopify_api::{Shopify, graphql}; + +async fn recent_order_names(shopify: &Shopify, limit: u32) -> shopify_api::Result> { + let data = shopify + .execute(graphql!( + "query RecentOrders($first: Int!) { orders(first: $first, reverse: true) { nodes { id name } } }", + first = limit, + )) + .await?; + + Ok(data.orders.nodes.into_iter().map(|order| order.name).collect()) +} +``` + +[`Shopify::execute`] returns the contents of Shopify's `data`: read +`data.orders`, not `data.data`. + +The operation is a string literal, with or without a leading `#graphql` +comment, or `file("path.graphql")`, relative to the crate's `Cargo.toml`. It +holds one query or mutation and the fragments it uses. Its name, when it has +one, is sent as `operationName`, which Shopify shows in its logs. + +Reading a field the operation does not select is a compile error too: +`no field `name` on type `DataOrdersNodes``. + +# Result types + +Each selection is a struct with a field per selected key, in snake case: +`lineItems` is `line_items`, an alias gives its own name, `__typename` is +`typename`, a Rust keyword is written raw (`r#type`). + +| GraphQL | Rust | +| --- | --- | +| `String`, `ID` | `String` | +| `Int` | `i64` | +| `Float` | `f64` | +| `Boolean` | `bool` | +| `JSON` | `serde_json::Value` | +| Shopify's other scalars: `DateTime`, `Date`, `Decimal`, `Money`, `URL`, `HTML`, `UnsignedInt64`, `BigInt`… | `String`, as Shopify sends them | +| Enum | `String` holding the value, such as `"PAID"` | +| Object, interface, union | A struct | +| `T` without `!` | `Option` | +| `[T]` | `Vec` | + +Enum values are strings so that a value Shopify adds later does not break +reading an answer; enum values written in the operation, such as +`sortKey: CREATED_AT`, are checked. + +A field selected in a fragment on another type, as `title` below, is an +`Option`, `None` for the other types; so is a field under `@include` or +`@skip`, and the subfields only such a place selects. The schema's other +directives, such as Shopify's `@idempotent(key:)` on a mutation, are checked +like arguments. A fragment on the type itself or on one of its interfaces adds plain +fields. + +```rust,no_run +# async fn run(shopify: shopify_api::Shopify, ids: Vec) -> shopify_api::Result<()> { +let data = shopify + .execute(shopify_api::graphql!( + "query($ids: [ID!]!) { + nodes(ids: $ids) { + __typename + id + ... on Product { title } + ... on Order { name } + } + }", + ids = &ids, + )) + .await?; + +// `nodes` is `[Node]!`: a list of nullable nodes. +for node in data.nodes.iter().flatten() { + println!("{} {} {:?} {:?}", node.typename, node.id, node.title, node.name); +} +# Ok(()) +# } +``` + +The types derive `Debug`, `Clone`, `PartialEq`, `Serialize` and +`Deserialize`; they serialize under the names of the GraphQL fields. + +The types of an inline operation have no name you can write: let inference +carry them, convert them to your own types, or use a [module](#named-operations). + +# Variables + +Values follow the operation as `name = value`. A variable that is non-null +without a default needs one; the others can be left out, and are then not sent. +A value is converted to the Rust type of its variable, so the usual +spellings work: + +| Variable | Accepted values | +| --- | --- | +| `String`, `ID`, enums, string-encoded scalars | `String`, `&str`, `&String`, `Cow` | +| `Int` | Any integer type | +| `Float` | `f32`, `f64`, `i32`, `u32` | +| `Boolean` | `bool` | +| `JSON` | `Value`, `&Value` | +| Nullable | The bare value, or an `Option` of it | +| List | A `Vec`, a slice, an array or a `&Vec` of accepted values | +| Input object | Any serializable value, such as `json!({ … })`, checked by nothing: use a module to check its fields | + +Another type is a compile error on the value: `` `&str` is not a value for a +GraphQL variable of Rust type `i64` `` (see [`IntoVariable`]). + +# Named operations + +A module names the types of an operation: to share it, to return its data +from a function, or to build input objects whose fields are checked. + +```rust,no_run +use shopify_api::{Shopify, graphql}; + +graphql! { + /// Writes metafields and returns what Shopify refused. + pub mod metafields_set = "mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { + metafields { id key } + userErrors { field message code } + } + }"; +} + +async fn set_color(shopify: &Shopify, product_id: &str) -> shopify_api::Result> { + let variables = metafields_set::Variables { + metafields: vec![metafields_set::MetafieldsSetInput { + owner_id: product_id.to_string(), + namespace: Some("custom".to_string()), + key: "color".to_string(), + value: "blue".to_string(), + ..Default::default() + }], + }; + let data: metafields_set::Data = shopify.execute(metafields_set::operation(variables)).await?; + + let payload = data.metafields_set.expect("a payload"); + Ok(payload.user_errors.into_iter().map(|error| error.message).collect()) +} +``` + +| Item | | +| --- | --- | +| `QUERY` | The text of the operation. | +| `NAME`, `KIND`, `API_VERSION` | Its name, query or mutation, and the version it was checked against. | +| `Data` and nested structs | The result. A nested struct is named after its path: `DataMetafieldsSetUserErrors`. | +| `Variables` | A field per variable. Absent when there is none. | +| Input objects | A struct per input object the variables use, named as in the schema. | +| `operation(variables)` | The operation, for `execute`. Takes nothing when there are no variables. | + +In `Variables` and in input objects, a field that may be left out is an +`Option`, not sent when `None`; the structs implement `Default`. A deprecated +input field is `#[deprecated]`: setting it warns. An explicit `null` cannot be +written this way: use [`Shopify::graphql`] with a `json!` value for the few +mutations that need one. + +Operations kept in files read the same, and editors that know GraphQL help +writing them: + +```rust,ignore +graphql! { + pub mod order = file("graphql/order.graphql"); +} +``` + +# Schema and API version + +The schema bundled with the crate is the one of [`ApiVersion::DEFAULT`], +2026-10. Nothing has to be downloaded to use `graphql!`. + +For another version, download its schema next to your `Cargo.toml`: + +```bash +cargo install shopify_api --features cli +shopify-api schema download --api-version 2026-07 +``` + +This writes `graphql/admin.schema.json` (from Shopify's public endpoint, or +through a shop with `--shop`), and `graphql!` then checks every operation of +the crate against it. Commit the file: builds need it. + +| Source, in order | | +| --- | --- | +| `SHOPIFY_GRAPHQL_SCHEMA` | Path of a schema file, relative to `Cargo.toml` or absolute. It applies to the packages cargo builds, not to their dependencies, which keep their own schema. | +| `graphql/admin.schema.json` | Written by `shopify-api schema download`. | +| The bundled schema | [`ApiVersion::DEFAULT`]. | + +An operation goes to the version of the schema it was checked against: a +crate whose schema is 2026-07 calls the 2026-07 endpoint, with nothing to +configure. A client created with [`ShopifyBuilder::api_version`] sends +everything to that version instead, and logs a warning for an operation +checked against another. + +`execute` fails when `data` does not fit the operation, with the path of the +first mismatch: `` Shopify's answer does not match the operation at `orders.nodes[0]`: missing field `name` ``. +That happens when a shop runs another version than the schema, or when a test +scripts an answer that leaves out a non-null field. + +# Limits + +- Subscriptions are refused, and one `graphql!` takes one operation. +- The error points at the whole operation; the line and column in its message + locate the mistake inside it. +- The generated code refers to `::shopify_api`: the dependency cannot be renamed. diff --git a/crates/shopify_api/examples/bulk_export.rs b/crates/shopify_api/examples/bulk_export.rs new file mode 100644 index 0000000..13fe93b --- /dev/null +++ b/crates/shopify_api/examples/bulk_export.rs @@ -0,0 +1,58 @@ +//! Exports every variant of a shop with a bulk operation, outside the rate limit. +//! +//! ```bash +//! SHOPIFY_SHOP=my-shop SHOPIFY_CLIENT_ID=… SHOPIFY_CLIENT_SECRET=… cargo run -p shopify_api --example bulk_export +//! ``` + +use serde::Deserialize; +use shopify_api::bulk::BulkWaitOptions; +use shopify_api::{Auth, Shopify, graphql}; + +// Checked against the schema like any other operation; run as a bulk query. +graphql! { + mod variants = "{ + productVariants { + edges { node { id sku price inventoryQuantity product { title } } } + } + }"; +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Variant { + id: String, + sku: Option, + price: String, + inventory_quantity: Option, + product: Product, +} + +#[derive(Debug, Deserialize)] +struct Product { + title: String, +} + +#[tokio::main] +async fn main() -> shopify_api::Result<()> { + let shop = std::env::var("SHOPIFY_SHOP").expect("SHOPIFY_SHOP"); + let client_id = std::env::var("SHOPIFY_CLIENT_ID").expect("SHOPIFY_CLIENT_ID"); + let client_secret = std::env::var("SHOPIFY_CLIENT_SECRET").expect("SHOPIFY_CLIENT_SECRET"); + // The client credentials grant: a store of the organization that owns the app. + let shopify = Shopify::new(shop, Auth::client_credentials(client_id, client_secret))?; + + let rows: Vec = shopify + .bulk_query_rows(variants::QUERY, BulkWaitOptions::default()) + .await?; + for variant in &rows { + println!( + "{} {:<12} {:>8} {:>5?} {}", + variant.id, + variant.sku.as_deref().unwrap_or("-"), + variant.price, + variant.inventory_quantity, + variant.product.title + ); + } + println!("{} variants", rows.len()); + Ok(()) +} diff --git a/crates/shopify_api/examples/products.rs b/crates/shopify_api/examples/products.rs new file mode 100644 index 0000000..142a8c9 --- /dev/null +++ b/crates/shopify_api/examples/products.rs @@ -0,0 +1,47 @@ +//! Lists the products of a shop, page after page. +//! +//! ```bash +//! SHOPIFY_SHOP=my-shop SHOPIFY_ACCESS_TOKEN=shpat_… cargo run -p shopify_api --example products +//! ``` + +use shopify_api::{Auth, Page, Shopify, graphql}; + +#[tokio::main] +async fn main() -> shopify_api::Result<()> { + let shop = std::env::var("SHOPIFY_SHOP").expect("SHOPIFY_SHOP"); + let token = std::env::var("SHOPIFY_ACCESS_TOKEN").expect("SHOPIFY_ACCESS_TOKEN"); + let shopify = Shopify::new(shop, Auth::access_token(token))?; + + let products = shopify + .paginate( + |after| { + graphql!( + "query Products($after: String) { + products(first: 100, after: $after, sortKey: TITLE) { + nodes { id title status totalInventory } + pageInfo { hasNextPage endCursor } + } + }", + after = after, + ) + }, + |data| { + let page_info = data.products.page_info; + Page::new( + data.products.nodes, + page_info.has_next_page, + page_info.end_cursor, + ) + }, + ) + .await?; + + for product in &products { + println!( + "{:<10} {:>6?} {}", + product.status, product.total_inventory, product.title + ); + } + println!("{} products", products.len()); + Ok(()) +} diff --git a/crates/shopify_api/src/auth.rs b/crates/shopify_api/src/auth.rs new file mode 100644 index 0000000..bd0a5a1 --- /dev/null +++ b/crates/shopify_api/src/auth.rs @@ -0,0 +1,667 @@ +//! Access tokens: a static token, the client credentials grant, or an +//! expiring offline token renewed with its refresh token. + +use std::fmt; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use tokio::sync::{Mutex, OwnedMutexGuard}; + +use crate::transport::{BoxFuture, HttpRequest, Method, Transport}; +use crate::{Error, Result, ShopDomain}; + +/// How a [`Shopify`](crate::Shopify) client gets its access token. +/// +/// ``` +/// use shopify_api::{Auth, TokenData}; +/// +/// // A token of a custom app, or one your app stored at installation. +/// let auth = Auth::access_token("shpat_…"); +/// +/// // A token Shopify gives for 24 hours to an app and a store of the same +/// // organization, asked for again before it expires. +/// let auth = Auth::client_credentials("client-id", "client-secret"); +/// +/// // An expiring offline token, renewed with its refresh token. +/// let mut stored = TokenData::new("shpat_…"); +/// stored.refresh_token = Some("shprt_…".to_string()); +/// let auth = Auth::expiring_token("client-id", "client-secret", stored); +/// ``` +#[derive(Clone)] +pub struct Auth { + kind: Kind, + token: Option, +} + +#[derive(Clone)] +enum Kind { + /// The token is the token: nothing renews it. + Static, + /// The client credentials grant gives a new token. + ClientCredentials { + client_id: String, + client_secret: String, + }, + /// The refresh token of the current token gives a new token. + Refresh { + client_id: String, + client_secret: String, + }, +} + +impl Auth { + /// A token that is used as it is: an Admin API token of a custom app, or + /// a non-expiring offline token. + pub fn access_token(token: impl Into) -> Self { + Self::token(TokenData::new(token)) + } + + /// A token used as it is, with what is known of it (its scopes, when it + /// expires). Nothing renews it. + pub fn token(token: TokenData) -> Self { + Self { + kind: Kind::Static, + token: Some(token), + } + } + + /// The client credentials grant: Shopify gives a token, valid about 24 + /// hours, to an app for a store of the organization that owns the app. + /// The client asks for one at its first request, and again five minutes + /// before it expires or when Shopify refuses it. + pub fn client_credentials( + client_id: impl Into, + client_secret: impl Into, + ) -> Self { + Self { + kind: Kind::ClientCredentials { + client_id: client_id.into(), + client_secret: client_secret.into(), + }, + token: None, + } + } + + /// An expiring offline token and its refresh token: the client renews + /// it five minutes before it expires, or when Shopify refuses it. Shopify + /// gives a new refresh token each time: save it with a + /// [`TokenStore`]. + pub fn expiring_token( + client_id: impl Into, + client_secret: impl Into, + token: TokenData, + ) -> Self { + Self { + kind: Kind::Refresh { + client_id: client_id.into(), + client_secret: client_secret.into(), + }, + token: Some(token), + } + } + + /// Starts from a token you stored, such as the last client credentials + /// token, instead of asking Shopify for one at the first request. + pub fn with_token(mut self, token: TokenData) -> Self { + self.token = Some(token); + self + } +} + +impl fmt::Debug for Auth { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.kind { + Kind::Static => "Static", + Kind::ClientCredentials { .. } => "ClientCredentials", + Kind::Refresh { .. } => "Refresh", + }; + formatter + .debug_struct("Auth") + .field("kind", &kind) + .field("token", &self.token) + .finish_non_exhaustive() + } +} + +/// An access token and what Shopify said about it. +/// +/// It serializes to JSON, to be stored and given back with +/// [`Auth::with_token`] or [`Auth::expiring_token`]. `Debug` hides the tokens. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct TokenData { + pub access_token: String, + /// The access scopes granted, comma-separated. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scope: Option, + /// When the access token expires; `None` when it does not. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expires_at: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refresh_token_expires_at: Option>, + /// For an online token: the staff member it acts for. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub associated_user: Option, + /// For an online token: the scopes of that staff member. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub associated_user_scope: Option, +} + +impl TokenData { + /// A token of which nothing else is known. + pub fn new(access_token: impl Into) -> Self { + Self { + access_token: access_token.into(), + scope: None, + expires_at: None, + refresh_token: None, + refresh_token_expires_at: None, + associated_user: None, + associated_user_scope: None, + } + } + + /// The access token expires within `leeway`, or has expired. + pub fn expires_within(&self, leeway: chrono::Duration) -> bool { + self.expires_at + .is_some_and(|expires_at| match Utc::now().checked_add_signed(leeway) { + Some(limit) => expires_at <= limit, + // A leeway beyond the calendar: everything expires within it. + None => true, + }) + } + + /// The refresh token is still valid, as far as is known. + pub fn can_refresh(&self) -> bool { + self.refresh_token.is_some() + && self + .refresh_token_expires_at + .is_none_or(|expires_at| Utc::now() < expires_at) + } + + /// The granted scopes. + pub fn scopes(&self) -> Vec<&str> { + self.scope + .as_deref() + .unwrap_or_default() + .split(',') + .map(str::trim) + .filter(|scope| !scope.is_empty()) + .collect() + } +} + +impl fmt::Debug for TokenData { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("TokenData") + .field("access_token", &"[redacted]") + .field("scope", &self.scope) + .field("expires_at", &self.expires_at) + .field( + "refresh_token", + &self.refresh_token.as_ref().map(|_| "[redacted]"), + ) + .field("refresh_token_expires_at", &self.refresh_token_expires_at) + .field("associated_user", &self.associated_user) + .field("associated_user_scope", &self.associated_user_scope) + .finish() + } +} + +/// The staff member an online token acts for. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct AssociatedUser { + pub id: u64, + #[serde(default)] + pub first_name: Option, + #[serde(default)] + pub last_name: Option, + #[serde(default)] + pub email: Option, + #[serde(default)] + pub email_verified: Option, + #[serde(default)] + pub account_owner: Option, + #[serde(default)] + pub locale: Option, + #[serde(default)] + pub collaborator: Option, +} + +/// Where a client saves the tokens it obtains or renews, so that a restart +/// reuses them. An expiring offline token comes with a new refresh token +/// each time: without a store, a restart is left with one that no longer works. +/// +/// Saves run one at a time, in the order of the renewals, in a task of their +/// own: a request that is cancelled does not cancel its save. A store must +/// not call the client whose token it saves. +/// +/// ``` +/// use shopify_api::transport::BoxFuture; +/// use shopify_api::{ShopDomain, TokenData, TokenStore}; +/// +/// struct Database; +/// +/// impl TokenStore for Database { +/// fn save<'a>( +/// &'a self, +/// shop: &'a ShopDomain, +/// token: &'a TokenData, +/// ) -> BoxFuture<'a, Result<(), Box>> { +/// Box::pin(async move { +/// let json = serde_json::to_string(token)?; +/// // UPDATE installations SET token = $json WHERE shop = $shop +/// let _ = (shop, json); +/// Ok(()) +/// }) +/// } +/// } +/// ``` +pub trait TokenStore: Send + Sync + 'static { + fn save<'a>( + &'a self, + shop: &'a ShopDomain, + token: &'a TokenData, + ) -> BoxFuture<'a, std::result::Result<(), Box>>; +} + +// ─── Token endpoint ────────────────────────────────────────────────── + +#[derive(Deserialize)] +struct TokenResponse { + access_token: String, + #[serde(default)] + scope: Option, + #[serde(default)] + expires_in: Option, + #[serde(default)] + refresh_token: Option, + #[serde(default)] + refresh_token_expires_in: Option, + #[serde(default)] + associated_user: Option, + #[serde(default)] + associated_user_scope: Option, +} + +impl TokenResponse { + fn into_token(self) -> TokenData { + // Whatever Shopify says, a date that exists: never in the past, at most the last one. + let at = |seconds: i64| { + chrono::Duration::try_seconds(seconds.max(0)) + .and_then(|duration| Utc::now().checked_add_signed(duration)) + .unwrap_or(DateTime::::MAX_UTC) + }; + TokenData { + access_token: self.access_token, + scope: self.scope, + expires_at: self.expires_in.map(at), + refresh_token: self.refresh_token, + refresh_token_expires_at: self.refresh_token_expires_in.map(at), + associated_user: self.associated_user, + associated_user_scope: self.associated_user_scope, + } + } +} + +/// `https://{shop}/admin/oauth/access_token`. +pub(crate) fn token_url(shop: &ShopDomain) -> String { + format!("https://{shop}/admin/oauth/access_token") +} + +/// How the fields of a token request travel. +#[derive(Clone, Copy)] +pub(crate) enum Encoding { + /// `application/x-www-form-urlencoded`, as Shopify documents the client credentials grant. + Form, + /// `application/json`, as Shopify's libraries send the code and token exchanges. + Json, +} + +/// Asks the token endpoint of `shop` for a token. A refusal says what +/// Shopify answered, never what was sent. +pub(crate) async fn request_token( + transport: &dyn Transport, + shop: &ShopDomain, + user_agent: &str, + encoding: Encoding, + fields: &[(&str, &str)], +) -> Result { + let url = token_url(shop); + let request = HttpRequest::new(Method::Post, &url) + .with_header("Accept", "application/json") + .with_header("User-Agent", user_agent) + .with_timeout(std::time::Duration::from_secs(30)); + let request = match encoding { + Encoding::Form => request.with_form(fields), + Encoding::Json => { + let body: serde_json::Map = fields + .iter() + .map(|(name, value)| (name.to_string(), serde_json::Value::from(*value))) + .collect(); + request.with_json(&serde_json::Value::Object(body)) + } + }; + let response = transport + .send(request) + .await + .map_err(|source| Error::transport(&url, source))?; + if !response.is_success() { + let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap_or_default(); + let code = body.get("error").and_then(serde_json::Value::as_str); + let description = body + .get("error_description") + .and_then(serde_json::Value::as_str); + let detail = match (code, description) { + (Some(code), Some(description)) => format!("{code}: {description}"), + (Some(code), None) => code.to_string(), + _ => { + let text = response.text(); + text.chars().take(300).collect() + } + }; + return Err(Error::Auth(format!( + "the token endpoint of {shop} answered {}: {detail}", + response.status + ))); + } + let parsed: TokenResponse = serde_json::from_slice(&response.body).map_err(|error| { + Error::Auth(format!( + "the token endpoint of {shop} answered an invalid token: {error}" + )) + })?; + Ok(parsed.into_token()) +} + +// ─── Token of a client ─────────────────────────────────────────────── + +/// How long a failed renewal ahead of expiry holds back the next one, while +/// the current token still works. +pub(crate) const RENEWAL_BACKOFF: Duration = Duration::from_secs(30); + +/// How long a failed renewal is the answer of the requests that wait for a +/// token, instead of each asking Shopify again. +pub(crate) const FAILURE_HOLD: Duration = Duration::from_secs(5); + +/// What the client needs to ask for a token. +pub(crate) struct Endpoint { + pub transport: Arc, + pub shop: ShopDomain, + pub user_agent: String, +} + +/// The token of a client and of its clones. +/// +/// One renewal runs at a time, in a task of its own: a caller that is +/// cancelled (a request handler dropped, a timeout) does not cancel it, so a +/// refresh token Shopify rotated is never lost halfway. +pub(crate) struct Tokens { + kind: Arc, + state: Arc>, + /// Saves run in the order of the renewals, outside the lock of the state. + saves: Arc>, + store: Option>, + leeway: chrono::Duration, +} + +struct State { + token: Option, + /// When the last renewal failed, and why. + failure: Option<(Instant, String)>, +} + +impl State { + /// The access token, if it has not expired. + fn valid(&self) -> Option { + self.token + .as_ref() + .filter(|token| !token.expires_within(chrono::Duration::zero())) + .map(|token| token.access_token.clone()) + } + + /// The last failure, if it is recent enough to be the answer. + fn held_failure(&self) -> Option { + let (at, message) = self.failure.as_ref()?; + (at.elapsed() < FAILURE_HOLD) + .then(|| Error::Auth(format!("{message} (asked again in a few seconds)"))) + } +} + +impl Tokens { + pub fn new(auth: Auth, store: Option>, leeway: chrono::Duration) -> Self { + Self { + kind: Arc::new(auth.kind), + state: Arc::new(Mutex::new(State { + token: auth.token, + failure: None, + })), + saves: Arc::new(Mutex::new(())), + store, + leeway, + } + } + + /// The token to send, obtained or renewed first when it is missing or + /// about to expire. + /// + /// When a renewal ahead of expiry fails, the token that has not expired + /// yet is still sent, and the renewal is not tried again for + /// [`RENEWAL_BACKOFF`]. + pub async fn get(&self, endpoint: &Arc) -> Result { + let state = self.state.clone().lock_owned().await; + let still_valid = state.valid(); + if let Some(token) = state.token.as_ref() { + let renewable = !matches!(*self.kind, Kind::Static); + let backing_off = state + .failure + .as_ref() + .is_some_and(|(at, _)| at.elapsed() < RENEWAL_BACKOFF); + if !renewable + || !token.expires_within(self.leeway) + || (backing_off && still_valid.is_some()) + { + return Ok(token.access_token.clone()); + } + } + if still_valid.is_none() + && let Some(error) = state.held_failure() + { + return Err(error); + } + match self.renew_locked(state, endpoint).await { + Err(error) if !matches!(error, Error::TokenStore(_)) => match still_valid { + Some(token) => { + tracing::warn!( + "renewing the token of {} ahead of its expiry failed, the current one is sent: {error}", + endpoint.shop + ); + Ok(token) + } + None => Err(error), + }, + outcome => outcome, + } + } + + /// A token to send again after Shopify refused `rejected`: the one + /// another request already obtained, or a new one. `None` when nothing + /// can renew it. + pub async fn renew(&self, endpoint: &Arc, rejected: &str) -> Result> { + if matches!(*self.kind, Kind::Static) { + return Ok(None); + } + let state = self.state.clone().lock_owned().await; + if let Some(token) = state.token.as_ref() + && token.access_token != rejected + { + return Ok(Some(token.access_token.clone())); + } + if let Some(error) = state.held_failure() { + return Err(error); + } + self.renew_locked(state, endpoint).await.map(Some) + } + + /// The current token, without asking Shopify for one. + pub async fn current(&self) -> Option { + self.state.lock().await.token.clone() + } + + /// Obtains a new token in a task of its own, which keeps the lock of the + /// state until the token is in it, and saves it in the order of the renewals. + async fn renew_locked( + &self, + mut state: OwnedMutexGuard, + endpoint: &Arc, + ) -> Result { + if matches!(*self.kind, Kind::Static) { + // A static client always starts with its token. + return state + .token + .as_ref() + .map(|token| token.access_token.clone()) + .ok_or_else(|| Error::Auth("no access token".to_string())); + } + let kind = self.kind.clone(); + let endpoint = endpoint.clone(); + let store = self.store.clone(); + let saves = self.saves.clone(); + let renewal = tokio::spawn(async move { + let token = match obtain(&kind, &state, &endpoint).await { + Ok(token) => token, + Err(error) => { + state.failure = Some((Instant::now(), error.to_string())); + return Err(error); + } + }; + let access_token = token.access_token.clone(); + state.token = Some(token.clone()); + state.failure = None; + let turn = saves.lock_owned().await; + drop(state); + let saved = match &store { + Some(store) => store + .save(&endpoint.shop, &token) + .await + .map_err(Error::TokenStore), + None => Ok(()), + }; + drop(turn); + saved.map(|()| access_token) + }); + renewal.await.map_err(|stopped| { + Error::Auth(format!("the renewal of the token stopped: {stopped}")) + })? + } +} + +/// Asks Shopify for a new token, as `kind` does. +async fn obtain(kind: &Kind, state: &State, endpoint: &Endpoint) -> Result { + let transport = endpoint.transport.as_ref(); + match kind { + Kind::Static => Err(Error::Auth("a static token is not renewed".to_string())), + Kind::ClientCredentials { + client_id, + client_secret, + } => { + let fields = [ + ("grant_type", "client_credentials"), + ("client_id", client_id.as_str()), + ("client_secret", client_secret.as_str()), + ]; + request_token( + transport, + &endpoint.shop, + &endpoint.user_agent, + Encoding::Form, + &fields, + ) + .await + } + Kind::Refresh { + client_id, + client_secret, + } => { + let refresh_token = state + .token + .as_ref() + .filter(|token| token.can_refresh()) + .and_then(|token| token.refresh_token.clone()) + .ok_or_else(|| { + Error::Auth(format!( + "the token of {} expired and its refresh token is missing or expired: \ + the app must get a new token (token exchange or OAuth)", + endpoint.shop + )) + })?; + let fields = [ + ("grant_type", "refresh_token"), + ("client_id", client_id.as_str()), + ("client_secret", client_secret.as_str()), + ("refresh_token", refresh_token.as_str()), + ]; + request_token( + transport, + &endpoint.shop, + &endpoint.user_agent, + Encoding::Json, + &fields, + ) + .await + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expiry_uses_the_leeway() { + let mut token = TokenData::new("token"); + assert!(!token.expires_within(chrono::Duration::days(365))); + token.expires_at = Some(Utc::now() + chrono::Duration::minutes(1)); + assert!(token.expires_within(chrono::Duration::minutes(5))); + assert!(!token.expires_within(chrono::Duration::seconds(1))); + } + + #[test] + fn a_refresh_token_works_until_it_expires() { + let mut token = TokenData::new("token"); + assert!(!token.can_refresh()); + token.refresh_token = Some("refresh".to_string()); + assert!(token.can_refresh()); + token.refresh_token_expires_at = Some(Utc::now() - chrono::Duration::seconds(1)); + assert!(!token.can_refresh()); + } + + #[test] + fn debug_hides_tokens_and_secrets() { + let mut token = TokenData::new("shpat_secret"); + token.refresh_token = Some("shprt_secret".to_string()); + let auth = Auth::expiring_token("id", "client-secret", token); + let shown = format!("{auth:?}"); + for secret in ["shpat_secret", "shprt_secret", "client-secret"] { + assert!(!shown.contains(secret), "{shown}"); + } + } + + #[test] + fn tokens_round_trip_through_json() { + let mut token = TokenData::new("shpat"); + token.scope = Some("read_products, write_orders".to_string()); + token.expires_at = Some(Utc::now()); + let json = serde_json::to_string(&token).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), token); + assert_eq!(token.scopes(), ["read_products", "write_orders"]); + // Fields left out of a stored token are read as absent. + let minimal: TokenData = serde_json::from_str(r#"{"access_token":"shpat"}"#).unwrap(); + assert_eq!(minimal, TokenData::new("shpat")); + } +} diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs new file mode 100644 index 0000000..a49a90d --- /dev/null +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -0,0 +1,298 @@ +//! `shopify-api`: downloads Shopify Admin schemas for `graphql!`, and checks +//! `.graphql` files against them. + +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +use clap::{Args, Parser, Subcommand}; +use shopify_api::{ApiVersion, Auth, Shopify}; +use shopify_api_graphql::{PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, analyze}; + +#[derive(Debug, Parser)] +#[command( + name = "shopify-api", + version, + about = "Shopify Admin GraphQL schemas for the graphql! macro of shopify_api" +)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Admin GraphQL schemas. + Schema { + #[command(subcommand)] + command: SchemaCommand, + }, + /// Checks `.graphql` files against the schema `graphql!` would use here. + Check(CheckArgs), +} + +#[derive(Debug, Subcommand)] +enum SchemaCommand { + /// Downloads the Admin schema of a version, where `graphql!` reads it. + /// + /// From Shopify's public endpoint by default; through a shop with --shop. + Download(DownloadArgs), +} + +#[derive(Debug, Args)] +struct DownloadArgs { + /// The Admin API version. + #[arg(long, default_value_t = ApiVersion::DEFAULT.to_string())] + api_version: String, + /// Where to write it. By default, `graphql/admin.schema.json` next to the + /// nearest `Cargo.toml` of a package, where `graphql!` reads it + /// (`graphql/admin.introspection.json` with --introspection). + #[arg(long)] + out: Option, + /// Writes the raw introspection result, for other GraphQL tools, instead + /// of the compact form `graphql!` reads. + #[arg(long)] + introspection: bool, + /// Downloads through this shop, with its token: the schema the token sees. + #[arg(long, env = "SHOPIFY_SHOP")] + shop: Option, + #[arg(long, env = "SHOPIFY_ACCESS_TOKEN", hide_env_values = true)] + access_token: Option, + #[arg(long, env = "SHOPIFY_CLIENT_ID")] + client_id: Option, + #[arg(long, env = "SHOPIFY_CLIENT_SECRET", hide_env_values = true)] + client_secret: Option, +} + +#[derive(Debug, Args)] +struct CheckArgs { + /// The `.graphql` files, one operation each. + #[arg(required = true)] + files: Vec, + /// The schema file; else the one `graphql!` would use for the nearest package. + #[arg(long)] + schema: Option, + /// Fails on a deprecated field, argument or value too. + #[arg(long)] + deny_deprecated: bool, +} + +#[tokio::main] +async fn main() -> ExitCode { + let cli = Cli::parse(); + let outcome = match cli.command { + Command::Schema { + command: SchemaCommand::Download(args), + } => download(args).await, + Command::Check(args) => check(args), + }; + match outcome { + Ok(code) => code, + Err(message) => { + eprintln!("error: {message}"); + ExitCode::FAILURE + } + } +} + +async fn download(args: DownloadArgs) -> Result { + let version = ApiVersion::new(&args.api_version).map_err(|error| error.to_string())?; + let introspection = match &args.shop { + None => { + eprintln!("Downloading the Admin schema {version} from Shopify's public endpoint…"); + shopify_api::schema::download_public_admin_schema(version) + .await + .map_err(|error| error.to_string())? + } + Some(shop) => { + let auth = match (&args.access_token, &args.client_id, &args.client_secret) { + (Some(token), _, _) => Auth::access_token(token), + (None, Some(id), Some(secret)) => Auth::client_credentials(id, secret), + _ => { + return Err( + "--shop needs --access-token, or --client-id and --client-secret" + .to_string(), + ); + } + }; + let shopify = Shopify::builder(shop) + .auth(auth) + .api_version(version) + .build() + .map_err(|error| error.to_string())?; + eprintln!( + "Downloading the Admin schema {version} through {}…", + shopify.shop() + ); + shopify + .download_admin_schema() + .await + .map_err(|error| error.to_string())? + } + }; + + let (out, project) = match &args.out { + Some(out) => (out.clone(), false), + None => { + let root = package_root().ok_or( + "no Cargo.toml of a package in this directory or above: run it in the crate's directory, or pass --out", + )?; + let file = if args.introspection { + "graphql/admin.introspection.json" + } else { + PROJECT_SCHEMA_PATH + }; + (root.join(file), !args.introspection) + } + }; + let created = !out.exists(); + let (contents, types) = if args.introspection { + let types = introspection + .pointer("/data/__schema/types") + .and_then(|types| types.as_array()) + .map_or(0, Vec::len); + let pretty = + serde_json::to_string_pretty(&introspection).map_err(|error| error.to_string())?; + (format!("{pretty}\n"), types) + } else { + let schema = Schema::from_introspection(&introspection, &version.to_string()) + .map_err(|error| error.to_string())?; + (schema.to_json(), schema.types.len()) + }; + if let Some(parent) = out.parent().filter(|parent| !parent.as_os_str().is_empty()) { + std::fs::create_dir_all(parent) + .map_err(|error| format!("cannot create {}: {error}", parent.display()))?; + } + std::fs::write(&out, contents) + .map_err(|error| format!("cannot write {}: {error}", out.display()))?; + eprintln!("Wrote {} ({types} types).", out.display()); + + if project { + if created && let Some(root) = out.parent().and_then(Path::parent) { + touch_sources(root); + } + eprintln!( + "`graphql!` now checks the operations of this crate against the Admin API {version}, \ + and sends them to that version. Commit the file: builds need it." + ); + } else if !args.introspection { + eprintln!( + "Set {SCHEMA_ENV}={} for `graphql!` to use it.", + out.display() + ); + } + Ok(ExitCode::SUCCESS) +} + +/// Cargo follows a schema file once `graphql!` read it, not before it +/// exists: touching the sources makes the next build read the new file. +fn touch_sources(package: &Path) { + for source in ["src/main.rs", "src/lib.rs"] { + if let Ok(file) = std::fs::File::options() + .write(true) + .open(package.join(source)) + { + let _ = file.set_modified(std::time::SystemTime::now()); + } + } +} + +/// The directory of the nearest `Cargo.toml` that declares a package, from +/// the current directory up: where `graphql!` resolves its paths. +fn package_root() -> Option { + let mut directory = std::env::current_dir().ok()?; + loop { + let manifest = std::fs::read_to_string(directory.join("Cargo.toml")); + if manifest.is_ok_and(|text| text.lines().any(|line| line.trim() == "[package]")) { + return Some(directory); + } + if !directory.pop() { + return None; + } + } +} + +/// The schema `graphql!` would use for the nearest package, as it looks for it. +fn load_schema(path: Option<&Path>) -> Result<(Schema, String), String> { + let root = package_root(); + let resolve = |path: PathBuf| match &root { + Some(root) if path.is_relative() => root.join(path), + _ => path, + }; + let named = std::env::var_os(SCHEMA_ENV) + .filter(|value| !value.is_empty()) + .map(PathBuf::from) + .map(resolve); + let project = root + .as_ref() + .map(|root| root.join(PROJECT_SCHEMA_PATH)) + .filter(|path| path.is_file()); + let path = path.map(Path::to_path_buf).or(named).or(project); + match path { + Some(path) => { + let json = std::fs::read_to_string(&path) + .map_err(|error| format!("cannot read {}: {error}", path.display()))?; + let schema = + Schema::from_json(&json).map_err(|error| format!("{}: {error}", path.display()))?; + Ok((schema, path.display().to_string())) + } + None => Ok((Schema::bundled().clone(), "the bundled schema".to_string())), + } +} + +fn check(args: CheckArgs) -> Result { + let (schema, source) = load_schema(args.schema.as_deref())?; + eprintln!( + "Checking against the Admin API {} ({source}).", + schema.api_version + ); + let mut failed = false; + for file in &args.files { + let text = match std::fs::read_to_string(file) { + Ok(text) => text, + Err(error) => { + eprintln!("{}: cannot read: {error}", file.display()); + failed = true; + continue; + } + }; + match analyze(&schema, &text) { + Ok(operation) => { + for deprecation in &operation.deprecations { + let (line, column) = deprecation.position; + let level = if args.deny_deprecated { + "error" + } else { + "warning" + }; + eprintln!( + "{}:{line}:{column}: {level}: `{}` is deprecated: {}", + file.display(), + deprecation.coordinate, + deprecation.reason + ); + } + failed |= args.deny_deprecated && !operation.deprecations.is_empty(); + let name = operation.name.as_deref().unwrap_or("(anonymous)"); + eprintln!("{}: ok, {:?} {name}", file.display(), operation.kind); + } + Err(error) => { + failed = true; + match error.position { + Some((line, column)) => { + eprintln!( + "{}:{line}:{column}: error: {}", + file.display(), + error.message + ) + } + None => eprintln!("{}: error: {}", file.display(), error.message), + } + } + } + } + Ok(if failed { + ExitCode::FAILURE + } else { + ExitCode::SUCCESS + }) +} diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs new file mode 100644 index 0000000..693bd23 --- /dev/null +++ b/crates/shopify_api/src/bulk.rs @@ -0,0 +1,760 @@ +//! Bulk operations: a query over a whole catalog, or a mutation over +//! thousands of inputs, run by Shopify in the background, outside the rate limit. +//! +//! ```no_run +//! use serde::Deserialize; +//! use shopify_api::bulk::BulkWaitOptions; +//! +//! #[derive(Deserialize)] +//! struct Product { +//! id: String, +//! title: String, +//! } +//! +//! # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { +//! // Start, wait for the end, download and read every line. +//! let products: Vec = shopify +//! .bulk_query_rows("{ products { edges { node { id title } } } }", BulkWaitOptions::default()) +//! .await?; +//! # Ok(()) +//! # } +//! ``` +//! +//! The query of a bulk operation is a plain string. To have it checked when +//! the crate compiles, declare it with [`graphql!`](crate::graphql!) and pass +//! its `QUERY`: +//! +//! ```no_run +//! shopify_api::graphql! { +//! mod all_products = "{ products { edges { node { id title } } } }"; +//! } +//! +//! # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { +//! let operation = shopify.run_bulk_query(all_products::QUERY).await?; +//! # Ok(()) +//! # } +//! ``` + +use std::time::Duration; + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use tokio::time::Instant; + +use crate::transport::{HttpRequest, Method}; +use crate::{Error, Page, Result, Shopify, UserError, graphql}; + +/// How long a download of results may take. +const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60); + +graphql! { + mod run_query = "#graphql + mutation BulkOperationRunQuery($query: String!, $groupObjects: Boolean!) { + bulkOperationRunQuery(query: $query, groupObjects: $groupObjects) { + bulkOperation { ...BulkOperationFields } + userErrors { field message code } + } + } + fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query + }"; +} + +graphql! { + mod run_mutation = "#graphql + mutation BulkOperationRunMutation($mutation: String!, $stagedUploadPath: String!, $clientIdentifier: String) { + bulkOperationRunMutation(mutation: $mutation, stagedUploadPath: $stagedUploadPath, clientIdentifier: $clientIdentifier) { + bulkOperation { ...BulkOperationFields } + userErrors { field message code } + } + } + fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query + }"; +} + +graphql! { + mod get = "#graphql + query BulkOperation($id: ID!) { + bulkOperation(id: $id) { ...BulkOperationFields } + } + fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query + }"; +} + +graphql! { + mod list = "#graphql + query BulkOperations($first: Int!, $after: String, $query: String, $reverse: Boolean) { + bulkOperations(first: $first, after: $after, query: $query, reverse: $reverse, sortKey: CREATED_AT) { + nodes { ...BulkOperationFields } + pageInfo { hasNextPage endCursor } + } + } + fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query + }"; +} + +graphql! { + mod cancel = "#graphql + mutation BulkOperationCancel($id: ID!) { + bulkOperationCancel(id: $id) { + bulkOperation { ...BulkOperationFields } + userErrors { field message } + } + } + fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query + }"; +} + +graphql! { + mod staged_uploads = "#graphql + mutation StagedUploadsCreate($input: [StagedUploadInput!]!) { + stagedUploadsCreate(input: $input) { + stagedTargets { url resourceUrl parameters { name value } } + userErrors { field message } + } + }"; +} + +/// A bulk operation, as Shopify last reported it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct BulkOperation { + pub id: String, + pub kind: BulkOperationType, + pub status: BulkOperationStatus, + /// Why it failed: `ACCESS_DENIED`, `INTERNAL_SERVER_ERROR`, `TIMEOUT`. + pub error_code: Option, + pub created_at: String, + pub completed_at: Option, + /// The objects written so far, nested ones included. + pub object_count: u64, + /// The top-level objects written so far. + pub root_object_count: u64, + /// The size of the result file, in bytes. + pub file_size: Option, + /// Where to download the results, once completed. It expires a week later. + pub url: Option, + /// Where to download what was written before a failure. + pub partial_data_url: Option, + pub query: String, +} + +/// The status of a bulk operation. A status Shopify adds later is `Other`. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[non_exhaustive] +pub enum BulkOperationStatus { + Created, + Running, + Completed, + Canceling, + Canceled, + Failed, + Expired, + Other(String), +} + +impl BulkOperationStatus { + fn parse(value: &str) -> Self { + match value { + "CREATED" => Self::Created, + "RUNNING" => Self::Running, + "COMPLETED" => Self::Completed, + "CANCELING" => Self::Canceling, + "CANCELED" => Self::Canceled, + "FAILED" => Self::Failed, + "EXPIRED" => Self::Expired, + other => Self::Other(other.to_string()), + } + } + + /// It will not change anymore. + pub fn is_terminal(&self) -> bool { + matches!( + self, + Self::Completed | Self::Canceled | Self::Failed | Self::Expired + ) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[non_exhaustive] +pub enum BulkOperationType { + Query, + Mutation, + Other(String), +} + +impl BulkOperationType { + fn parse(value: &str) -> Self { + match value { + "QUERY" => Self::Query, + "MUTATION" => Self::Mutation, + other => Self::Other(other.to_string()), + } + } +} + +/// The selection every operation of this module makes on `BulkOperation`, +/// as Shopify sends it. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Wire { + id: String, + #[serde(rename = "type")] + kind: String, + status: String, + error_code: Option, + created_at: String, + completed_at: Option, + object_count: String, + root_object_count: String, + file_size: Option, + url: Option, + partial_data_url: Option, + query: String, +} + +impl Wire { + fn into_operation(self) -> Result { + let number = |field: &str, value: &str| { + value + .parse::() + .map_err(|_| Error::Bulk(format!("`{field}` is not a number: {value}"))) + }; + Ok(BulkOperation { + object_count: number("objectCount", &self.object_count)?, + root_object_count: number("rootObjectCount", &self.root_object_count)?, + file_size: self + .file_size + .as_deref() + .map(|size| number("fileSize", size)) + .transpose()?, + id: self.id, + kind: BulkOperationType::parse(&self.kind), + status: BulkOperationStatus::parse(&self.status), + error_code: self.error_code, + created_at: self.created_at, + completed_at: self.completed_at, + url: self.url, + partial_data_url: self.partial_data_url, + query: self.query, + }) + } +} + +/// Reads the `BulkOperationFields` of a generated type. +fn operation_of(selection: &impl Serialize) -> Result { + let wire: Wire = crate::graphql::decode(serde_json::to_value(selection)?)?; + wire.into_operation() +} + +/// The user errors of a generated payload. +fn user_errors(errors: &impl Serialize) -> Result> { + crate::graphql::decode(serde_json::to_value(errors)?) +} + +/// How [`Shopify::wait_for_bulk_operation`] polls. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BulkWaitOptions { + first_poll: Duration, + poll_interval: Duration, + timeout: Option, +} + +impl BulkWaitOptions { + /// The first poll a second after the start, then twice as late each + /// time, up to every ten seconds; no timeout. + pub const fn new() -> Self { + Self { + first_poll: Duration::from_secs(1), + poll_interval: Duration::from_secs(10), + timeout: None, + } + } + + /// The longest wait between two polls. + pub const fn poll_interval(mut self, interval: Duration) -> Self { + self.poll_interval = interval; + if self.first_poll.as_nanos() > interval.as_nanos() { + self.first_poll = interval; + } + self + } + + /// Gives up after `timeout`, with [`Error::Timeout`]. The operation keeps running. + pub const fn timeout(mut self, timeout: Duration) -> Self { + self.timeout = Some(timeout); + self + } +} + +impl Default for BulkWaitOptions { + fn default() -> Self { + Self::new() + } +} + +/// Which bulk operations [`Shopify::bulk_operations`] lists, newest first. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BulkOperationsFilter { + first: u32, + after: Option, + query: Option, +} + +impl BulkOperationsFilter { + /// The ten newest operations. + pub fn new() -> Self { + Self { + first: 10, + after: None, + query: None, + } + } + + /// How many per page, up to 250. + pub fn first(mut self, first: u32) -> Self { + self.first = first.clamp(1, 250); + self + } + + /// The page after this cursor. + pub fn after(mut self, cursor: impl Into) -> Self { + self.after = Some(cursor.into()); + self + } + + /// A search, such as `status:RUNNING` or `operation_type:QUERY`. + pub fn query(mut self, query: impl Into) -> Self { + self.query = Some(query.into()); + self + } +} + +impl Default for BulkOperationsFilter { + fn default() -> Self { + Self::new() + } +} + +impl Shopify { + /// Starts a bulk query. Shopify refuses a query that is not a bulk + /// query (one connection at the root, no `first`) with user errors, + /// returned as [`Error::UserErrors`]. + pub async fn run_bulk_query(&self, query: &str) -> Result { + self.run_bulk_query_grouped(query, false).await + } + + /// [`Shopify::run_bulk_query`], with nested objects written right after + /// their parent (`groupObjects`), which is slower. + pub async fn run_bulk_query_grouped( + &self, + query: &str, + group_objects: bool, + ) -> Result { + let data = self + .execute(run_query::operation(run_query::Variables { + query: query.to_string(), + group_objects, + })) + .await?; + let payload = data + .bulk_operation_run_query + .ok_or_else(|| Error::Bulk("bulkOperationRunQuery returned nothing".to_string()))?; + started( + "bulkOperationRunQuery", + payload.bulk_operation, + &payload.user_errors, + ) + } + + /// Starts a bulk mutation over `variables`: one run of `mutation` per + /// item, which holds the variables of that run. The items are uploaded + /// as a JSONL file first. + /// + /// ```no_run + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let rows = vec![ + /// serde_json::json!({ "product": { "id": "gid://shopify/Product/1", "title": "New title" } }), + /// serde_json::json!({ "product": { "id": "gid://shopify/Product/2", "title": "Other title" } }), + /// ]; + /// let operation = shopify + /// .run_bulk_mutation( + /// "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + /// &rows, + /// ) + /// .await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn run_bulk_mutation( + &self, + mutation: &str, + variables: &[T], + ) -> Result { + let path = self.stage_bulk_variables(variables).await?; + self.run_bulk_mutation_staged(mutation, &path, None).await + } + + /// Starts a bulk mutation over a JSONL file already uploaded with + /// [`Shopify::stage_bulk_variables`]. `client_identifier` is yours, kept + /// with the operation. + pub async fn run_bulk_mutation_staged( + &self, + mutation: &str, + staged_upload_path: &str, + client_identifier: Option<&str>, + ) -> Result { + let data = self + .execute(run_mutation::operation(run_mutation::Variables { + mutation: mutation.to_string(), + staged_upload_path: staged_upload_path.to_string(), + client_identifier: client_identifier.map(str::to_string), + })) + .await?; + let payload = data + .bulk_operation_run_mutation + .ok_or_else(|| Error::Bulk("bulkOperationRunMutation returned nothing".to_string()))?; + started( + "bulkOperationRunMutation", + payload.bulk_operation, + &payload.user_errors, + ) + } + + /// Uploads `variables` as the JSONL file of a bulk mutation, one item per + /// line, and returns its staged upload path. + pub async fn stage_bulk_variables(&self, variables: &[T]) -> Result { + let mut jsonl = Vec::new(); + for item in variables { + serde_json::to_writer(&mut jsonl, item)?; + jsonl.push(b'\n'); + } + + let data = self + .execute(staged_uploads::operation(staged_uploads::Variables { + input: vec![staged_uploads::StagedUploadInput { + filename: "bulk_op_vars.jsonl".to_string(), + mime_type: "text/jsonl".to_string(), + resource: "BULK_MUTATION_VARIABLES".to_string(), + http_method: Some("POST".to_string()), + ..Default::default() + }], + })) + .await?; + let payload = data + .staged_uploads_create + .ok_or_else(|| Error::Bulk("stagedUploadsCreate returned nothing".to_string()))?; + let errors = user_errors(&payload.user_errors)?; + if !errors.is_empty() { + return Err(Error::UserErrors { + mutation: "stagedUploadsCreate", + errors, + }); + } + let target = payload + .staged_targets + .into_iter() + .flatten() + .next() + .ok_or_else(|| Error::Bulk("stagedUploadsCreate returned no target".to_string()))?; + let url = target + .url + .ok_or_else(|| Error::Bulk("the staged upload target has no address".to_string()))?; + let parameters: Vec<(String, String)> = target + .parameters + .into_iter() + .map(|parameter| (parameter.name, parameter.value)) + .collect(); + let key = parameters + .iter() + .find(|(name, _)| name == "key") + .map(|(_, value)| value.clone()) + .ok_or_else(|| { + Error::Bulk("the staged upload target has no `key` parameter".to_string()) + })?; + + let (content_type, body) = + multipart(¶meters, "bulk_op_vars.jsonl", "text/jsonl", &jsonl); + let request = HttpRequest::new(Method::Post, &url) + .with_header("Content-Type", content_type) + .with_body(body) + .with_timeout(DOWNLOAD_TIMEOUT); + let response = self + .shared + .endpoint + .transport + .send(request) + .await + .map_err(|source| Error::transport(&url, source))?; + if !response.is_success() { + return Err(Error::http(&url, &response)); + } + Ok(key) + } + + /// A bulk operation by ID, `None` when the shop has none of that ID. + pub async fn bulk_operation(&self, id: &str) -> Result> { + let data = self + .execute(get::operation(get::Variables { id: id.to_string() })) + .await?; + data.bulk_operation.as_ref().map(operation_of).transpose() + } + + /// One page of the shop's bulk operations, newest first. + pub async fn bulk_operations( + &self, + filter: BulkOperationsFilter, + ) -> Result> { + let data = self + .execute(list::operation(list::Variables { + first: i64::from(filter.first), + after: filter.after, + query: filter.query, + reverse: Some(true), + })) + .await?; + let connection = data.bulk_operations; + let items = connection + .nodes + .iter() + .map(operation_of) + .collect::>()?; + Ok(Page::new( + items, + connection.page_info.has_next_page, + connection.page_info.end_cursor, + )) + } + + /// Asks Shopify to cancel a running bulk operation. + pub async fn cancel_bulk_operation(&self, id: &str) -> Result { + let data = self + .execute(cancel::operation(cancel::Variables { id: id.to_string() })) + .await?; + let payload = data + .bulk_operation_cancel + .ok_or_else(|| Error::Bulk("bulkOperationCancel returned nothing".to_string()))?; + started( + "bulkOperationCancel", + payload.bulk_operation, + &payload.user_errors, + ) + } + + /// Polls a bulk operation until it completes, fails, is canceled or expires. + pub async fn wait_for_bulk_operation( + &self, + id: &str, + options: BulkWaitOptions, + ) -> Result { + let started = Instant::now(); + let mut wait = options.first_poll; + loop { + if let Some(timeout) = options.timeout { + let elapsed = started.elapsed(); + if elapsed >= timeout { + return Err(Error::Timeout(format!( + "the bulk operation {id} did not end within {timeout:?}" + ))); + } + wait = wait.min(timeout - elapsed); + } + tokio::time::sleep(wait).await; + let operation = self + .bulk_operation(id) + .await? + .ok_or_else(|| Error::Bulk(format!("the bulk operation {id} does not exist")))?; + // A status this version does not know ends the wait too: it is + // the caller's to read, rather than a loop that never ends. + if operation.status.is_terminal() + || matches!(operation.status, BulkOperationStatus::Other(_)) + { + return Ok(operation); + } + wait = wait.saturating_mul(2).min(options.poll_interval); + } + } + + /// Runs a bulk query to its end and reads every line of its results as + /// `T`. Fails when the operation does not complete. + /// + /// A nested connection writes its objects on lines of their own, with + /// the `__parentId` of their parent: read the lines as `serde_json::Value`, + /// or as an enum of your types, to put them back together. + pub async fn bulk_query_rows( + &self, + query: &str, + options: BulkWaitOptions, + ) -> Result> { + let operation = self.run_bulk_query(query).await?; + let operation = self.wait_for_bulk_operation(&operation.id, options).await?; + if operation.status != BulkOperationStatus::Completed { + return Err(Error::Bulk(format!( + "the bulk operation {} ended {:?}{}", + operation.id, + operation.status, + operation + .error_code + .map(|code| format!(" ({code})")) + .unwrap_or_default() + ))); + } + match &operation.url { + Some(url) => self.download_bulk_results(url).await, + // An operation that found nothing has no file. + None => Ok(Vec::new()), + } + } + + /// Downloads the results of a bulk operation and reads each line as `T`. + /// + /// The file is held in memory while it is read: for an export of + /// gigabytes, download `url` with a client of your own and read it with + /// [`parse_jsonl`] chunk by chunk. The address is signed: errors leave + /// its query string out. + pub async fn download_bulk_results(&self, url: &str) -> Result> { + let request = HttpRequest::new(Method::Get, url).with_timeout(DOWNLOAD_TIMEOUT); + let response = self + .shared + .endpoint + .transport + .send(request) + .await + .map_err(|source| Error::transport(url, source))?; + if !response.is_success() { + return Err(Error::http(url, &response)); + } + parse_jsonl(&response.body) + } +} + +/// The operation a bulk mutation started, or the user errors that refused it. +fn started( + mutation: &'static str, + operation: Option, + errors: &E, +) -> Result { + let errors = user_errors(errors)?; + if !errors.is_empty() { + return Err(Error::UserErrors { mutation, errors }); + } + let operation = + operation.ok_or_else(|| Error::Bulk(format!("{mutation} returned no operation")))?; + operation_of(&operation) +} + +/// Reads each non-empty line of a JSONL file as `T`. +pub fn parse_jsonl(body: &[u8]) -> Result> { + body.split(|byte| *byte == b'\n') + .enumerate() + .filter(|(_, line)| !line.iter().all(u8::is_ascii_whitespace)) + .map(|(index, line)| { + let mut deserializer = serde_json::Deserializer::from_slice(line); + serde_path_to_error::deserialize(&mut deserializer).map_err(|error| { + // The position serde_json adds is within the line, not the file. + let inner = error.inner(); + let position = format!(" at line {} column {}", inner.line(), inner.column()); + let message = inner.to_string(); + Error::Decode { + path: format!("line {}: {}", index + 1, error.path()), + message: message + .strip_suffix(&position) + .unwrap_or(&message) + .to_string(), + } + }) + }) + .collect() +} + +/// A `multipart/form-data` body: the fields, then the file. Returns its +/// `Content-Type` and its bytes. +fn multipart( + fields: &[(String, String)], + filename: &str, + mime: &str, + file: &[u8], +) -> (String, Vec) { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_nanos()) + .unwrap_or_default(); + let boundary = format!("shopify-api-{nanos:x}"); + let quoted = |text: &str| text.replace('\\', "\\\\").replace('"', "\\\""); + let mut body = Vec::new(); + for (name, value) in fields { + body.extend_from_slice( + format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{value}\r\n", + quoted(name) + ) + .as_bytes(), + ); + } + body.extend_from_slice( + format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{}\"\r\nContent-Type: {mime}\r\n\r\n", + quoted(filename) + ) + .as_bytes(), + ); + body.extend_from_slice(file); + body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); + (format!("multipart/form-data; boundary={boundary}"), body) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_jsonl_and_names_the_line_at_fault() { + let rows: Vec = parse_jsonl(b"{\"id\":1}\n\n{\"id\":2}\n").unwrap(); + assert_eq!(rows.len(), 2); + assert_eq!(rows[1]["id"], 2); + + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + struct Row { + id: String, + } + let error = parse_jsonl::(b"{\"id\":\"a\"}\n{\"id\":2}\n").unwrap_err(); + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `line 2: id`: invalid type: integer `2`, expected a string" + ); + } + + #[test] + fn builds_a_multipart_body() { + let fields = vec![("key".to_string(), "tmp/1/bulk".to_string())]; + let (content_type, body) = multipart(&fields, "vars.jsonl", "text/jsonl", b"{}\n"); + let boundary = content_type + .strip_prefix("multipart/form-data; boundary=") + .unwrap(); + let body = String::from_utf8(body).unwrap(); + assert_eq!( + body, + format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"key\"\r\n\r\ntmp/1/bulk\r\n\ + --{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"vars.jsonl\"\r\nContent-Type: text/jsonl\r\n\r\n{{}}\n\r\n\ + --{boundary}--\r\n" + ) + ); + } + + #[test] + fn statuses_say_when_they_end() { + assert!(BulkOperationStatus::parse("COMPLETED").is_terminal()); + assert!(!BulkOperationStatus::parse("RUNNING").is_terminal()); + assert_eq!( + BulkOperationStatus::parse("PAUSED"), + BulkOperationStatus::Other("PAUSED".to_string()) + ); + } +} diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs new file mode 100644 index 0000000..4bbfbe6 --- /dev/null +++ b/crates/shopify_api/src/client.rs @@ -0,0 +1,465 @@ +//! The client of one shop. + +use std::sync::Arc; +use std::time::Duration; + +use crate::auth::{Endpoint, Tokens}; +use crate::transport::{Transport, default_transport}; +use crate::{ApiVersion, Auth, Error, Result, ShopDomain, TokenData, TokenStore}; + +/// The `User-Agent` of every request, unless [`ShopifyBuilder::user_agent`] sets another. +pub const USER_AGENT: &str = concat!("shopify_api/", env!("CARGO_PKG_VERSION"), " (Rust)"); + +/// The Admin API of one shop. +/// +/// A client is cheap to clone: clones share the transport and the token, so +/// that one renewal serves them all. +/// +/// ```no_run +/// use shopify_api::{Shopify, graphql}; +/// +/// # async fn run() -> shopify_api::Result<()> { +/// let shopify = Shopify::new("my-shop", shopify_api::Auth::access_token("shpat_…"))?; +/// +/// let data = shopify +/// .execute(graphql!("query { shop { name currencyCode } }")) +/// .await?; +/// println!("{} sells in {}", data.shop.name, data.shop.currency_code); +/// # Ok(()) +/// # } +/// ``` +#[derive(Clone)] +pub struct Shopify { + pub(crate) shared: Arc, + /// The version every request goes to, when one was chosen. + pinned: Option, + pub(crate) retry: RetryPolicy, +} + +pub(crate) struct Shared { + pub endpoint: Arc, + pub tokens: Tokens, +} + +impl std::fmt::Debug for Shopify { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Shopify") + .field("shop", &self.shared.endpoint.shop) + .field("api_version", &self.pinned) + .field("retry", &self.retry) + .finish_non_exhaustive() + } +} + +impl Shopify { + /// A client of `shop` (`my-shop` or `my-shop.myshopify.com`) with the + /// default transport, retries and API version. + pub fn new(shop: impl AsRef, auth: Auth) -> Result { + Self::builder(shop).auth(auth).build() + } + + pub fn builder(shop: impl AsRef) -> ShopifyBuilder { + ShopifyBuilder { + shop: shop.as_ref().to_string(), + auth: None, + api_version: None, + transport: None, + retry: RetryPolicy::default(), + token_store: None, + refresh_leeway: Duration::from_secs(5 * 60), + user_agent: USER_AGENT.to_string(), + } + } + + pub fn shop(&self) -> &ShopDomain { + &self.shared.endpoint.shop + } + + /// The version requests go to: the one pinned with + /// [`ShopifyBuilder::api_version`], else [`ApiVersion::DEFAULT`]. + /// + /// Without a pinned version, an operation of [`graphql!`](crate::graphql!) + /// goes to the version of the schema it was checked against. + pub fn api_version(&self) -> ApiVersion { + self.pinned.unwrap_or_default() + } + + /// The version pinned with [`ShopifyBuilder::api_version`], if any. + pub fn pinned_api_version(&self) -> Option { + self.pinned + } + + /// A clone that sends every request to `version`, sharing the token. + pub fn with_api_version(&self, version: ApiVersion) -> Self { + Self { + pinned: Some(version), + ..self.clone() + } + } + + /// A clone with other retries, sharing the token. + pub fn with_retry(&self, retry: RetryPolicy) -> Self { + Self { + retry, + ..self.clone() + } + } + + /// `https://{shop}/admin/api/{version}/graphql.json`. + pub fn graphql_url(&self, version: ApiVersion) -> String { + format!( + "https://{}/admin/api/{version}/graphql.json", + self.shared.endpoint.shop + ) + } + + /// The access token requests send, obtained or renewed first when it is + /// missing or about to expire. + pub async fn access_token(&self) -> Result { + self.shared.tokens.get(&self.shared.endpoint).await + } + + /// The token the client holds, without asking Shopify for one: to store + /// it, or to read its scopes. + pub async fn token(&self) -> Option { + self.shared.tokens.current().await + } + + pub(crate) fn endpoint(&self) -> &Arc { + &self.shared.endpoint + } + + /// The version `operation` goes to: the pinned one, else the one its + /// schema was checked against. + pub(crate) fn version_for(&self, checked_against: Option<&'static str>) -> Result { + match (self.pinned, checked_against) { + (Some(pinned), Some(checked)) => { + if pinned.to_string() != checked { + warn_mismatch(pinned, checked); + } + Ok(pinned) + } + (Some(pinned), None) => Ok(pinned), + (None, Some(checked)) => ApiVersion::new(checked), + (None, None) => Ok(ApiVersion::DEFAULT), + } + } +} + +/// Warns once per pair of versions that an operation goes to another +/// version than the one it was checked against. +fn warn_mismatch(pinned: ApiVersion, checked: &'static str) { + static WARNED: std::sync::Mutex> = + std::sync::Mutex::new(Vec::new()); + let mut warned = WARNED + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if !warned.contains(&(pinned, checked)) { + warned.push((pinned, checked)); + tracing::warn!( + "an operation checked against the Admin API {checked} is sent to {pinned}: \ + download the schema of {pinned} with `shopify-api schema download --api-version {pinned}`, \ + or let the client follow the schema by not pinning a version" + ); + } +} + +/// How a client retries what Shopify did not run. +/// +/// A request Shopify throttled (`THROTTLED`, or a `429`) is sent again after +/// the time its cost says the bucket needs. A query is also sent again after +/// a `5xx` or a network failure, with exponential backoff; a mutation is not, +/// since it may have run. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RetryPolicy { + max_retries: u32, + base_delay: Duration, + max_delay: Duration, +} + +impl RetryPolicy { + /// At most `max_retries` retries, from one second up to thirty seconds apart. + pub const fn new(max_retries: u32) -> Self { + Self { + max_retries, + base_delay: Duration::from_secs(1), + max_delay: Duration::from_secs(30), + } + } + + /// Never retries. + pub const fn none() -> Self { + Self::new(0) + } + + /// The first backoff, doubled at each retry. + pub const fn with_base_delay(mut self, delay: Duration) -> Self { + self.base_delay = delay; + self + } + + /// The longest wait between two attempts. + pub const fn with_max_delay(mut self, delay: Duration) -> Self { + self.max_delay = delay; + self + } + + pub const fn max_retries(&self) -> u32 { + self.max_retries + } + + /// The longest wait between two attempts. + pub const fn max_delay(&self) -> Duration { + self.max_delay + } + + /// The wait before retry number `retry` (from 0): exponential, with up + /// to a quarter of jitter, capped at the longest wait. + pub(crate) fn backoff(&self, retry: u32) -> Duration { + let exponential = self.base_delay.saturating_mul(1u32 << retry.min(16)); + let jitter = exponential.mul_f64(jitter_fraction() * 0.25); + exponential.saturating_add(jitter).min(self.max_delay) + } + + /// The wait before sending a throttled request again: until the bucket + /// holds its cost, as Shopify reported it, else the backoff. + pub(crate) fn throttled(&self, retry: u32, cost: Option) -> Duration { + match cost.map(|cost| cost.seconds_until_available()) { + Some(seconds) if seconds > 0.0 => { + // A little more than needed: the bucket refills continuously. + // What does not fit in a `Duration` is the longest wait. + Duration::try_from_secs_f64(seconds + 0.1) + .map_or(self.max_delay, |wait| wait.min(self.max_delay)) + } + _ => self.backoff(retry), + } + } +} + +impl Default for RetryPolicy { + /// Four retries. + fn default() -> Self { + Self::new(4) + } +} + +/// A fraction in `[0, 1)`, from the clock: retries need no better randomness. +fn jitter_fraction() -> f64 { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.subsec_nanos()) + .unwrap_or_default(); + f64::from(nanos % 1000) / 1000.0 +} + +/// Builds a [`Shopify`] client. +/// +/// ``` +/// use std::time::Duration; +/// use shopify_api::{ApiVersion, RetryPolicy, Shopify}; +/// +/// let shopify = Shopify::builder("my-shop") +/// .client_credentials("client-id", "client-secret") +/// .api_version(ApiVersion::V2026_10) +/// .retry(RetryPolicy::new(6).with_max_delay(Duration::from_secs(10))) +/// .build()?; +/// # Ok::<(), shopify_api::Error>(()) +/// ``` +#[must_use] +pub struct ShopifyBuilder { + shop: String, + auth: Option, + api_version: Option, + transport: Option>, + retry: RetryPolicy, + token_store: Option>, + refresh_leeway: Duration, + user_agent: String, +} + +impl std::fmt::Debug for ShopifyBuilder { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ShopifyBuilder") + .field("shop", &self.shop) + .field("auth", &self.auth) + .field("api_version", &self.api_version) + .field("retry", &self.retry) + .finish_non_exhaustive() + } +} + +impl ShopifyBuilder { + pub fn auth(mut self, auth: Auth) -> Self { + self.auth = Some(auth); + self + } + + /// [`Auth::access_token`]. + pub fn access_token(self, token: impl Into) -> Self { + self.auth(Auth::access_token(token)) + } + + /// [`Auth::client_credentials`]. + pub fn client_credentials( + self, + client_id: impl Into, + client_secret: impl Into, + ) -> Self { + self.auth(Auth::client_credentials(client_id, client_secret)) + } + + /// Sends every request to `version`, instead of the version each + /// [`graphql!`](crate::graphql!) operation was checked against. + pub fn api_version(mut self, version: ApiVersion) -> Self { + self.api_version = Some(version); + self + } + + /// Sends the requests through `transport`, such as a + /// [`MockTransport`](crate::testing::MockTransport) in tests. + pub fn transport(mut self, transport: impl Transport) -> Self { + self.transport = Some(Arc::new(transport)); + self + } + + /// [`ShopifyBuilder::transport`], for a transport already shared. + pub fn shared_transport(mut self, transport: Arc) -> Self { + self.transport = Some(transport); + self + } + + pub fn retry(mut self, retry: RetryPolicy) -> Self { + self.retry = retry; + self + } + + /// Saves the tokens the client obtains or renews. + pub fn token_store(mut self, store: impl TokenStore) -> Self { + self.token_store = Some(Arc::new(store)); + self + } + + /// How long before it expires a token is renewed: five minutes by default. + pub fn refresh_leeway(mut self, leeway: Duration) -> Self { + self.refresh_leeway = leeway; + self + } + + pub fn user_agent(mut self, user_agent: impl Into) -> Self { + self.user_agent = user_agent.into(); + self + } + + pub fn build(self) -> Result { + let shop = ShopDomain::new(&self.shop)?; + let auth = self.auth.ok_or_else(|| { + Error::Auth( + "no credentials: call `access_token`, `client_credentials` or `auth`".to_string(), + ) + })?; + let transport = match self.transport { + Some(transport) => transport, + None => default_transport()?, + }; + let leeway = + chrono::Duration::from_std(self.refresh_leeway).unwrap_or(chrono::Duration::MAX); + Ok(Shopify { + shared: Arc::new(Shared { + endpoint: Arc::new(Endpoint { + transport, + shop, + user_agent: self.user_agent, + }), + tokens: Tokens::new(auth, self.token_store, leeway), + }), + pinned: self.api_version, + retry: self.retry, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backoff_doubles_up_to_the_longest_wait() { + let retry = RetryPolicy::new(5) + .with_base_delay(Duration::from_millis(100)) + .with_max_delay(Duration::from_secs(1)); + let within = |retry_number: u32, low: u64, high: u64| { + let wait = retry.backoff(retry_number); + assert!( + wait >= Duration::from_millis(low) && wait <= Duration::from_millis(high), + "retry {retry_number}: {wait:?}" + ); + }; + within(0, 100, 125); + within(1, 200, 250); + within(2, 400, 500); + within(4, 1000, 1000); + within(30, 1000, 1000); + } + + #[test] + fn a_throttled_request_waits_for_its_cost() { + let retry = RetryPolicy::default(); + let cost = crate::graphql::Cost { + requested_query_cost: 500.0, + actual_query_cost: None, + throttle_status: crate::graphql::ThrottleStatus { + maximum_available: 2000.0, + currently_available: 300.0, + restore_rate: 100.0, + }, + }; + assert_eq!(retry.throttled(0, Some(cost)), Duration::from_millis(2100)); + let far = crate::graphql::Cost { + requested_query_cost: 20000.0, + ..cost + }; + assert_eq!(retry.throttled(0, Some(far)), Duration::from_secs(30)); + } + + #[cfg(feature = "testing")] + #[test] + fn the_version_follows_the_schema_unless_one_is_pinned() { + let mock = crate::testing::MockTransport::new(); + let shopify = Shopify::builder("shop") + .access_token("t") + .transport(mock) + .build() + .unwrap(); + assert_eq!(shopify.version_for(None).unwrap(), ApiVersion::DEFAULT); + assert_eq!( + shopify.version_for(Some("2026-07")).unwrap(), + ApiVersion::V2026_07 + ); + assert!(shopify.version_for(Some("2025-01")).is_err()); + let pinned = shopify.with_api_version(ApiVersion::UNSTABLE); + assert_eq!( + pinned.version_for(Some("2026-07")).unwrap(), + ApiVersion::UNSTABLE + ); + assert_eq!(pinned.api_version(), ApiVersion::UNSTABLE); + assert_eq!(shopify.api_version(), ApiVersion::DEFAULT); + assert_eq!( + shopify.graphql_url(ApiVersion::V2026_10), + "https://shop.myshopify.com/admin/api/2026-10/graphql.json" + ); + } + + #[test] + fn building_needs_a_shop_and_credentials() { + assert!(matches!( + Shopify::builder("not a shop").access_token("t").build(), + Err(Error::InvalidShop(_)) + )); + assert!(matches!( + Shopify::builder("shop").build(), + Err(Error::Auth(_)) + )); + } +} diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs new file mode 100644 index 0000000..161064e --- /dev/null +++ b/crates/shopify_api/src/error.rs @@ -0,0 +1,276 @@ +//! The error of every fallible call of this crate. + +use std::fmt; + +use crate::graphql::{Cost, GraphqlError, UserError}; +use crate::transport::{HttpResponse, TransportError}; + +/// `Result`. +pub type Result = std::result::Result; + +/// What went wrong, with what Shopify said about it. +/// +/// Secrets never appear in an error: no access token, client secret or +/// refresh token, and no query string of an address, which may be signed +/// (the results of a bulk operation). +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + /// Not a shop's handle or `myshopify.com` domain. + #[error("invalid shop `{0}`: expected `` or `.myshopify.com`")] + InvalidShop(String), + + #[error("invalid API version `{version}`: {reason}")] + #[non_exhaustive] + InvalidApiVersion { version: String, reason: String }, + + /// The request did not reach Shopify, or its answer did not arrive. + #[error("request to {url} failed: {source}")] + #[non_exhaustive] + Transport { + /// The address, without its query string. + url: String, + #[source] + source: TransportError, + }, + + /// Shopify answered with a status other than 2xx. + #[error("Shopify answered {status} to {url}: {body}")] + #[non_exhaustive] + Http { + status: u16, + /// The address, without its query string. + url: String, + /// The body of the answer, cut at 2 KiB. + body: String, + /// Shopify's `X-Request-Id`, which its support asks for. + request_id: Option, + }, + + /// The answer has a non-empty `errors` list. + #[error("GraphQL errors: {0}")] + Graphql(GraphqlErrors), + + /// Shopify still throttled the request after the retries of the client's + /// [`RetryPolicy`](crate::RetryPolicy). + #[error("throttled by Shopify after {retries} retries")] + #[non_exhaustive] + Throttled { retries: u32, cost: Option }, + + /// The `data` of the answer does not fit the type it is read as: the + /// shop runs another API version than the schema the operation was + /// checked against, or a test scripts an answer without a non-null field. + #[error("Shopify's answer does not match the operation at `{path}`: {message}")] + #[non_exhaustive] + Decode { path: String, message: String }, + + /// A body that is not the JSON it should be. + #[error("invalid JSON: {0}")] + Json(#[from] serde_json::Error), + + /// Variables that do not serialize, or not to an object. + #[error("invalid variables: {0}")] + Variables(String), + + /// A token could not be obtained or renewed. + #[error("authentication failed: {0}")] + Auth(String), + + /// A mutation that this crate runs for you returned `userErrors`. + #[error("{mutation} refused: {}", UserErrors(errors))] + #[non_exhaustive] + UserErrors { + mutation: &'static str, + errors: Vec, + }, + + /// A bulk operation failed, or its answer misses what was expected. + #[error("bulk operation: {0}")] + Bulk(String), + + #[error("timed out: {0}")] + Timeout(String), + + /// The [`TokenStore`](crate::TokenStore) of the client failed to save a + /// renewed token. The client holds the new token all the same. + #[error("the token store failed: {0}")] + TokenStore(#[source] Box), + + /// The client has no transport: enable the `rustls` or `native-tls` + /// feature, or give one with [`ShopifyBuilder::transport`](crate::ShopifyBuilder::transport). + #[error( + "no HTTP transport: enable the `rustls` or `native-tls` feature, or set one with `ShopifyBuilder::transport`" + )] + NoTransport, + + /// A webhook, an OAuth callback, an app proxy request or a session token + /// that does not verify. + #[error("verification failed: {0}")] + Verification(String), + + /// A client that cannot be set up, such as a transport that does not start. + #[error("configuration: {0}")] + Config(String), +} + +impl Error { + /// The HTTP status Shopify answered with, for [`Error::Http`]. + pub fn status(&self) -> Option { + match self { + Self::Http { status, .. } => Some(*status), + _ => None, + } + } + + /// Shopify refused the access token: `401`. + pub fn is_unauthorized(&self) -> bool { + self.status() == Some(401) + } + + /// The request ID Shopify gave, for [`Error::Http`]. + pub fn request_id(&self) -> Option<&str> { + match self { + Self::Http { request_id, .. } => request_id.as_deref(), + _ => None, + } + } + + /// The errors Shopify returned, for [`Error::Graphql`]. + pub fn graphql_errors(&self) -> &[GraphqlError] { + match self { + Self::Graphql(errors) => &errors.errors, + _ => &[], + } + } + + pub(crate) fn transport(url: &str, source: TransportError) -> Self { + Self::Transport { + url: without_query(url), + source, + } + } + + /// The error of an answer that is not a success. + pub(crate) fn http(url: &str, response: &HttpResponse) -> Self { + Self::http_parts( + response.status, + url, + &response.body, + response.header("X-Request-Id").map(str::to_string), + ) + } + + fn http_parts(status: u16, url: &str, body: &[u8], request_id: Option) -> Self { + const LIMIT: usize = 2048; + let text = String::from_utf8_lossy(body); + let body = if text.len() > LIMIT { + let mut end = LIMIT; + while !text.is_char_boundary(end) { + end -= 1; + } + format!("{}…", &text[..end]) + } else { + text.into_owned() + }; + Self::Http { + status, + url: without_query(url), + body, + request_id, + } + } +} + +/// `url` without its query string and fragment, which may hold a signature. +pub(crate) fn without_query(url: &str) -> String { + url.split(['?', '#']).next().unwrap_or_default().to_string() +} + +/// The `errors` of a GraphQL answer, and its `data` when it had some. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct GraphqlErrors { + pub errors: Vec, + /// GraphQL may answer part of a query and fail another part. + pub data: Option, +} + +impl fmt::Display for GraphqlErrors { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + for (index, error) in self.errors.iter().enumerate() { + if index > 0 { + formatter.write_str("; ")?; + } + formatter.write_str(&error.message)?; + if let Some(code) = error.code() { + write!(formatter, " ({code})")?; + } + } + Ok(()) + } +} + +struct UserErrors<'a>(&'a [UserError]); + +impl fmt::Display for UserErrors<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + for (index, error) in self.0.iter().enumerate() { + if index > 0 { + formatter.write_str("; ")?; + } + if let Some(field) = error.field.as_ref().filter(|field| !field.is_empty()) { + write!(formatter, "{}: ", field.join("."))?; + } + formatter.write_str(&error.message)?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn http_errors_cut_long_bodies_and_keep_no_signature() { + let error = Error::http_parts( + 500, + "https://storage.example.com/results.jsonl?X-Goog-Signature=secret#x", + "é".repeat(2000).as_bytes(), + Some("a1b2".to_string()), + ); + let Error::Http { body, url, .. } = &error else { + panic!("an HTTP error"); + }; + assert!(body.ends_with('…')); + assert!(body.len() <= 2048 + '…'.len_utf8()); + assert_eq!(url, "https://storage.example.com/results.jsonl"); + assert!(!error.to_string().contains("secret")); + assert_eq!(error.status(), Some(500)); + assert_eq!(error.request_id(), Some("a1b2")); + assert!(!error.is_unauthorized()); + } + + #[test] + fn user_errors_name_their_field() { + let error = Error::UserErrors { + mutation: "webhookSubscriptionCreate", + errors: vec![ + UserError { + field: Some(vec!["webhookSubscription".to_string(), "uri".to_string()]), + message: "Address is invalid".to_string(), + code: None, + }, + UserError { + field: None, + message: "Too many".to_string(), + code: None, + }, + ], + }; + assert_eq!( + error.to_string(), + "webhookSubscriptionCreate refused: webhookSubscription.uri: Address is invalid; Too many" + ); + } +} diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs new file mode 100644 index 0000000..b7ccd50 --- /dev/null +++ b/crates/shopify_api/src/graphql.rs @@ -0,0 +1,219 @@ +//! Running GraphQL operations: typed ones from [`graphql!`](crate::graphql!), +//! untyped ones from any text. + +mod operation; +mod response; + +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Map, Value}; + +pub use operation::{IntoVariable, Operation, OperationKind}; +pub use response::{ + Cost, GraphqlError, Location, RawResponse, Response, ThrottleStatus, UserError, +}; + +use crate::error::GraphqlErrors; +use crate::transport::{HttpRequest, Method}; +use crate::{ApiVersion, Error, Result, Shopify}; + +pub(crate) use response::decode; + +impl Shopify { + /// Runs an operation and returns its typed `data`. + /// + /// Fails when Shopify answers with `errors` (after retrying a throttled + /// request), and when `data` does not fit the operation. The `userErrors` + /// of a mutation are part of `data`: read them. + /// + /// ```no_run + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let data = shopify + /// .execute(shopify_api::graphql!( + /// "query($first: Int!) { products(first: $first) { nodes { id title } } }", + /// first = 10, + /// )) + /// .await?; + /// for product in data.products.nodes { + /// println!("{} {}", product.id, product.title); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn execute(&self, operation: Operation) -> Result { + Ok(self.execute_response(operation).await?.data) + } + + /// [`Shopify::execute`], with the `extensions` of the answer: the cost of + /// the operation and the state of the rate limit. + pub async fn execute_response( + &self, + operation: Operation, + ) -> Result> { + let version = self.version_for(operation.checked_against())?; + let body = operation.body()?; + let raw = self.send_graphql(version, &body, operation.kind()).await?; + let (data, extensions) = into_data(raw)?; + Ok(Response { + data: decode(data)?, + extensions, + }) + } + + /// Runs any query or mutation and returns its `data`. Nothing checks the + /// text: prefer [`graphql!`](crate::graphql!) for an operation known + /// when the crate compiles. + /// + /// `variables` is anything that serializes to an object, or `()` for none. + /// + /// ```no_run + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let data = shopify + /// .graphql("query($id: ID!) { product(id: $id) { title } }", serde_json::json!({ "id": "gid://shopify/Product/1" })) + /// .await?; + /// let title = data.pointer("/product/title").and_then(|title| title.as_str()); + /// # Ok(()) + /// # } + /// ``` + pub async fn graphql(&self, query: &str, variables: impl Serialize) -> Result { + let raw = self.graphql_raw(query, variables).await?; + Ok(into_data(raw)?.0) + } + + /// [`Shopify::graphql`], with `data` read as `T`. + pub async fn graphql_as( + &self, + query: &str, + variables: impl Serialize, + ) -> Result { + decode(self.graphql(query, variables).await?) + } + + /// Runs any query or mutation and returns the answer as Shopify sent + /// it, `errors` included: for an operation whose partial `data` matters. + /// A throttled request is still retried. + pub async fn graphql_raw(&self, query: &str, variables: impl Serialize) -> Result { + let variables = match serde_json::to_value(variables) + .map_err(|error| Error::Variables(error.to_string()))? + { + Value::Null => Map::new(), + Value::Object(variables) => variables, + _ => { + return Err(Error::Variables( + "the variables must serialize to an object".to_string(), + )); + } + }; + let mut body = Map::new(); + body.insert("query".to_string(), Value::String(query.to_string())); + if !variables.is_empty() { + body.insert("variables".to_string(), Value::Object(variables)); + } + let version = self.version_for(None)?; + self.send_graphql(version, &Value::Object(body), OperationKind::of(query)) + .await + } + + /// Sends a GraphQL body to `version`, retrying what Shopify did not run, + /// and renewing the token once when Shopify refuses it. + pub(crate) async fn send_graphql( + &self, + version: ApiVersion, + body: &Value, + kind: OperationKind, + ) -> Result { + let url = self.graphql_url(version); + let body = serde_json::to_vec(body)?; + let endpoint = self.endpoint(); + let mut token = self.shared.tokens.get(endpoint).await?; + let mut retries = 0; + let mut renewed = false; + loop { + let request = HttpRequest::new(Method::Post, &url) + .with_header("Content-Type", "application/json") + .with_header("Accept", "application/json") + .with_header("User-Agent", &self.shared.endpoint.user_agent) + .with_header("X-Shopify-Access-Token", &token) + .with_body(body.clone()); + let may_retry = retries < self.retry.max_retries(); + let response = match self.shared.endpoint.transport.send(request).await { + Ok(response) => response, + Err(error) if may_retry && !kind.is_mutation() => { + tracing::debug!("retrying a query after a network failure: {error}"); + tokio::time::sleep(self.retry.backoff(retries)).await; + retries += 1; + continue; + } + Err(source) => return Err(Error::transport(&url, source)), + }; + + match response.status { + 200..=299 => {} + 401 if !renewed => { + renewed = true; + match self.shared.tokens.renew(endpoint, &token).await? { + Some(new) => { + token = new; + continue; + } + None => return Err(Error::http(&url, &response)), + } + } + 429 if may_retry => { + let wait = retry_after(&response) + .unwrap_or_else(|| self.retry.backoff(retries)) + .min(self.retry.max_delay()); + tracing::debug!("Shopify answered 429: retrying in {wait:?}"); + tokio::time::sleep(wait).await; + retries += 1; + continue; + } + 429 => { + return Err(Error::Throttled { + retries, + cost: None, + }); + } + 500..=599 if may_retry && !kind.is_mutation() => { + tracing::debug!("Shopify answered {}: retrying the query", response.status); + tokio::time::sleep(self.retry.backoff(retries)).await; + retries += 1; + continue; + } + _ => return Err(Error::http(&url, &response)), + } + + let raw: RawResponse = serde_json::from_slice(&response.body)?; + if raw.is_throttled() { + let cost = raw.cost(); + if !may_retry { + return Err(Error::Throttled { retries, cost }); + } + let wait = self.retry.throttled(retries, cost); + tracing::debug!("throttled by Shopify: retrying in {wait:?}"); + tokio::time::sleep(wait).await; + retries += 1; + continue; + } + return Ok(raw); + } + } +} + +/// The wait a `Retry-After` header asks for, in seconds; `None` for a +/// value that is not a wait. +fn retry_after(response: &crate::transport::HttpResponse) -> Option { + let seconds: f64 = response.header("Retry-After")?.trim().parse().ok()?; + std::time::Duration::try_from_secs_f64(seconds).ok() +} + +/// The `data` and `extensions` of an answer without errors. +fn into_data(raw: RawResponse) -> Result<(Value, Option)> { + if !raw.errors.is_empty() { + return Err(Error::Graphql(GraphqlErrors { + errors: raw.errors, + data: raw.data, + })); + } + Ok((raw.data.unwrap_or(Value::Null), raw.extensions)) +} diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs new file mode 100644 index 0000000..be067b4 --- /dev/null +++ b/crates/shopify_api/src/graphql/operation.rs @@ -0,0 +1,538 @@ +//! Operations, as built by [`graphql!`](crate::graphql!) or by hand. + +use std::borrow::Cow; +use std::marker::PhantomData; + +use serde::Serialize; +use serde_json::{Map, Value}; + +use crate::{ApiVersion, Error, Result}; + +/// A query or a mutation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum OperationKind { + Query, + Mutation, +} + +impl OperationKind { + /// Reads the kind of a document: a mutation as soon as one of its + /// operations is one, so that a document that holds a mutation is never + /// sent twice by a retry. + pub fn of(document: &str) -> Self { + let mut rest = document; + loop { + rest = skip_ignored(rest); + if rest.is_empty() { + return Self::Query; + } + let word: String = rest + .chars() + .take_while(|character| character.is_ascii_alphanumeric() || *character == '_') + .collect(); + if word == "mutation" { + return Self::Mutation; + } + // A query, a fragment or a shorthand `{ … }`: on to the next definition. + match skip_block(&rest[word.len()..]) { + Some(after) => rest = after, + None => return Self::Query, + } + } + } + + pub fn is_mutation(&self) -> bool { + matches!(self, Self::Mutation) + } +} + +/// Skips white space, commas, comments and a byte order mark. +fn skip_ignored(mut text: &str) -> &str { + loop { + let trimmed = text.trim_start_matches(|character: char| { + character.is_whitespace() || character == ',' || character == '\u{feff}' + }); + match trimmed.strip_prefix('#') { + Some(comment) => text = comment.split_once('\n').map_or("", |(_, after)| after), + None => return trimmed, + } + } +} + +/// What follows the next `{ … }` block, strings and comments taken into account. +fn skip_block(text: &str) -> Option<&str> { + let start = text.find('{')?; + let mut depth = 0usize; + let mut chars = text[start..].char_indices().peekable(); + while let Some((index, character)) = chars.next() { + match character { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + return Some(&text[start + index + 1..]); + } + } + '#' => { + for (_, character) in chars.by_ref() { + if character == '\n' { + break; + } + } + } + '"' => { + let mut escaped = false; + for (_, character) in chars.by_ref() { + match character { + '\\' if !escaped => escaped = true, + '"' if !escaped => break, + _ => escaped = false, + } + } + } + _ => {} + } + } + None +} + +/// An operation, its variables, and the type `D` of its `data`. +/// +/// [`graphql!`](crate::graphql!) builds it after checking the operation +/// against Shopify's schema; [`Shopify::execute`](crate::Shopify::execute) +/// runs it. [`Operation::new`] builds one from any text, checked by nothing. +pub struct Operation { + query: Cow<'static, str>, + kind: OperationKind, + name: Option>, + /// The Admin API version of the schema the operation was checked against. + checked_against: Option<&'static str>, + variables: std::result::Result, String>, + data: PhantomData D>, +} + +impl Operation { + /// An operation that nothing checked: its result is read as `D` when it runs. + pub fn new(query: impl Into>) -> Self { + let query = query.into(); + Self { + kind: OperationKind::of(&query), + query, + name: None, + checked_against: None, + variables: Ok(Map::new()), + data: PhantomData, + } + } + + /// What `graphql!` builds. + #[doc(hidden)] + pub fn __checked( + query: &'static str, + kind: OperationKind, + name: Option<&'static str>, + checked_against: &'static str, + ) -> Self { + Self { + query: Cow::Borrowed(query), + kind, + name: name.map(Cow::Borrowed), + checked_against: Some(checked_against), + variables: Ok(Map::new()), + data: PhantomData, + } + } + + /// The text of the operation. + pub fn query(&self) -> &str { + &self.query + } + + pub fn kind(&self) -> OperationKind { + self.kind + } + + /// The name of the operation, sent as `operationName`. + pub fn name(&self) -> Option<&str> { + self.name.as_deref() + } + + /// Names the operation: Shopify shows the name in its logs. + pub fn with_name(mut self, name: impl Into>) -> Self { + self.name = Some(name.into()); + self + } + + /// The Admin API version of the schema `graphql!` checked the operation + /// against; `None` for an operation built with [`Operation::new`]. + pub fn checked_against(&self) -> Option<&'static str> { + self.checked_against + } + + /// The Admin API version the operation is sent to when the client pins + /// none: the one it was checked against, else [`ApiVersion::DEFAULT`]. + pub fn api_version(&self) -> Result { + match self.checked_against { + Some(version) => ApiVersion::new(version), + None => Ok(ApiVersion::DEFAULT), + } + } + + fn set(mut self, name: &str, value: serde_json::Result) -> Self { + match (&mut self.variables, value) { + (Ok(variables), Ok(value)) => { + variables.insert(name.to_string(), value); + } + (Ok(_), Err(error)) => { + self.variables = Err(format!("invalid value for variable `${name}`: {error}")) + } + (Err(_), _) => {} + } + self + } + + /// Sets a variable to a value convertible to `T`, the Rust type of its + /// GraphQL type. + pub fn variable>(self, name: &str, value: V) -> Self { + self.set(name, serde_json::to_value(value.into_variable())) + } + + /// Sets a variable to any serializable value, checked by nothing. + pub fn json_variable(self, name: &str, value: V) -> Self { + self.set(name, serde_json::to_value(value)) + } + + /// Replaces the variables with the fields of a serializable struct or map. + pub fn variables(mut self, variables: V) -> Self { + self.variables = match serde_json::to_value(variables) { + Ok(Value::Object(variables)) => Ok(variables), + Ok(Value::Null) => Ok(Map::new()), + Ok(_) => Err("the variables of an operation must serialize to an object".to_string()), + Err(error) => Err(format!("{error}")), + }; + self + } + + /// The variables, as they are sent. + pub fn variables_json(&self) -> Result<&Map> { + self.variables + .as_ref() + .map_err(|message| Error::Variables(message.clone())) + } + + /// The body Shopify receives: `query`, `variables` and `operationName`. + pub fn body(&self) -> Result { + let mut body = Map::new(); + body.insert("query".to_string(), Value::String(self.query.to_string())); + let variables = self.variables_json()?; + if !variables.is_empty() { + body.insert("variables".to_string(), Value::Object(variables.clone())); + } + if let Some(name) = &self.name { + body.insert("operationName".to_string(), Value::String(name.to_string())); + } + Ok(Value::Object(body)) + } +} + +impl Clone for Operation { + fn clone(&self) -> Self { + Self { + query: self.query.clone(), + kind: self.kind, + name: self.name.clone(), + checked_against: self.checked_against, + variables: self.variables.clone(), + data: PhantomData, + } + } +} + +impl std::fmt::Debug for Operation { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Operation") + .field("kind", &self.kind) + .field("name", &self.name) + .field("query", &self.query) + .field("variables", &self.variables) + .field("checked_against", &self.checked_against) + .finish() + } +} + +/// A Rust value accepted for a GraphQL variable whose Rust type is `T`. +/// +/// `graphql!` picks `T` from the type of the variable: `String` for strings, +/// IDs, enum values and Shopify's string-encoded scalars, `i64` for `Int`, +/// `f64` for `Float`, `bool` for `Boolean`, `Value` for `JSON`, wrapped in +/// `Option` when the variable is nullable and in `Vec` for lists. The +/// implementations then accept the usual Rust spellings of those values: +/// `&str` for a string, any integer for an `Int`, a bare value for a nullable +/// variable, a slice for a list. +#[diagnostic::on_unimplemented( + message = "`{Self}` is not a value for a GraphQL variable of Rust type `{T}`", + label = "the variable expects a value convertible to `{T}`" +)] +pub trait IntoVariable { + fn into_variable(self) -> T; +} + +macro_rules! into_variable { + ($target:ty: $($source:ty => |$value:ident| $convert:expr),+ $(,)?) => {$( + impl IntoVariable<$target> for $source { + fn into_variable(self) -> $target { + let $value = self; + $convert + } + } + + impl IntoVariable> for $source { + fn into_variable(self) -> Option<$target> { + Some(IntoVariable::<$target>::into_variable(self)) + } + } + )+}; +} + +into_variable!(String: + String => |value| value, + &str => |value| value.to_string(), + &String => |value| value.clone(), + Cow<'_, str> => |value| value.into_owned(), +); +into_variable!(i64: + i8 => |value| value.into(), + i16 => |value| value.into(), + i32 => |value| value.into(), + i64 => |value| value, + u8 => |value| value.into(), + u16 => |value| value.into(), + u32 => |value| value.into(), + // Larger than any GraphQL `Int`: Shopify rejects the saturated value. + u64 => |value| i64::try_from(value).unwrap_or(i64::MAX), + usize => |value| i64::try_from(value).unwrap_or(i64::MAX), + isize => |value| i64::try_from(value).unwrap_or(if value < 0 { i64::MIN } else { i64::MAX }), +); +into_variable!(f64: + f32 => |value| value.into(), + f64 => |value| value, + i32 => |value| value.into(), + u32 => |value| value.into(), +); +into_variable!(bool: bool => |value| value); +into_variable!(Value: + Value => |value| value, + &Value => |value| value.clone(), +); + +impl> IntoVariable> for Option { + fn into_variable(self) -> Option { + self.map(IntoVariable::into_variable) + } +} + +impl> IntoVariable> for Vec { + fn into_variable(self) -> Vec { + self.into_iter().map(IntoVariable::into_variable).collect() + } +} + +impl + Clone> IntoVariable> for &[V] { + fn into_variable(self) -> Vec { + self.iter() + .cloned() + .map(IntoVariable::into_variable) + .collect() + } +} + +impl + Clone> IntoVariable> for &Vec { + fn into_variable(self) -> Vec { + self.as_slice().into_variable() + } +} + +impl, const N: usize> IntoVariable> for [V; N] { + fn into_variable(self) -> Vec { + self.into_iter().map(IntoVariable::into_variable).collect() + } +} + +impl> IntoVariable>> for Vec { + fn into_variable(self) -> Option> { + Some(self.into_variable()) + } +} + +impl + Clone> IntoVariable>> for &[V] { + fn into_variable(self) -> Option> { + Some(self.into_variable()) + } +} + +impl + Clone> IntoVariable>> for &Vec { + fn into_variable(self) -> Option> { + Some(self.into_variable()) + } +} + +impl, const N: usize> IntoVariable>> for [V; N] { + fn into_variable(self) -> Option> { + Some(self.into_variable()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn variables(operation: Operation) -> Value { + Value::Object(operation.variables_json().unwrap().clone()) + } + + #[test] + fn reads_the_kind_of_a_document() { + for (document, kind) in [ + ("{ shop { name } }", OperationKind::Query), + ("query Q { shop { name } }", OperationKind::Query), + (" # comment\n mutation { a }", OperationKind::Mutation), + ("\u{feff}mutation M($x: ID!) { a }", OperationKind::Mutation), + ( + "fragment F on Shop { name \"}\" # }\n } , mutation { a { ...F } }", + OperationKind::Mutation, + ), + ( + "fragment F on Shop { name } query { shop { ...F } }", + OperationKind::Query, + ), + ("mutations", OperationKind::Query), + ("", OperationKind::Query), + ] { + assert_eq!(OperationKind::of(document), kind, "{document}"); + } + } + + #[test] + fn converts_the_usual_spellings_of_a_value() { + let operation = Operation::<()>::new("query { shop { id } }") + .variable::("id", "gid://shopify/Order/1") + .variable::, _>("query", "status:open") + .variable::, _>("after", None::) + .variable::("first", 10_u32) + .variable::("count", 3_usize) + .variable::, _>("last", Some(2)) + .variable::("ratio", 1.5_f32) + .variable::("reverse", true) + .variable::, _>("ids", ["a", "b"]) + .variable::, _>("tags", &["x".to_string()][..]) + .variable::>, _>("quantities", vec![1_u8, 2]) + .variable::>, _>("holes", vec![Some("a"), None]) + .variable::("payload", json!({ "a": 1 })) + .json_variable("input", json!({ "title": "Shirt" })); + + assert_eq!(operation.query(), "query { shop { id } }"); + assert_eq!( + variables(operation), + json!({ + "id": "gid://shopify/Order/1", + "query": "status:open", + "after": null, + "first": 10, + "count": 3, + "last": 2, + "ratio": 1.5, + "reverse": true, + "ids": ["a", "b"], + "tags": ["x"], + "quantities": [1, 2], + "holes": ["a", null], + "payload": { "a": 1 }, + "input": { "title": "Shirt" }, + }) + ); + } + + #[test] + fn integers_that_do_not_fit_are_saturated() { + let operation = Operation::<()>::new("query { shop { id } }") + .variable::("big", u64::MAX) + .variable::("fits", 7_u64); + assert_eq!(variables(operation), json!({ "big": i64::MAX, "fits": 7 })); + } + + #[test] + fn variables_can_come_from_a_struct() { + #[derive(Serialize)] + struct Variables { + first: i64, + #[serde(skip_serializing_if = "Option::is_none")] + after: Option, + } + let operation = Operation::<()>::new("query { shop { id } }") + .variable::("ignored", 1) + .variables(Variables { + first: 5, + after: None, + }); + assert_eq!(variables(operation), json!({ "first": 5 })); + + let error = Operation::<()>::new("query { shop { id } }") + .variables(vec![1]) + .body() + .unwrap_err(); + assert_eq!( + error.to_string(), + "invalid variables: the variables of an operation must serialize to an object" + ); + } + + #[test] + fn a_value_that_does_not_serialize_is_reported_when_the_operation_runs() { + struct Broken; + impl Serialize for Broken { + fn serialize( + &self, + _serializer: S, + ) -> std::result::Result { + Err(serde::ser::Error::custom("no")) + } + } + let error = Operation::<()>::new("query { shop { id } }") + .json_variable("input", Broken) + .variable::("first", 1) + .body() + .unwrap_err(); + assert_eq!( + error.to_string(), + "invalid variables: invalid value for variable `$input`: no" + ); + } + + #[test] + fn the_body_holds_the_query_its_variables_and_its_name() { + let operation = Operation::<()>::__checked( + "query Shop { shop { id } }", + OperationKind::Query, + Some("Shop"), + "2026-07", + ); + assert_eq!( + operation.body().unwrap(), + json!({ "query": "query Shop { shop { id } }", "operationName": "Shop" }) + ); + assert_eq!(operation.api_version().unwrap(), ApiVersion::V2026_07); + let operation = operation.variable::("first", 1); + assert_eq!( + operation.body().unwrap(), + json!({ "query": "query Shop { shop { id } }", "variables": { "first": 1 }, "operationName": "Shop" }) + ); + assert_eq!( + Operation::<()>::new("{ shop { id } }") + .api_version() + .unwrap(), + ApiVersion::DEFAULT + ); + } +} diff --git a/crates/shopify_api/src/graphql/response.rs b/crates/shopify_api/src/graphql/response.rs new file mode 100644 index 0000000..5f59823 --- /dev/null +++ b/crates/shopify_api/src/graphql/response.rs @@ -0,0 +1,222 @@ +//! What a GraphQL answer holds besides `data`: errors, user errors, cost. + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// An entry of the `errors` of an answer. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct GraphqlError { + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locations: Option>, + /// The path of the field that failed, names and indexes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub extensions: Option, +} + +impl GraphqlError { + /// `extensions.code`, such as `THROTTLED`, `ACCESS_DENIED` or `MAX_COST_EXCEEDED`. + pub fn code(&self) -> Option<&str> { + self.extensions.as_ref()?.get("code")?.as_str() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct Location { + pub line: u32, + pub column: u32, +} + +/// An entry of the `userErrors` of a mutation: what Shopify refused, and why. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct UserError { + /// The path of the input field at fault. + #[serde(default)] + pub field: Option>, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub code: Option, +} + +/// The cost of a query and the state of the shop's rate limit, from +/// `extensions.cost`. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct Cost { + pub requested_query_cost: f64, + #[serde(default)] + pub actual_query_cost: Option, + pub throttle_status: ThrottleStatus, +} + +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct ThrottleStatus { + /// The size of the bucket. + pub maximum_available: f64, + /// What is left in it. + pub currently_available: f64, + /// What comes back each second. + pub restore_rate: f64, +} + +impl Cost { + /// How long until the bucket holds the requested cost again, in seconds. + pub fn seconds_until_available(&self) -> f64 { + let missing = self.requested_query_cost - self.throttle_status.currently_available; + if missing <= 0.0 || self.throttle_status.restore_rate <= 0.0 { + 0.0 + } else { + missing / self.throttle_status.restore_rate + } + } +} + +fn cost_of(extensions: Option<&Value>) -> Option { + serde_json::from_value(extensions?.get("cost")?.clone()).ok() +} + +/// The typed `data` of an operation, with the `extensions` of the answer. +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub struct Response { + pub data: D, + pub extensions: Option, +} + +impl Response { + /// What the operation cost, and what is left of the rate limit. + pub fn cost(&self) -> Option { + cost_of(self.extensions.as_ref()) + } +} + +/// A GraphQL answer as Shopify sent it: `data`, `errors` and `extensions`. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[non_exhaustive] +pub struct RawResponse { + #[serde(default)] + pub data: Option, + #[serde(default, deserialize_with = "errors")] + pub errors: Vec, + #[serde(default)] + pub extensions: Option, +} + +/// `errors` is a list of errors; Shopify answers a few refusals with a +/// string instead (`"errors": "Not Found"`). +fn errors<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Errors { + List(Vec), + Message(String), + Other(Value), + } + Ok(match Option::::deserialize(deserializer)? { + None => Vec::new(), + Some(Errors::List(errors)) => errors, + Some(Errors::Message(message)) => vec![GraphqlError { + message, + locations: None, + path: None, + extensions: None, + }], + Some(Errors::Other(value)) => vec![GraphqlError { + message: value.to_string(), + locations: None, + path: None, + extensions: None, + }], + }) +} + +impl RawResponse { + pub fn cost(&self) -> Option { + cost_of(self.extensions.as_ref()) + } + + /// Shopify did not run the operation: the rate limit of the shop is reached. + pub fn is_throttled(&self) -> bool { + self.errors + .iter() + .any(|error| error.code() == Some("THROTTLED")) + } + + /// The `data` read as `T`, the path of the first mismatch in the error. + pub fn data_as(&self) -> crate::Result { + decode(self.data.clone().unwrap_or(Value::Null)) + } +} + +/// Reads `value` as `T`, naming the path of the first field that does not fit. +pub(crate) fn decode(value: Value) -> crate::Result { + serde_path_to_error::deserialize(value).map_err(|error| crate::Error::Decode { + path: error.path().to_string(), + message: error.inner().to_string(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn reads_errors_cost_and_throttling() { + let raw: RawResponse = serde_json::from_value(json!({ + "errors": [{ "message": "Throttled", "extensions": { "code": "THROTTLED" } }], + "extensions": { "cost": { + "requestedQueryCost": 752, + "actualQueryCost": null, + "throttleStatus": { "maximumAvailable": 2000.0, "currentlyAvailable": 252, "restoreRate": 100.0 }, + } }, + })) + .unwrap(); + assert!(raw.is_throttled()); + assert_eq!(raw.errors[0].code(), Some("THROTTLED")); + let cost = raw.cost().unwrap(); + assert_eq!(cost.requested_query_cost, 752.0); + assert_eq!(cost.seconds_until_available(), 5.0); + } + + #[test] + fn a_string_of_errors_is_one_error() { + let raw: RawResponse = serde_json::from_str(r#"{"errors":"Not Found"}"#).unwrap(); + assert_eq!(raw.errors.len(), 1); + assert_eq!(raw.errors[0].message, "Not Found"); + let raw: RawResponse = + serde_json::from_str(r#"{"data":{"shop":{"name":"x"}},"errors":null}"#).unwrap(); + assert!(raw.errors.is_empty()); + } + + #[test] + fn decoding_names_the_path_of_the_mismatch() { + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + struct Data { + orders: Vec, + } + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + struct Order { + name: String, + } + let error = + decode::(json!({ "orders": [{ "name": "#1" }, { "id": 2 }] })).unwrap_err(); + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `orders[1]`: missing field `name`" + ); + } +} diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs new file mode 100644 index 0000000..c2826c5 --- /dev/null +++ b/crates/shopify_api/src/lib.rs @@ -0,0 +1,101 @@ +//! A Shopify Admin GraphQL client for Rust. +//! +//! - **Checked operations.** [`graphql!`] checks a query or a mutation +//! against Shopify's Admin schema while your crate compiles, and gives its +//! variables and its result Rust types. A field that does not exist is a +//! compile error; a deprecated one is a compiler warning with Shopify's reason. +//! - **Tokens handled.** A static token, the client credentials grant, or an +//! expiring offline token: the client obtains and renews it, once for all +//! its clones, and saves it where you say ([`TokenStore`]). +//! - **Throttling handled.** A throttled request waits for the time its cost +//! needs, then goes again ([`RetryPolicy`]). +//! - **The rest of the Admin API work:** cursor [pagination](Shopify::paginate), +//! [bulk operations](crate::bulk), [webhooks] and +//! [OAuth](oauth), a [`MockTransport`](testing::MockTransport) +//! for tests, and the `shopify-api` command, which downloads the schema of +//! another API version. +//! +//! ```no_run +//! use shopify_api::{Auth, Shopify, graphql}; +//! +//! # async fn run() -> shopify_api::Result<()> { +//! let shopify = Shopify::new("my-shop", Auth::access_token("shpat_…"))?; +//! +//! let data = shopify +//! .execute(graphql!( +//! "query Products($first: Int!) { +//! products(first: $first) { nodes { id title totalInventory } } +//! }", +//! first = 10, +//! )) +//! .await?; +//! +//! for product in data.products.nodes { +//! println!("{} has {:?} in stock", product.title, product.total_inventory); +//! } +//! # Ok(()) +//! # } +//! ``` +//! +//! See the [`graphql!`] macro for the mapping of types, named operations, +//! input objects and the schema of other API versions. +//! +//! # Features +//! +//! | Feature | | +//! | --- | --- | +//! | `rustls` (default) | [`ReqwestTransport`](transport::ReqwestTransport) over rustls. | +//! | `native-tls` | The same over the platform's TLS. | +//! | `webhooks` | [`webhooks`]: verification, parsing, subscriptions. | +//! | `oauth` | [`oauth`]: install links, callbacks, token exchange, session tokens, app proxies. | +//! | `testing` | [`testing::MockTransport`]. | +//! | `cli` | The `shopify-api` command. | +#![forbid(unsafe_code)] +#![cfg_attr(docsrs, feature(doc_cfg))] + +// The operations of this crate use `graphql!`, whose code refers to `::shopify_api`. +extern crate self as shopify_api; + +mod auth; +pub mod bulk; +mod client; +mod error; +mod graphql; +mod pagination; +pub mod schema; +mod shop; +pub mod transport; +mod version; + +#[cfg(feature = "oauth")] +#[cfg_attr(docsrs, doc(cfg(feature = "oauth")))] +pub mod oauth; +#[cfg(feature = "testing")] +#[cfg_attr(docsrs, doc(cfg(feature = "testing")))] +pub mod testing; +#[cfg(feature = "webhooks")] +#[cfg_attr(docsrs, doc(cfg(feature = "webhooks")))] +pub mod webhooks; + +pub use auth::{AssociatedUser, Auth, TokenData, TokenStore}; +pub use client::{RetryPolicy, Shopify, ShopifyBuilder, USER_AGENT}; +pub use error::{Error, GraphqlErrors, Result}; +pub use graphql::{ + Cost, GraphqlError, IntoVariable, Location, Operation, OperationKind, RawResponse, Response, + ThrottleStatus, UserError, +}; +pub use pagination::Page; +pub use shop::ShopDomain; +pub use version::ApiVersion; + +/// Checks a Shopify Admin GraphQL operation against Shopify's schema while +/// the crate compiles, and gives its variables and its result Rust types. +#[doc = include_str!("../docs/graphql.md")] +pub use shopify_api_macros::graphql; + +/// What the code `graphql!` generates refers to. Not a public API. +#[doc(hidden)] +pub mod __private { + pub use serde; + pub use serde_json; +} diff --git a/crates/shopify_api/src/oauth.rs b/crates/shopify_api/src/oauth.rs new file mode 100644 index 0000000..f0c3670 --- /dev/null +++ b/crates/shopify_api/src/oauth.rs @@ -0,0 +1,884 @@ +//! OAuth and the requests Shopify signs for an app: install links and their +//! callback, session tokens and the token exchange of embedded apps, app proxies. +//! +//! An embedded app gets its tokens from the session token of each request: +//! +//! ```no_run +//! use shopify_api::oauth::{RequestedToken, ShopifyApp}; +//! +//! # async fn handle(bearer: &str) -> shopify_api::Result<()> { +//! let app = ShopifyApp::new("client-id", "client-secret"); +//! +//! // `Authorization: Bearer …` of a request from the app's frontend. +//! let session = app.verify_session_token(bearer)?; +//! let token = app.exchange_session_token(&session, RequestedToken::ExpiringOffline).await?; +//! // Store `token` (it serializes), then: +//! let shopify = app.client(session.shop(), token)?; +//! # Ok(()) +//! # } +//! ``` +//! +//! An app outside Shopify admin installs through a link and a callback: +//! +//! ```no_run +//! use shopify_api::ShopDomain; +//! use shopify_api::oauth::{AuthorizationRequest, ShopifyApp}; +//! +//! # async fn run(query_of_the_callback: &str) -> shopify_api::Result<()> { +//! let app = ShopifyApp::new("client-id", "client-secret"); +//! let shop = ShopDomain::new("my-shop")?; +//! let link = app.authorization_url( +//! &shop, +//! &AuthorizationRequest::new("https://example.com/auth/callback", "a-random-state") +//! .scopes(["read_products", "write_orders"]), +//! ); +//! +//! // On the callback: check the signature, then the state you stored. +//! let callback = app.verify_query(query_of_the_callback)?; +//! assert_eq!(callback.get("state"), Some("a-random-state")); +//! let token = app.exchange_code(&callback).await?; +//! # Ok(()) +//! # } +//! ``` + +use std::sync::Arc; + +use base64::Engine; +use base64::alphabet::URL_SAFE; +use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}; +use chrono::{DateTime, TimeZone, Utc}; +use hmac::{Hmac, KeyInit, Mac}; +use serde_json::Value; +use sha2::Sha256; + +use crate::auth::{Encoding, request_token}; +use crate::transport::{Transport, default_transport}; +use crate::{Auth, Error, Result, ShopDomain, Shopify, ShopifyBuilder, TokenData, USER_AGENT}; + +/// How far the `timestamp` of a signed query may be from now, as Shopify's libraries allow. +const QUERY_TOLERANCE_SECONDS: i64 = 90; + +/// How far `exp` and `nbf` of a session token may be from now, as Shopify's libraries allow. +const JWT_TOLERANCE_SECONDS: i64 = 10; + +/// The parameters of an app proxy request that Shopify sends once. +const PROXY_SINGLE_VALUES: [&str; 4] = ["hmac", "shop", "signature", "timestamp"]; + +/// base64url, with or without padding. +const BASE64_URL: GeneralPurpose = GeneralPurpose::new( + &URL_SAFE, + GeneralPurposeConfig::new() + .with_encode_padding(false) + .with_decode_padding_mode(DecodePaddingMode::Indifferent), +); + +fn mac(secret: &str) -> Hmac { + Hmac::::new_from_slice(secret.as_bytes()).expect("HMAC takes a key of any length") +} + +fn invalid(message: impl Into) -> Error { + Error::Verification(message.into()) +} + +/// An app: its client ID and secret, what it signs and verifies, and the +/// tokens it obtains for shops. +#[derive(Clone)] +pub struct ShopifyApp { + client_id: String, + client_secret: String, + transport: Option>, + user_agent: String, +} + +impl std::fmt::Debug for ShopifyApp { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ShopifyApp") + .field("client_id", &self.client_id) + .finish_non_exhaustive() + } +} + +/// What the install link asks the merchant for. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthorizationRequest { + redirect_uri: String, + state: String, + scopes: Vec, + online: bool, +} + +impl AuthorizationRequest { + /// `redirect_uri` is one of the app's allowed redirection addresses; + /// `state` a random value you keep for the browser, and compare on the callback. + pub fn new(redirect_uri: impl Into, state: impl Into) -> Self { + Self { + redirect_uri: redirect_uri.into(), + state: state.into(), + scopes: Vec::new(), + online: false, + } + } + + /// The access scopes, such as `read_products`. + pub fn scopes, S: Into>(mut self, scopes: I) -> Self { + self.scopes = scopes.into_iter().map(Into::into).collect(); + self + } + + /// An online token, bound to the staff member who installs, instead of + /// an offline token of the shop. + pub fn online(mut self) -> Self { + self.online = true; + self + } +} + +/// A query string whose signature was verified: an OAuth callback, a launch +/// from Shopify admin, an app proxy request. +/// +/// `Debug` shows the names of the parameters and the shop, not the values, +/// which hold an authorization code or a session token. +#[derive(Clone, PartialEq, Eq)] +pub struct SignedQuery { + params: Vec<(String, String)>, + shop: Option, +} + +impl std::fmt::Debug for SignedQuery { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let names: Vec<&str> = self.params.iter().map(|(name, _)| name.as_str()).collect(); + formatter + .debug_struct("SignedQuery") + .field("params", &names) + .field("shop", &self.shop) + .finish() + } +} + +impl SignedQuery { + /// The first value of a parameter. + pub fn get(&self, name: &str) -> Option<&str> { + self.params + .iter() + .find(|(given, _)| given == name) + .map(|(_, value)| value.as_str()) + } + + /// Every parameter, as received. + pub fn params(&self) -> &[(String, String)] { + &self.params + } + + /// The `shop` parameter, when it is a shop's domain. + pub fn shop(&self) -> Option<&ShopDomain> { + self.shop.as_ref() + } +} + +/// The token an embedded app asks for with a session token. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RequestedToken { + /// A token of the shop that does not expire. + Offline, + /// A token of the shop that expires after an hour, with a refresh token. + ExpiringOffline, + /// A token bound to the staff member of the session. + Online, +} + +/// A session token whose signature and dates were verified. +/// +/// `Debug` hides the token itself, which is a bearer. +#[derive(Clone, PartialEq)] +pub struct SessionToken { + shop: ShopDomain, + user_id: Option, + session_id: Option, + expires_at: DateTime, + claims: Value, + token: String, +} + +impl std::fmt::Debug for SessionToken { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("SessionToken") + .field("shop", &self.shop) + .field("user_id", &self.user_id) + .field("session_id", &self.session_id) + .field("expires_at", &self.expires_at) + .finish_non_exhaustive() + } +} + +impl SessionToken { + /// The shop of `dest`. + pub fn shop(&self) -> &ShopDomain { + &self.shop + } + + /// The staff member, `sub`. + pub fn user_id(&self) -> Option<&str> { + self.user_id.as_deref() + } + + /// The session, `sid`. + pub fn session_id(&self) -> Option<&str> { + self.session_id.as_deref() + } + + pub fn expires_at(&self) -> DateTime { + self.expires_at + } + + /// Every claim of the token. + pub fn claims(&self) -> &Value { + &self.claims + } + + /// The token itself, as the frontend sent it. + pub fn as_str(&self) -> &str { + &self.token + } +} + +impl ShopifyApp { + pub fn new(client_id: impl Into, client_secret: impl Into) -> Self { + Self { + client_id: client_id.into(), + client_secret: client_secret.into(), + // Without one, the requests that need it fail with `NoTransport`. + transport: default_transport().ok(), + user_agent: USER_AGENT.to_string(), + } + } + + /// Sends the token requests, and the requests of the clients it builds, + /// through `transport`. + pub fn with_transport(mut self, transport: impl Transport) -> Self { + self.transport = Some(Arc::new(transport)); + self + } + + pub fn with_user_agent(mut self, user_agent: impl Into) -> Self { + self.user_agent = user_agent.into(); + self + } + + pub fn client_id(&self) -> &str { + &self.client_id + } + + fn transport(&self) -> Result<&dyn Transport> { + self.transport.as_deref().ok_or(Error::NoTransport) + } + + /// The secret to verify with. An empty one would verify what anyone signs. + fn secret(&self) -> Result<&str> { + if self.client_secret.is_empty() { + return Err(invalid( + "the client secret of the app is empty: nothing can be verified with it", + )); + } + Ok(&self.client_secret) + } + + // ─── Clients ───────────────────────────────────────────────────── + + /// A builder of a client of `shop` that uses the app's transport. + pub fn builder(&self, shop: &ShopDomain) -> ShopifyBuilder { + let builder = Shopify::builder(shop).user_agent(&self.user_agent); + match &self.transport { + Some(transport) => builder.shared_transport(transport.clone()), + None => builder, + } + } + + /// A client of `shop` with a token the app obtained: renewed with its + /// refresh token when it has one, used as it is otherwise. + pub fn client(&self, shop: &ShopDomain, token: TokenData) -> Result { + let auth = if token.refresh_token.is_some() { + Auth::expiring_token(&self.client_id, &self.client_secret, token) + } else { + Auth::token(token) + }; + self.builder(shop).auth(auth).build() + } + + /// A client of `shop` that gets its tokens with the client credentials + /// grant: for a shop of the organization that owns the app. + pub fn client_credentials_client(&self, shop: &ShopDomain) -> Result { + self.builder(shop) + .client_credentials(&self.client_id, &self.client_secret) + .build() + } + + // ─── Install link and callback ─────────────────────────────────── + + /// The address that asks the merchant to install the app. + pub fn authorization_url(&self, shop: &ShopDomain, request: &AuthorizationRequest) -> String { + let scope = request.scopes.join(","); + let mut params = vec![ + ("client_id", self.client_id.as_str()), + ("scope", scope.as_str()), + ("redirect_uri", request.redirect_uri.as_str()), + ("state", request.state.as_str()), + ]; + if request.online { + params.push(("grant_options[]", "per-user")); + } + let query = serde_urlencoded::to_string(¶ms) + .unwrap_or_default() + .replace('+', "%20"); + format!("https://{shop}/admin/oauth/authorize?{query}") + } + + /// Exchanges the `code` of a verified callback for a token. + pub async fn exchange_code(&self, callback: &SignedQuery) -> Result { + self.exchange_code_with(callback, false).await + } + + /// [`ShopifyApp::exchange_code`], asking for an expiring offline token + /// with a refresh token. + pub async fn exchange_code_expiring(&self, callback: &SignedQuery) -> Result { + self.exchange_code_with(callback, true).await + } + + async fn exchange_code_with( + &self, + callback: &SignedQuery, + expiring: bool, + ) -> Result { + let shop = callback + .shop() + .ok_or_else(|| invalid("the callback has no valid `shop`"))?; + let code = callback + .get("code") + .filter(|code| !code.is_empty()) + .ok_or_else(|| invalid("the callback has no `code`"))?; + let mut fields = vec![ + ("client_id", self.client_id.as_str()), + ("client_secret", self.client_secret.as_str()), + ("code", code), + ]; + if expiring { + fields.push(("expiring", "1")); + } + request_token( + self.transport()?, + shop, + &self.user_agent, + Encoding::Json, + &fields, + ) + .await + } + + // ─── Signed queries ────────────────────────────────────────────── + + /// Verifies the `hmac` of a query string from Shopify admin: the OAuth + /// callback, a launch of the app, an admin link. Its `timestamp` must be + /// within 90 seconds of now. + /// + /// `query` is the raw query string, with or without its `?`. The message + /// signed is the one Shopify's JavaScript library computes: the + /// parameters but `hmac` and `signature`, sorted by name, form-encoded, + /// the values of a repeated one (`ids[]`) joined with commas. + pub fn verify_query(&self, query: &str) -> Result { + self.verify_query_at(query, Utc::now()) + } + + fn verify_query_at(&self, query: &str, now: DateTime) -> Result { + let params = parse_query(query)?; + let signature = + single(¶ms, "hmac")?.ok_or_else(|| invalid("the query has no `hmac`"))?; + check_timestamp(¶ms, now)?; + let expected = hex::decode(signature) + .map_err(|_| invalid("the `hmac` of the query is not hexadecimal"))?; + let mut mac = mac(self.secret()?); + mac.update(admin_message(¶ms).as_bytes()); + mac.verify_slice(&expected) + .map_err(|_| invalid("the signature of the query does not match"))?; + Ok(signed(params)) + } + + /// The `hmac` Shopify signs a query of Shopify admin with: for tests. + pub fn sign_query(&self, query: &str) -> Result { + let params = parse_query(query)?; + let mut mac = mac(&self.client_secret); + mac.update(admin_message(¶ms).as_bytes()); + Ok(hex::encode(mac.finalize().into_bytes())) + } + + /// Verifies the `signature` of an app proxy request. Its `timestamp` + /// must be within 90 seconds of now. + pub fn verify_app_proxy(&self, query: &str) -> Result { + self.verify_app_proxy_at(query, Utc::now()) + } + + fn verify_app_proxy_at(&self, query: &str, now: DateTime) -> Result { + let params = parse_query(query)?; + for name in PROXY_SINGLE_VALUES { + single(¶ms, name)?; + } + let signature = + single(¶ms, "signature")?.ok_or_else(|| invalid("the query has no `signature`"))?; + check_timestamp(¶ms, now)?; + let expected = hex::decode(signature) + .map_err(|_| invalid("the `signature` of the query is not hexadecimal"))?; + let mut mac = mac(self.secret()?); + mac.update(proxy_message(¶ms).as_bytes()); + mac.verify_slice(&expected) + .map_err(|_| invalid("the signature of the app proxy request does not match"))?; + Ok(signed(params)) + } + + /// The `signature` Shopify signs an app proxy request with: for tests. + pub fn sign_app_proxy(&self, query: &str) -> Result { + let params = parse_query(query)?; + let mut mac = mac(&self.client_secret); + mac.update(proxy_message(¶ms).as_bytes()); + Ok(hex::encode(mac.finalize().into_bytes())) + } + + // ─── Session tokens ────────────────────────────────────────────── + + /// Verifies a session token from the app's frontend (the bearer of its + /// requests): signed by the app's secret with HS256, issued for the app, + /// within its dates, from a shop. + pub fn verify_session_token(&self, token: &str) -> Result { + self.verify_session_token_at(token, Utc::now()) + } + + fn verify_session_token_at(&self, token: &str, now: DateTime) -> Result { + let token = token.trim(); + let token = token.strip_prefix("Bearer ").unwrap_or(token); + let mut parts = token.split('.'); + let (Some(header), Some(payload), Some(signature), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(invalid("the session token is not a JWT")); + }; + let decode = |part: &str| { + BASE64_URL + .decode(part) + .map_err(|_| invalid("the session token is not base64url")) + }; + let header: Value = serde_json::from_slice(&decode(header)?) + .map_err(|_| invalid("the session token has an invalid header"))?; + if header.get("alg").and_then(Value::as_str) != Some("HS256") { + return Err(invalid("the session token is not signed with HS256")); + } + let mut mac = mac(self.secret()?); + // What is signed: the header and the payload, with the dot between them. + mac.update(&token.as_bytes()[..token.len() - signature.len() - 1]); + mac.verify_slice(&decode(signature)?) + .map_err(|_| invalid("the signature of the session token does not match"))?; + + let claims: Value = serde_json::from_slice(&decode(payload)?) + .map_err(|_| invalid("the session token has invalid claims"))?; + let time = |name: &str| claims.get(name).and_then(Value::as_i64); + let now = now.timestamp(); + let expires = time("exp").ok_or_else(|| invalid("the session token has no `exp`"))?; + if now > expires + JWT_TOLERANCE_SECONDS { + return Err(invalid("the session token has expired")); + } + if time("nbf").is_some_and(|not_before| now < not_before - JWT_TOLERANCE_SECONDS) { + return Err(invalid("the session token is not valid yet")); + } + let audience_matches = match claims.get("aud") { + Some(Value::String(audience)) => audience == &self.client_id, + Some(Value::Array(audiences)) => audiences + .iter() + .any(|audience| audience.as_str() == Some(&self.client_id)), + _ => false, + }; + if !audience_matches { + return Err(invalid("the session token was issued for another app")); + } + let destination = claims + .get("dest") + .and_then(Value::as_str) + .ok_or_else(|| invalid("the session token has no `dest`"))?; + let shop = destination + .strip_prefix("https://") + .and_then(|host| ShopDomain::new(host).ok()) + .ok_or_else(|| invalid("the `dest` of the session token is not a shop"))?; + let issuer = claims.get("iss").and_then(Value::as_str); + if issuer.is_some_and(|issuer| !issuer.starts_with(&shop.origin())) { + return Err(invalid( + "the `iss` and `dest` of the session token name different shops", + )); + } + let text = |name: &str| claims.get(name).and_then(Value::as_str).map(str::to_string); + Ok(SessionToken { + user_id: text("sub"), + session_id: text("sid"), + expires_at: Utc + .timestamp_opt(expires, 0) + .single() + .ok_or_else(|| invalid("the `exp` of the session token is out of range"))?, + shop, + claims, + token: token.to_string(), + }) + } + + /// A session token signed with the app's secret, as Shopify makes them: + /// for tests. `claims` should hold `iss`, `dest`, `aud`, `exp` and `nbf`. + pub fn sign_session_token(&self, claims: &Value) -> String { + let header = BASE64_URL.encode(br#"{"alg":"HS256","typ":"JWT"}"#); + let payload = BASE64_URL.encode(serde_json::to_vec(claims).unwrap_or_default()); + let mut mac = mac(&self.client_secret); + mac.update(format!("{header}.{payload}").as_bytes()); + let signature = BASE64_URL.encode(mac.finalize().into_bytes()); + format!("{header}.{payload}.{signature}") + } + + /// Exchanges a verified session token for an access token of its shop. + pub async fn exchange_session_token( + &self, + session: &SessionToken, + requested: RequestedToken, + ) -> Result { + let (requested_type, expiring) = match requested { + RequestedToken::Offline => ( + "urn:shopify:params:oauth:token-type:offline-access-token", + "0", + ), + RequestedToken::ExpiringOffline => ( + "urn:shopify:params:oauth:token-type:offline-access-token", + "1", + ), + RequestedToken::Online => ( + "urn:shopify:params:oauth:token-type:online-access-token", + "0", + ), + }; + let fields = [ + ("client_id", self.client_id.as_str()), + ("client_secret", self.client_secret.as_str()), + ( + "grant_type", + "urn:ietf:params:oauth:grant-type:token-exchange", + ), + ("subject_token", session.as_str()), + ( + "subject_token_type", + "urn:ietf:params:oauth:token-type:id_token", + ), + ("requested_token_type", requested_type), + ("expiring", expiring), + ]; + request_token( + self.transport()?, + session.shop(), + &self.user_agent, + Encoding::Json, + &fields, + ) + .await + } +} + +fn parse_query(query: &str) -> Result> { + let query = query.trim(); + let query = query.strip_prefix('?').unwrap_or(query); + serde_urlencoded::from_str(query).map_err(|_| invalid("the query string does not parse")) +} + +/// The value of a parameter that must not appear twice. +fn single<'a>(params: &'a [(String, String)], name: &str) -> Result> { + let mut values = params.iter().filter(|(given, _)| given == name); + let first = values.next().map(|(_, value)| value.as_str()); + if values.next().is_some() { + return Err(invalid(format!("the query has `{name}` more than once"))); + } + Ok(first) +} + +fn check_timestamp(params: &[(String, String)], now: DateTime) -> Result<()> { + let timestamp: i64 = single(params, "timestamp")? + .and_then(|timestamp| timestamp.parse().ok()) + .ok_or_else(|| invalid("the query has no valid `timestamp`"))?; + if (now.timestamp() - timestamp).abs() > QUERY_TOLERANCE_SECONDS { + return Err(invalid( + "the `timestamp` of the query is more than 90 seconds away", + )); + } + Ok(()) +} + +/// The parameters signed: every one but the signature, the values of a +/// repeated one joined with commas, in the order of the names. +fn signed_params(params: &[(String, String)]) -> Vec<(String, String)> { + let mut grouped: Vec<(String, String)> = Vec::new(); + for (name, value) in params { + if name == "hmac" || name == "signature" { + continue; + } + match grouped.iter_mut().find(|(given, _)| given == name) { + Some((_, joined)) => { + joined.push(','); + joined.push_str(value); + } + None => grouped.push((name.clone(), value.clone())), + } + } + grouped.sort_by(|left, right| left.0.cmp(&right.0)); + grouped +} + +/// What Shopify admin signs: `name=value` pairs, form-encoded with `%20` +/// for spaces, joined with `&`. +fn admin_message(params: &[(String, String)]) -> String { + serde_urlencoded::to_string(signed_params(params)) + .unwrap_or_default() + .replace('+', "%20") +} + +/// What an app proxy signs: `name=value` pairs, as received, joined with nothing. +fn proxy_message(params: &[(String, String)]) -> String { + signed_params(params) + .into_iter() + .map(|(name, value)| format!("{name}={value}")) + .collect() +} + +fn signed(params: Vec<(String, String)>) -> SignedQuery { + let shop = params + .iter() + .find(|(name, _)| name == "shop") + .and_then(|(_, shop)| ShopDomain::new(shop).ok()); + SignedQuery { params, shop } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn app() -> ShopifyApp { + ShopifyApp::new("client-id", "hush") + } + + fn at(timestamp: i64) -> DateTime { + Utc.timestamp_opt(timestamp, 0).unwrap() + } + + #[test] + fn verifies_the_example_of_shopify_documentation() { + // The OAuth callback of Shopify's documentation, signed with "hush". + let query = "code=0907a61c0c8d55e99db179b68161bc00&hmac=700e2dadb827fcc8609e9d5ce208b2e9cdaab9df07390d2cbca10d7c328fc4bf&shop=some-shop.myshopify.com&state=0.6784241404160823×tamp=1337178173"; + let callback = app().verify_query_at(query, at(1337178173 + 30)).unwrap(); + assert_eq!( + callback.get("code"), + Some("0907a61c0c8d55e99db179b68161bc00") + ); + assert_eq!(callback.shop().unwrap().as_str(), "some-shop.myshopify.com"); + + let error = app() + .verify_query_at(query, at(1337178173 + 91)) + .unwrap_err(); + assert_eq!( + error.to_string(), + "verification failed: the `timestamp` of the query is more than 90 seconds away" + ); + let tampered = query.replace("some-shop", "other-shop"); + assert_eq!( + app() + .verify_query_at(&tampered, at(1337178173)) + .unwrap_err() + .to_string(), + "verification failed: the signature of the query does not match" + ); + } + + #[test] + fn signs_queries_as_shopify_admin_does() { + // Spaces as %20, repeated values joined, names sorted, the signature left out. + let params = + parse_query("shop=a.myshopify.com&ids[]=2&ids[]=3×tamp=10¬e=a b&hmac=x") + .unwrap(); + assert_eq!( + admin_message(¶ms), + "ids%5B%5D=2%2C3¬e=a%20b&shop=a.myshopify.com×tamp=10" + ); + let query = format!( + "timestamp={}&shop=a.myshopify.com&host=YWRtaW4", + Utc::now().timestamp() + ); + let signature = app().sign_query(&query).unwrap(); + assert!( + app() + .verify_query(&format!("?{query}&hmac={signature}")) + .is_ok() + ); + assert_eq!( + app().verify_query(&query).unwrap_err().to_string(), + "verification failed: the query has no `hmac`" + ); + } + + #[test] + fn verifies_app_proxy_requests() { + let now = Utc::now().timestamp(); + let query = + format!("shop=a.myshopify.com&path_prefix=%2Fapps%2Fx×tamp={now}&extra=1&extra=2"); + assert_eq!( + proxy_message(&parse_query(&query).unwrap()), + format!("extra=1,2path_prefix=/apps/xshop=a.myshopify.comtimestamp={now}") + ); + let signature = app().sign_app_proxy(&query).unwrap(); + let verified = app() + .verify_app_proxy(&format!("{query}&signature={signature}")) + .unwrap(); + assert_eq!(verified.get("path_prefix"), Some("/apps/x")); + assert!( + app() + .verify_app_proxy(&format!( + "{query}&signature={signature}&shop=b.myshopify.com" + )) + .is_err() + ); + } + + fn claims(now: i64) -> Value { + json!({ + "iss": "https://my-shop.myshopify.com/admin", + "dest": "https://my-shop.myshopify.com", + "aud": "client-id", + "sub": "42", + "exp": now + 60, + "nbf": now - 1, + "iat": now - 1, + "jti": "f8912129-1af6-4cad-9ca3-76b0f7621087", + "sid": "aaea182f2732d44c23057c0fea584021a4485b2bd25d3eb7fd349313ad24c685", + }) + } + + #[test] + fn verifies_session_tokens() { + let now = 1_800_000_000; + let token = app().sign_session_token(&claims(now)); + let session = app() + .verify_session_token_at(&format!("Bearer {token}"), at(now)) + .unwrap(); + assert_eq!(session.shop().as_str(), "my-shop.myshopify.com"); + assert_eq!(session.user_id(), Some("42")); + assert_eq!(session.expires_at(), at(now + 60)); + assert_eq!(session.as_str(), token); + + let refusal = |token: &str, time: i64| { + app() + .verify_session_token_at(token, at(time)) + .unwrap_err() + .to_string() + }; + assert_eq!( + refusal(&token, now + 71), + "verification failed: the session token has expired" + ); + assert_eq!( + refusal(&token, now - 12), + "verification failed: the session token is not valid yet" + ); + let other_app = ShopifyApp::new("other", "hush").sign_session_token(&claims(now)); + assert_eq!( + ShopifyApp::new("client-id", "other") + .verify_session_token_at(&other_app, at(now)) + .unwrap_err() + .to_string(), + "verification failed: the signature of the session token does not match" + ); + let mut audience = claims(now); + audience["aud"] = json!("other"); + assert_eq!( + refusal(&app().sign_session_token(&audience), now), + "verification failed: the session token was issued for another app" + ); + let mut foreign = claims(now); + foreign["dest"] = json!("https://evil.example.com"); + assert_eq!( + refusal(&app().sign_session_token(&foreign), now), + "verification failed: the `dest` of the session token is not a shop" + ); + let mut mixed = claims(now); + mixed["iss"] = json!("https://other-shop.myshopify.com/admin"); + assert_eq!( + refusal(&app().sign_session_token(&mixed), now), + "verification failed: the `iss` and `dest` of the session token name different shops" + ); + // A token whose header claims another algorithm is refused before its signature. + let unsigned = format!( + "{}.{}.", + BASE64_URL.encode(br#"{"alg":"none"}"#), + BASE64_URL.encode(b"{}") + ); + assert_eq!( + refusal(&unsigned, now), + "verification failed: the session token is not signed with HS256" + ); + assert_eq!( + refusal("a.b", now), + "verification failed: the session token is not a JWT" + ); + } + + #[test] + fn an_empty_secret_verifies_nothing() { + let unset = ShopifyApp::new("client-id", ""); + let now = Utc::now().timestamp(); + let query = format!("shop=a.myshopify.com×tamp={now}"); + let signature = unset.sign_query(&query).unwrap(); + assert_eq!( + unset + .verify_query(&format!("{query}&hmac={signature}")) + .unwrap_err() + .to_string(), + "verification failed: the client secret of the app is empty: nothing can be verified with it" + ); + let token = unset.sign_session_token(&claims(now)); + assert!(unset.verify_session_token(&token).is_err()); + let signature = unset.sign_app_proxy(&query).unwrap(); + assert!( + unset + .verify_app_proxy(&format!("{query}&signature={signature}")) + .is_err() + ); + } + + #[test] + fn debug_hides_codes_and_tokens() { + let now = Utc::now().timestamp(); + let query = format!("code=secret-code&shop=a.myshopify.com×tamp={now}"); + let signature = app().sign_query(&query).unwrap(); + let callback = app() + .verify_query(&format!("{query}&hmac={signature}")) + .unwrap(); + let shown = format!("{callback:?}"); + assert!(!shown.contains("secret-code"), "{shown}"); + assert!(shown.contains("\"code\""), "{shown}"); + + let token = app().sign_session_token(&claims(now)); + let session = app().verify_session_token(&token).unwrap(); + assert!(!format!("{session:?}").contains(&token)); + } + + #[test] + fn builds_install_links() { + let shop = ShopDomain::new("my-shop").unwrap(); + let link = app().authorization_url( + &shop, + &AuthorizationRequest::new("https://example.com/auth/callback", "nonce 1") + .scopes(["read_products", "write_orders"]) + .online(), + ); + assert_eq!( + link, + "https://my-shop.myshopify.com/admin/oauth/authorize?client_id=client-id&scope=read_products%2Cwrite_orders\ + &redirect_uri=https%3A%2F%2Fexample.com%2Fauth%2Fcallback&state=nonce%201&grant_options%5B%5D=per-user" + ); + } +} diff --git a/crates/shopify_api/src/pagination.rs b/crates/shopify_api/src/pagination.rs new file mode 100644 index 0000000..46ed59a --- /dev/null +++ b/crates/shopify_api/src/pagination.rs @@ -0,0 +1,97 @@ +//! Cursor pagination over a connection. + +use serde::de::DeserializeOwned; + +use crate::{Error, Operation, Result, Shopify}; + +/// One page of a connection: its items and its `pageInfo`. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Page { + pub items: Vec, + pub has_next_page: bool, + pub end_cursor: Option, +} + +impl Page { + pub fn new(items: Vec, has_next_page: bool, end_cursor: Option) -> Self { + Self { + items, + has_next_page, + end_cursor, + } + } + + /// The items converted, the page info kept. + pub fn map(self, convert: impl FnMut(T) -> U) -> Page { + Page { + items: self.items.into_iter().map(convert).collect(), + has_next_page: self.has_next_page, + end_cursor: self.end_cursor, + } + } +} + +impl Shopify { + /// Runs `operation` page after page and collects every item. + /// + /// `operation` receives the cursor to start after, `None` for the first + /// page; `page` reads the items and the `pageInfo` out of each answer. + /// + /// ```no_run + /// use shopify_api::{Page, graphql}; + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let products = shopify + /// .paginate( + /// |after| { + /// graphql!( + /// "query($after: String) { + /// products(first: 250, after: $after) { + /// nodes { id title } + /// pageInfo { hasNextPage endCursor } + /// } + /// }", + /// after = after, + /// ) + /// }, + /// |data| { + /// let page_info = data.products.page_info; + /// Page::new(data.products.nodes, page_info.has_next_page, page_info.end_cursor) + /// }, + /// ) + /// .await?; + /// println!("{} products", products.len()); + /// # Ok(()) + /// # } + /// ``` + /// + /// For a large catalog, a [bulk operation](crate::bulk) reads everything + /// at once, without the rate limit. + pub async fn paginate(&self, mut operation: O, mut page: P) -> Result> + where + D: DeserializeOwned, + O: FnMut(Option) -> Operation, + P: FnMut(D) -> Page, + { + let mut items = Vec::new(); + let mut cursor: Option = None; + loop { + let data = self.execute(operation(cursor.clone())).await?; + let current = page(data); + items.extend(current.items); + if !current.has_next_page { + return Ok(items); + } + match current.end_cursor { + Some(next) if cursor.as_ref() != Some(&next) => cursor = Some(next), + _ => { + return Err(Error::Decode { + path: "pageInfo.endCursor".to_string(), + message: "`hasNextPage` is true but the cursor does not move: select `pageInfo { hasNextPage endCursor }` and pass the cursor as `after`".to_string(), + }); + } + } + } + } +} diff --git a/crates/shopify_api/src/schema.rs b/crates/shopify_api/src/schema.rs new file mode 100644 index 0000000..a79de46 --- /dev/null +++ b/crates/shopify_api/src/schema.rs @@ -0,0 +1,134 @@ +//! Downloading Shopify's Admin GraphQL schema, as an introspection result. +//! +//! [`graphql!`](crate::graphql!) checks operations against the schema of +//! [`ApiVersion::DEFAULT`], bundled with this crate. For another version, +//! the `shopify-api schema download` command stores the schema where +//! `graphql!` reads it; these functions return the raw introspection result, +//! for other tools. + +use serde_json::{Value, json}; + +use crate::transport::{HttpRequest, Method, Transport}; +use crate::{ApiVersion, Error, Result, Shopify}; + +/// Shopify's public copy of the Admin schema: a GraphQL endpoint per version +/// that answers introspection without a token. +pub const PUBLIC_ADMIN_SCHEMA_ENDPOINT: &str = "https://shopify.dev/admin-graphql-direct-proxy"; + +/// The introspection query: types, fields, arguments, enum values, +/// directives and deprecations, without descriptions. +pub const INTROSPECTION_QUERY: &str = "\ +query IntrospectionQuery { + __schema { + queryType { name } + mutationType { name } + types { + kind + name + fields(includeDeprecated: true) { + name + args(includeDeprecated: true) { ...InputValue } + type { ...TypeRef } + isDeprecated + deprecationReason + } + inputFields(includeDeprecated: true) { ...InputValue } + interfaces { name } + enumValues(includeDeprecated: true) { name isDeprecated deprecationReason } + possibleTypes { name } + } + directives { + name + locations + isRepeatable + args(includeDeprecated: true) { ...InputValue } + } + } +} +fragment InputValue on __InputValue { + name + type { ...TypeRef } + defaultValue + isDeprecated + deprecationReason +} +fragment TypeRef on __Type { + kind name + ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } +} +"; + +/// Downloads the Admin schema of `version` from Shopify's public endpoint, +/// with the default transport. +#[cfg(any(feature = "rustls", feature = "native-tls"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))] +pub async fn download_public_admin_schema(version: ApiVersion) -> Result { + download_public_admin_schema_with(&crate::transport::ReqwestTransport::new()?, version).await +} + +/// Downloads the Admin schema of `version` from Shopify's public endpoint. +pub async fn download_public_admin_schema_with( + transport: &dyn Transport, + version: ApiVersion, +) -> Result { + let url = format!("{PUBLIC_ADMIN_SCHEMA_ENDPOINT}/{version}"); + let request = HttpRequest::new(Method::Post, &url) + .with_header("Accept", "application/json") + .with_header("User-Agent", crate::USER_AGENT) + .with_json(&json!({ "query": INTROSPECTION_QUERY })) + .with_timeout(std::time::Duration::from_secs(120)); + let response = transport + .send(request) + .await + .map_err(|source| Error::transport(&url, source))?; + if !response.is_success() { + return Err(Error::http(&url, &response)); + } + let value: Value = serde_json::from_slice(&response.body)?; + check(value) +} + +impl Shopify { + /// Downloads the Admin schema of the client's version through the shop: + /// the schema the shop's token sees. + pub async fn download_admin_schema(&self) -> Result { + let raw = self.graphql_raw(INTROSPECTION_QUERY, ()).await?; + if !raw.errors.is_empty() { + return Err(Error::Graphql(crate::GraphqlErrors { + errors: raw.errors, + data: None, + })); + } + check(json!({ "data": raw.data })) + } +} + +/// An introspection result, or why it is not one. +fn check(value: Value) -> Result { + if let Some(message) = value.get("error").and_then(Value::as_str) { + return Err(Error::Http { + status: 200, + url: PUBLIC_ADMIN_SCHEMA_ENDPOINT.to_string(), + body: message.to_string(), + request_id: None, + }); + } + if value.pointer("/data/__schema/types").is_none() { + return Err(Error::Decode { + path: "data.__schema".to_string(), + message: "the answer is not an introspection result".to_string(), + }); + } + Ok(value) +} + +#[cfg(all(test, feature = "cli"))] +mod tests { + #[test] + fn the_query_is_the_one_graphql_reads() { + assert_eq!( + super::INTROSPECTION_QUERY, + shopify_api_graphql::INTROSPECTION_QUERY + ); + } +} diff --git a/crates/shopify_api/src/shop.rs b/crates/shopify_api/src/shop.rs new file mode 100644 index 0000000..f7dd2d0 --- /dev/null +++ b/crates/shopify_api/src/shop.rs @@ -0,0 +1,171 @@ +//! The domain of a shop, which every request and every token is bound to. + +use std::fmt; +use std::str::FromStr; + +use crate::Error; + +const SUFFIX: &str = ".myshopify.com"; + +/// The permanent domain of a shop: `my-shop.myshopify.com`. +/// +/// Requests and tokens go to the address built from it, so it only takes a +/// shop's handle or its `myshopify.com` domain, never another host: +/// +/// ``` +/// use shopify_api::ShopDomain; +/// +/// assert_eq!(ShopDomain::new("my-shop")?.as_str(), "my-shop.myshopify.com"); +/// assert_eq!(ShopDomain::new("https://My-Shop.myshopify.com/")?.handle(), "my-shop"); +/// assert!(ShopDomain::new("my-shop.example.com").is_err()); +/// assert!(ShopDomain::new("evil.com/x?.myshopify.com").is_err()); +/// # Ok::<(), shopify_api::Error>(()) +/// ``` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ShopDomain(String); + +impl ShopDomain { + /// Accepts `my-shop`, `my-shop.myshopify.com`, with or without `https://` + /// and a trailing `/`, in any case. + pub fn new(shop: &str) -> Result { + let invalid = || Error::InvalidShop(shop.to_string()); + let trimmed = shop.trim(); + let trimmed = trimmed.strip_prefix("https://").unwrap_or(trimmed); + let trimmed = trimmed.strip_suffix('/').unwrap_or(trimmed); + let lowered = trimmed.to_ascii_lowercase(); + let handle = lowered.strip_suffix(SUFFIX).unwrap_or(&lowered); + let valid = !handle.is_empty() + && handle.len() <= 63 + && handle + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') + && !handle.starts_with('-') + && !handle.ends_with('-'); + if !valid { + return Err(invalid()); + } + Ok(Self(format!("{handle}{SUFFIX}"))) + } + + /// `my-shop.myshopify.com`. + pub fn as_str(&self) -> &str { + &self.0 + } + + /// `my-shop`. + pub fn handle(&self) -> &str { + &self.0[..self.0.len() - SUFFIX.len()] + } + + /// `https://my-shop.myshopify.com`. + pub fn origin(&self) -> String { + format!("https://{}", self.0) + } +} + +impl fmt::Display for ShopDomain { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } +} + +impl AsRef for ShopDomain { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl FromStr for ShopDomain { + type Err = Error; + + fn from_str(shop: &str) -> Result { + Self::new(shop) + } +} + +impl TryFrom<&str> for ShopDomain { + type Error = Error; + + fn try_from(shop: &str) -> Result { + Self::new(shop) + } +} + +impl TryFrom for ShopDomain { + type Error = Error; + + fn try_from(shop: String) -> Result { + Self::new(&shop) + } +} + +impl TryFrom<&String> for ShopDomain { + type Error = Error; + + fn try_from(shop: &String) -> Result { + Self::new(shop) + } +} + +impl serde::Serialize for ShopDomain { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.0) + } +} + +impl<'de> serde::Deserialize<'de> for ShopDomain { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Self::new(&text).map_err(serde::de::Error::custom) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn normalizes_handles_and_domains() { + for input in [ + "my-shop", + "my-shop.myshopify.com", + "MY-SHOP.myshopify.com", + " https://my-shop.myshopify.com/ ", + "my-shop.MyShopify.com", + ] { + let shop = ShopDomain::new(input).unwrap(); + assert_eq!(shop.as_str(), "my-shop.myshopify.com", "{input}"); + assert_eq!(shop.handle(), "my-shop"); + assert_eq!(shop.origin(), "https://my-shop.myshopify.com"); + } + assert_eq!( + ShopDomain::new("shop2").unwrap().as_str(), + "shop2.myshopify.com" + ); + } + + #[test] + fn refuses_any_other_host() { + for input in [ + "", + ".myshopify.com", + "my shop", + "my_shop", + "-shop", + "shop-", + "my-shop.example.com", + "http://my-shop.myshopify.com", + "my-shop.myshopify.com.evil.com", + "evil.com/x?.myshopify.com", + "evil.com#.myshopify.com", + "user@my-shop.myshopify.com", + "my-shop.myshopify.com:8443", + "a.b.myshopify.com", + ] { + assert!( + matches!(ShopDomain::new(input), Err(Error::InvalidShop(_))), + "{input}" + ); + } + } +} diff --git a/crates/shopify_api/src/testing.rs b/crates/shopify_api/src/testing.rs new file mode 100644 index 0000000..cecd0ca --- /dev/null +++ b/crates/shopify_api/src/testing.rs @@ -0,0 +1,212 @@ +//! Testing code that calls Shopify, without the network. +//! +//! A [`MockTransport`] records the requests a client sends and answers them +//! with what the test scripts: queued answers first, in order, then a +//! handler, then `404`. +//! +//! ``` +//! use shopify_api::graphql; +//! use shopify_api::testing::{MockTransport, client}; +//! +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() -> shopify_api::Result<()> { +//! let mock = MockTransport::new(); +//! mock.push_data(serde_json::json!({ "shop": { "name": "Test shop" } })); +//! let shopify = client(&mock); +//! +//! let data = shopify.execute(graphql!("query Shop { shop { name } }")).await?; +//! +//! assert_eq!(data.shop.name, "Test shop"); +//! let sent = mock.graphql_requests(); +//! assert_eq!(sent[0].operation_name.as_deref(), Some("Shop")); +//! # Ok(()) +//! # } +//! ``` + +use std::collections::VecDeque; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::transport::{BoxFuture, HttpRequest, HttpResponse, Transport, TransportError}; +use crate::{RetryPolicy, Shopify}; + +type Handler = dyn Fn(&HttpRequest) -> Result + Send + Sync; + +/// A [`Transport`] that answers what the test says. Clones share their state. +#[derive(Clone, Default)] +pub struct MockTransport { + state: Arc>, +} + +#[derive(Default)] +struct State { + queue: VecDeque>, + handler: Option>, + requests: Vec, +} + +impl std::fmt::Debug for MockTransport { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let state = self.state(); + formatter + .debug_struct("MockTransport") + .field("queued", &state.queue.len()) + .field("handler", &state.handler.is_some()) + .field("requests", &state.requests.len()) + .finish() + } +} + +impl MockTransport { + pub fn new() -> Self { + Self::default() + } + + fn state(&self) -> MutexGuard<'_, State> { + self.state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Answers every request that finds no queued answer. + pub fn respond_with( + &self, + handler: impl Fn(&HttpRequest) -> Result + Send + Sync + 'static, + ) -> &Self { + self.state().handler = Some(Arc::new(handler)); + self + } + + /// Answers the next request that finds no answer queued before this one. + pub fn push(&self, response: HttpResponse) -> &Self { + self.state().queue.push_back(Ok(response)); + self + } + + /// Fails the next request, as a network failure. + pub fn push_error(&self, error: TransportError) -> &Self { + self.state().queue.push_back(Err(error)); + self + } + + /// Answers the next request with `200` and `body`. + pub fn push_json(&self, body: Value) -> &Self { + self.push(HttpResponse::json(200, &body)) + } + + /// Answers the next request with `200` and `{ "data": data }`. + pub fn push_data(&self, data: Value) -> &Self { + self.push_json(json!({ "data": data })) + } + + /// Answers the next request with `200` and Shopify's `THROTTLED` error. + pub fn push_throttled(&self) -> &Self { + self.push_json(json!({ + "errors": [{ "message": "Throttled", "extensions": { "code": "THROTTLED" } }], + "extensions": { "cost": { + "requestedQueryCost": 10, + "actualQueryCost": null, + "throttleStatus": { "maximumAvailable": 2000.0, "currentlyAvailable": 0, "restoreRate": 100.0 }, + } }, + })) + } + + /// Every request sent so far, in order. + pub fn requests(&self) -> Vec { + self.state().requests.clone() + } + + pub fn last_request(&self) -> Option { + self.state().requests.last().cloned() + } + + /// The GraphQL requests sent so far, read. + pub fn graphql_requests(&self) -> Vec { + self.state() + .requests + .iter() + .filter_map(GraphqlRequest::read) + .collect() + } + + /// Forgets the requests, the queued answers and the handler. + pub fn clear(&self) { + *self.state() = State::default(); + } +} + +impl Transport for MockTransport { + fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result> { + let answer = { + let mut state = self.state(); + state.requests.push(request.clone()); + match state.queue.pop_front() { + Some(answer) => answer, + None => match state.handler.clone() { + Some(handler) => { + drop(state); + handler(&request) + } + None => Ok(HttpResponse::new( + 404, + format!("not mocked: {:?} {}", request.method, request.url), + )), + }, + } + }; + Box::pin(async move { answer }) + } +} + +/// A GraphQL request, as a [`MockTransport`] received it. +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub struct GraphqlRequest { + pub url: String, + /// The version of the address: `2026-10`. + pub api_version: String, + pub query: String, + /// The variables, `{}` when there are none. + pub variables: Value, + pub operation_name: Option, + pub access_token: Option, +} + +impl GraphqlRequest { + fn read(request: &HttpRequest) -> Option { + let (_, path) = request.url.split_once("/admin/api/")?; + let (api_version, rest) = path.split_once('/')?; + if rest != "graphql.json" { + return None; + } + let body = request.json()?; + Some(Self { + url: request.url.clone(), + api_version: api_version.to_string(), + query: body.get("query")?.as_str()?.to_string(), + variables: body.get("variables").cloned().unwrap_or_else(|| json!({})), + operation_name: body + .get("operationName") + .and_then(Value::as_str) + .map(str::to_string), + access_token: request.header("X-Shopify-Access-Token").map(str::to_string), + }) + } +} + +/// A client of `test-shop.myshopify.com` with the token `test-token`, +/// sending through `mock`, retrying without waiting. +pub fn client(mock: &MockTransport) -> Shopify { + Shopify::builder("test-shop") + .access_token("test-token") + .transport(mock.clone()) + .retry( + RetryPolicy::new(4) + .with_base_delay(Duration::ZERO) + .with_max_delay(Duration::ZERO), + ) + .build() + .expect("a valid test client") +} diff --git a/crates/shopify_api/src/transport.rs b/crates/shopify_api/src/transport.rs new file mode 100644 index 0000000..39b8f46 --- /dev/null +++ b/crates/shopify_api/src/transport.rs @@ -0,0 +1,372 @@ +//! The HTTP layer, behind a trait: [`ReqwestTransport`] by default, a +//! [`MockTransport`](crate::testing::MockTransport) in tests, or your own. + +use std::fmt; +use std::future::Future; +use std::pin::Pin; +use std::time::Duration; + +/// A boxed, sendable future, as [`Transport::send`] returns. +pub type BoxFuture<'a, T> = Pin + Send + 'a>>; + +/// Header names whose value is a secret, hidden by `Debug`. +const SECRET_HEADERS: [&str; 3] = ["x-shopify-access-token", "authorization", "cookie"]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum Method { + Get, + Post, +} + +/// A request this crate sends. +/// +/// `Debug` hides the value of secret headers and the body, which may hold a +/// client secret or a refresh token. +#[derive(Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct HttpRequest { + pub method: Method, + pub url: String, + pub headers: Vec<(String, String)>, + pub body: Vec, + /// How long the whole request may take, when it differs from the transport's default. + pub timeout: Option, +} + +impl HttpRequest { + pub fn new(method: Method, url: impl Into) -> Self { + Self { + method, + url: url.into(), + headers: Vec::new(), + body: Vec::new(), + timeout: None, + } + } + + pub fn with_header(mut self, name: impl Into, value: impl Into) -> Self { + self.headers.push((name.into(), value.into())); + self + } + + pub fn with_body(mut self, body: impl Into>) -> Self { + self.body = body.into(); + self + } + + /// A JSON body, with its `Content-Type`. + pub(crate) fn with_json(self, body: &serde_json::Value) -> Self { + self.with_header("Content-Type", "application/json") + .with_body(serde_json::to_vec(body).unwrap_or_default()) + } + + /// A URL-encoded form body, with its `Content-Type`. + pub(crate) fn with_form(self, fields: &[(&str, &str)]) -> Self { + self.with_header("Content-Type", "application/x-www-form-urlencoded") + .with_body(serde_urlencoded::to_string(fields).unwrap_or_default()) + } + + pub(crate) fn with_timeout(mut self, timeout: Duration) -> Self { + self.timeout = Some(timeout); + self + } + + /// The first value of a header, whatever the case of its name. + pub fn header(&self, name: &str) -> Option<&str> { + header(&self.headers, name) + } + + /// The body read as JSON, `None` when it is not. + pub fn json(&self) -> Option { + serde_json::from_slice(&self.body).ok() + } + + /// The body read as a URL-encoded form. + pub fn form(&self) -> Vec<(String, String)> { + serde_urlencoded::from_bytes(&self.body).unwrap_or_default() + } +} + +impl fmt::Debug for HttpRequest { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let headers: Vec<(&str, &str)> = self + .headers + .iter() + .map(|(name, value)| { + let secret = SECRET_HEADERS + .iter() + .any(|secret| name.eq_ignore_ascii_case(secret)); + ( + name.as_str(), + if secret { "[redacted]" } else { value.as_str() }, + ) + }) + .collect(); + formatter + .debug_struct("HttpRequest") + .field("method", &self.method) + .field("url", &self.url) + .field("headers", &headers) + .field("body", &format_args!("[{} bytes]", self.body.len())) + .field("timeout", &self.timeout) + .finish() + } +} + +/// An answer to an [`HttpRequest`]. +/// +/// `Debug` hides the body, which may hold a token. +#[derive(Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct HttpResponse { + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl fmt::Debug for HttpResponse { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("HttpResponse") + .field("status", &self.status) + .field("headers", &self.headers) + .field("body", &format_args!("[{} bytes]", self.body.len())) + .finish() + } +} + +impl HttpResponse { + pub fn new(status: u16, body: impl Into>) -> Self { + Self { + status, + headers: Vec::new(), + body: body.into(), + } + } + + /// An answer with a JSON body. + pub fn json(status: u16, body: &serde_json::Value) -> Self { + Self::new(status, serde_json::to_vec(body).unwrap_or_default()) + .with_header("Content-Type", "application/json") + } + + pub fn with_header(mut self, name: impl Into, value: impl Into) -> Self { + self.headers.push((name.into(), value.into())); + self + } + + pub fn is_success(&self) -> bool { + (200..300).contains(&self.status) + } + + /// The first value of a header, whatever the case of its name. + pub fn header(&self, name: &str) -> Option<&str> { + header(&self.headers, name) + } + + /// The body as text, what is not UTF-8 replaced. + pub fn text(&self) -> String { + String::from_utf8_lossy(&self.body).into_owned() + } +} + +fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> { + headers + .iter() + .find(|(given, _)| given.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.as_str()) +} + +/// A request that did not get an answer: no connection, a timeout, a body +/// that stopped halfway. +#[derive(Debug)] +pub struct TransportError { + message: String, + timeout: bool, + source: Option>, +} + +impl TransportError { + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + timeout: false, + source: None, + } + } + + /// The request took longer than it may. + pub fn timeout(message: impl Into) -> Self { + Self { + timeout: true, + ..Self::new(message) + } + } + + pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self { + self.source = Some(Box::new(source)); + self + } + + pub fn is_timeout(&self) -> bool { + self.timeout + } +} + +impl fmt::Display for TransportError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.message) + } +} + +impl std::error::Error for TransportError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.source.as_deref().map(|source| source as _) + } +} + +/// Sends the requests of a [`Shopify`](crate::Shopify) client. +/// +/// Requests carry secrets in their headers or their body: an implementation +/// must not follow redirections, and returns a `3xx` as the answer, so that a +/// secret is never sent on to another host. +pub trait Transport: Send + Sync + 'static { + fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result>; +} + +/// The `reqwest` this crate is built with, for [`ReqwestTransport::from_builder`]. +#[cfg(any(feature = "rustls", feature = "native-tls"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))] +pub use reqwest; + +/// The default [`Transport`], over `reqwest`: no redirections, a 10-second +/// connection timeout and a 60-second request timeout. +#[cfg(any(feature = "rustls", feature = "native-tls"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))] +#[derive(Debug, Clone)] +pub struct ReqwestTransport { + client: reqwest::Client, +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +impl ReqwestTransport { + pub fn new() -> Result { + Self::from_builder( + reqwest::Client::builder() + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(60)), + ) + } + + /// A transport from a client you configure: a proxy, other timeouts, + /// other certificates. Redirections are turned off whatever the builder + /// says, as [`Transport`] requires. + /// + /// Build `builder` with the [`reqwest`] this module re-exports. + pub fn from_builder(builder: reqwest::ClientBuilder) -> Result { + let client = builder + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|error| { + crate::Error::Config(format!("the HTTP client does not start: {error}")) + })?; + Ok(Self { client }) + } +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +impl Transport for ReqwestTransport { + fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result> { + Box::pin(async move { + let failed = |error: reqwest::Error| { + // Its address may hold a signature: errors leave it out. + let error = error.without_url(); + let message = error.to_string(); + if error.is_timeout() { + TransportError::timeout(message).with_source(error) + } else { + TransportError::new(message).with_source(error) + } + }; + let method = match request.method { + Method::Get => reqwest::Method::GET, + Method::Post => reqwest::Method::POST, + }; + let mut builder = self.client.request(method, &request.url); + for (name, value) in &request.headers { + builder = builder.header(name, value); + } + if let Some(timeout) = request.timeout { + builder = builder.timeout(timeout); + } + if !request.body.is_empty() { + builder = builder.body(request.body); + } + let response = builder.send().await.map_err(failed)?; + let status = response.status().as_u16(); + let headers = response + .headers() + .iter() + .filter_map(|(name, value)| { + Some((name.to_string(), value.to_str().ok()?.to_string())) + }) + .collect(); + let body = response.bytes().await.map_err(failed)?.to_vec(); + Ok(HttpResponse { + status, + headers, + body, + }) + }) + } +} + +/// The transport a client uses when it is given none. +pub(crate) fn default_transport() -> Result, crate::Error> { + #[cfg(any(feature = "rustls", feature = "native-tls"))] + { + Ok(std::sync::Arc::new(ReqwestTransport::new()?)) + } + #[cfg(not(any(feature = "rustls", feature = "native-tls")))] + { + Err(crate::Error::NoTransport) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_hides_secrets() { + let request = HttpRequest::new( + Method::Post, + "https://shop.myshopify.com/admin/oauth/access_token", + ) + .with_header("X-Shopify-Access-Token", "shpat_secret") + .with_form(&[("client_secret", "very-secret")]); + let shown = format!("{request:?}"); + assert!(!shown.contains("shpat_secret"), "{shown}"); + assert!(!shown.contains("very-secret"), "{shown}"); + assert!(shown.contains("[redacted]"), "{shown}"); + assert_eq!( + request.header("x-shopify-access-token"), + Some("shpat_secret") + ); + assert_eq!( + request.form(), + [("client_secret".to_string(), "very-secret".to_string())] + ); + } + + #[test] + fn responses_read_headers_whatever_their_case() { + let response = HttpResponse::json(429, &serde_json::json!({ "errors": "Throttled" })) + .with_header("Retry-After", "2.0"); + assert_eq!(response.header("retry-after"), Some("2.0")); + assert_eq!(response.header("content-type"), Some("application/json")); + assert!(!response.is_success()); + assert_eq!(response.text(), "{\"errors\":\"Throttled\"}"); + } +} diff --git a/crates/shopify_api/src/version.rs b/crates/shopify_api/src/version.rs new file mode 100644 index 0000000..98e900b --- /dev/null +++ b/crates/shopify_api/src/version.rs @@ -0,0 +1,220 @@ +//! Shopify Admin API versions. + +use std::fmt; +use std::str::FromStr; + +use crate::Error; + +/// A Shopify Admin API version: a quarterly release such as `2026-10`, or `unstable`. +/// +/// ``` +/// use shopify_api::ApiVersion; +/// +/// let version: ApiVersion = "2026-07".parse()?; +/// assert_eq!(version, ApiVersion::V2026_07); +/// assert!(version < ApiVersion::DEFAULT); +/// assert_eq!(ApiVersion::UNSTABLE.to_string(), "unstable"); +/// # Ok::<(), shopify_api::Error>(()) +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ApiVersion(Repr); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +enum Repr { + Dated { year: u16, month: u8 }, + Unstable, +} + +impl ApiVersion { + pub const V2026_04: Self = Self::dated(2026, 4); + pub const V2026_07: Self = Self::dated(2026, 7); + pub const V2026_10: Self = Self::dated(2026, 10); + /// The release candidate of 2027-01. + pub const V2027_01: Self = Self::dated(2027, 1); + pub const UNSTABLE: Self = Self(Repr::Unstable); + + /// The version this crate calls when none is chosen: the one of the + /// schema bundled with it, which `graphql!` checks operations against. + pub const DEFAULT: Self = Self::V2026_10; + + /// The oldest version this crate accepts: the first whose bulk operation + /// API (`bulkOperation(id:)`, `bulkOperations`) it relies on. + pub const MINIMUM: Self = Self::V2026_04; + + const fn dated(year: u16, month: u8) -> Self { + Self(Repr::Dated { year, month }) + } + + /// Parses `2026-10` or `unstable`. Shopify releases a version each + /// quarter, in January, April, July and October. + pub fn new(version: &str) -> Result { + let invalid = |reason: &str| Error::InvalidApiVersion { + version: version.to_string(), + reason: reason.to_string(), + }; + if version == "unstable" { + return Ok(Self::UNSTABLE); + } + let bytes = version.as_bytes(); + let well_formed = bytes.len() == 7 + && bytes[4] == b'-' + && bytes[..4].iter().chain(&bytes[5..]).all(u8::is_ascii_digit); + if !well_formed { + return Err(invalid( + "expected `YYYY-MM`, such as `2026-10`, or `unstable`", + )); + } + let year: u16 = version[..4].parse().map_err(|_| invalid("invalid year"))?; + let month: u8 = version[5..].parse().map_err(|_| invalid("invalid month"))?; + if !matches!(month, 1 | 4 | 7 | 10) { + return Err(invalid( + "Shopify releases a version in January, April, July and October", + )); + } + let parsed = Self::dated(year, month); + if parsed < Self::MINIMUM { + return Err(invalid("the oldest version this crate supports is 2026-04")); + } + Ok(parsed) + } + + pub fn is_unstable(&self) -> bool { + matches!(self.0, Repr::Unstable) + } +} + +impl Default for ApiVersion { + fn default() -> Self { + Self::DEFAULT + } +} + +impl fmt::Display for ApiVersion { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + Repr::Dated { year, month } => write!(formatter, "{year:04}-{month:02}"), + Repr::Unstable => formatter.write_str("unstable"), + } + } +} + +impl FromStr for ApiVersion { + type Err = Error; + + fn from_str(version: &str) -> Result { + Self::new(version) + } +} + +impl TryFrom<&str> for ApiVersion { + type Error = Error; + + fn try_from(version: &str) -> Result { + Self::new(version) + } +} + +impl serde::Serialize for ApiVersion { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +impl<'de> serde::Deserialize<'de> for ApiVersion { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Self::new(&text).map_err(serde::de::Error::custom) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_and_prints_versions() { + for text in [ + "2026-04", "2026-07", "2026-10", "2027-01", "2030-10", "unstable", + ] { + assert_eq!(ApiVersion::new(text).unwrap().to_string(), text); + } + assert_eq!(ApiVersion::DEFAULT.to_string(), "2026-10"); + assert!(ApiVersion::UNSTABLE.is_unstable()); + assert!(ApiVersion::V2026_04 < ApiVersion::V2026_10); + assert!(ApiVersion::V2027_01 < ApiVersion::UNSTABLE); + } + + #[test] + fn refuses_what_shopify_does_not_release() { + for (text, reason) in [ + ( + "2026-4", + "expected `YYYY-MM`, such as `2026-10`, or `unstable`", + ), + ( + "latest", + "expected `YYYY-MM`, such as `2026-10`, or `unstable`", + ), + ( + "2026-10/../x", + "expected `YYYY-MM`, such as `2026-10`, or `unstable`", + ), + ( + "2026-05", + "Shopify releases a version in January, April, July and October", + ), + ( + "2026-01", + "the oldest version this crate supports is 2026-04", + ), + ( + "2025-10", + "the oldest version this crate supports is 2026-04", + ), + ] { + match ApiVersion::new(text) { + Err(Error::InvalidApiVersion { + version, + reason: given, + }) => { + assert_eq!((version.as_str(), given.as_str()), (text, reason)); + } + other => panic!("{text}: {other:?}"), + } + } + } + + #[cfg(feature = "cli")] + #[test] + fn the_minimum_is_the_one_graphql_checks() { + assert_eq!( + ApiVersion::MINIMUM.to_string(), + shopify_api_graphql::MINIMUM_API_VERSION + ); + for version in ["2026-04", "2026-07", "2027-10", "unstable"] { + assert!( + shopify_api_graphql::is_supported_api_version(version), + "{version}" + ); + assert!(ApiVersion::new(version).is_ok(), "{version}"); + } + for version in ["2026-01", "2025-10", "2026-05", "2026-4", "latest"] { + assert!( + !shopify_api_graphql::is_supported_api_version(version), + "{version}" + ); + assert!(ApiVersion::new(version).is_err(), "{version}"); + } + } + + #[test] + fn travels_as_a_string() { + let json = serde_json::to_string(&ApiVersion::V2026_07).unwrap(); + assert_eq!(json, "\"2026-07\""); + assert_eq!( + serde_json::from_str::(&json).unwrap(), + ApiVersion::V2026_07 + ); + assert!(serde_json::from_str::("\"2026-02\"").is_err()); + } +} diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs new file mode 100644 index 0000000..c7b8fa9 --- /dev/null +++ b/crates/shopify_api/src/webhooks.rs @@ -0,0 +1,739 @@ +//! Webhooks: verify and read what Shopify sends, and manage the webhook +//! subscriptions of a shop. +//! +//! ``` +//! use shopify_api::webhooks::Webhook; +//! +//! # fn handle(headers: &[(&str, &str)], body: &[u8]) -> shopify_api::Result<()> { +//! // In your HTTP handler, with the raw body, before parsing it. +//! let webhook = Webhook::verify(headers.iter().copied(), body, "the app's client secret")?; +//! match webhook.topic() { +//! "orders/create" => { +//! let order: serde_json::Value = webhook.payload()?; +//! println!("order {} on {}", order["name"], webhook.shop()); +//! } +//! other => println!("{other} ignored"), +//! } +//! # Ok(()) +//! # } +//! ``` +//! +//! Shopify may deliver a webhook more than once: [`Webhook::event_id`] +//! identifies the event across deliveries. +//! +//! The signature covers the body only. The headers (the topic, the shop, the +//! IDs) are what Shopify sent along, unsigned: a captured body could be +//! replayed with other headers. Check what matters against the body, or +//! against your own records of the shop. + +use base64::Engine; +use base64::engine::general_purpose::STANDARD; +use hmac::{Hmac, KeyInit, Mac}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use sha2::Sha256; + +use crate::{Error, Result, ShopDomain, Shopify, UserError, graphql}; + +/// Whether `hmac_header` (`X-Shopify-Hmac-Sha256`) is the signature of +/// `body` with `secret`, the client secret of the app. Compares in constant time. +pub fn verify_hmac(secret: &str, body: &[u8], hmac_header: &str) -> bool { + // Anyone can sign with an empty key: it verifies nothing. + if secret.is_empty() { + return false; + } + let Ok(expected) = STANDARD.decode(hmac_header.trim()) else { + return false; + }; + let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { + return false; + }; + mac.update(body); + mac.verify_slice(&expected).is_ok() +} + +/// The signature Shopify would send for `body`, base64: for tests. +pub fn sign(secret: &str, body: &[u8]) -> String { + let mut mac = + Hmac::::new_from_slice(secret.as_bytes()).expect("HMAC takes a key of any length"); + mac.update(body); + STANDARD.encode(mac.finalize().into_bytes()) +} + +/// A webhook whose signature was verified. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Webhook { + topic: String, + shop: ShopDomain, + webhook_id: Option, + event_id: Option, + api_version: Option, + triggered_at: Option, + sub_topic: Option, + name: Option, + body: Vec, +} + +impl Webhook { + /// Verifies a webhook from its headers and raw body, and reads its headers. + /// + /// `headers` are name and value pairs, the names in any case. Fails when + /// the signature is missing or does not match, or a header Shopify always + /// sends is missing. + pub fn verify( + headers: impl IntoIterator, + body: impl Into>, + secret: &str, + ) -> Result + where + K: AsRef, + V: AsRef, + { + Self::verify_with_secrets(headers, body, &[secret]) + } + + /// [`Webhook::verify`], accepting the signature of any of `secrets`: + /// while the client secret of the app is being rotated. + pub fn verify_with_secrets( + headers: impl IntoIterator, + body: impl Into>, + secrets: &[&str], + ) -> Result + where + K: AsRef, + V: AsRef, + { + let headers: Vec<(String, String)> = headers + .into_iter() + .map(|(name, value)| { + ( + name.as_ref().to_ascii_lowercase(), + value.as_ref().to_string(), + ) + }) + .collect(); + let header = |name: &str| { + headers + .iter() + .find(|(given, _)| given == name) + .map(|(_, value)| value.trim().to_string()) + }; + let required = |name: &'static str| { + header(name) + .ok_or_else(|| Error::Verification(format!("the webhook has no `{name}` header"))) + }; + + let body = body.into(); + let signature = required("x-shopify-hmac-sha256")?; + if secrets.iter().all(|secret| secret.is_empty()) { + return Err(Error::Verification( + "no secret to verify the webhook with: the client secret of the app is empty" + .to_string(), + )); + } + if !secrets + .iter() + .any(|secret| verify_hmac(secret, &body, &signature)) + { + return Err(Error::Verification( + "the signature of the webhook does not match".to_string(), + )); + } + let shop = ShopDomain::new(&required("x-shopify-shop-domain")?).map_err(|error| { + Error::Verification(format!("the webhook names an invalid shop: {error}")) + })?; + Ok(Self { + topic: required("x-shopify-topic")?, + shop, + webhook_id: header("x-shopify-webhook-id"), + event_id: header("x-shopify-event-id"), + api_version: header("x-shopify-api-version"), + triggered_at: header("x-shopify-triggered-at"), + sub_topic: header("x-shopify-sub-topic"), + name: header("x-shopify-name"), + body, + }) + } + + /// `orders/create`. + pub fn topic(&self) -> &str { + &self.topic + } + + /// The topic as the Admin API writes it: `ORDERS_CREATE`. + pub fn topic_enum(&self) -> String { + topic_enum(&self.topic) + } + + pub fn shop(&self) -> &ShopDomain { + &self.shop + } + + /// Identifies this delivery. + pub fn webhook_id(&self) -> Option<&str> { + self.webhook_id.as_deref() + } + + /// Identifies the event, the same across deliveries: to ignore a duplicate. + pub fn event_id(&self) -> Option<&str> { + self.event_id.as_deref() + } + + /// The API version of the payload. + pub fn api_version(&self) -> Option<&str> { + self.api_version.as_deref() + } + + /// When the event happened, as Shopify wrote it. + pub fn triggered_at(&self) -> Option<&str> { + self.triggered_at.as_deref() + } + + pub fn sub_topic(&self) -> Option<&str> { + self.sub_topic.as_deref() + } + + /// The name of the subscription, when it has one. + pub fn name(&self) -> Option<&str> { + self.name.as_deref() + } + + /// The raw body. + pub fn body(&self) -> &[u8] { + &self.body + } + + /// The body read as `T`, the path of the first mismatch in the error. + pub fn payload(&self) -> Result { + let mut deserializer = serde_json::Deserializer::from_slice(&self.body); + serde_path_to_error::deserialize(&mut deserializer).map_err(|error| Error::Decode { + path: error.path().to_string(), + message: error.inner().to_string(), + }) + } +} + +/// `orders/create` → `ORDERS_CREATE`. A topic already in that form is kept. +pub fn topic_enum(topic: &str) -> String { + topic + .trim() + .replace(['/', '.', '-'], "_") + .to_ascii_uppercase() +} + +// ─── Subscriptions ─────────────────────────────────────────────────── + +graphql! { + mod list = "#graphql + query WebhookSubscriptions($after: String) { + webhookSubscriptions(first: 250, after: $after) { + nodes { ...WebhookSubscriptionFields } + pageInfo { hasNextPage endCursor } + } + } + fragment WebhookSubscriptionFields on WebhookSubscription { + id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt + apiVersion { handle } + }"; +} + +graphql! { + mod create = "#graphql + mutation WebhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) { + webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) { + webhookSubscription { ...WebhookSubscriptionFields } + userErrors { field message } + } + } + fragment WebhookSubscriptionFields on WebhookSubscription { + id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt + apiVersion { handle } + }"; +} + +graphql! { + mod update = "#graphql + mutation WebhookSubscriptionUpdate($id: ID!, $webhookSubscription: WebhookSubscriptionInput!) { + webhookSubscriptionUpdate(id: $id, webhookSubscription: $webhookSubscription) { + webhookSubscription { ...WebhookSubscriptionFields } + userErrors { field message } + } + } + fragment WebhookSubscriptionFields on WebhookSubscription { + id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt + apiVersion { handle } + }"; +} + +/// The input of `create` or `update` for a spec. An update sends every +/// option, empty when the spec has none, so that it replaces the old ones. +macro_rules! input { + ($module:ident, $spec:expr, $replace:expr) => {{ + let spec: &WebhookSubscriptionSpec = $spec; + let replace: bool = $replace; + let list = |values: &Vec| (replace || !values.is_empty()).then(|| values.clone()); + $module::WebhookSubscriptionInput { + uri: Some(spec.uri.clone()), + format: Some(spec.format.clone().unwrap_or_else(|| "JSON".to_string())), + filter: spec.filter.clone().or_else(|| replace.then(String::new)), + include_fields: list(&spec.include_fields), + metafield_namespaces: list(&spec.metafield_namespaces), + name: spec.name.clone(), + ..Default::default() + } + }}; +} + +graphql! { + mod delete = "#graphql + mutation WebhookSubscriptionDelete($id: ID!) { + webhookSubscriptionDelete(id: $id) { + deletedWebhookSubscriptionId + userErrors { field message } + } + }"; +} + +/// A webhook subscription of a shop. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct WebhookSubscription { + pub id: String, + /// `ORDERS_CREATE`. + pub topic: String, + /// An HTTPS address, a `pubsub://` or an Amazon EventBridge `arn:`. + pub uri: String, + /// `JSON` or `XML`. + pub format: String, + pub filter: Option, + pub include_fields: Vec, + pub metafield_namespaces: Vec, + pub name: Option, + /// The API version of the payloads. + pub api_version: String, + pub created_at: String, + pub updated_at: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Wire { + id: String, + topic: String, + uri: String, + format: String, + filter: Option, + include_fields: Vec, + metafield_namespaces: Vec, + name: Option, + created_at: String, + updated_at: String, + api_version: WireVersion, +} + +#[derive(Deserialize)] +struct WireVersion { + handle: String, +} + +fn subscription_of(selection: &impl Serialize) -> Result { + let wire: Wire = crate::graphql::decode(serde_json::to_value(selection)?)?; + Ok(WebhookSubscription { + id: wire.id, + topic: wire.topic, + uri: wire.uri, + format: wire.format, + filter: wire.filter, + include_fields: wire.include_fields, + metafield_namespaces: wire.metafield_namespaces, + name: wire.name, + api_version: wire.api_version.handle, + created_at: wire.created_at, + updated_at: wire.updated_at, + }) +} + +fn refused(mutation: &'static str, errors: &impl Serialize) -> Result<()> { + let errors: Vec = crate::graphql::decode(serde_json::to_value(errors)?)?; + if errors.is_empty() { + Ok(()) + } else { + Err(Error::UserErrors { mutation, errors }) + } +} + +/// A webhook subscription to create. +/// +/// ``` +/// use shopify_api::webhooks::WebhookSubscriptionSpec; +/// +/// let spec = WebhookSubscriptionSpec::new("orders/create", "https://example.com/webhooks") +/// .include_fields(["id", "name", "total_price"]) +/// .filter("total_price:>100"); +/// assert_eq!(spec.topic(), "ORDERS_CREATE"); +/// ``` +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WebhookSubscriptionSpec { + topic: String, + uri: String, + format: Option, + filter: Option, + include_fields: Vec, + metafield_namespaces: Vec, + name: Option, +} + +impl WebhookSubscriptionSpec { + /// `topic` as `orders/create` or `ORDERS_CREATE`; `uri` an HTTPS address, + /// a `pubsub://project:topic` or an Amazon EventBridge `arn:`. + pub fn new(topic: impl AsRef, uri: impl Into) -> Self { + Self { + topic: topic_enum(topic.as_ref()), + uri: uri.into(), + format: None, + filter: None, + include_fields: Vec::new(), + metafield_namespaces: Vec::new(), + name: None, + } + } + + /// `JSON` (the default) or `XML`. + pub fn format(mut self, format: impl AsRef) -> Self { + self.format = Some(format.as_ref().to_ascii_uppercase()); + self + } + + /// Only the events that match this search. + pub fn filter(mut self, filter: impl Into) -> Self { + self.filter = Some(filter.into()); + self + } + + /// Only these fields of the payload. + pub fn include_fields, S: Into>(mut self, fields: I) -> Self { + self.include_fields = fields.into_iter().map(Into::into).collect(); + self + } + + /// The metafields of these namespaces in the payload. + pub fn metafield_namespaces, S: Into>( + mut self, + namespaces: I, + ) -> Self { + self.metafield_namespaces = namespaces.into_iter().map(Into::into).collect(); + self + } + + /// A name, sent in the `X-Shopify-Name` header of each delivery. + pub fn name(mut self, name: impl Into) -> Self { + self.name = Some(name.into()); + self + } + + pub fn topic(&self) -> &str { + &self.topic + } + + pub fn uri(&self) -> &str { + &self.uri + } + + /// Whether `subscription` is this one: same topic, address and options. + pub fn matches(&self, subscription: &WebhookSubscription) -> bool { + let sorted = |values: &[String]| { + let mut values = values.to_vec(); + values.sort(); + values + }; + subscription.topic == self.topic + && subscription.uri == self.uri + && subscription.format == self.format.as_deref().unwrap_or("JSON") + && subscription + .filter + .as_deref() + .filter(|filter| !filter.is_empty()) + == self.filter.as_deref() + && sorted(&subscription.include_fields) == sorted(&self.include_fields) + && sorted(&subscription.metafield_namespaces) == sorted(&self.metafield_namespaces) + && (self.name.is_none() || subscription.name == self.name) + } +} + +/// What [`Shopify::sync_webhook_subscriptions`] did. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct SyncReport { + pub created: Vec, + /// Subscriptions of a desired topic and address whose options changed. + pub updated: Vec, + /// The IDs of the subscriptions deleted. + pub deleted: Vec, + pub kept: Vec, +} + +impl Shopify { + /// Every webhook subscription the app has on the shop. Those of the + /// app's configuration file (`shopify.app.toml`) are not listed by + /// Shopify. + pub async fn webhook_subscriptions(&self) -> Result> { + let pages = self + .paginate( + |after| list::operation(list::Variables { after }), + |data| { + let connection = data.webhook_subscriptions; + crate::Page::new( + connection.nodes, + connection.page_info.has_next_page, + connection.page_info.end_cursor, + ) + }, + ) + .await?; + pages.iter().map(subscription_of).collect() + } + + pub async fn create_webhook_subscription( + &self, + spec: &WebhookSubscriptionSpec, + ) -> Result { + let input = input!(create, spec, false); + let data = self + .execute(create::operation(create::Variables { + topic: spec.topic.clone(), + webhook_subscription: input, + })) + .await?; + let payload = data + .webhook_subscription_create + .ok_or_else(|| Error::Decode { + path: "webhookSubscriptionCreate".to_string(), + message: "Shopify returned nothing".to_string(), + })?; + refused("webhookSubscriptionCreate", &payload.user_errors)?; + let subscription = payload.webhook_subscription.ok_or_else(|| Error::Decode { + path: "webhookSubscriptionCreate.webhookSubscription".to_string(), + message: "Shopify returned no subscription".to_string(), + })?; + subscription_of(&subscription) + } + + pub async fn delete_webhook_subscription(&self, id: &str) -> Result<()> { + let data = self + .execute(delete::operation(delete::Variables { id: id.to_string() })) + .await?; + let payload = data + .webhook_subscription_delete + .ok_or_else(|| Error::Decode { + path: "webhookSubscriptionDelete".to_string(), + message: "Shopify returned nothing".to_string(), + })?; + refused("webhookSubscriptionDelete", &payload.user_errors) + } + + /// Replaces the options of a subscription with those of `spec`; its + /// topic stays. + pub async fn update_webhook_subscription( + &self, + id: &str, + spec: &WebhookSubscriptionSpec, + ) -> Result { + let data = self + .execute(update::operation(update::Variables { + id: id.to_string(), + webhook_subscription: input!(update, spec, true), + })) + .await?; + let payload = data + .webhook_subscription_update + .ok_or_else(|| Error::Decode { + path: "webhookSubscriptionUpdate".to_string(), + message: "Shopify returned nothing".to_string(), + })?; + refused("webhookSubscriptionUpdate", &payload.user_errors)?; + let subscription = payload.webhook_subscription.ok_or_else(|| Error::Decode { + path: "webhookSubscriptionUpdate.webhookSubscription".to_string(), + message: "Shopify returned no subscription".to_string(), + })?; + subscription_of(&subscription) + } + + /// Makes the shop's subscriptions exactly `desired`: those that match are + /// kept, those of a desired topic and address are updated, the missing + /// ones created, then the others deleted. Nothing is deleted before what + /// replaces it exists, so no event is missed in between. + /// + /// It deletes every subscription of the app on the shop that `desired` + /// does not list, including those another part of the app created. + pub async fn sync_webhook_subscriptions( + &self, + desired: &[WebhookSubscriptionSpec], + ) -> Result { + let mut report = SyncReport::default(); + let mut missing: Vec<&WebhookSubscriptionSpec> = desired.iter().collect(); + let mut extra = Vec::new(); + for subscription in self.webhook_subscriptions().await? { + match missing.iter().position(|spec| spec.matches(&subscription)) { + Some(index) => { + missing.remove(index); + report.kept.push(subscription); + } + None => extra.push(subscription), + } + } + // A desired topic and address that exists with other options. + let mut leftover = Vec::new(); + for subscription in extra { + let same_place = missing + .iter() + .position(|spec| spec.topic == subscription.topic && spec.uri == subscription.uri); + match same_place { + Some(index) => { + let spec = missing.remove(index); + report.updated.push( + self.update_webhook_subscription(&subscription.id, spec) + .await?, + ); + } + None => leftover.push(subscription), + } + } + for spec in missing { + report + .created + .push(self.create_webhook_subscription(spec).await?); + } + for subscription in leftover { + self.delete_webhook_subscription(&subscription.id).await?; + report.deleted.push(subscription.id); + } + Ok(report) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verifies_the_signature_of_shopify() { + let body = br#"{"id":1}"#; + let signature = sign("secret", body); + assert!(verify_hmac("secret", body, &signature)); + assert!(!verify_hmac("other", body, &signature)); + assert!(!verify_hmac("secret", b"{\"id\":2}", &signature)); + assert!(!verify_hmac("secret", body, "not base64!")); + assert!(!verify_hmac("secret", body, "")); + } + + fn headers(signature: &str) -> Vec<(&'static str, String)> { + vec![ + ("X-Shopify-Topic", "orders/create".to_string()), + ("X-Shopify-Hmac-SHA256", signature.to_string()), + ("x-shopify-shop-domain", "my-shop.myshopify.com".to_string()), + ("X-Shopify-Webhook-Id", "b54557e4".to_string()), + ("X-Shopify-Event-Id", "98880550".to_string()), + ("X-Shopify-API-Version", "2026-10".to_string()), + ("X-Shopify-Triggered-At", "2026-10-22T10:00:00Z".to_string()), + ] + } + + #[test] + fn reads_a_verified_webhook() { + let body = br##"{"id":1,"name":"#1001"}"##.to_vec(); + let webhook = + Webhook::verify(headers(&sign("secret", &body)), body.clone(), "secret").unwrap(); + assert_eq!(webhook.topic(), "orders/create"); + assert_eq!(webhook.topic_enum(), "ORDERS_CREATE"); + assert_eq!(webhook.shop().as_str(), "my-shop.myshopify.com"); + assert_eq!(webhook.webhook_id(), Some("b54557e4")); + assert_eq!(webhook.event_id(), Some("98880550")); + assert_eq!(webhook.api_version(), Some("2026-10")); + assert_eq!(webhook.triggered_at(), Some("2026-10-22T10:00:00Z")); + assert_eq!(webhook.sub_topic(), None); + assert_eq!(webhook.body(), body); + + #[derive(Deserialize)] + struct Order { + name: String, + } + assert_eq!(webhook.payload::().unwrap().name, "#1001"); + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + struct Wrong { + name: u32, + } + assert_eq!( + webhook.payload::().unwrap_err().to_string(), + "Shopify's answer does not match the operation at `name`: invalid type: string \"#1001\", expected u32 at line 1 column 22" + ); + } + + #[test] + fn refuses_what_does_not_verify() { + let body = b"{}".to_vec(); + let error = + Webhook::verify(headers(&sign("other", &body)), body.clone(), "secret").unwrap_err(); + assert_eq!( + error.to_string(), + "verification failed: the signature of the webhook does not match" + ); + + let unsigned: Vec<_> = headers("") + .into_iter() + .filter(|(name, _)| !name.contains("Hmac")) + .collect(); + let error = Webhook::verify(unsigned, body.clone(), "secret").unwrap_err(); + assert_eq!( + error.to_string(), + "verification failed: the webhook has no `x-shopify-hmac-sha256` header" + ); + + // An empty secret, as from an unset variable, verifies nothing. + let error = Webhook::verify(headers(&sign("", &body)), body.clone(), "").unwrap_err(); + assert!( + error + .to_string() + .contains("the client secret of the app is empty"), + "{error}" + ); + assert!(!verify_hmac("", &body, &sign("", &body))); + + // A rotated secret: either verifies. + let webhook = Webhook::verify_with_secrets( + headers(&sign("old", &body)), + body.clone(), + &["new", "old"], + ); + assert!(webhook.is_ok()); + + let mut wrong_shop = headers(&sign("secret", &body)); + wrong_shop[2].1 = "evil.example.com".to_string(); + assert!(Webhook::verify(wrong_shop, body, "secret").is_err()); + } + + #[test] + fn specs_match_subscriptions_whatever_the_order_of_their_fields() { + let spec = WebhookSubscriptionSpec::new("orders/create", "https://example.com/hooks") + .include_fields(["b", "a"]); + let mut subscription = WebhookSubscription { + id: "gid://shopify/WebhookSubscription/1".to_string(), + topic: "ORDERS_CREATE".to_string(), + uri: "https://example.com/hooks".to_string(), + format: "JSON".to_string(), + filter: Some(String::new()), + include_fields: vec!["a".to_string(), "b".to_string()], + metafield_namespaces: Vec::new(), + name: None, + api_version: "2026-10".to_string(), + created_at: String::new(), + updated_at: String::new(), + }; + assert!(spec.matches(&subscription)); + subscription.uri = "https://example.com/other".to_string(); + assert!(!spec.matches(&subscription)); + assert_eq!(topic_enum("app/uninstalled"), "APP_UNINSTALLED"); + assert_eq!(topic_enum("ORDERS_PAID"), "ORDERS_PAID"); + } +} diff --git a/crates/shopify_api/tests/auth.rs b/crates/shopify_api/tests/auth.rs new file mode 100644 index 0000000..417e942 --- /dev/null +++ b/crates/shopify_api/tests/auth.rs @@ -0,0 +1,430 @@ +//! Tokens: obtained, reused, renewed and saved. +#![cfg(feature = "testing")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde_json::json; +use shopify_api::testing::MockTransport; +use shopify_api::transport::{BoxFuture, HttpRequest, HttpResponse}; +use shopify_api::{Auth, Error, RetryPolicy, ShopDomain, Shopify, TokenData, TokenStore}; + +const TOKEN_URL: &str = "https://test-shop.myshopify.com/admin/oauth/access_token"; + +/// Answers token requests with `shpat_` and GraphQL requests with a shop, +/// refusing the tokens in `refused` with a 401. +fn shopify_like(mock: &MockTransport, expires_in: i64, refused: Vec<&'static str>) { + let issued = Arc::new(Mutex::new(0)); + mock.respond_with(move |request: &HttpRequest| { + if request.url == TOKEN_URL { + let mut issued = issued.lock().unwrap(); + *issued += 1; + return Ok(HttpResponse::json( + 200, + &json!({ + "access_token": format!("shpat_{issued}"), + "scope": "read_products", + "expires_in": expires_in, + "refresh_token": format!("shprt_{issued}"), + "refresh_token_expires_in": 7_776_000, + }), + )); + } + let token = request.header("X-Shopify-Access-Token").unwrap_or_default(); + if refused.contains(&token) { + return Ok(HttpResponse::new( + 401, + "[API] Invalid API key or access token", + )); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); +} + +fn token_requests(mock: &MockTransport) -> Vec { + mock.requests() + .into_iter() + .filter(|request| request.url == TOKEN_URL) + .collect() +} + +fn builder(mock: &MockTransport) -> shopify_api::ShopifyBuilder { + Shopify::builder("test-shop") + .transport(mock.clone()) + .retry(RetryPolicy::none()) +} + +#[tokio::test] +async fn client_credentials_are_asked_once_and_reused() { + let mock = MockTransport::new(); + shopify_like(&mock, 86_399, vec![]); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + shopify + .clone() + .graphql("{ shop { name } }", ()) + .await + .unwrap(); + + let asked = token_requests(&mock); + assert_eq!(asked.len(), 1); + assert_eq!( + asked[0].header("content-type"), + Some("application/x-www-form-urlencoded") + ); + assert_eq!( + asked[0].form(), + [ + ("grant_type".to_string(), "client_credentials".to_string()), + ("client_id".to_string(), "id".to_string()), + ("client_secret".to_string(), "secret".to_string()), + ] + ); + assert_eq!( + mock.graphql_requests()[1].access_token.as_deref(), + Some("shpat_1") + ); + let token = shopify.token().await.unwrap(); + assert_eq!(token.scopes(), ["read_products"]); + assert!(token.expires_at.is_some()); +} + +#[tokio::test] +async fn concurrent_requests_share_one_token_request() { + let mock = MockTransport::new(); + shopify_like(&mock, 86_399, vec![]); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + let calls = (0..8).map(|_| { + let shopify = shopify.clone(); + tokio::spawn(async move { shopify.graphql("{ shop { name } }", ()).await }) + }); + for call in calls { + call.await.unwrap().unwrap(); + } + assert_eq!(token_requests(&mock).len(), 1); +} + +#[tokio::test] +async fn a_token_about_to_expire_is_renewed_first() { + let mock = MockTransport::new(); + // Each token expires within the five minutes of leeway: each request renews it. + shopify_like(&mock, 60, vec![]); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(token_requests(&mock).len(), 2); + + // With a shorter leeway, the token lasts. + let mock = MockTransport::new(); + shopify_like(&mock, 60, vec![]); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .refresh_leeway(Duration::from_secs(10)) + .build() + .unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(token_requests(&mock).len(), 1); +} + +#[tokio::test] +async fn a_refused_token_is_renewed_once_and_the_request_sent_again() { + let mock = MockTransport::new(); + shopify_like(&mock, 86_399, vec!["stored"]); + let shopify = builder(&mock) + .auth(Auth::client_credentials("id", "secret").with_token(TokenData::new("stored"))) + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + let tokens: Vec> = mock + .graphql_requests() + .into_iter() + .map(|request| request.access_token) + .collect(); + assert_eq!( + tokens, + [Some("stored".to_string()), Some("shpat_1".to_string())] + ); + + // A token refused again is the answer: no loop. + let mock = MockTransport::new(); + shopify_like(&mock, 86_399, vec!["stored", "shpat_1"]); + let shopify = builder(&mock) + .auth(Auth::client_credentials("id", "secret").with_token(TokenData::new("stored"))) + .build() + .unwrap(); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(error.is_unauthorized(), "{error:?}"); + assert_eq!(mock.requests().len(), 3); +} + +#[tokio::test] +async fn a_static_token_that_is_refused_is_the_answer() { + let mock = MockTransport::new(); + shopify_like(&mock, 0, vec!["shpat_static"]); + let shopify = builder(&mock).access_token("shpat_static").build().unwrap(); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(error.is_unauthorized()); + assert!(token_requests(&mock).is_empty()); +} + +#[derive(Default, Clone)] +struct Saved(Arc>>); + +impl TokenStore for Saved { + fn save<'a>( + &'a self, + shop: &'a ShopDomain, + token: &'a TokenData, + ) -> BoxFuture<'a, Result<(), Box>> { + Box::pin(async move { + self.0 + .lock() + .unwrap() + .push((shop.to_string(), token.clone())); + Ok(()) + }) + } +} + +#[tokio::test] +async fn an_expiring_token_is_refreshed_and_saved() { + let mock = MockTransport::new(); + shopify_like(&mock, 3600, vec![]); + let saved = Saved::default(); + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + let shopify = builder(&mock) + .auth(Auth::expiring_token("id", "secret", stored)) + .token_store(saved.clone()) + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + + let refresh = &token_requests(&mock)[0]; + assert_eq!(refresh.header("content-type"), Some("application/json")); + assert_eq!( + refresh.json().unwrap(), + json!({ "grant_type": "refresh_token", "client_id": "id", "client_secret": "secret", "refresh_token": "shprt_old" }) + ); + let saved = saved.0.lock().unwrap(); + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].0, "test-shop.myshopify.com"); + assert_eq!(saved[0].1.access_token, "shpat_1"); + assert_eq!(saved[0].1.refresh_token.as_deref(), Some("shprt_1")); + assert_eq!( + mock.graphql_requests()[0].access_token.as_deref(), + Some("shpat_1") + ); +} + +#[tokio::test] +async fn an_expired_refresh_token_says_what_to_do() { + let mock = MockTransport::new(); + shopify_like(&mock, 3600, vec![]); + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + stored.refresh_token_expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + let shopify = builder(&mock) + .auth(Auth::expiring_token("id", "secret", stored)) + .build() + .unwrap(); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(matches!(error, Error::Auth(_)), "{error:?}"); + assert!( + error + .to_string() + .contains("refresh token is missing or expired"), + "{error}" + ); + assert!(mock.requests().is_empty()); +} + +#[tokio::test] +async fn a_refused_grant_says_what_shopify_answered_and_never_the_secret() { + let mock = MockTransport::new(); + mock.push(HttpResponse::json( + 400, + &json!({ "error": "shop_not_permitted", "error_description": "Client credentials cannot be performed on this shop." }), + )); + let shopify = builder(&mock) + .client_credentials("id", "top-secret") + .build() + .unwrap(); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + let message = error.to_string(); + assert_eq!( + message, + "authentication failed: the token endpoint of test-shop.myshopify.com answered 400: shop_not_permitted: Client credentials cannot be performed on this shop." + ); + assert!(!format!("{error:?}").contains("top-secret")); +} + +#[tokio::test] +async fn a_failed_renewal_ahead_of_expiry_keeps_the_token_that_still_works() { + let mock = MockTransport::new(); + mock.respond_with(|request: &HttpRequest| { + if request.url == TOKEN_URL { + return Ok(HttpResponse::new(503, "unavailable")); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + // A token that expires in a minute: within the five minutes of leeway. + let mut stored = TokenData::new("shpat_soon"); + stored.expires_at = Some(chrono::Utc::now() + chrono::Duration::seconds(60)); + let shopify = builder(&mock) + .auth(Auth::client_credentials("id", "secret").with_token(stored)) + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + + // One renewal tried, then held back; the current token sent both times. + assert_eq!(token_requests(&mock).len(), 1); + let sent: Vec<_> = mock + .graphql_requests() + .into_iter() + .map(|request| request.access_token) + .collect(); + assert_eq!( + sent, + [ + Some("shpat_soon".to_string()), + Some("shpat_soon".to_string()) + ] + ); +} + +/// Answers token requests after `delay`, and counts them. +struct Slow { + delay: Duration, + asked: Arc>, +} + +impl shopify_api::transport::Transport for Slow { + fn send( + &self, + request: HttpRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + if request.url == TOKEN_URL { + *self.asked.lock().unwrap() += 1; + tokio::time::sleep(self.delay).await; + return Ok(HttpResponse::json( + 200, + &json!({ "access_token": "shpat_new", "expires_in": 3600, "refresh_token": "shprt_new" }), + )); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }) + } +} + +#[tokio::test] +async fn a_cancelled_request_does_not_lose_the_rotated_refresh_token() { + let asked = Arc::new(Mutex::new(0)); + let saved = Saved::default(); + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + let shopify = Shopify::builder("test-shop") + .auth(Auth::expiring_token("id", "secret", stored)) + .transport(Slow { + delay: Duration::from_millis(100), + asked: asked.clone(), + }) + .token_store(saved.clone()) + .build() + .unwrap(); + + // The caller gives up while Shopify is answering the refresh. + let gave_up = tokio::time::timeout(Duration::from_millis(10), shopify.access_token()).await; + assert!(gave_up.is_err()); + tokio::time::sleep(Duration::from_millis(200)).await; + + // The renewal finished anyway: the new tokens are held and saved. + let token = shopify.token().await.unwrap(); + assert_eq!(token.refresh_token.as_deref(), Some("shprt_new")); + assert_eq!(saved.0.lock().unwrap().len(), 1); + assert_eq!(shopify.access_token().await.unwrap(), "shpat_new"); + assert_eq!(*asked.lock().unwrap(), 1); +} + +#[tokio::test] +async fn a_failed_grant_answers_the_requests_that_wait_for_it() { + let mock = MockTransport::new(); + mock.respond_with(|request: &HttpRequest| { + if request.url == TOKEN_URL { + return Ok(HttpResponse::new(503, "unavailable")); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + let calls: Vec<_> = (0..5) + .map(|_| { + let shopify = shopify.clone(); + tokio::spawn(async move { shopify.graphql("{ shop { name } }", ()).await }) + }) + .collect(); + for call in calls { + let error = call.await.unwrap().unwrap_err(); + assert!(matches!(error, Error::Auth(_)), "{error:?}"); + } + // One request to the token endpoint; the others got its failure. + assert_eq!(token_requests(&mock).len(), 1); +} + +#[tokio::test] +async fn a_token_that_never_expires_in_practice_is_read() { + let mock = MockTransport::new(); + mock.push_json(json!({ "access_token": "shpat_long", "expires_in": i64::MAX, "refresh_token_expires_in": -1 })); + mock.push_data(json!({ "shop": { "name": "x" } })); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + let token = shopify.token().await.unwrap(); + assert_eq!( + token.expires_at, + Some(chrono::DateTime::::MAX_UTC) + ); + assert!(!token.expires_within(chrono::Duration::days(365))); +} diff --git a/crates/shopify_api/tests/bulk.rs b/crates/shopify_api/tests/bulk.rs new file mode 100644 index 0000000..5adb2bb --- /dev/null +++ b/crates/shopify_api/tests/bulk.rs @@ -0,0 +1,266 @@ +//! Bulk operations against a scripted Shopify. +#![cfg(feature = "testing")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde::Deserialize; +use serde_json::{Value, json}; +use shopify_api::bulk::{BulkOperationStatus, BulkOperationsFilter, BulkWaitOptions}; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::transport::{HttpRequest, HttpResponse, Method}; +use shopify_api::{Error, Shopify}; + +const RESULTS_URL: &str = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-east1/bulk-operation-outputs/1.jsonl"; +const UPLOAD_URL: &str = "https://shopify-staged-uploads.storage.googleapis.com/"; + +fn operation(status: &str, url: Option<&str>) -> Value { + json!({ + "id": "gid://shopify/BulkOperation/1", + "type": "QUERY", + "status": status, + "errorCode": null, + "createdAt": "2026-10-22T10:00:00Z", + "completedAt": if status == "COMPLETED" { json!("2026-10-22T10:01:00Z") } else { Value::Null }, + "objectCount": "2", + "rootObjectCount": "2", + "fileSize": url.map(|_| "120"), + "url": url, + "partialDataUrl": null, + "query": "{ products { edges { node { id title } } } }", + }) +} + +fn operation_name(request: &HttpRequest) -> Option { + request + .json()? + .get("operationName")? + .as_str() + .map(str::to_string) +} + +fn fast() -> BulkWaitOptions { + BulkWaitOptions::new().poll_interval(Duration::from_millis(1)) +} + +#[tokio::test] +async fn a_bulk_query_runs_to_its_end_and_its_rows_are_read() { + let mock = MockTransport::new(); + let polls = Arc::new(Mutex::new(0)); + mock.respond_with(move |request| { + if request.url == RESULTS_URL { + assert_eq!(request.method, Method::Get); + assert_eq!(request.header("X-Shopify-Access-Token"), None, "the token stays with Shopify"); + return Ok(HttpResponse::new( + 200, + "{\"id\":\"gid://shopify/Product/1\",\"title\":\"Shirt\"}\n{\"id\":\"gid://shopify/Product/2\",\"title\":\"Hat\"}\n", + )); + } + let data = match operation_name(request).as_deref() { + Some("BulkOperationRunQuery") => { + json!({ "bulkOperationRunQuery": { "bulkOperation": operation("CREATED", None), "userErrors": [] } }) + } + Some("BulkOperation") => { + let mut polls = polls.lock().unwrap(); + *polls += 1; + let status = if *polls < 3 { "RUNNING" } else { "COMPLETED" }; + let url = (status == "COMPLETED").then_some(RESULTS_URL); + json!({ "bulkOperation": operation(status, url) }) + } + other => panic!("unexpected operation {other:?}"), + }; + Ok(HttpResponse::json(200, &json!({ "data": data }))) + }); + let shopify = client(&mock); + + #[derive(Debug, Deserialize, PartialEq)] + struct Product { + id: String, + title: String, + } + let products: Vec = shopify + .bulk_query_rows("{ products { edges { node { id title } } } }", fast()) + .await + .unwrap(); + assert_eq!( + products + .iter() + .map(|product| product.title.as_str()) + .collect::>(), + ["Shirt", "Hat"] + ); + + let sent = mock.graphql_requests(); + assert_eq!( + sent[0].variables, + json!({ "query": "{ products { edges { node { id title } } } }", "groupObjects": false }) + ); + assert_eq!(sent.len(), 4, "a start and three polls"); +} + +#[tokio::test] +async fn a_refused_bulk_query_returns_the_user_errors() { + let mock = MockTransport::new(); + mock.push_data(json!({ "bulkOperationRunQuery": { + "bulkOperation": null, + "userErrors": [{ "field": ["query"], "message": "Bulk queries cannot contain a connection argument named first.", "code": "INVALID" }], + } })); + let shopify = client(&mock); + + let error = shopify + .run_bulk_query("{ products(first: 1) { nodes { id } } }") + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "bulkOperationRunQuery refused: query: Bulk queries cannot contain a connection argument named first." + ); + let Error::UserErrors { errors, .. } = error else { + panic!("user errors"); + }; + assert_eq!(errors[0].code.as_deref(), Some("INVALID")); +} + +#[tokio::test] +async fn a_failed_operation_is_an_error() { + let mock = MockTransport::new(); + mock.push_data(json!({ "bulkOperationRunQuery": { "bulkOperation": operation("CREATED", None), "userErrors": [] } })); + let mut failed = operation("FAILED", None); + failed["errorCode"] = json!("ACCESS_DENIED"); + mock.push_data(json!({ "bulkOperation": failed })); + let shopify = client(&mock); + + let error = shopify + .bulk_query_rows::("{ orders { edges { node { id } } } }", fast()) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: the bulk operation gid://shopify/BulkOperation/1 ended Failed (ACCESS_DENIED)" + ); +} + +#[tokio::test] +async fn a_bulk_mutation_uploads_its_variables_then_runs() { + let mock = MockTransport::new(); + let uploaded = Arc::new(Mutex::new(None)); + let seen = uploaded.clone(); + mock.respond_with(move |request| { + if request.url == UPLOAD_URL { + *seen.lock().unwrap() = Some(request.clone()); + return Ok(HttpResponse::new(201, "")); + } + let data = match operation_name(request).as_deref() { + Some("StagedUploadsCreate") => json!({ "stagedUploadsCreate": { + "stagedTargets": [{ + "url": UPLOAD_URL, + "resourceUrl": null, + "parameters": [ + { "name": "key", "value": "tmp/1/bulk/vars.jsonl" }, + { "name": "policy", "value": "abc" }, + ], + }], + "userErrors": [], + } }), + Some("BulkOperationRunMutation") => { + let mut started = operation("CREATED", None); + started["type"] = json!("MUTATION"); + json!({ "bulkOperationRunMutation": { "bulkOperation": started, "userErrors": [] } }) + } + other => panic!("unexpected operation {other:?}"), + }; + Ok(HttpResponse::json(200, &json!({ "data": data }))) + }); + let shopify = client(&mock); + + let rows = [ + json!({ "product": { "id": "gid://shopify/Product/1", "title": "A" } }), + json!({ "product": { "id": "gid://shopify/Product/2", "title": "B" } }), + ]; + let mutation = "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }"; + let started = shopify.run_bulk_mutation(mutation, &rows).await.unwrap(); + assert_eq!(started.kind, shopify_api::bulk::BulkOperationType::Mutation); + assert_eq!(started.status, BulkOperationStatus::Created); + + let sent = mock.graphql_requests(); + assert_eq!( + sent[0].variables, + json!({ "input": [{ "filename": "bulk_op_vars.jsonl", "mimeType": "text/jsonl", "resource": "BULK_MUTATION_VARIABLES", "httpMethod": "POST" }] }) + ); + assert_eq!( + sent[1].variables, + json!({ "mutation": mutation, "stagedUploadPath": "tmp/1/bulk/vars.jsonl" }) + ); + + let upload = uploaded.lock().unwrap().clone().expect("an upload"); + let body = String::from_utf8(upload.body.clone()).unwrap(); + assert!( + upload + .header("content-type") + .unwrap() + .starts_with("multipart/form-data; boundary=") + ); + assert!(body.contains("name=\"policy\"\r\n\r\nabc\r\n"), "{body}"); + assert!( + body.contains( + "{\"product\":{\"id\":\"gid://shopify/Product/1\",\"title\":\"A\"}}\n{\"product\":{\"id\":\"gid://shopify/Product/2\",\"title\":\"B\"}}\n" + ), + "{body}" + ); +} + +#[tokio::test] +async fn bulk_operations_are_listed_and_cancelled() { + let mock = MockTransport::new(); + mock.push_data(json!({ "bulkOperations": { + "nodes": [operation("RUNNING", None)], + "pageInfo": { "hasNextPage": true, "endCursor": "c1" }, + } })); + let mut canceling = operation("CANCELING", None); + canceling["objectCount"] = json!("12"); + mock.push_data( + json!({ "bulkOperationCancel": { "bulkOperation": canceling, "userErrors": [] } }), + ); + let shopify = client(&mock); + + let page = shopify + .bulk_operations(BulkOperationsFilter::new().first(5).query("status:RUNNING")) + .await + .unwrap(); + assert_eq!(page.items[0].status, BulkOperationStatus::Running); + assert_eq!(page.end_cursor.as_deref(), Some("c1")); + assert_eq!( + mock.graphql_requests()[0].variables, + json!({ "first": 5, "query": "status:RUNNING", "reverse": true }) + ); + + let cancelled = shopify + .cancel_bulk_operation("gid://shopify/BulkOperation/1") + .await + .unwrap(); + assert_eq!(cancelled.status, BulkOperationStatus::Canceling); + assert_eq!(cancelled.object_count, 12); +} + +#[tokio::test(start_paused = true)] +async fn waiting_gives_up_after_its_timeout() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(HttpResponse::json( + 200, + &json!({ "data": { "bulkOperation": operation("RUNNING", None) } }), + )) + }); + let shopify: Shopify = client(&mock); + + let error = shopify + .wait_for_bulk_operation( + "gid://shopify/BulkOperation/1", + BulkWaitOptions::new().timeout(Duration::from_secs(30)), + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout(_)), "{error:?}"); + // 1 + 2 + 4 + 8 + 10 seconds, then the 5 that are left. + assert_eq!(mock.requests().len(), 6); +} diff --git a/crates/shopify_api/tests/compile_fail.rs b/crates/shopify_api/tests/compile_fail.rs new file mode 100644 index 0000000..d3e8ea8 --- /dev/null +++ b/crates/shopify_api/tests/compile_fail.rs @@ -0,0 +1,8 @@ +//! What `graphql!` refuses at compile time, and how it says so. The expected +//! errors are in `tests/ui/*.stderr`; `mise run ui:bless` rewrites them. + +#[test] +fn graphql_refusals() { + let cases = trybuild::TestCases::new(); + cases.compile_fail("tests/ui/*.rs"); +} diff --git a/crates/shopify_api/tests/graphql.rs b/crates/shopify_api/tests/graphql.rs new file mode 100644 index 0000000..a5b84f1 --- /dev/null +++ b/crates/shopify_api/tests/graphql.rs @@ -0,0 +1,368 @@ +//! `graphql!` operations end to end: what is sent, and how the answer is typed. +#![cfg(feature = "testing")] + +use serde_json::{Value, json}; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::{ApiVersion, Error, OperationKind, graphql}; + +graphql! { + /// Writes metafields and reports what Shopify refused. + pub mod metafields_set = "#graphql + mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { + metafields { id key namespace } + userErrors { field message code } + } + }"; +} + +graphql! { + mod shop_name = "query ShopName { shop { name } }"; +} + +graphql! { + mod from_file = file("tests/graphql/order.graphql"); +} + +#[tokio::test] +async fn an_inline_query_sends_its_variables_and_returns_typed_data() { + let mock = MockTransport::new(); + mock.push_data(json!({ "orders": { "nodes": [ + { "id": "gid://shopify/Order/1", "name": "#1001" }, + { "id": "gid://shopify/Order/2", "name": "#1002" }, + ] } })); + let shopify = client(&mock); + let limit: u32 = 2; + + let data = shopify + .execute(graphql!( + "query Recent($first: Int!, $query: String) { orders(first: $first, query: $query) { nodes { id name } } }", + first = limit, + query = "status:open", + )) + .await + .unwrap(); + + let names: Vec<&str> = data + .orders + .nodes + .iter() + .map(|order| order.name.as_str()) + .collect(); + assert_eq!(names, ["#1001", "#1002"]); + + let sent = &mock.graphql_requests()[0]; + assert_eq!( + sent.url, + "https://test-shop.myshopify.com/admin/api/2026-10/graphql.json" + ); + assert_eq!(sent.api_version, "2026-10"); + assert_eq!( + sent.variables, + json!({ "first": 2, "query": "status:open" }) + ); + assert_eq!(sent.operation_name.as_deref(), Some("Recent")); + assert_eq!(sent.access_token.as_deref(), Some("test-token")); + let request = mock.last_request().unwrap(); + assert_eq!(request.header("content-type"), Some("application/json")); + assert!( + request + .header("user-agent") + .unwrap() + .starts_with("shopify_api/") + ); +} + +#[tokio::test] +async fn nullability_lists_aliases_fragments_and_scalars_follow_the_schema() { + let mock = MockTransport::new(); + mock.push_data(json!({ + "order": { + "id": "gid://shopify/Order/1", + "note": null, + "createdAt": "2026-10-01T00:00:00Z", + "tags": ["vip", "b2b"], + "displayFinancialStatus": "PAID", + "total": { "shopMoney": { "amount": "42.50", "currencyCode": "EUR" } }, + "customer": null, + "metafield": { "jsonValue": { "gift": true }, "type": "json" }, + "lineItems": { "nodes": [{ "title": "Shirt", "quantity": 2 }] }, + }, + "nodes": [ + { "__typename": "Product", "id": "gid://shopify/Product/1", "title": "Shirt" }, + null, + { "__typename": "Collection", "id": "gid://shopify/Collection/1" }, + ], + })); + let shopify = client(&mock); + + let data = shopify + .execute(graphql!( + r#"#graphql + query Order($id: ID!, $ids: [ID!]!, $namespace: String) { + order(id: $id) { + id + note + createdAt + tags + displayFinancialStatus + total: totalPriceSet { shopMoney { amount currencyCode } } + customer { displayName } + metafield(namespace: $namespace, key: "settings") { jsonValue type } + lineItems(first: 5) { nodes { title quantity } } + } + nodes(ids: $ids) { + __typename + id + ... on Product { title } + } + }"#, + id = "gid://shopify/Order/1", + ids = ["gid://shopify/Product/1", "gid://shopify/Collection/1"], + namespace = "custom", + )) + .await + .unwrap(); + + // `order` is nullable in the schema. + let order = data.order.expect("an order"); + let note: Option = order.note; + assert_eq!(note, None); + let created_at: String = order.created_at; + assert_eq!(created_at, "2026-10-01T00:00:00Z"); + assert_eq!(order.tags, ["vip", "b2b"]); + // Enum values are strings. + assert_eq!(order.display_financial_status.as_deref(), Some("PAID")); + // An alias names its field. + assert_eq!(order.total.shop_money.amount, "42.50"); + assert_eq!(order.customer, None); + // `JSON` is any value. + let metafield = order.metafield.unwrap(); + assert_eq!(metafield.json_value, json!({ "gift": true })); + // `Int` is `i64`. + let quantity: i64 = order.line_items.nodes[0].quantity; + assert_eq!(quantity, 2); + + // A field under a fragment on another type is an `Option`. + let nodes = data.nodes; + assert_eq!(nodes.len(), 3); + let product = nodes[0].as_ref().unwrap(); + assert_eq!( + (product.typename.as_str(), product.title.as_deref()), + ("Product", Some("Shirt")) + ); + assert!(nodes[1].is_none()); + assert_eq!(nodes[2].as_ref().unwrap().title, None); +} + +#[tokio::test] +async fn a_module_names_its_types_and_builds_input_objects() { + let mock = MockTransport::new(); + mock.push_data(json!({ "metafieldsSet": { + "metafields": [{ "id": "gid://shopify/Metafield/1", "key": "color", "namespace": "custom" }], + "userErrors": [], + } })); + let shopify = client(&mock); + + let variables = metafields_set::Variables { + metafields: vec![metafields_set::MetafieldsSetInput { + owner_id: "gid://shopify/Product/1".to_string(), + namespace: Some("custom".to_string()), + key: "color".to_string(), + value: "blue".to_string(), + ..Default::default() + }], + }; + let data: metafields_set::Data = shopify + .execute(metafields_set::operation(variables)) + .await + .unwrap(); + let payload: metafields_set::DataMetafieldsSet = data.metafields_set.unwrap(); + assert!(payload.user_errors.is_empty()); + assert_eq!(payload.metafields.unwrap()[0].key, "color"); + + assert_eq!(metafields_set::NAME, Some("MetafieldsSet")); + assert_eq!(metafields_set::KIND, OperationKind::Mutation); + assert_eq!(metafields_set::API_VERSION, ApiVersion::DEFAULT.to_string()); + // Fields left to `None` are not sent. + assert_eq!( + mock.graphql_requests()[0].variables, + json!({ "metafields": [{ "ownerId": "gid://shopify/Product/1", "namespace": "custom", "key": "color", "value": "blue" }] }) + ); +} + +#[tokio::test] +async fn an_operation_can_come_from_a_file() { + let mock = MockTransport::new(); + mock.push_data(json!({ "order": { "name": "#1001", "email": null } })); + let shopify = client(&mock); + + let data = shopify + .execute(from_file::operation(from_file::Variables { + id: "gid://shopify/Order/1".to_string(), + })) + .await + .unwrap(); + assert_eq!(data.order.unwrap().name, "#1001"); + assert_eq!(from_file::QUERY, include_str!("graphql/order.graphql")); + assert_eq!( + mock.graphql_requests()[0].operation_name.as_deref(), + Some("OrderFromFile") + ); +} + +#[tokio::test] +async fn graphql_errors_fail_the_operation_and_keep_partial_data() { + let mock = MockTransport::new(); + mock.push_json(json!({ + "data": { "shop": null }, + "errors": [{ "message": "Access denied for shop field.", "extensions": { "code": "ACCESS_DENIED" }, "path": ["shop"] }], + })); + let shopify = client(&mock); + + let error = shopify.execute(shop_name::operation()).await.unwrap_err(); + assert_eq!( + error.to_string(), + "GraphQL errors: Access denied for shop field. (ACCESS_DENIED)" + ); + let Error::Graphql(errors) = &error else { + panic!("GraphQL errors: {error:?}"); + }; + assert_eq!(errors.data, Some(json!({ "shop": null }))); + assert_eq!(error.graphql_errors()[0].code(), Some("ACCESS_DENIED")); + + // The raw answer holds both. + mock.push_json(json!({ "data": { "shop": null }, "errors": [{ "message": "Denied" }] })); + let raw = shopify.graphql_raw("{ shop { name } }", ()).await.unwrap(); + assert_eq!(raw.errors[0].message, "Denied"); + assert_eq!(raw.data, Some(json!({ "shop": null }))); +} + +#[tokio::test] +async fn an_answer_that_does_not_fit_names_the_path() { + let mock = MockTransport::new(); + mock.push_data(json!({ "shop": {} })); + let shopify = client(&mock); + + let error = shopify.execute(shop_name::operation()).await.unwrap_err(); + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `shop`: missing field `name`" + ); +} + +#[tokio::test] +async fn http_errors_say_what_shopify_answered() { + let mock = MockTransport::new(); + mock.push(shopify_api::transport::HttpResponse::new( + 403, + "[API] This action requires merchant approval for write_orders scope.", + )); + let shopify = client(&mock); + + let error = shopify.execute(shop_name::operation()).await.unwrap_err(); + assert_eq!(error.status(), Some(403)); + assert_eq!( + error.to_string(), + "Shopify answered 403 to https://test-shop.myshopify.com/admin/api/2026-10/graphql.json: [API] This action requires merchant approval for write_orders scope." + ); +} + +#[tokio::test] +async fn untyped_calls_take_any_serializable_variables() { + let mock = MockTransport::new(); + mock.push_data(json!({ "product": { "title": "Shirt" } })); + mock.push_data(json!({ "product": { "title": "Shirt" } })); + let shopify = client(&mock); + + let data: Value = shopify + .graphql( + "query($id: ID!) { product(id: $id) { title } }", + json!({ "id": "gid://shopify/Product/1" }), + ) + .await + .unwrap(); + assert_eq!(data.pointer("/product/title"), Some(&json!("Shirt"))); + + #[derive(serde::Deserialize)] + struct Data { + product: Option, + } + #[derive(serde::Deserialize)] + struct Product { + title: String, + } + #[derive(serde::Serialize)] + struct Variables<'a> { + id: &'a str, + } + let data: Data = shopify + .graphql_as( + "query($id: ID!) { product(id: $id) { title } }", + Variables { + id: "gid://shopify/Product/1", + }, + ) + .await + .unwrap(); + assert_eq!(data.product.unwrap().title, "Shirt"); + + let error = shopify + .graphql("{ shop { name } }", [1, 2]) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "invalid variables: the variables must serialize to an object" + ); + // Nothing was sent for it. + assert_eq!(mock.requests().len(), 2); +} + +#[tokio::test] +async fn operations_go_to_the_version_of_their_schema_unless_one_is_pinned() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(shopify_api::transport::HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + let shopify = client(&mock); + + shopify.execute(shop_name::operation()).await.unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + let pinned = shopify.with_api_version(ApiVersion::V2026_07); + pinned.execute(shop_name::operation()).await.unwrap(); + pinned.graphql("{ shop { name } }", ()).await.unwrap(); + + let versions: Vec = mock + .graphql_requests() + .into_iter() + .map(|request| request.api_version) + .collect(); + assert_eq!(versions, ["2026-10", "2026-10", "2026-07", "2026-07"]); +} + +#[tokio::test] +async fn the_response_carries_the_cost() { + let mock = MockTransport::new(); + mock.push_json(json!({ + "data": { "shop": { "name": "x" } }, + "extensions": { "cost": { + "requestedQueryCost": 1, + "actualQueryCost": 1, + "throttleStatus": { "maximumAvailable": 2000.0, "currentlyAvailable": 1999, "restoreRate": 100.0 }, + } }, + })); + let shopify = client(&mock); + + let response = shopify + .execute_response(shop_name::operation()) + .await + .unwrap(); + assert_eq!(response.data.shop.name, "x"); + let cost = response.cost().unwrap(); + assert_eq!(cost.actual_query_cost, Some(1.0)); + assert_eq!(cost.throttle_status.currently_available, 1999.0); +} diff --git a/crates/shopify_api/tests/graphql/order.graphql b/crates/shopify_api/tests/graphql/order.graphql new file mode 100644 index 0000000..e26fb29 --- /dev/null +++ b/crates/shopify_api/tests/graphql/order.graphql @@ -0,0 +1,7 @@ +# An operation kept in a file: `graphql! { mod from_file = file("tests/graphql/order.graphql"); }`. +query OrderFromFile($id: ID!) { + order(id: $id) { + name + email + } +} diff --git a/crates/shopify_api/tests/live.rs b/crates/shopify_api/tests/live.rs new file mode 100644 index 0000000..2d7c61d --- /dev/null +++ b/crates/shopify_api/tests/live.rs @@ -0,0 +1,85 @@ +//! Against a real development store. Ignored by default: `mise run test:live` +//! runs them, with `SHOPIFY_TEST_SHOP` and either `SHOPIFY_TEST_ACCESS_TOKEN` +//! or `SHOPIFY_TEST_CLIENT_ID` and `SHOPIFY_TEST_CLIENT_SECRET`. +#![cfg(feature = "rustls")] + +use std::time::Duration; + +use shopify_api::bulk::{BulkOperationStatus, BulkOperationsFilter, BulkWaitOptions}; +use shopify_api::{Auth, Shopify, graphql}; + +fn live() -> Shopify { + let env = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); + let shop = env("SHOPIFY_TEST_SHOP").expect("SHOPIFY_TEST_SHOP"); + let auth = match ( + env("SHOPIFY_TEST_ACCESS_TOKEN"), + env("SHOPIFY_TEST_CLIENT_ID"), + env("SHOPIFY_TEST_CLIENT_SECRET"), + ) { + (Some(token), _, _) => Auth::access_token(token), + (None, Some(id), Some(secret)) => Auth::client_credentials(id, secret), + _ => panic!( + "set SHOPIFY_TEST_ACCESS_TOKEN, or SHOPIFY_TEST_CLIENT_ID and SHOPIFY_TEST_CLIENT_SECRET" + ), + }; + Shopify::new(shop, auth).expect("a valid shop") +} + +#[tokio::test] +#[ignore = "calls a real store: mise run test:live"] +async fn reads_the_shop_with_a_typed_query() { + let data = live() + .execute(graphql!( + "query Shop { shop { name myshopifyDomain currencyCode } }" + )) + .await + .unwrap(); + assert!(!data.shop.name.is_empty()); + assert!(data.shop.myshopify_domain.ends_with(".myshopify.com")); +} + +#[tokio::test] +#[ignore = "calls a real store: mise run test:live"] +async fn the_answer_carries_the_cost() { + let response = live() + .execute_response(graphql!("{ products(first: 1) { nodes { id } } }")) + .await + .unwrap(); + let cost = response.cost().expect("Shopify reports the cost"); + assert!(cost.throttle_status.maximum_available > 0.0); +} + +#[tokio::test] +#[ignore = "calls a real store: mise run test:live"] +async fn downloads_the_schema_through_the_shop() { + let schema = live().download_admin_schema().await.unwrap(); + assert!(schema.pointer("/data/__schema/types").is_some()); +} + +#[tokio::test] +#[ignore = "calls a real store: mise run test:live"] +async fn runs_a_bulk_query_to_its_end() { + let shopify = live(); + let operation = shopify + .run_bulk_query("{ products { edges { node { id title } } } }") + .await + .unwrap(); + let listed = shopify + .bulk_operations(BulkOperationsFilter::new().first(5)) + .await + .unwrap(); + assert!(listed.items.iter().any(|listed| listed.id == operation.id)); + + let operation = shopify + .wait_for_bulk_operation( + &operation.id, + BulkWaitOptions::new().timeout(Duration::from_secs(180)), + ) + .await + .unwrap(); + assert_eq!(operation.status, BulkOperationStatus::Completed); + if let Some(url) = operation.url { + let rows: Vec = shopify.download_bulk_results(&url).await.unwrap(); + assert!(rows.iter().all(|row| row.get("id").is_some())); + } +} diff --git a/crates/shopify_api/tests/oauth.rs b/crates/shopify_api/tests/oauth.rs new file mode 100644 index 0000000..bec5b7f --- /dev/null +++ b/crates/shopify_api/tests/oauth.rs @@ -0,0 +1,127 @@ +//! The token requests of OAuth and of the token exchange. +#![cfg(all(feature = "testing", feature = "oauth"))] + +use serde_json::json; +use shopify_api::oauth::{RequestedToken, ShopifyApp}; +use shopify_api::testing::MockTransport; +use shopify_api::transport::HttpResponse; + +fn app(mock: &MockTransport) -> ShopifyApp { + ShopifyApp::new("client-id", "client-secret").with_transport(mock.clone()) +} + +fn now() -> i64 { + chrono::Utc::now().timestamp() +} + +#[tokio::test] +async fn the_code_of_a_verified_callback_becomes_a_token() { + let mock = MockTransport::new(); + mock.push_json(json!({ "access_token": "shpat_1", "scope": "read_products,write_orders" })); + let app = app(&mock); + + let query = format!( + "code=abc&shop=my-shop.myshopify.com&state=s1×tamp={}", + now() + ); + let signature = app.sign_query(&query).unwrap(); + let callback = app + .verify_query(&format!("{query}&hmac={signature}")) + .unwrap(); + let token = app.exchange_code(&callback).await.unwrap(); + + assert_eq!(token.access_token, "shpat_1"); + assert_eq!(token.scopes(), ["read_products", "write_orders"]); + let request = mock.last_request().unwrap(); + assert_eq!( + request.url, + "https://my-shop.myshopify.com/admin/oauth/access_token" + ); + assert_eq!( + request.json().unwrap(), + json!({ "client_id": "client-id", "client_secret": "client-secret", "code": "abc" }) + ); +} + +#[tokio::test] +async fn a_session_token_becomes_an_expiring_token_and_a_client_that_refreshes_it() { + let mock = MockTransport::new(); + mock.push_json(json!({ + "access_token": "shpat_1", + "scope": "read_products", + "expires_in": 3600, + "refresh_token": "shprt_1", + "refresh_token_expires_in": 7_776_000, + })); + let app = app(&mock); + let now = now(); + let bearer = app.sign_session_token(&json!({ + "iss": "https://my-shop.myshopify.com/admin", + "dest": "https://my-shop.myshopify.com", + "aud": "client-id", + "sub": "42", + "exp": now + 60, + "nbf": now, + })); + + let session = app.verify_session_token(&bearer).unwrap(); + let token = app + .exchange_session_token(&session, RequestedToken::ExpiringOffline) + .await + .unwrap(); + assert_eq!(token.refresh_token.as_deref(), Some("shprt_1")); + assert_eq!( + mock.last_request().unwrap().json().unwrap(), + json!({ + "client_id": "client-id", + "client_secret": "client-secret", + "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", + "subject_token": bearer, + "subject_token_type": "urn:ietf:params:oauth:token-type:id_token", + "requested_token_type": "urn:shopify:params:oauth:token-type:offline-access-token", + "expiring": "1", + }) + ); + + // The client of that token sends it, through the app's transport. + mock.push_data(json!({ "shop": { "name": "My shop" } })); + let shopify = app.client(session.shop(), token).unwrap(); + let data = shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(data["shop"]["name"], "My shop"); + assert_eq!( + mock.graphql_requests()[0].access_token.as_deref(), + Some("shpat_1") + ); +} + +#[tokio::test] +async fn an_online_token_names_its_staff_member() { + let mock = MockTransport::new(); + mock.push(HttpResponse::json( + 200, + &json!({ + "access_token": "shpua_1", + "scope": "read_products", + "expires_in": 86_399, + "associated_user_scope": "read_products", + "associated_user": { "id": 902541635, "first_name": "Ada", "email": "ada@example.com", "account_owner": true }, + }), + )); + let app = app(&mock); + let now = now(); + let bearer = app.sign_session_token(&json!({ + "dest": "https://my-shop.myshopify.com", + "aud": "client-id", + "exp": now + 60, + })); + let session = app.verify_session_token(&bearer).unwrap(); + + let token = app + .exchange_session_token(&session, RequestedToken::Online) + .await + .unwrap(); + let user = token.associated_user.unwrap(); + assert_eq!(user.id, 902541635); + assert_eq!(user.first_name.as_deref(), Some("Ada")); + assert_eq!(user.account_owner, Some(true)); +} diff --git a/crates/shopify_api/tests/pagination.rs b/crates/shopify_api/tests/pagination.rs new file mode 100644 index 0000000..8f354eb --- /dev/null +++ b/crates/shopify_api/tests/pagination.rs @@ -0,0 +1,99 @@ +//! Cursor pagination with typed operations. +#![cfg(feature = "testing")] + +use serde_json::json; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::{Page, graphql}; + +#[tokio::test] +async fn collects_every_page_following_the_cursor() { + let mock = MockTransport::new(); + for (ids, next, cursor) in [ + (vec![1, 2], true, Some("c2")), + (vec![3, 4], true, Some("c4")), + (vec![5], false, None), + ] { + let nodes: Vec<_> = ids + .iter() + .map(|id| json!({ "id": format!("gid://shopify/Product/{id}"), "title": format!("P{id}") })) + .collect(); + mock.push_data(json!({ "products": { + "nodes": nodes, + "pageInfo": { "hasNextPage": next, "endCursor": cursor }, + } })); + } + let shopify = client(&mock); + + let products = shopify + .paginate( + |after| { + graphql!( + "query Products($after: String) { + products(first: 2, after: $after) { + nodes { id title } + pageInfo { hasNextPage endCursor } + } + }", + after = after, + ) + }, + |data| { + let page_info = data.products.page_info; + Page::new( + data.products.nodes, + page_info.has_next_page, + page_info.end_cursor, + ) + }, + ) + .await + .unwrap(); + + let titles: Vec<&str> = products + .iter() + .map(|product| product.title.as_str()) + .collect(); + assert_eq!(titles, ["P1", "P2", "P3", "P4", "P5"]); + let cursors: Vec<_> = mock + .graphql_requests() + .into_iter() + .map(|request| request.variables.get("after").cloned()) + .collect(); + assert_eq!( + cursors, + [Some(json!(null)), Some(json!("c2")), Some(json!("c4"))] + ); +} + +#[tokio::test] +async fn a_cursor_that_does_not_move_stops_the_loop() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(shopify_api::transport::HttpResponse::json( + 200, + &json!({ "data": { "products": { "nodes": [], "pageInfo": { "hasNextPage": true, "endCursor": "same" } } } }), + )) + }); + let shopify = client(&mock); + + let error = shopify + .paginate( + |after| { + graphql!( + "query($after: String) { products(first: 2, after: $after) { nodes { id } pageInfo { hasNextPage endCursor } } }", + after = after, + ) + }, + |data| { + let page_info = data.products.page_info; + Page::new(data.products.nodes, page_info.has_next_page, page_info.end_cursor) + }, + ) + .await + .unwrap_err(); + assert!( + error.to_string().contains("the cursor does not move"), + "{error}" + ); + assert_eq!(mock.requests().len(), 2); +} diff --git a/crates/shopify_api/tests/retry.rs b/crates/shopify_api/tests/retry.rs new file mode 100644 index 0000000..9c6917e --- /dev/null +++ b/crates/shopify_api/tests/retry.rs @@ -0,0 +1,149 @@ +//! What the client sends again, and what it does not. +#![cfg(feature = "testing")] + +use std::time::Duration; + +use serde_json::json; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::transport::{HttpResponse, TransportError}; +use shopify_api::{Error, RetryPolicy, Shopify}; + +fn shop() -> serde_json::Value { + json!({ "shop": { "name": "x" } }) +} + +#[tokio::test] +async fn a_throttled_request_is_sent_again() { + let mock = MockTransport::new(); + mock.push_throttled().push_throttled().push_data(shop()); + let shopify = client(&mock); + + let data = shopify + .execute(shopify_api::graphql!("{ shop { name } }")) + .await + .unwrap(); + assert_eq!(data.shop.name, "x"); + assert_eq!(mock.requests().len(), 3); +} + +#[tokio::test(start_paused = true)] +async fn a_throttled_request_waits_for_its_cost() { + let mock = MockTransport::new(); + // 10 requested, 0 available, 100 per second: 0.1 s, and a little more. + mock.push_throttled().push_data(shop()); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(mock.clone()) + .build() + .unwrap(); + + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(started.elapsed(), Duration::from_millis(200)); +} + +#[tokio::test] +async fn throttling_that_lasts_ends_in_an_error_with_the_cost() { + let mock = MockTransport::new(); + for _ in 0..5 { + mock.push_throttled(); + } + let shopify = client(&mock); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + let Error::Throttled { retries, cost, .. } = error else { + panic!("throttled: {error:?}"); + }; + assert_eq!(retries, 4); + assert_eq!(cost.unwrap().requested_query_cost, 10.0); + assert_eq!(mock.requests().len(), 5); +} + +#[tokio::test(start_paused = true)] +async fn a_429_waits_for_its_retry_after() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "2.0")) + .push_data(shop()); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(mock.clone()) + .build() + .unwrap(); + + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(started.elapsed(), Duration::from_secs(2)); +} + +#[tokio::test] +async fn a_query_is_sent_again_after_a_server_error_or_a_network_failure() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(502, "Bad Gateway")) + .push_error(TransportError::timeout("timed out")) + .push_data(shop()); + let shopify = client(&mock); + + shopify + .graphql("query { shop { name } }", ()) + .await + .unwrap(); + assert_eq!(mock.requests().len(), 3); +} + +#[tokio::test] +async fn a_mutation_is_not_sent_again_when_it_may_have_run() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(502, "Bad Gateway")); + let shopify = client(&mock); + + let mutation = "mutation { tagsAdd(id: \"gid://shopify/Order/1\", tags: [\"a\"]) { userErrors { message } } }"; + let error = shopify.graphql(mutation, ()).await.unwrap_err(); + assert_eq!(error.status(), Some(502)); + assert_eq!(mock.requests().len(), 1); + + mock.clear(); + mock.push_error(TransportError::new("connection reset")); + let error = shopify.graphql(mutation, ()).await.unwrap_err(); + assert!(matches!(error, Error::Transport { .. }), "{error:?}"); + assert_eq!(mock.requests().len(), 1); + + // A throttled mutation did not run: it goes again. + mock.clear(); + mock.push_throttled() + .push_data(json!({ "tagsAdd": { "userErrors": [] } })); + shopify.graphql(mutation, ()).await.unwrap(); + assert_eq!(mock.requests().len(), 2); +} + +#[tokio::test] +async fn no_retry_policy_sends_once() { + let mock = MockTransport::new(); + mock.push_throttled(); + let shopify = client(&mock).with_retry(RetryPolicy::none()); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!( + matches!(error, Error::Throttled { retries: 0, .. }), + "{error:?}" + ); + assert_eq!(mock.requests().len(), 1); +} + +#[tokio::test] +async fn waits_shopify_cannot_mean_do_not_panic() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "1e300")) + .push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "-5")) + .push_json(json!({ + "errors": [{ "message": "Throttled", "extensions": { "code": "THROTTLED" } }], + "extensions": { "cost": { + "requestedQueryCost": 10, + "throttleStatus": { "maximumAvailable": 2000.0, "currentlyAvailable": 0, "restoreRate": 1e-320 }, + } }, + })) + .push_data(shop()); + let shopify = client(&mock); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(mock.requests().len(), 4); +} diff --git a/crates/shopify_api/tests/ui/deprecated_field_denied.rs b/crates/shopify_api/tests/ui/deprecated_field_denied.rs new file mode 100644 index 0000000..4d2ba36 --- /dev/null +++ b/crates/shopify_api/tests/ui/deprecated_field_denied.rs @@ -0,0 +1,5 @@ +#![deny(deprecated)] + +fn main() { + let _ = shopify_api::graphql!("{ product(id: \"gid://shopify/Product/1\") { bodyHtml } }"); +} diff --git a/crates/shopify_api/tests/ui/deprecated_field_denied.stderr b/crates/shopify_api/tests/ui/deprecated_field_denied.stderr new file mode 100644 index 0000000..7495888 --- /dev/null +++ b/crates/shopify_api/tests/ui/deprecated_field_denied.stderr @@ -0,0 +1,11 @@ +error: use of deprecated constant `main::_::SHOPIFY_DEPRECATION`: `Product.bodyHtml` is deprecated in the Shopify Admin API 2026-10: Use `descriptionHtml` instead. (line 1, column 44 of the operation) + --> tests/ui/deprecated_field_denied.rs:4:35 + | +4 | let _ = shopify_api::graphql!("{ product(id: \"gid://shopify/Product/1\") { bodyHtml } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: the lint level is defined here + --> tests/ui/deprecated_field_denied.rs:1:9 + | +1 | #![deny(deprecated)] + | ^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/integer_out_of_range.rs b/crates/shopify_api/tests/ui/integer_out_of_range.rs new file mode 100644 index 0000000..f5cdd9a --- /dev/null +++ b/crates/shopify_api/tests/ui/integer_out_of_range.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("{ products(first: 3000000000) { nodes { title } } }"); +} diff --git a/crates/shopify_api/tests/ui/integer_out_of_range.stderr b/crates/shopify_api/tests/ui/integer_out_of_range.stderr new file mode 100644 index 0000000..cf90e49 --- /dev/null +++ b/crates/shopify_api/tests/ui/integer_out_of_range.stderr @@ -0,0 +1,6 @@ +error: The integer is outside the range of `Int`, a 32-bit integer, given for argument `first` of `QueryRoot.products` (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/integer_out_of_range.rs:2:35 + | +2 | let _ = shopify_api::graphql!("{ products(first: 3000000000) { nodes { title } } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/missing_file.rs b/crates/shopify_api/tests/ui/missing_file.rs new file mode 100644 index 0000000..5cd195d --- /dev/null +++ b/crates/shopify_api/tests/ui/missing_file.rs @@ -0,0 +1,5 @@ +shopify_api::graphql! { + mod orders = file("graphql/missing.graphql"); +} + +fn main() {} diff --git a/crates/shopify_api/tests/ui/missing_file.stderr b/crates/shopify_api/tests/ui/missing_file.stderr new file mode 100644 index 0000000..610c77f --- /dev/null +++ b/crates/shopify_api/tests/ui/missing_file.stderr @@ -0,0 +1,5 @@ +error: Cannot read `graphql/missing.graphql`, relative to the Cargo.toml of the crate: No such file or directory (os error 2) + --> tests/ui/missing_file.rs:2:23 + | +2 | mod orders = file("graphql/missing.graphql"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/missing_variable.rs b/crates/shopify_api/tests/ui/missing_variable.rs new file mode 100644 index 0000000..116726e --- /dev/null +++ b/crates/shopify_api/tests/ui/missing_variable.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("query($id: ID!) { product(id: $id) { title } }"); +} diff --git a/crates/shopify_api/tests/ui/missing_variable.stderr b/crates/shopify_api/tests/ui/missing_variable.stderr new file mode 100644 index 0000000..098176f --- /dev/null +++ b/crates/shopify_api/tests/ui/missing_variable.stderr @@ -0,0 +1,5 @@ +error: Variable `$id: ID!` needs a value: add `id = …` after the operation + --> tests/ui/missing_variable.rs:2:35 + | +2 | let _ = shopify_api::graphql!("query($id: ID!) { product(id: $id) { title } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/subscription.rs b/crates/shopify_api/tests/ui/subscription.rs new file mode 100644 index 0000000..42ecf22 --- /dev/null +++ b/crates/shopify_api/tests/ui/subscription.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("subscription { shop { name } }"); +} diff --git a/crates/shopify_api/tests/ui/subscription.stderr b/crates/shopify_api/tests/ui/subscription.stderr new file mode 100644 index 0000000..dafecce --- /dev/null +++ b/crates/shopify_api/tests/ui/subscription.stderr @@ -0,0 +1,6 @@ +error: Subscriptions are not supported (line 1, column 1) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/subscription.rs:2:35 + | +2 | let _ = shopify_api::graphql!("subscription { shop { name } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/syntax_error.rs b/crates/shopify_api/tests/ui/syntax_error.rs new file mode 100644 index 0000000..3820079 --- /dev/null +++ b/crates/shopify_api/tests/ui/syntax_error.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("{ shop { name }"); +} diff --git a/crates/shopify_api/tests/ui/syntax_error.stderr b/crates/shopify_api/tests/ui/syntax_error.stderr new file mode 100644 index 0000000..de5157d --- /dev/null +++ b/crates/shopify_api/tests/ui/syntax_error.stderr @@ -0,0 +1,6 @@ +error: Invalid GraphQL: Parse error at 1:16 Unexpected end of input Expected } + (checked against the Shopify Admin API 2026-10) + --> tests/ui/syntax_error.rs:2:35 + | +2 | let _ = shopify_api::graphql!("{ shop { name }"); + | ^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/unknown_enum_value.rs b/crates/shopify_api/tests/ui/unknown_enum_value.rs new file mode 100644 index 0000000..a1c45e4 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_enum_value.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("{ orders(first: 1, sortKey: CREATED) { nodes { id } } }"); +} diff --git a/crates/shopify_api/tests/ui/unknown_enum_value.stderr b/crates/shopify_api/tests/ui/unknown_enum_value.stderr new file mode 100644 index 0000000..2b0b1f8 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_enum_value.stderr @@ -0,0 +1,6 @@ +error: `CREATED` is not a value of the enum `OrderSortKeys` (did you mean `CREATED_AT`?) (in argument `sortKey` of `QueryRoot.orders`) (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/unknown_enum_value.rs:2:35 + | +2 | let _ = shopify_api::graphql!("{ orders(first: 1, sortKey: CREATED) { nodes { id } } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/unknown_field.rs b/crates/shopify_api/tests/ui/unknown_field.rs new file mode 100644 index 0000000..9dd2626 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_field.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("{ shop { nam } }"); +} diff --git a/crates/shopify_api/tests/ui/unknown_field.stderr b/crates/shopify_api/tests/ui/unknown_field.stderr new file mode 100644 index 0000000..ad34093 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_field.stderr @@ -0,0 +1,6 @@ +error: Type `Shop` has no field `nam` (did you mean `name`?) (line 1, column 10) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/unknown_field.rs:2:35 + | +2 | let _ = shopify_api::graphql!("{ shop { nam } }"); + | ^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/unknown_variable.rs b/crates/shopify_api/tests/ui/unknown_variable.rs new file mode 100644 index 0000000..36802b9 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_variable.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("query($id: ID!) { product(id: $id) { title } }", id = "1", first = 2); +} diff --git a/crates/shopify_api/tests/ui/unknown_variable.stderr b/crates/shopify_api/tests/ui/unknown_variable.stderr new file mode 100644 index 0000000..ec5cdf5 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_variable.stderr @@ -0,0 +1,5 @@ +error: The operation has no variable `$first`: it declares $id + --> tests/ui/unknown_variable.rs:2:95 + | +2 | let _ = shopify_api::graphql!("query($id: ID!) { product(id: $id) { title } }", id = "1", first = 2); + | ^^^^^ diff --git a/crates/shopify_api/tests/ui/unselected_field.rs b/crates/shopify_api/tests/ui/unselected_field.rs new file mode 100644 index 0000000..4dd7e6f --- /dev/null +++ b/crates/shopify_api/tests/ui/unselected_field.rs @@ -0,0 +1,6 @@ +async fn email(shopify: &shopify_api::Shopify) -> shopify_api::Result { + let data = shopify.execute(shopify_api::graphql!("{ shop { name } }")).await?; + Ok(data.shop.email) +} + +fn main() {} diff --git a/crates/shopify_api/tests/ui/unselected_field.stderr b/crates/shopify_api/tests/ui/unselected_field.stderr new file mode 100644 index 0000000..074c770 --- /dev/null +++ b/crates/shopify_api/tests/ui/unselected_field.stderr @@ -0,0 +1,7 @@ +error[E0609]: no field `email` on type `DataShop` + --> tests/ui/unselected_field.rs:3:18 + | +3 | Ok(data.shop.email) + | ^^^^^ unknown field + | + = note: available field is: `name` diff --git a/crates/shopify_api/tests/ui/wrong_value_type.rs b/crates/shopify_api/tests/ui/wrong_value_type.rs new file mode 100644 index 0000000..132b55a --- /dev/null +++ b/crates/shopify_api/tests/ui/wrong_value_type.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("query($first: Int!) { products(first: $first) { nodes { id } } }", first = "ten"); +} diff --git a/crates/shopify_api/tests/ui/wrong_value_type.stderr b/crates/shopify_api/tests/ui/wrong_value_type.stderr new file mode 100644 index 0000000..1669745 --- /dev/null +++ b/crates/shopify_api/tests/ui/wrong_value_type.stderr @@ -0,0 +1,29 @@ +error[E0277]: `&str` is not a value for a GraphQL variable of Rust type `i64` + --> tests/ui/wrong_value_type.rs:2:111 + | +2 | let _ = shopify_api::graphql!("query($first: Int!) { products(first: $first) { nodes { id } } }", first = "ten"); + | ^^^^^ the variable expects a value convertible to `i64` + | + = help: the trait `IntoVariable` is not implemented for `&str` +help: `&str` implements trait `IntoVariable` + --> src/graphql/operation.rs + | + | impl IntoVariable<$target> for $source { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `IntoVariable` +... + | impl IntoVariable> for $source { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `IntoVariable>` +... + | / into_variable!(String: + | | String => |value| value, + | | &str => |value| value.to_string(), + | | &String => |value| value.clone(), + | | Cow<'_, str> => |value| value.into_owned(), + | | ); + | |_- in this macro invocation +note: required by a bound in `Operation::::variable` + --> src/graphql/operation.rs + | + | pub fn variable>(self, name: &str, value: V) -> Self { + | ^^^^^^^^^^^^^^^ required by this bound in `Operation::::variable` + = note: this error originates in the macro `into_variable` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/webhooks.rs b/crates/shopify_api/tests/webhooks.rs new file mode 100644 index 0000000..2fad94a --- /dev/null +++ b/crates/shopify_api/tests/webhooks.rs @@ -0,0 +1,128 @@ +//! Webhook subscriptions against a scripted Shopify. +#![cfg(all(feature = "testing", feature = "webhooks"))] + +use serde_json::{Value, json}; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::webhooks::WebhookSubscriptionSpec; + +fn subscription(id: u32, topic: &str, uri: &str) -> Value { + json!({ + "id": format!("gid://shopify/WebhookSubscription/{id}"), + "topic": topic, + "uri": uri, + "format": "JSON", + "filter": null, + "includeFields": [], + "metafieldNamespaces": [], + "name": null, + "createdAt": "2026-10-01T00:00:00Z", + "updatedAt": "2026-10-01T00:00:00Z", + "apiVersion": { "handle": "2026-10" }, + }) +} + +#[tokio::test] +async fn sync_keeps_updates_creates_then_deletes() { + let mock = MockTransport::new(); + // Two pages of existing subscriptions. + mock.push_data(json!({ "webhookSubscriptions": { + "nodes": [subscription(1, "ORDERS_CREATE", "https://example.com/hooks")], + "pageInfo": { "hasNextPage": true, "endCursor": "c1" }, + } })); + mock.push_data(json!({ "webhookSubscriptions": { + "nodes": [ + subscription(2, "PRODUCTS_UPDATE", "https://old.example.com/hooks"), + subscription(3, "PRODUCTS_UPDATE", "https://example.com/hooks"), + ], + "pageInfo": { "hasNextPage": false, "endCursor": "c2" }, + } })); + let mut updated = subscription(3, "PRODUCTS_UPDATE", "https://example.com/hooks"); + updated["includeFields"] = json!(["id"]); + mock.push_data(json!({ "webhookSubscriptionUpdate": { "webhookSubscription": updated, "userErrors": [] } })); + mock.push_data(json!({ "webhookSubscriptionCreate": { + "webhookSubscription": subscription(4, "APP_UNINSTALLED", "https://example.com/hooks"), + "userErrors": [], + } })); + mock.push_data(json!({ "webhookSubscriptionDelete": { + "deletedWebhookSubscriptionId": "gid://shopify/WebhookSubscription/2", + "userErrors": [], + } })); + let shopify = client(&mock); + + let report = shopify + .sync_webhook_subscriptions(&[ + WebhookSubscriptionSpec::new("orders/create", "https://example.com/hooks"), + WebhookSubscriptionSpec::new("products/update", "https://example.com/hooks") + .include_fields(["id"]), + WebhookSubscriptionSpec::new("app/uninstalled", "https://example.com/hooks"), + ]) + .await + .unwrap(); + + assert_eq!(report.kept.len(), 1); + assert_eq!(report.updated[0].include_fields, ["id"]); + assert_eq!(report.created[0].topic, "APP_UNINSTALLED"); + assert_eq!(report.created[0].api_version, "2026-10"); + assert_eq!(report.deleted, ["gid://shopify/WebhookSubscription/2"]); + + let sent = mock.graphql_requests(); + let names: Vec<_> = sent + .iter() + .map(|request| request.operation_name.clone().unwrap()) + .collect(); + // Nothing is deleted before what replaces it exists. + assert_eq!( + names, + [ + "WebhookSubscriptions", + "WebhookSubscriptions", + "WebhookSubscriptionUpdate", + "WebhookSubscriptionCreate", + "WebhookSubscriptionDelete", + ] + ); + assert_eq!(sent[1].variables, json!({ "after": "c1" })); + // An update sends every option, so that it replaces the old ones. + assert_eq!( + sent[2].variables, + json!({ + "id": "gid://shopify/WebhookSubscription/3", + "webhookSubscription": { + "uri": "https://example.com/hooks", + "format": "JSON", + "filter": "", + "includeFields": ["id"], + "metafieldNamespaces": [], + }, + }) + ); + assert_eq!( + sent[3].variables, + json!({ + "topic": "APP_UNINSTALLED", + "webhookSubscription": { "uri": "https://example.com/hooks", "format": "JSON" }, + }) + ); +} + +#[tokio::test] +async fn a_refused_subscription_returns_the_user_errors() { + let mock = MockTransport::new(); + mock.push_data(json!({ "webhookSubscriptionCreate": { + "webhookSubscription": null, + "userErrors": [{ "field": ["webhookSubscription", "callbackUrl"], "message": "Address is invalid" }], + } })); + let shopify = client(&mock); + + let error = shopify + .create_webhook_subscription(&WebhookSubscriptionSpec::new( + "ORDERS_CREATE", + "http://localhost", + )) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "webhookSubscriptionCreate refused: webhookSubscription.callbackUrl: Address is invalid" + ); +} diff --git a/crates/shopify_api_graphql/Cargo.toml b/crates/shopify_api_graphql/Cargo.toml new file mode 100644 index 0000000..52b502d --- /dev/null +++ b/crates/shopify_api_graphql/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "shopify_api_graphql" +description = "Checks Shopify Admin GraphQL operations against the schema and generates their Rust types. Used by the `graphql!` macro of `shopify_api`." +documentation = "https://docs.rs/shopify_api_graphql" +keywords = ["shopify", "graphql", "codegen"] +categories = ["development-tools", "api-bindings"] +readme = "README.md" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +include = ["src/**", "schema/**", "Cargo.toml", "README.md"] + +[dependencies] +graphql-parser.workspace = true +proc-macro2.workspace = true +quote.workspace = true +serde.workspace = true +serde_json.workspace = true + +[lints] +workspace = true diff --git a/crates/shopify_api_graphql/README.md b/crates/shopify_api_graphql/README.md new file mode 100644 index 0000000..d94ba9b --- /dev/null +++ b/crates/shopify_api_graphql/README.md @@ -0,0 +1,11 @@ +# shopify_api_graphql + +The compile-time half of [`shopify_api`](https://crates.io/crates/shopify_api)'s +`graphql!` macro: it reads Shopify's Admin GraphQL schema, checks an operation +against it, and generates the Rust types of its variables and of its result. + +You do not need to depend on it directly: use `shopify_api::graphql!`. It is a +separate crate so that the macro and the `shopify-api` command line share it. + +It also bundles the Admin schema of the API version `shopify_api` calls by +default, in a compact form (one line per type, no descriptions). diff --git a/crates/shopify_api_graphql/schema/admin-2026-10.json b/crates/shopify_api_graphql/schema/admin-2026-10.json new file mode 100644 index 0000000..b571286 --- /dev/null +++ b/crates/shopify_api_graphql/schema/admin-2026-10.json @@ -0,0 +1,3711 @@ +{"format":1,"apiVersion":"2026-10","query":"QueryRoot","mutation":"Mutation", +"directives":{"idempotent":{"l":["FIELD"],"a":{"key":"String!"}},"include":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}},"skip":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}}},"types":{ +"ARN":"s", +"AbandonedCheckout":{"o":{"f":{"abandonedCheckoutUrl":"URL!","billingAddress":"MailingAddress","completedAt":"DateTime","createdAt":"DateTime!","customAttributes":"[Attribute!]!","customer":"Customer","defaultCursor":"String!","discountCodes":"[String!]!","id":"ID!","lineItems":["AbandonedCheckoutLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"lineItemsQuantity":"Int!","name":"String!","note":"String!","shippingAddress":"MailingAddress","subtotalPriceSet":"MoneyBag!","taxLines":"[TaxLine!]!","taxesIncluded":"Boolean!","totalDiscountSet":"MoneyBag!","totalDutiesSet":"MoneyBag","totalLineItemsPriceSet":"MoneyBag!","totalPriceSet":"MoneyBag!","totalTaxSet":"MoneyBag","updatedAt":"DateTime!"},"t":["Navigable","Node"],"d":{"lineItemsQuantity":"Use [AbandonedCheckoutLineItem.quantity](https://shopify.dev/api/admin-graphql/unstable/objects/AbandonedCheckoutLineItem#field-quantity) instead."}}}, +"AbandonedCheckoutConnection":{"o":{"f":{"edges":"[AbandonedCheckoutEdge!]!","nodes":"[AbandonedCheckout!]!","pageInfo":"PageInfo!"}}}, +"AbandonedCheckoutEdge":{"o":{"f":{"cursor":"String!","node":"AbandonedCheckout!"}}}, +"AbandonedCheckoutLineItem":{"o":{"f":{"components":"[AbandonedCheckoutLineItemComponent!]","customAttributes":"[Attribute!]!","discountAllocations":["DiscountAllocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountedTotalPriceSet":"MoneyBag!","discountedTotalPriceWithCodeDiscount":"MoneyBag!","discountedUnitPriceSet":"MoneyBag!","discountedUnitPriceWithCodeDiscount":"MoneyBag!","id":"ID!","image":"Image","originalTotalPriceSet":"MoneyBag!","originalUnitPriceSet":"MoneyBag!","parentRelationship":"AbandonedCheckoutLineItemParentRelationship","product":"Product","quantity":"Int!","sku":"String","title":"String","variant":"ProductVariant","variantTitle":"String"},"t":["Node"]}}, +"AbandonedCheckoutLineItemComponent":{"o":{"f":{"id":"ID!","image":"Image","quantity":"Int!","title":"String!","variantTitle":"String"}}}, +"AbandonedCheckoutLineItemConnection":{"o":{"f":{"edges":"[AbandonedCheckoutLineItemEdge!]!","nodes":"[AbandonedCheckoutLineItem!]!","pageInfo":"PageInfo!"}}}, +"AbandonedCheckoutLineItemEdge":{"o":{"f":{"cursor":"String!","node":"AbandonedCheckoutLineItem!"}}}, +"AbandonedCheckoutLineItemParentRelationship":{"o":{"f":{"parent":"AbandonedCheckoutLineItem!"}}}, +"AbandonedCheckoutSortKeys":{"e":["CHECKOUT_ID","CREATED_AT","CUSTOMER_NAME","ID","RELEVANCE","TOTAL_PRICE"]}, +"Abandonment":{"o":{"f":{"abandonedCheckoutPayload":"AbandonedCheckout","abandonmentType":"AbandonmentAbandonmentType!","app":"App!","cartUrl":"URL","createdAt":"DateTime!","customer":"Customer!","customerHasNoDraftOrderSinceAbandonment":"Boolean!","customerHasNoOrderSinceAbandonment":"Boolean!","daysSinceLastAbandonmentEmail":"Int!","emailSentAt":"DateTime","emailState":"AbandonmentEmailState","hoursSinceLastAbandonedCheckout":"Float","id":"ID!","inventoryAvailable":"Boolean!","isFromCustomStorefront":"Boolean!","isFromOnlineStore":"Boolean!","isFromShopApp":"Boolean!","isFromShopPay":"Boolean!","isMostSignificantAbandonment":"Boolean!","lastBrowseAbandonmentDate":"DateTime!","lastCartAbandonmentDate":"DateTime!","lastCheckoutAbandonmentDate":"DateTime!","mostRecentStep":"AbandonmentAbandonmentType!","productsAddedToCart":["CustomerVisitProductInfoConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productsViewed":["CustomerVisitProductInfoConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"visitStartedAt":"DateTime"},"t":["Node"]}}, +"AbandonmentAbandonmentType":{"e":["BROWSE","CART","CHECKOUT"]}, +"AbandonmentDeliveryState":{"e":["NOT_SENT","SENT","SCHEDULED"]}, +"AbandonmentEmailState":{"e":["NOT_SENT","SENT","SCHEDULED"]}, +"AbandonmentEmailStateUpdatePayload":{"o":{"f":{"abandonment":"Abandonment","userErrors":"[AbandonmentEmailStateUpdateUserError!]!"}}}, +"AbandonmentEmailStateUpdateUserError":{"o":{"f":{"code":"AbandonmentEmailStateUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AbandonmentEmailStateUpdateUserErrorCode":{"e":["ABANDONMENT_NOT_FOUND"]}, +"AbandonmentUpdateActivitiesDeliveryStatusesPayload":{"o":{"f":{"abandonment":"Abandonment","userErrors":"[AbandonmentUpdateActivitiesDeliveryStatusesUserError!]!"}}}, +"AbandonmentUpdateActivitiesDeliveryStatusesUserError":{"o":{"f":{"code":"AbandonmentUpdateActivitiesDeliveryStatusesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AbandonmentUpdateActivitiesDeliveryStatusesUserErrorCode":{"e":["ABANDONMENT_NOT_FOUND","MARKETING_ACTIVITY_NOT_FOUND","DELIVERY_STATUS_INFO_NOT_FOUND"]}, +"AccessScope":{"o":{"f":{"description":"String!","handle":"String!"}}}, +"AccountType":{"e":["REGULAR","RESTRICTED","INVITED","REQUESTED","COLLABORATOR","COLLABORATOR_TEAM_MEMBER","SAML","INVITED_STORE_OWNER"]}, +"AddAllProductsOperation":{"o":{"f":{"id":"ID!","processedRowCount":"Int","rowCount":"RowCount","status":"ResourceOperationStatus!"},"t":["Node","ResourceOperation"]}}, +"AdditionalFee":{"o":{"f":{"id":"ID!","name":"String!","price":"MoneyBag!","taxLines":"[TaxLine!]!"},"t":["Node"]}}, +"AdditionalFeeSale":{"o":{"f":{"actionType":"SaleActionType!","additionalFee":"SaleAdditionalFee!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"AdjustmentSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"AdjustmentsSortKeys":{"e":["ID","TIME"]}, +"AllDiscountItems":{"o":{"f":{"allItems":"Boolean!"}}}, +"AnalyticsAnnotation":{"o":{"f":{"createdAt":"DateTime","createdByApp":"App","description":"String","endedAt":"DateTime","id":"ID!","source":"AnalyticsAnnotationSource!","startedAt":"DateTime!","title":"String","type":"String!","updatedAt":"DateTime"},"t":["Node"]}}, +"AnalyticsAnnotationConnection":{"o":{"f":{"edges":"[AnalyticsAnnotationEdge!]!","nodes":"[AnalyticsAnnotation!]!","pageInfo":"PageInfo!"}}}, +"AnalyticsAnnotationCreateInput":{"i":{"description":"String","endedAt":"DateTime","startedAt":"DateTime!","title":"String!","type":"String!"}}, +"AnalyticsAnnotationCreatePayload":{"o":{"f":{"analyticsAnnotation":"AnalyticsAnnotation","userErrors":"[AnalyticsAnnotationCreateUserError!]!"}}}, +"AnalyticsAnnotationCreateUserError":{"o":{"f":{"code":"AnalyticsAnnotationCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsAnnotationCreateUserErrorCode":{"e":["LIMIT_REACHED","SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID"]}, +"AnalyticsAnnotationDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[AnalyticsAnnotationDeleteUserError!]!"}}}, +"AnalyticsAnnotationDeleteUserError":{"o":{"f":{"code":"AnalyticsAnnotationDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsAnnotationDeleteUserErrorCode":{"e":["NOT_FOUND","SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID"]}, +"AnalyticsAnnotationEdge":{"o":{"f":{"cursor":"String!","node":"AnalyticsAnnotation!"}}}, +"AnalyticsAnnotationSortKeys":{"e":["CREATED_AT","ENDED_AT","ID","STARTED_AT","UPDATED_AT"]}, +"AnalyticsAnnotationSource":{"e":["SHOPIFY","STAFF","APP"]}, +"AnalyticsAnnotationUpdateInput":{"i":{"description":"String","endedAt":"DateTime","startedAt":"DateTime","title":"String","type":"String"}}, +"AnalyticsAnnotationUpdatePayload":{"o":{"f":{"analyticsAnnotation":"AnalyticsAnnotation","userErrors":"[AnalyticsAnnotationUpdateUserError!]!"}}}, +"AnalyticsAnnotationUpdateUserError":{"o":{"f":{"code":"AnalyticsAnnotationUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsAnnotationUpdateUserErrorCode":{"e":["NOT_FOUND","SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID"]}, +"AnalyticsTarget":{"o":{"f":{"createdAt":"DateTime!","currencyCode":"CurrencyCode!","endDate":"Date!","expectedValue":"Decimal!","filters":"String","id":"ID!","metric":"String!","name":"String!","presentmentExpectedValue":["MoneyV2",{"currencyCode":"CurrencyCode!"}],"shopifyqlQuery":"String","startDate":"Date!","updatedAt":"DateTime!"},"t":["Node"]}}, +"AnalyticsTargetConnection":{"o":{"f":{"edges":"[AnalyticsTargetEdge!]!","nodes":"[AnalyticsTarget!]!","pageInfo":"PageInfo!"}}}, +"AnalyticsTargetCreateInput":{"i":{"endDate":"Date!","expectedValue":"Decimal!","filters":"String","metric":"String!","name":"String!","startDate":"Date!"}}, +"AnalyticsTargetCreatePayload":{"o":{"f":{"analyticsTarget":"AnalyticsTarget","userErrors":"[AnalyticsTargetCreateUserError!]!"}}}, +"AnalyticsTargetCreateUserError":{"o":{"f":{"code":"AnalyticsTargetCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsTargetCreateUserErrorCode":{"e":["SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID_METRIC","INVALID","TAKEN"]}, +"AnalyticsTargetEdge":{"o":{"f":{"cursor":"String!","node":"AnalyticsTarget!"}}}, +"AnalyticsTargetSortKeys":{"e":["CREATED_AT","END_DATE","EXPECTED_VALUE","ID","METRIC","NAME","START_DATE"]}, +"AnalyticsTargetUpdateInput":{"i":{"endDate":"Date","expectedValue":"Decimal","filters":"String","metric":"String","name":"String","startDate":"Date"}}, +"AnalyticsTargetUpdatePayload":{"o":{"f":{"analyticsTarget":"AnalyticsTarget","userErrors":"[AnalyticsTargetUpdateUserError!]!"}}}, +"AnalyticsTargetUpdateUserError":{"o":{"f":{"code":"AnalyticsTargetUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsTargetUpdateUserErrorCode":{"e":["NOT_FOUND","SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID_METRIC","INVALID","TAKEN"]}, +"AnalyticsTargetsDeletePayload":{"o":{"f":{"deletedIds":"[ID!]","userErrors":"[AnalyticsTargetsDeleteUserError!]!"}}}, +"AnalyticsTargetsDeleteUserError":{"o":{"f":{"code":"AnalyticsTargetsDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsTargetsDeleteUserErrorCode":{"e":["NOT_FOUND","SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID"]}, +"AndroidApplication":{"o":{"f":{"appLinksEnabled":"Boolean!","applicationId":"String","id":"ID!","sha256CertFingerprints":"[String!]!"}}}, +"ApiVersion":{"o":{"f":{"displayName":"String!","handle":"String!","supported":"Boolean!"}}}, +"App":{"o":{"f":{"apiKey":"String!","appStoreAppUrl":"URL","appStoreDeveloperUrl":"URL","availableAccessScopes":"[AccessScope!]!","banner":"Image!","channels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"description":"String","developerName":"String","developerType":"AppDeveloperType!","developerUrl":"URL!","embedded":"Boolean!","failedRequirements":"[FailedRequirement!]!","features":"[String!]!","feedback":"AppFeedback","handle":"String","icon":"Image!","id":"ID!","installUrl":"URL","installation":"AppInstallation","isPostPurchaseAppInUse":"Boolean!","launchUrl":"URL!","navigationItems":"[NavigationItem!]!","optionalAccessScopes":"[AccessScope!]!","previouslyInstalled":"Boolean!","pricingDetails":"String","pricingDetailsSummary":"String!","privacyPolicyUrl":"URL","publicCategory":"AppPublicCategory!","published":"Boolean!","requestedAccessScopes":"[AccessScope!]!","screenshots":"[Image!]!","shopifyDeveloped":"Boolean!","title":"String!","uninstallMessage":"String!","uninstallUrl":"URL","webhookApiVersion":"String!"},"t":["Node"],"d":{"developerUrl":"Use `appStoreDeveloperUrl` instead.","launchUrl":"Use AppInstallation.launchUrl instead","navigationItems":"Use AppInstallation.navigationItems instead","uninstallUrl":"Use AppInstallation.uninstallUrl instead"}}}, +"AppCatalog":{"o":{"f":{"apps":["AppConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"channels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"id":"ID!","operations":"[ResourceOperation!]!","priceList":"PriceList","publication":"Publication","status":"CatalogStatus!","title":"String!"},"t":["Catalog","Node"]}}, +"AppConnection":{"o":{"f":{"edges":"[AppEdge!]!","nodes":"[App!]!","pageInfo":"PageInfo!"}}}, +"AppCredit":{"o":{"f":{"amount":"MoneyV2!","createdAt":"DateTime!","description":"String!","id":"ID!","test":"Boolean!"},"t":["Node"]}}, +"AppCreditConnection":{"o":{"f":{"edges":"[AppCreditEdge!]!","nodes":"[AppCredit!]!","pageInfo":"PageInfo!"}}}, +"AppCreditEdge":{"o":{"f":{"cursor":"String!","node":"AppCredit!"}}}, +"AppDeveloperType":{"e":["SHOPIFY","PARTNER","MERCHANT","UNKNOWN"]}, +"AppDiscountType":{"o":{"f":{"app":"App!","appBridge":"FunctionsAppBridge!","appKey":"String!","description":"String","discountClass":"DiscountClass!","discountClasses":"[DiscountClass!]!","functionId":"String!","targetType":"DiscountApplicationTargetType!","title":"String!"},"d":{"discountClass":"Use `discountClasses` instead.","targetType":"Use `discountClasses` instead."}}}, +"AppDiscountTypeConnection":{"o":{"f":{"edges":"[AppDiscountTypeEdge!]!","nodes":"[AppDiscountType!]!","pageInfo":"PageInfo!"}}}, +"AppDiscountTypeEdge":{"o":{"f":{"cursor":"String!","node":"AppDiscountType!"}}}, +"AppEdge":{"o":{"f":{"cursor":"String!","node":"App!"}}}, +"AppFeedback":{"o":{"f":{"app":"App!","channel":"Channel","feedbackGeneratedAt":"DateTime!","link":"Link","messages":"[UserError!]!","state":"ResourceFeedbackState!"}}}, +"AppInstallation":{"o":{"f":{"accessScopes":"[AccessScope!]!","activeSubscriptions":"[AppSubscription!]!","allSubscriptions":["AppSubscriptionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AppSubscriptionSortKeys="}],"app":"App!","channel":"Channel","credits":["AppCreditConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AppTransactionSortKeys="}],"id":"ID!","launchUrl":"URL!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"oneTimePurchases":["AppPurchaseOneTimeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AppTransactionSortKeys="}],"publication":"Publication","revenueAttributionRecords":["AppRevenueAttributionRecordConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AppRevenueAttributionRecordSortKeys="}],"subscriptions":"[AppSubscription!]!","uninstallUrl":"URL"},"t":["HasMetafields","Node"],"d":{"channel":"Use the root-level `channels` query instead.","publication":"Use the root-level `publications` query instead.","subscriptions":"Use `activeSubscriptions` instead."}}}, +"AppInstallationCategory":{"e":["CHANNEL","POS_EMBEDDED"]}, +"AppInstallationConnection":{"o":{"f":{"edges":"[AppInstallationEdge!]!","nodes":"[AppInstallation!]!","pageInfo":"PageInfo!"}}}, +"AppInstallationEdge":{"o":{"f":{"cursor":"String!","node":"AppInstallation!"}}}, +"AppInstallationPrivacy":{"e":["PUBLIC","PRIVATE"]}, +"AppInstallationSortKeys":{"e":["APP_TITLE","ID","INSTALLED_AT"]}, +"AppPlanInput":{"i":{"appRecurringPricingDetails":"AppRecurringPricingInput","appUsagePricingDetails":"AppUsagePricingInput"}}, +"AppPlanV2":{"o":{"f":{"pricingDetails":"AppPricingDetails!"}}}, +"AppPricingDetails":{"u":["AppRecurringPricing","AppUsagePricing"]}, +"AppPricingInterval":{"e":["ANNUAL","EVERY_30_DAYS"]}, +"AppPublicCategory":{"e":["PRIVATE","PUBLIC","CUSTOM","OTHER"]}, +"AppPurchase":{"n":{"f":{"createdAt":"DateTime!","name":"String!","price":"MoneyV2!","status":"AppPurchaseStatus!","test":"Boolean!"},"t":["AppPurchaseOneTime"]}}, +"AppPurchaseOneTime":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","name":"String!","price":"MoneyV2!","status":"AppPurchaseStatus!","test":"Boolean!"},"t":["AppPurchase","Node"]}}, +"AppPurchaseOneTimeConnection":{"o":{"f":{"edges":"[AppPurchaseOneTimeEdge!]!","nodes":"[AppPurchaseOneTime!]!","pageInfo":"PageInfo!"}}}, +"AppPurchaseOneTimeCreatePayload":{"o":{"f":{"appPurchaseOneTime":"AppPurchaseOneTime","confirmationUrl":"URL","userErrors":"[UserError!]!"}}}, +"AppPurchaseOneTimeEdge":{"o":{"f":{"cursor":"String!","node":"AppPurchaseOneTime!"}}}, +"AppPurchaseStatus":{"e":{"v":["ACCEPTED","ACTIVE","DECLINED","EXPIRED","PENDING"],"d":{"ACCEPTED":"When a merchant accepts an app purchase, the status immediately changes from `pending` to `active`."}}}, +"AppRecurringPricing":{"o":{"f":{"discount":"AppSubscriptionDiscount","interval":"AppPricingInterval!","planHandle":"String","price":"MoneyV2!"}}}, +"AppRecurringPricingInput":{"i":{"discount":"AppSubscriptionDiscountInput","interval":"AppPricingInterval=","price":"MoneyInput!"}}, +"AppRevenueAttributionRecord":{"o":{"f":{"amount":"MoneyV2!","capturedAt":"DateTime!","createdAt":"DateTime!","id":"ID!","idempotencyKey":"String!","test":"Boolean!","type":"AppRevenueAttributionType!"},"t":["Node"]}}, +"AppRevenueAttributionRecordConnection":{"o":{"f":{"edges":"[AppRevenueAttributionRecordEdge!]!","nodes":"[AppRevenueAttributionRecord!]!","pageInfo":"PageInfo!"}}}, +"AppRevenueAttributionRecordEdge":{"o":{"f":{"cursor":"String!","node":"AppRevenueAttributionRecord!"}}}, +"AppRevenueAttributionRecordSortKeys":{"e":["CREATED_AT","ID"]}, +"AppRevenueAttributionType":{"e":["APPLICATION_PURCHASE","APPLICATION_SUBSCRIPTION","APPLICATION_USAGE","OTHER"]}, +"AppRevokeAccessScopesAppRevokeScopeError":{"o":{"f":{"code":"AppRevokeAccessScopesAppRevokeScopeErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AppRevokeAccessScopesAppRevokeScopeErrorCode":{"e":["MISSING_SOURCE_APP","APPLICATION_CANNOT_BE_FOUND","UNKNOWN_SCOPES","CANNOT_REVOKE_REQUIRED_SCOPES","CANNOT_REVOKE_IMPLIED_SCOPES","CANNOT_REVOKE_UNDECLARED_SCOPES","APP_NOT_INSTALLED"]}, +"AppRevokeAccessScopesPayload":{"o":{"f":{"revoked":"[AccessScope!]","userErrors":"[AppRevokeAccessScopesAppRevokeScopeError!]!"}}}, +"AppSubscription":{"o":{"f":{"createdAt":"DateTime!","currentPeriodEnd":"DateTime","id":"ID!","lineItems":"[AppSubscriptionLineItem!]!","name":"String!","returnUrl":"URL!","status":"AppSubscriptionStatus!","test":"Boolean!","trialDays":"Int!"},"t":["Node"]}}, +"AppSubscriptionCancelPayload":{"o":{"f":{"appSubscription":"AppSubscription","userErrors":"[UserError!]!"}}}, +"AppSubscriptionConnection":{"o":{"f":{"edges":"[AppSubscriptionEdge!]!","nodes":"[AppSubscription!]!","pageInfo":"PageInfo!"}}}, +"AppSubscriptionCreatePayload":{"o":{"f":{"appSubscription":"AppSubscription","confirmationUrl":"URL","userErrors":"[UserError!]!"}}}, +"AppSubscriptionDiscount":{"o":{"f":{"durationLimitInIntervals":"Int","priceAfterDiscount":"MoneyV2!","remainingDurationInIntervals":"Int","value":"AppSubscriptionDiscountValue!"}}}, +"AppSubscriptionDiscountAmount":{"o":{"f":{"amount":"MoneyV2!"}}}, +"AppSubscriptionDiscountInput":{"i":{"durationLimitInIntervals":"Int","value":"AppSubscriptionDiscountValueInput"}}, +"AppSubscriptionDiscountPercentage":{"o":{"f":{"percentage":"Float!"}}}, +"AppSubscriptionDiscountValue":{"u":["AppSubscriptionDiscountAmount","AppSubscriptionDiscountPercentage"]}, +"AppSubscriptionDiscountValueInput":{"i":{"amount":"Decimal","percentage":"Float"}}, +"AppSubscriptionEdge":{"o":{"f":{"cursor":"String!","node":"AppSubscription!"}}}, +"AppSubscriptionLineItem":{"o":{"f":{"id":"ID!","plan":"AppPlanV2!","usageRecords":["AppUsageRecordConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AppUsageRecordSortKeys="}]}}}, +"AppSubscriptionLineItemInput":{"i":{"plan":"AppPlanInput!"}}, +"AppSubscriptionLineItemUpdatePayload":{"o":{"f":{"appSubscription":"AppSubscription","confirmationUrl":"URL","userErrors":"[UserError!]!"}}}, +"AppSubscriptionReplacementBehavior":{"e":["APPLY_IMMEDIATELY","APPLY_ON_NEXT_BILLING_CYCLE","STANDARD"]}, +"AppSubscriptionSortKeys":{"e":["CREATED_AT","ID"]}, +"AppSubscriptionStatus":{"e":{"v":["PENDING","ACCEPTED","ACTIVE","DECLINED","EXPIRED","FROZEN","CANCELLED"],"d":{"ACCEPTED":"When a merchant approves an app subscription, the status immediately transitions from `pending` to `active`."}}}, +"AppSubscriptionTrialExtendPayload":{"o":{"f":{"appSubscription":"AppSubscription","userErrors":"[AppSubscriptionTrialExtendUserError!]!"}}}, +"AppSubscriptionTrialExtendUserError":{"o":{"f":{"code":"AppSubscriptionTrialExtendUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AppSubscriptionTrialExtendUserErrorCode":{"e":["SUBSCRIPTION_NOT_FOUND","TRIAL_NOT_ACTIVE","SUBSCRIPTION_NOT_ACTIVE"]}, +"AppTransactionSortKeys":{"e":["CREATED_AT","ID"]}, +"AppUninstallAppUninstallError":{"o":{"f":{"code":"AppUninstallAppUninstallErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AppUninstallAppUninstallErrorCode":{"e":["APP_NOT_FOUND","APP_NOT_INSTALLED","USER_PERMISSIONS_INSUFFICIENT","APP_UNINSTALL_ERROR"]}, +"AppUninstallPayload":{"o":{"f":{"app":"App","userErrors":"[AppUninstallAppUninstallError!]!"}}}, +"AppUsagePricing":{"o":{"f":{"balanceUsed":"MoneyV2!","cappedAmount":"MoneyV2!","interval":"AppPricingInterval!","terms":"String!"}}}, +"AppUsagePricingInput":{"i":{"cappedAmount":"MoneyInput!","terms":"String!"}}, +"AppUsageRecord":{"o":{"f":{"createdAt":"DateTime!","description":"String!","id":"ID!","idempotencyKey":"String","price":"MoneyV2!","subscriptionLineItem":"AppSubscriptionLineItem!"},"t":["Node"]}}, +"AppUsageRecordConnection":{"o":{"f":{"edges":"[AppUsageRecordEdge!]!","nodes":"[AppUsageRecord!]!","pageInfo":"PageInfo!"}}}, +"AppUsageRecordCreatePayload":{"o":{"f":{"appUsageRecord":"AppUsageRecord","userErrors":"[UserError!]!"}}}, +"AppUsageRecordEdge":{"o":{"f":{"cursor":"String!","node":"AppUsageRecord!"}}}, +"AppUsageRecordSortKeys":{"e":["CREATED_AT","ID"]}, +"AppleApplication":{"o":{"f":{"appClipApplicationId":"String","appClipsEnabled":"Boolean!","appId":"String","id":"ID!","sharedWebCredentialsEnabled":"Boolean!","universalLinksEnabled":"Boolean!"}}}, +"Article":{"o":{"f":{"author":"ArticleAuthor","blog":"Blog!","body":"HTML!","comments":["CommentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"commentsCount":["Count",{"limit":"Int=","query":"String"}],"createdAt":"DateTime!","defaultCursor":"String!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"handle":"String!","id":"ID!","image":"Image","isPublished":"Boolean!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"publishedAt":"DateTime","summary":"HTML","tags":"[String!]!","templateSuffix":"String","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"updatedAt":"DateTime"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Navigable","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"ArticleAuthor":{"o":{"f":{"name":"String!"}}}, +"ArticleAuthorConnection":{"o":{"f":{"edges":"[ArticleAuthorEdge!]!","nodes":"[ArticleAuthor!]!","pageInfo":"PageInfo!"}}}, +"ArticleAuthorEdge":{"o":{"f":{"cursor":"String!","node":"ArticleAuthor!"}}}, +"ArticleBlogInput":{"i":{"title":"String!"}}, +"ArticleConnection":{"o":{"f":{"edges":"[ArticleEdge!]!","nodes":"[Article!]!","pageInfo":"PageInfo!"}}}, +"ArticleCreateInput":{"i":{"author":"AuthorInput!","blogId":"ID","body":"HTML","handle":"String","image":"ArticleImageInput","isPublished":"Boolean","metafields":"[MetafieldInput!]","publishDate":"DateTime","summary":"HTML","tags":"[String!]","templateSuffix":"String","title":"String!"}}, +"ArticleCreatePayload":{"o":{"f":{"article":"Article","userErrors":"[ArticleCreateUserError!]!"}}}, +"ArticleCreateUserError":{"o":{"f":{"code":"ArticleCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ArticleCreateUserErrorCode":{"e":["AMBIGUOUS_AUTHOR","AMBIGUOUS_BLOG","AUTHOR_FIELD_REQUIRED","AUTHOR_MUST_EXIST","INVALID_PUBLISH_DATE","BLOG_REFERENCE_REQUIRED","UPLOAD_FAILED","BLANK","NOT_FOUND","TOO_LONG","TOO_SHORT","TAKEN","INVALID","INVALID_VALUE","INVALID_TYPE"]}, +"ArticleDeletePayload":{"o":{"f":{"deletedArticleId":"ID","userErrors":"[ArticleDeleteUserError!]!"}}}, +"ArticleDeleteUserError":{"o":{"f":{"code":"ArticleDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ArticleDeleteUserErrorCode":{"e":["NOT_FOUND"]}, +"ArticleEdge":{"o":{"f":{"cursor":"String!","node":"Article!"}}}, +"ArticleImageInput":{"i":{"altText":"String","url":"String"}}, +"ArticleSortKeys":{"e":["AUTHOR","BLOG_TITLE","ID","PUBLISHED_AT","TITLE","UPDATED_AT"]}, +"ArticleTagSort":{"e":["ALPHABETICAL","POPULAR"]}, +"ArticleUpdateInput":{"i":{"author":"AuthorInput","blogId":"ID","body":"HTML","handle":"String","image":"ArticleImageInput","isPublished":"Boolean","metafields":"[MetafieldInput!]","publishDate":"DateTime","redirectNewHandle":"Boolean=","summary":"HTML","tags":"[String!]","templateSuffix":"String","title":"String"}}, +"ArticleUpdatePayload":{"o":{"f":{"article":"Article","userErrors":"[ArticleUpdateUserError!]!"}}}, +"ArticleUpdateUserError":{"o":{"f":{"code":"ArticleUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ArticleUpdateUserErrorCode":{"e":["AMBIGUOUS_AUTHOR","AMBIGUOUS_BLOG","AUTHOR_MUST_EXIST","INVALID_PUBLISH_DATE","UPLOAD_FAILED","BLANK","NOT_FOUND","TOO_LONG","TAKEN","INVALID","INVALID_VALUE","INVALID_TYPE"]}, +"Attribute":{"o":{"f":{"key":"String!","value":"String"}}}, +"AttributeInput":{"i":{"key":"String!","value":"String!"}}, +"Audience":{"e":["CUSTOMERVIEW","MERCHANTVIEW"]}, +"AuditTrailAdjustment":{"o":{"f":{"label":"String!","price":"MoneyV2!","type":"AuditTrailAdjustmentType!","value":"Decimal!"}}}, +"AuditTrailAdjustmentType":{"e":["ADDITION","MULTIPLICATION","REPLACEMENT"]}, +"AuthorInput":{"i":{"name":"String","userId":"ID"}}, +"AutomaticDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","index":"Int!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","title":"String!","value":"PricingValue!"},"t":["DiscountApplication"]}}, +"AutomaticDiscountSortKeys":{"e":["CREATED_AT","ID"]}, +"AvailableChannelDefinitionsByChannel":{"o":{"f":{"channelDefinitions":"[ChannelDefinition!]!","channelName":"String!"},"d":{"channelDefinitions":"Use [`QueryRoot.orderAttributionDefinitions`](https://shopify.dev/docs/api/admin-graphql/latest/queries/orderAttributionDefinitions) and select `id`, `handle`, `displayName`, and `icon` instead.","channelName":"Use [`OrderAttributionDefinition.displayName`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.displayName) instead."}}}, +"B2BType":{"o":{"f":{"enabled":"Boolean!"}}}, +"BackupRegionUpdateInput":{"i":{"countryCode":"CountryCode!"}}, +"BackupRegionUpdatePayload":{"o":{"f":{"backupRegion":"MarketRegion","userErrors":"[MarketUserError!]!"}}}, +"BadgeType":{"e":["DEFAULT","SUCCESS","ATTENTION","WARNING","INFO","CRITICAL"]}, +"BalanceTransactionSortKeys":{"e":["AMOUNT","FEE","ID","NET","ORDER_NAME","PAYMENT_METHOD_NAME","PAYOUT_DATE","PAYOUT_STATUS","PROCESSED_AT","TRANSACTION_TYPE"]}, +"BankAccount":{"o":{"f":{"accountHolderType":"BankAccountHolderType!","accountType":"BankAccountType!","bankName":"String!","billingAddress":"CustomerPaymentInstrumentBillingAddress","lastDigits":"String!"}}}, +"BankAccountHolderType":{"e":["COMPANY","INDIVIDUAL"]}, +"BankAccountType":{"e":["CHECKING","SAVINGS"]}, +"BankingFinanceAppAccess":{"e":["READ_ACCESS","MOVE_MONEY","MONEY_MOVEMENT_RESTRICTED","MONEY_MOVEMENT_BLOCKED_MFA"]}, +"BarcodeInput":{"i":{"type":"BarcodeType","value":"String!"}}, +"BarcodeType":{"e":["UPC","EAN","ISBN","GTIN","ASIN","NS_PID"]}, +"BasePaymentDetails":{"n":{"f":{"paymentMethodName":"String"},"t":["CardPaymentDetails","LocalPaymentMethodsPaymentDetails","PaypalWalletPaymentDetails","ShopPayInstallmentsPaymentDetails"]}}, +"BasicEvent":{"o":{"f":{"action":"String!","additionalContent":"JSON","additionalData":"JSON","appTitle":"String","arguments":"JSON","attributeToApp":"Boolean!","attributeToUser":"Boolean!","author":"String","createdAt":"DateTime!","criticalAlert":"Boolean!","hasAdditionalContent":"Boolean!","id":"ID!","message":"FormattedString!","secondaryMessage":"FormattedString","subject":"HasEvents","subjectId":"ID!","subjectType":"EventSubjectType!"},"t":["Event","Node"]}}, +"BigInt":"s", +"BillingAttemptUserError":{"o":{"f":{"code":"BillingAttemptUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BillingAttemptUserErrorCode":{"e":["INVALID","BLANK","CONTRACT_NOT_FOUND","ORIGIN_TIME_BEFORE_CONTRACT_CREATION","UPCOMING_CYCLE_LIMIT_EXCEEDED","CYCLE_INDEX_OUT_OF_RANGE","CYCLE_START_DATE_OUT_OF_RANGE","ORIGIN_TIME_OUT_OF_RANGE","BILLING_CYCLE_CHARGE_BEFORE_EXPECTED_DATE","BILLING_CYCLE_SKIPPED","CONTRACT_UNDER_REVIEW","CONTRACT_TERMINATED","CONTRACT_PAUSED","THROTTLED","PROCESSING_FAILED"]}, +"Blog":{"o":{"f":{"articles":["ArticleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"articlesCount":["Count",{"limit":"Int="}],"commentPolicy":"CommentPolicy!","createdAt":"DateTime!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"feed":"BlogFeed","handle":"String!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"tags":"[String!]!","templateSuffix":"String","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"updatedAt":"DateTime"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"BlogConnection":{"o":{"f":{"edges":"[BlogEdge!]!","nodes":"[Blog!]!","pageInfo":"PageInfo!"}}}, +"BlogCreateInput":{"i":{"commentPolicy":"CommentPolicy","handle":"String","metafields":"[MetafieldInput!]","templateSuffix":"String","title":"String!"}}, +"BlogCreatePayload":{"o":{"f":{"blog":"Blog","userErrors":"[BlogCreateUserError!]!"}}}, +"BlogCreateUserError":{"o":{"f":{"code":"BlogCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BlogCreateUserErrorCode":{"e":["BLANK","INVALID","TOO_LONG","INCLUSION","INVALID_VALUE","INVALID_TYPE"]}, +"BlogDeletePayload":{"o":{"f":{"deletedBlogId":"ID","userErrors":"[BlogDeleteUserError!]!"}}}, +"BlogDeleteUserError":{"o":{"f":{"code":"BlogDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BlogDeleteUserErrorCode":{"e":["NOT_FOUND"]}, +"BlogEdge":{"o":{"f":{"cursor":"String!","node":"Blog!"}}}, +"BlogFeed":{"o":{"f":{"location":"URL!","path":"String!"}}}, +"BlogSortKeys":{"e":["HANDLE","ID","TITLE"]}, +"BlogUpdateInput":{"i":{"commentPolicy":"CommentPolicy","handle":"String","metafields":"[MetafieldInput!]","redirectArticles":"Boolean=","redirectNewHandle":"Boolean=","templateSuffix":"String","title":"String"}}, +"BlogUpdatePayload":{"o":{"f":{"blog":"Blog","userErrors":"[BlogUpdateUserError!]!"}}}, +"BlogUpdateUserError":{"o":{"f":{"code":"BlogUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BlogUpdateUserErrorCode":{"e":["NOT_FOUND","INVALID","BLANK","TOO_LONG","INCLUSION"]}, +"Boolean":"s", +"BulkMutationErrorCode":{"e":["OPERATION_IN_PROGRESS","INVALID_MUTATION","INVALID_STAGED_UPLOAD_FILE","NO_SUCH_FILE","INTERNAL_FILE_SERVER_ERROR","LIMIT_REACHED"]}, +"BulkMutationUserError":{"o":{"f":{"code":"BulkMutationErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BulkOperation":{"o":{"f":{"completedAt":"DateTime","createdAt":"DateTime!","errorCode":"BulkOperationErrorCode","fileSize":"UnsignedInt64","id":"ID!","objectCount":"UnsignedInt64!","partialDataUrl":"URL","query":"String!","rootObjectCount":"UnsignedInt64!","status":"BulkOperationStatus!","type":"BulkOperationType!","url":"URL"},"t":["Node"]}}, +"BulkOperationCancelPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[UserError!]!"}}}, +"BulkOperationConnection":{"o":{"f":{"edges":"[BulkOperationEdge!]!","nodes":"[BulkOperation!]!","pageInfo":"PageInfo!"}}}, +"BulkOperationEdge":{"o":{"f":{"cursor":"String!","node":"BulkOperation!"}}}, +"BulkOperationErrorCode":{"e":["ACCESS_DENIED","INTERNAL_SERVER_ERROR","TIMEOUT"]}, +"BulkOperationRunMutationPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[BulkMutationUserError!]!"}}}, +"BulkOperationRunQueryPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[BulkOperationUserError!]!"}}}, +"BulkOperationStatus":{"e":["CANCELED","CANCELING","COMPLETED","CREATED","EXPIRED","FAILED","RUNNING"]}, +"BulkOperationType":{"e":["QUERY","MUTATION"]}, +"BulkOperationUserError":{"o":{"f":{"code":"BulkOperationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BulkOperationUserErrorCode":{"e":["OPERATION_IN_PROGRESS","INVALID","LIMIT_REACHED"]}, +"BulkOperationsSortKeys":{"e":["COMPLETED_AT","CREATED_AT"]}, +"BulkProductResourceFeedbackCreatePayload":{"o":{"f":{"feedback":"[ProductResourceFeedback!]","userErrors":"[BulkProductResourceFeedbackCreateUserError!]!"}}}, +"BulkProductResourceFeedbackCreateUserError":{"o":{"f":{"code":"BulkProductResourceFeedbackCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BulkProductResourceFeedbackCreateUserErrorCode":{"e":["MAXIMUM_FEEDBACK_LIMIT_EXCEEDED","OUTDATED_FEEDBACK","PRODUCT_NOT_FOUND","NOT_FOUND","INVALID","BLANK","PRESENT","LESS_THAN_OR_EQUAL_TO"]}, +"BundlesDraftOrderBundleLineItemComponentInput":{"i":{"quantity":"Int!","uuid":"String","variantId":"ID"}}, +"BundlesFeature":{"o":{"f":{"eligibleForBundles":"Boolean!","ineligibilityReason":"String","sellsBundles":"Boolean!"}}}, +"BusinessCustomerErrorCode":{"e":["INTERNAL_ERROR","RESOURCE_NOT_FOUND","FAILED_TO_DELETE","REQUIRED","NO_INPUT","INVALID_INPUT","UNEXPECTED_TYPE","TOO_LONG","LIMIT_REACHED","INVALID","BLANK","TAKEN"]}, +"BusinessCustomerUserError":{"o":{"f":{"code":"BusinessCustomerErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BusinessEntity":{"o":{"f":{"address":"BusinessEntityAddress!","archived":"Boolean!","companyName":"String","displayName":"String!","id":"ID!","legalEntityId":"BigInt","primary":"Boolean!","shopifyPaymentsAccount":"ShopifyPaymentsAccount"},"t":["Node"]}}, +"BusinessEntityAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","countryCode":"CountryCode!","province":"String","zip":"String"}}}, +"BuyerExperienceConfiguration":{"o":{"f":{"checkoutToDraft":"Boolean!","deposit":"DepositConfiguration","editableShippingAddress":"Boolean!","payNowOnly":"Boolean!","paymentTermsTemplate":"PaymentTermsTemplate"},"d":{"payNowOnly":"Please use `checkoutToDraft`(must be false) and `paymentTermsTemplate`(must be nil) to derive this instead."}}}, +"BuyerExperienceConfigurationInput":{"i":{"checkoutToDraft":"Boolean","deposit":"DepositInput","editableShippingAddress":"Boolean","paymentTermsTemplateId":"ID"}}, +"BuyerSignalInput":{"i":{"countryCode":"CountryCode!"}}, +"CalculateExchangeLineItemInput":{"i":{"appliedDiscount":"ExchangeLineItemAppliedDiscountInput","quantity":"Int!","variantId":"ID"}}, +"CalculateRequestedOrderEditInput":{"i":{"lineItems":"CalculateRequestedOrderEditLineItemsInput!","orderId":"ID!"}}, +"CalculateRequestedOrderEditLineItemRemovalInput":{"i":{"lineItemId":"ID!","quantity":"Int!"}}, +"CalculateRequestedOrderEditLineItemsInput":{"i":{"removals":"[CalculateRequestedOrderEditLineItemRemovalInput!]!"}}, +"CalculateReturnInput":{"i":{"exchangeLineItems":"[CalculateExchangeLineItemInput!]=","orderId":"ID!","returnLineItems":"[CalculateReturnLineItemInput!]=","returnShippingFee":"ReturnShippingFeeInput"}}, +"CalculateReturnLineItemInput":{"i":{"fulfillmentLineItemId":"ID!","quantity":"Int!","restockingFee":"RestockingFeeInput"}}, +"CalculatedAutomaticDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","appliedTo":"DiscountApplicationLevel!","description":"String","id":"ID!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["CalculatedDiscountApplication"]}}, +"CalculatedDiscountAllocation":{"o":{"f":{"allocatedAmountSet":"MoneyBag!","discountApplication":"CalculatedDiscountApplication!"}}}, +"CalculatedDiscountApplication":{"n":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","appliedTo":"DiscountApplicationLevel!","description":"String","id":"ID!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["CalculatedAutomaticDiscountApplication","CalculatedDiscountCodeApplication","CalculatedManualDiscountApplication","CalculatedScriptDiscountApplication"]}}, +"CalculatedDiscountApplicationConnection":{"o":{"f":{"edges":"[CalculatedDiscountApplicationEdge!]!","nodes":"[CalculatedDiscountApplication!]!","pageInfo":"PageInfo!"}}}, +"CalculatedDiscountApplicationEdge":{"o":{"f":{"cursor":"String!","node":"CalculatedDiscountApplication!"}}}, +"CalculatedDiscountCodeApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","appliedTo":"DiscountApplicationLevel!","code":"String!","description":"String","id":"ID!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["CalculatedDiscountApplication"]}}, +"CalculatedDraftOrder":{"o":{"f":{"acceptAutomaticDiscounts":"Boolean","alerts":"[ResourceAlert!]!","allVariantPricesOverridden":"Boolean!","amountDueLaterSet":"MoneyBag!","amountDueNowSet":"MoneyBag!","anyVariantPricesOverridden":"Boolean!","appliedDiscount":"DraftOrderAppliedDiscount","availableShippingRates":"[ShippingRate!]!","billingAddressMatchesShippingAddress":"Boolean!","currencyCode":"CurrencyCode!","customer":"Customer","deposit":"DepositConfiguration","discountCodes":"[String!]!","lineItems":"[CalculatedDraftOrderLineItem!]!","lineItemsSubtotalPrice":"MoneyBag!","marketName":"String!","marketRegionCountryCode":"CountryCode!","phone":"String","platformDiscounts":"[DraftOrderPlatformDiscount!]!","presentmentCurrencyCode":"CurrencyCode!","purchasingEntity":"PurchasingEntity","shippingLine":"ShippingLine","subtotalPrice":"Money!","subtotalPriceSet":"MoneyBag!","taxLines":"[TaxLine!]!","taxesIncluded":"Boolean!","totalDiscountsSet":"MoneyBag!","totalLineItemsPriceSet":"MoneyBag!","totalPrice":"Money!","totalPriceSet":"MoneyBag!","totalQuantityOfLineItems":"Int!","totalShippingPrice":"Money!","totalShippingPriceSet":"MoneyBag!","totalTax":"Money!","totalTaxSet":"MoneyBag!","transformerFingerprint":"String","warnings":"[DraftOrderWarning!]!"},"d":{"marketName":"This field is now incompatible with Markets.","marketRegionCountryCode":"This field is now incompatible with Markets.","subtotalPrice":"Use `subtotalPriceSet` instead.","totalPrice":"Use `totalPriceSet` instead.","totalShippingPrice":"Use `totalShippingPriceSet` instead.","totalTax":"Use `totalTaxSet` instead."}}}, +"CalculatedDraftOrderLineItem":{"o":{"f":{"appliedDiscount":"DraftOrderAppliedDiscount","approximateDiscountedUnitPriceSet":"MoneyBag!","bundleComponents":"[CalculatedDraftOrderLineItem!]!","components":"[CalculatedDraftOrderLineItem!]!","custom":"Boolean!","customAttributes":"[Attribute!]!","customAttributesV2":"[TypedAttribute!]!","discountedTotal":"MoneyV2!","discountedTotalSet":"MoneyBag!","discountedUnitPrice":"MoneyV2!","discountedUnitPriceSet":"MoneyBag!","fulfillmentService":"FulfillmentService","image":"Image","isGiftCard":"Boolean!","name":"String!","originalTotal":"MoneyV2!","originalTotalSet":"MoneyBag!","originalUnitPrice":"MoneyV2!","originalUnitPriceSet":"MoneyBag!","originalUnitPriceWithCurrency":"MoneyV2","priceOverride":"MoneyV2","product":"Product","quantity":"Int!","requiresShipping":"Boolean!","sku":"String","taxable":"Boolean!","title":"String!","totalDiscount":"MoneyV2!","totalDiscountSet":"MoneyBag!","uuid":"String!","variant":"ProductVariant","variantTitle":"String","vendor":"String","weight":"Weight"},"d":{"bundleComponents":"Use `components` instead.","discountedUnitPrice":"Use `approximateDiscountedUnitPriceSet` instead.","discountedUnitPriceSet":"Use `approximateDiscountedUnitPriceSet` instead."}}}, +"CalculatedExchangeLineItem":{"o":{"f":{"calculatedDiscountAllocations":"[CalculatedDiscountAllocation!]!","discountedUnitPriceSet":"MoneyBag!","id":"ID","originalUnitPriceSet":"MoneyBag!","quantity":"Int!","subtotalSet":"MoneyBag!","totalTaxSet":"MoneyBag!","variant":"ProductVariant"}}}, +"CalculatedLineItem":{"o":{"f":{"calculatedDiscountAllocations":"[CalculatedDiscountAllocation!]!","customAttributes":"[Attribute!]!","discountAllocations":"[DiscountAllocation!]!","discountedUnitPriceSet":"MoneyBag!","editableQuantity":"Int!","editableQuantityBeforeChanges":"Int!","editableSubtotalSet":"MoneyBag!","hasStagedLineItemDiscount":"Boolean!","id":"ID!","image":"Image","originalUnitPriceSet":"MoneyBag!","quantity":"Int!","restockable":"Boolean!","restocking":"Boolean!","sku":"String","stagedChanges":"[OrderStagedChange!]!","title":"String!","uneditableSubtotalSet":"MoneyBag!","variant":"ProductVariant","variantTitle":"String"},"d":{"discountAllocations":"Use `calculatedDiscountAllocations` instead."}}}, +"CalculatedLineItemConnection":{"o":{"f":{"edges":"[CalculatedLineItemEdge!]!","nodes":"[CalculatedLineItem!]!","pageInfo":"PageInfo!"}}}, +"CalculatedLineItemEdge":{"o":{"f":{"cursor":"String!","node":"CalculatedLineItem!"}}}, +"CalculatedManualDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","appliedTo":"DiscountApplicationLevel!","description":"String","id":"ID!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["CalculatedDiscountApplication"]}}, +"CalculatedOrder":{"o":{"f":{"addedDiscountApplications":["CalculatedDiscountApplicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"addedLineItems":["CalculatedLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"cartDiscountAmountSet":"MoneyBag","committed":"Boolean!","id":"ID!","lineItems":["CalculatedLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"notificationPreviewHtml":"HTML","notificationPreviewTitle":"String!","originalOrder":"Order!","shippingLines":"[CalculatedShippingLine!]!","stagedChanges":["OrderStagedChangeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"subtotalLineItemsQuantity":"Int!","subtotalPriceSet":"MoneyBag","taxLines":"[TaxLine!]!","totalOutstandingSet":"MoneyBag!","totalPriceSet":"MoneyBag!"},"t":["Node"],"d":{"committed":"CalculatedOrder for committed order edits is being deprecated, and this field will also be removed in a future version. See [changelog](https://shopify.dev/changelog/deprecation-notice-calculatedorder-for-committed-order-edits) for more details."}}}, +"CalculatedRequestedOrderEdit":{"o":{"f":{"financialSummary":"RequestedOrderEditFinancialSummary!","lineItems":"CalculatedRequestedOrderEditLineItems!"}}}, +"CalculatedRequestedOrderEditLineItem":{"o":{"f":{"lineItem":"LineItem!","quantity":"Int!","subtotalSet":"MoneyBag!","totalTaxSet":"MoneyBag!"}}}, +"CalculatedRequestedOrderEditLineItemConnection":{"o":{"f":{"edges":"[CalculatedRequestedOrderEditLineItemEdge!]!","nodes":"[CalculatedRequestedOrderEditLineItem!]!","pageInfo":"PageInfo!"}}}, +"CalculatedRequestedOrderEditLineItemEdge":{"o":{"f":{"cursor":"String!","node":"CalculatedRequestedOrderEditLineItem!"}}}, +"CalculatedRequestedOrderEditLineItems":{"o":{"f":{"removals":["CalculatedRequestedOrderEditLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"CalculatedRestockingFee":{"o":{"f":{"amountSet":"MoneyBag!","id":"ID!","percentage":"Float!"},"t":["CalculatedReturnFee"]}}, +"CalculatedReturn":{"o":{"f":{"exchangeLineItems":"[CalculatedExchangeLineItem!]!","id":"ID!","returnLineItems":"[CalculatedReturnLineItem!]!","returnShippingFee":"CalculatedReturnShippingFee"}}}, +"CalculatedReturnFee":{"n":{"f":{"amountSet":"MoneyBag!","id":"ID!"},"t":["CalculatedRestockingFee","CalculatedReturnShippingFee"]}}, +"CalculatedReturnLineItem":{"o":{"f":{"fulfillmentLineItem":"FulfillmentLineItem!","id":"ID","quantity":"Int!","restockingFee":"CalculatedRestockingFee","subtotalBeforeOrderDiscountsSet":"MoneyBag!","subtotalSet":"MoneyBag!","totalTaxSet":"MoneyBag!"}}}, +"CalculatedReturnShippingFee":{"o":{"f":{"amountSet":"MoneyBag!","id":"ID!","taxAmountSet":"MoneyBag!"},"t":["CalculatedReturnFee"]}}, +"CalculatedScriptDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","appliedTo":"DiscountApplicationLevel!","description":"String","id":"ID!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["CalculatedDiscountApplication"]}}, +"CalculatedShippingLine":{"o":{"f":{"id":"ID","price":"MoneyBag!","stagedStatus":"CalculatedShippingLineStagedStatus!","title":"String!"}}}, +"CalculatedShippingLineStagedStatus":{"e":["NONE","ADDED","REMOVED"]}, +"CardPaymentDetails":{"o":{"f":{"avsResultCode":"String","bin":"String","company":"String","createdAt":"DateTime!","cvvResultCode":"String","expirationMonth":"Int","expirationYear":"Int","name":"String","number":"String","paymentMethodName":"String","wallet":"DigitalWallet"},"t":["BasePaymentDetails"]}}, +"CarrierServiceCreatePayload":{"o":{"f":{"carrierService":"DeliveryCarrierService","userErrors":"[CarrierServiceCreateUserError!]!"}}}, +"CarrierServiceCreateUserError":{"o":{"f":{"code":"CarrierServiceCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CarrierServiceCreateUserErrorCode":{"e":["CARRIER_SERVICE_CREATE_FAILED"]}, +"CarrierServiceDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[CarrierServiceDeleteUserError!]!"}}}, +"CarrierServiceDeleteUserError":{"o":{"f":{"code":"CarrierServiceDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CarrierServiceDeleteUserErrorCode":{"e":["CARRIER_SERVICE_DELETE_FAILED"]}, +"CarrierServiceSortKeys":{"e":["CREATED_AT","ID","UPDATED_AT"]}, +"CarrierServiceUpdatePayload":{"o":{"f":{"carrierService":"DeliveryCarrierService","userErrors":"[CarrierServiceUpdateUserError!]!"}}}, +"CarrierServiceUpdateUserError":{"o":{"f":{"code":"CarrierServiceUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CarrierServiceUpdateUserErrorCode":{"e":["CARRIER_SERVICE_UPDATE_FAILED"]}, +"CartTransform":{"o":{"f":{"blockOnFailure":"Boolean!","functionId":"String!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["HasMetafields","Node"]}}, +"CartTransformConnection":{"o":{"f":{"edges":"[CartTransformEdge!]!","nodes":"[CartTransform!]!","pageInfo":"PageInfo!"}}}, +"CartTransformCreatePayload":{"o":{"f":{"cartTransform":"CartTransform","userErrors":"[CartTransformCreateUserError!]!"}}}, +"CartTransformCreateUserError":{"o":{"f":{"code":"CartTransformCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CartTransformCreateUserErrorCode":{"e":["INPUT_INVALID","FUNCTION_NOT_FOUND","FUNCTION_ALREADY_REGISTERED","FUNCTION_DOES_NOT_IMPLEMENT","CUSTOM_APP_FUNCTION_NOT_ELIGIBLE","INVALID_METAFIELDS","MAXIMUM_CART_TRANSFORMS","MULTIPLE_FUNCTION_IDENTIFIERS","MISSING_FUNCTION_IDENTIFIER"]}, +"CartTransformDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[CartTransformDeleteUserError!]!"}}}, +"CartTransformDeleteUserError":{"o":{"f":{"code":"CartTransformDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CartTransformDeleteUserErrorCode":{"e":["NOT_FOUND","UNAUTHORIZED_APP_SCOPE"]}, +"CartTransformEdge":{"o":{"f":{"cursor":"String!","node":"CartTransform!"}}}, +"CartTransformEligibleOperations":{"o":{"f":{"expandOperation":"Boolean!","mergeOperation":"Boolean!","updateOperation":"Boolean!"}}}, +"CartTransformFeature":{"o":{"f":{"eligibleOperations":"CartTransformEligibleOperations!"}}}, +"CashActivitiesSortKeys":{"e":["ID","TIME"]}, +"CashActivity":{"n":{"f":{"cash":"MoneyV2!","paymentSession":"PointOfSaleDevicePaymentSession!","staffMember":"StaffMember!","time":"DateTime!"},"t":["CashAdjustmentActivity","CashCountActivity","CashTransactionActivity"]}}, +"CashActivityConnection":{"o":{"f":{"edges":"[CashActivityEdge!]!","nodes":"[CashActivity!]!","pageInfo":"PageInfo!"}}}, +"CashActivityEdge":{"o":{"f":{"cursor":"String!","node":"CashActivity!"}}}, +"CashAdjustmentActivity":{"o":{"f":{"cash":"MoneyV2!","giftCard":"GiftCard","note":"String","paymentSession":"PointOfSaleDevicePaymentSession!","reasonCode":"CashManagementReasonCode","staffMember":"StaffMember!","time":"DateTime!","type":"CashAdjustmentActivityType!"},"t":["CashActivity"]}}, +"CashAdjustmentActivityType":{"e":["ADJUSTMENT","CASH_PAYOUT","CLOSING_ADJUSTMENT"]}, +"CashCountActivity":{"o":{"f":{"cash":"MoneyV2!","cashCounted":"MoneyV2!","cashDiscrepancy":"MoneyV2!","cashExpected":"MoneyV2!","note":"String","paymentSession":"PointOfSaleDevicePaymentSession!","reasonCode":"CashManagementReasonCode","staffMember":"StaffMember!","time":"DateTime!","type":"CashCountActivityType!"},"t":["CashActivity"]}}, +"CashCountActivityType":{"e":["OPENING","CLOSING","MID_SESSION"]}, +"CashDrawer":{"o":{"f":{"balance":"MoneyV2!","cashActivities":["CashActivityConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CashActivitiesSortKeys=","staffMemberId":"ID"}],"id":"ID!","location":"Location!","name":"String!","netSales":["MoneyV2!",{"dateRange":"CashDrawerDateRangeInput!"}],"pointOfSaleDevices":["PointOfSaleDeviceConnection",{"after":"String","before":"String","first":"Int","last":"Int"}],"totalAdjustments":["MoneyV2!",{"dateRange":"CashDrawerDateRangeInput!"}],"totalDiscrepancies":["MoneyV2!",{"dateRange":"CashDrawerDateRangeInput!"}],"totalRefunds":["MoneyV2!",{"dateRange":"CashDrawerDateRangeInput!"}],"totalSales":["MoneyV2!",{"dateRange":"CashDrawerDateRangeInput!"}]},"t":["Node"]}}, +"CashDrawerConnection":{"o":{"f":{"edges":"[CashDrawerEdge!]!","nodes":"[CashDrawer!]!","pageInfo":"PageInfo!"}}}, +"CashDrawerCreatePayload":{"o":{"f":{"cashDrawer":"CashDrawer","userErrors":"[CashDrawerCreateUserError!]!"}}}, +"CashDrawerCreateUserError":{"o":{"f":{"code":"CashDrawerCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CashDrawerCreateUserErrorCode":{"e":["INTERNAL_ERROR","NOT_SAVED","CASH_DRAWER_ALREADY_EXISTS","LOCATION_NOT_FOUND","INVALID_NAME"]}, +"CashDrawerDateRangeInput":{"i":{"from":"DateTime!","to":"DateTime!"}}, +"CashDrawerEdge":{"o":{"f":{"cursor":"String!","node":"CashDrawer!"}}}, +"CashDrawerFindOrCreatePayload":{"o":{"f":{"cashDrawer":"CashDrawer","userErrors":"[CashDrawerFindOrCreateUserError!]!"}}}, +"CashDrawerFindOrCreateUserError":{"o":{"f":{"code":"CashDrawerFindOrCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CashDrawerFindOrCreateUserErrorCode":{"e":["INTERNAL_ERROR","NOT_SAVED","CASH_DRAWER_ASSIGNMENT_ALREADY_EXISTS","LOCATION_NOT_FOUND","POINT_OF_SALE_DEVICE_NOT_FOUND"]}, +"CashDrawerUpdateInput":{"i":{"name":"String!"}}, +"CashDrawerUpdatePayload":{"o":{"f":{"cashDrawer":"CashDrawer","userErrors":"[CashDrawerUpdateUserError!]!"}}}, +"CashDrawerUpdateUserError":{"o":{"f":{"code":"CashDrawerUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CashDrawerUpdateUserErrorCode":{"e":["INTERNAL_ERROR","NOT_SAVED","CASH_DRAWER_NOT_FOUND","CASH_DRAWER_ALREADY_EXISTS","INVALID_NAME"]}, +"CashManagementCustomReasonCode":{"o":{"f":{"code":"String!","id":"ID!"},"t":["Node"]}}, +"CashManagementDefaultReasonCode":{"o":{"f":{"code":"CashManagementDefaultReasonCodeEnum!","id":"ID!"},"t":["Node"]}}, +"CashManagementDefaultReasonCodeEnum":{"e":["CASH_PICKUP","CASH_COUNT","CHANGE_CORRECTION","PETTY_CASH","TIP_PAYOUT","CASH_PAYOUT","OTHER","AUTO_END_SESSION_LOGOUT","AUTO_END_SESSION_LOCATION_CHANGE","AUTO_START_SESSION_CHECKOUT"]}, +"CashManagementReasonCode":{"u":["CashManagementCustomReasonCode","CashManagementDefaultReasonCode","CashManagementSystemReasonCode"]}, +"CashManagementReasonCodeConnection":{"o":{"f":{"edges":"[CashManagementReasonCodeEdge!]!","nodes":"[CashManagementReasonCode!]!","pageInfo":"PageInfo!"}}}, +"CashManagementReasonCodeCreatePayload":{"o":{"f":{"reasonCode":"CashManagementCustomReasonCode","userErrors":"[CashManagementReasonCodeCreateUserError!]!"}}}, +"CashManagementReasonCodeCreateUserError":{"o":{"f":{"code":"CashManagementReasonCodeCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CashManagementReasonCodeCreateUserErrorCode":{"e":["CODE_ALREADY_EXISTS","NOT_SAVED","BLANK"]}, +"CashManagementReasonCodeDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[CashManagementReasonCodeDeleteUserError!]!"}}}, +"CashManagementReasonCodeDeleteUserError":{"o":{"f":{"code":"CashManagementReasonCodeDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CashManagementReasonCodeDeleteUserErrorCode":{"e":["NOT_FOUND","DATABASE_ERROR","NOT_DELETABLE"]}, +"CashManagementReasonCodeEdge":{"o":{"f":{"cursor":"String!","node":"CashManagementReasonCode!"}}}, +"CashManagementSummary":{"o":{"f":{"cashBalanceAtEnd":"MoneyV2!","cashBalanceAtStart":"MoneyV2!","netCash":"MoneyV2!","sessionsClosed":"Int!","sessionsOpened":"Int!","totalDiscrepancies":"MoneyV2!"}}}, +"CashManagementSystemReasonCode":{"o":{"f":{"code":"CashManagementSystemReasonCodeEnum!","id":"ID!"},"t":["Node"]}}, +"CashManagementSystemReasonCodeEnum":{"e":{"v":["FLOAT_SETUP","CASH_PAYOUT","OTHER","AUTO_END_SESSION_LOGOUT","AUTO_END_SESSION_LOCATION_CHANGE","AUTO_START_SESSION_CHECKOUT"],"d":{"OTHER":"Use CashManagementDefaultReasonCodeEnum.OTHER instead."}}}, +"CashRoundingAdjustment":{"o":{"f":{"paymentSet":"MoneyBag!","refundSet":"MoneyBag!"}}}, +"CashTrackingAdjustment":{"o":{"f":{"cash":"MoneyV2!","id":"ID!","note":"String","staffMember":"StaffMember!","time":"DateTime!"},"t":["Node"]}}, +"CashTrackingAdjustmentConnection":{"o":{"f":{"edges":"[CashTrackingAdjustmentEdge!]!","nodes":"[CashTrackingAdjustment!]!","pageInfo":"PageInfo!"}}}, +"CashTrackingAdjustmentEdge":{"o":{"f":{"cursor":"String!","node":"CashTrackingAdjustment!"}}}, +"CashTrackingSession":{"o":{"f":{"adjustments":["CashTrackingAdjustmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AdjustmentsSortKeys="}],"cashTrackingEnabled":"Boolean!","cashTransactions":["OrderTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CashTrackingSessionTransactionsSortKeys="}],"closingBalance":"MoneyV2","closingNote":"String","closingStaffMember":"StaffMember","closingTime":"DateTime","expectedBalance":"MoneyV2!","expectedClosingBalance":"MoneyV2","expectedOpeningBalance":"MoneyV2","id":"ID!","location":"Location","netCashSales":"MoneyV2!","openingBalance":"MoneyV2!","openingNote":"String","openingStaffMember":"StaffMember","openingTime":"DateTime!","registerName":"String!","totalAdjustments":"MoneyV2","totalCashRefunds":"MoneyV2!","totalCashSales":"MoneyV2!","totalDiscrepancy":"MoneyV2"},"t":["Node"]}}, +"CashTrackingSessionConnection":{"o":{"f":{"edges":"[CashTrackingSessionEdge!]!","nodes":"[CashTrackingSession!]!","pageInfo":"PageInfo!"}}}, +"CashTrackingSessionEdge":{"o":{"f":{"cursor":"String!","node":"CashTrackingSession!"}}}, +"CashTrackingSessionTransactionsSortKeys":{"e":["ID","PROCESSED_AT"]}, +"CashTrackingSessionsSortKeys":{"e":["CLOSING_TIME_ASC","CLOSING_TIME_DESC","ID","OPENING_TIME_ASC","OPENING_TIME_DESC","TOTAL_DISCREPANCY_ASC","TOTAL_DISCREPANCY_DESC"]}, +"CashTransactionActivity":{"o":{"f":{"cash":"MoneyV2!","orderTransaction":"OrderTransaction!","paymentSession":"PointOfSaleDevicePaymentSession!","staffMember":"StaffMember!","time":"DateTime!","type":"CashTransactionActivityType!"},"t":["CashActivity"]}}, +"CashTransactionActivityType":{"e":["SALE","REFUND","CHANGE"]}, +"Catalog":{"n":{"f":{"id":"ID!","operations":"[ResourceOperation!]!","priceList":"PriceList","publication":"Publication","status":"CatalogStatus!","title":"String!"},"t":["AppCatalog","CompanyLocationCatalog","MarketCatalog"]}}, +"CatalogConnection":{"o":{"f":{"edges":"[CatalogEdge!]!","nodes":"[Catalog!]!","pageInfo":"PageInfo!"}}}, +"CatalogContextInput":{"i":{"companyLocationIds":"[ID!]","marketIds":"[ID!]"}}, +"CatalogContextUpdatePayload":{"o":{"f":{"catalog":"Catalog","userErrors":"[CatalogUserError!]!"}}}, +"CatalogCreateInput":{"i":{"context":"CatalogContextInput!","priceListId":"ID","publicationId":"ID","status":"CatalogStatus!","title":"String!"}}, +"CatalogCreatePayload":{"o":{"f":{"catalog":"Catalog","userErrors":"[CatalogUserError!]!"}}}, +"CatalogCsvOperation":{"o":{"f":{"id":"ID!","processedRowCount":"Int","rowCount":"RowCount","status":"ResourceOperationStatus!"},"t":["Node","ResourceOperation"]}}, +"CatalogDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[CatalogUserError!]!"}}}, +"CatalogEdge":{"o":{"f":{"cursor":"String!","node":"Catalog!"}}}, +"CatalogSortKeys":{"e":["ID","RELEVANCE","TITLE","TYPE"]}, +"CatalogStatus":{"e":["ACTIVE","ARCHIVED","DRAFT"]}, +"CatalogType":{"e":["NONE","APP","COMPANY_LOCATION","MARKET"]}, +"CatalogUpdateInput":{"i":{"context":"CatalogContextInput","priceListId":"ID","publicationId":"ID","status":"CatalogStatus","title":"String"}}, +"CatalogUpdatePayload":{"o":{"f":{"catalog":"Catalog","userErrors":"[CatalogUserError!]!"}}}, +"CatalogUserError":{"o":{"f":{"code":"CatalogUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CatalogUserErrorCode":{"e":["APP_CATALOG_PRICE_LIST_ASSIGNMENT","B2B_CATALOG_LIMIT_REACHED","CATALOG_FAILED_TO_SAVE","CATALOG_NOT_FOUND","PRICE_LIST_NOT_ALLOWED_FOR_PRIMARY_MARKET","CATALOG_CONTEXT_DOES_NOT_SUPPORT_QUANTITY_RULES","CATALOG_CONTEXT_DOES_NOT_SUPPORT_QUANTITY_PRICE_BREAKS","CANNOT_ADD_MORE_THAN_ONE_MARKET","COMPANY_LOCATION_CATALOG_STATUS_PLAN","CONTEXT_ALREADY_ASSIGNED_TO_CATALOG","CONTEXT_CATALOG_LIMIT_REACHED","COMPANY_LOCATION_NOT_FOUND","CONTEXT_DRIVER_MISMATCH","COUNTRY_CATALOG_PRICE_LIST_ASSIGNMENT","COUNTRY_PRICE_LIST_ASSIGNMENT","INVALID_CATALOG_CONTEXT_TYPE","CATALOG_NOT_COMPATIBLE_WITH_CONDITION_TYPES","MARKET_CATALOG_STATUS","MARKET_NOT_FOUND","MARKET_AND_PRICE_LIST_CURRENCY_MISMATCH","MARKET_TAKEN","MANAGED_COUNTRY_BELONGS_TO_ANOTHER_CATALOG","MUST_PROVIDE_EXACTLY_ONE_CONTEXT_TYPE","PRICE_LIST_FAILED_TO_SAVE","PRICE_LIST_NOT_FOUND","PRICE_LIST_LOCKED","CATALOG_CONTEXT_LOCKED","PUBLICATION_NOT_FOUND","REQUIRES_CONTEXTS_TO_ADD_OR_REMOVE","UNSUPPORTED_CATALOG_ACTION","CANNOT_CREATE_APP_CATALOG","CANNOT_MODIFY_APP_CATALOG","CANNOT_DELETE_APP_CATALOG","CANNOT_CREATE_MARKET_CATALOG","CANNOT_MODIFY_MARKET_CATALOG","CANNOT_DELETE_MARKET_CATALOG","UNPERMITTED_ENTITLEMENTS_DIRECT_CATALOG_ASSIGNMENT","UNPERMITTED_ENTITLEMENTS_MARKET_CATALOGS","INVALID","TAKEN","TOO_LONG","TOO_SHORT","BLANK","INVALID_CONTEXT_CHANGE"]}, +"Channel":{"o":{"f":{"accountId":"String","accountName":"String","activeRegions":"[CountryCode!]!","app":"App!","collectionPublicationsV3":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"handle":"String!","hasCollection":["Boolean!",{"id":"ID!"}],"id":"ID!","markets":["MarketConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"marketsCount":"Count","name":"String!","navigationItems":"[NavigationItem!]!","overviewPath":"URL","productPublications":["ProductPublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productPublicationsV3":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productsCount":["Count",{"limit":"Int=","query":"String"}],"resourceFeedback":"AppFeedback","specificationHandle":"String","supportsFuturePublishing":"Boolean!"},"t":["Node"],"d":{"navigationItems":"Use [AppInstallation.navigationItems](\n https://shopify.dev/api/admin-graphql/current/objects/AppInstallation#field-appinstallation-navigationitems) instead.","overviewPath":"Use [AppInstallation.launchUrl](\n https://shopify.dev/api/admin-graphql/current/objects/AppInstallation#field-appinstallation-launchurl) instead.","productPublications":"Use `productPublicationsV3` instead."}}}, +"ChannelConnection":{"o":{"f":{"edges":"[ChannelEdge!]!","nodes":"[Channel!]!","pageInfo":"PageInfo!"}}}, +"ChannelCreateInput":{"i":{"accountId":"String!","accountName":"String!","handle":"String","specificationHandle":"String!"}}, +"ChannelCreatePayload":{"o":{"f":{"channel":"Channel","userErrors":"[ChannelCreateUserError!]!"}}}, +"ChannelCreateUserError":{"o":{"f":{"code":"ChannelCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ChannelCreateUserErrorCode":{"e":["INVALID","NOT_FOUND"]}, +"ChannelDefinition":{"o":{"f":{"channelName":"String!","handle":"String!","id":"ID!","isMarketplace":"Boolean!","subChannelName":"String!","svgIcon":"String"},"t":["Node"],"d":{"channelName":"Use [`OrderAttributionDefinition.displayName`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.displayName) instead.","handle":"Use [`OrderAttributionDefinition.handle`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.handle) instead.","id":"Use [`OrderAttributionDefinition.id`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.id) instead.","isMarketplace":"Use [`OrderAttributionDefinition.handle`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.handle) instead.","subChannelName":"Use [`OrderAttributionDefinition.displayName`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.displayName) instead.","svgIcon":"Use [`OrderAttributionDefinition.icon`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.icon) instead."}}}, +"ChannelDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[ChannelDeleteUserError!]!"}}}, +"ChannelDeleteUserError":{"o":{"f":{"code":"ChannelDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ChannelDeleteUserErrorCode":{"e":["INVALID","NOT_FOUND"]}, +"ChannelEdge":{"o":{"f":{"cursor":"String!","node":"Channel!"}}}, +"ChannelFullSyncPayload":{"o":{"f":{"fullSyncTraceInfo":"[FullSyncTraceInfo!]","userErrors":"[ChannelFullSyncUserError!]!"}}}, +"ChannelFullSyncUserError":{"o":{"f":{"code":"ChannelFullSyncUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ChannelFullSyncUserErrorCode":{"e":["INVALID","NOT_FOUND"]}, +"ChannelInformation":{"o":{"f":{"app":"App!","channelDefinition":"ChannelDefinition","channelId":"ID!","displayName":"String","id":"ID!"},"t":["Node"],"d":{"app":"Use [`Order.attribution`](https://shopify.dev/docs/api/admin-graphql/latest/objects/Order#field-Order.fields.attribution) for order attribution, or [`Order.app`](https://shopify.dev/docs/api/admin-graphql/latest/objects/Order#field-Order.fields.app) and [`Order.publication`](https://shopify.dev/docs/api/admin-graphql/latest/objects/Order#field-Order.fields.publication) for app and sales channel details.","channelDefinition":"Use [`QueryRoot.orderAttributionDefinitions`](https://shopify.dev/docs/api/admin-graphql/latest/queries/orderAttributionDefinitions) and select `id`, `handle`, `displayName`, and `icon` instead.","channelId":"Use [`Order.attribution.handle`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttribution#field-OrderAttribution.fields.handle) instead.","displayName":"Use [`Order.attribution.displayName`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttribution#field-OrderAttribution.fields.displayName) instead.","id":"Use [`Order.attribution.handle`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttribution#field-OrderAttribution.fields.handle) instead."}}}, +"ChannelUpdateInput":{"i":{"accountId":"String","accountName":"String","handle":"String","specificationHandle":"String"}}, +"ChannelUpdatePayload":{"o":{"f":{"channel":"Channel","userErrors":"[ChannelUpdateUserError!]!"}}}, +"ChannelUpdateUserError":{"o":{"f":{"code":"ChannelUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ChannelUpdateUserErrorCode":{"e":["INVALID","NOT_FOUND"]}, +"ChannelsCondition":{"o":{"f":{"applicationLevel":"MarketConditionApplicationType","channels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"channelsCount":"Count"}}}, +"CheckoutAndAccountsConfiguration":{"o":{"f":{"branding":"CheckoutAndAccountsConfigurationBranding","createdAt":"DateTime!","editedAt":"DateTime!","id":"ID!","isPublished":"Boolean!","name":"String!","overrides":"[CheckoutAndAccountsConfigurationOverride!]!","updatedAt":"DateTime!"},"t":["CheckoutAndAccountsConfigurationInterface","Node"]}}, +"CheckoutAndAccountsConfigurationBranding":{"o":{"f":{"components":"CheckoutAndAccountsConfigurationBrandingComponents","designTokens":"CheckoutAndAccountsConfigurationBrandingDesignTokens","surfaces":"CheckoutAndAccountsConfigurationBrandingSurfaces"}}}, +"CheckoutAndAccountsConfigurationBrandingBackground":{"e":["BASE","SUBDUED"]}, +"CheckoutAndAccountsConfigurationBrandingBaseColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingBaseColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}, +"CheckoutAndAccountsConfigurationBrandingBorder":{"e":["NONE","BLOCK_END","FULL"]}, +"CheckoutAndAccountsConfigurationBrandingBorderStyle":{"e":["BASE","DASHED","DOTTED"]}, +"CheckoutAndAccountsConfigurationBrandingBorderWidth":{"e":["BASE","LARGE","LARGE_100","LARGE_200"]}, +"CheckoutAndAccountsConfigurationBrandingButton":{"o":{"f":{"blockPadding":"CheckoutAndAccountsConfigurationBrandingSpacing","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","inlinePadding":"CheckoutAndAccountsConfigurationBrandingSpacing","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyle"}}}, +"CheckoutAndAccountsConfigurationBrandingButtonInput":{"i":{"blockPadding":"CheckoutAndAccountsConfigurationBrandingSpacing","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","inlinePadding":"CheckoutAndAccountsConfigurationBrandingSpacing","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput"}}, +"CheckoutAndAccountsConfigurationBrandingBuyerJourney":{"o":{"f":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}}, +"CheckoutAndAccountsConfigurationBrandingBuyerJourneyInput":{"i":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}, +"CheckoutAndAccountsConfigurationBrandingCartLink":{"o":{"f":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}}, +"CheckoutAndAccountsConfigurationBrandingCartLinkContentType":{"e":["ICON","IMAGE","TEXT"]}, +"CheckoutAndAccountsConfigurationBrandingCartLinkInput":{"i":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}, +"CheckoutAndAccountsConfigurationBrandingCheckbox":{"o":{"f":{"cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius"}}}, +"CheckoutAndAccountsConfigurationBrandingCheckboxInput":{"i":{"cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius"}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutComponents":{"o":{"f":{"buyerJourney":"CheckoutAndAccountsConfigurationBrandingBuyerJourney","cartLink":"CheckoutAndAccountsConfigurationBrandingCartLink","content":"CheckoutAndAccountsConfigurationBrandingContent","expressCheckout":"CheckoutAndAccountsConfigurationBrandingExpressCheckout","footer":"CheckoutAndAccountsConfigurationBrandingCheckoutFooter","header":"CheckoutAndAccountsConfigurationBrandingCheckoutHeader","main":"CheckoutAndAccountsConfigurationBrandingMain","orderSummary":"CheckoutAndAccountsConfigurationBrandingOrderSummary"}}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutComponentsInput":{"i":{"buyerJourney":"CheckoutAndAccountsConfigurationBrandingBuyerJourneyInput","cartLink":"CheckoutAndAccountsConfigurationBrandingCartLinkInput","content":"CheckoutAndAccountsConfigurationBrandingContentInput","expressCheckout":"CheckoutAndAccountsConfigurationBrandingExpressCheckoutInput","footer":"CheckoutAndAccountsConfigurationBrandingCheckoutFooterInput","header":"CheckoutAndAccountsConfigurationBrandingCheckoutHeaderInput","main":"CheckoutAndAccountsConfigurationBrandingMainInput","orderSummary":"CheckoutAndAccountsConfigurationBrandingOrderSummaryInput"}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutFooter":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColors","content":"CheckoutAndAccountsConfigurationBrandingFooterContent","divided":"Boolean","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","position":"CheckoutAndAccountsConfigurationBrandingFooterPosition"}}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutFooterInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","content":"CheckoutAndAccountsConfigurationBrandingFooterContentInput","divided":"Boolean","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","position":"CheckoutAndAccountsConfigurationBrandingFooterPosition"}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutHeader":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","cartLink":"CheckoutAndAccountsConfigurationBrandingHeaderCartLink","colors":"CheckoutAndAccountsConfigurationBrandingColors","divided":"Boolean","logo":"CheckoutAndAccountsConfigurationBrandingLogo","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","position":"CheckoutAndAccountsConfigurationBrandingHeaderPosition"}}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutHeaderInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","cartLink":"CheckoutAndAccountsConfigurationBrandingHeaderCartLinkInput","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","divided":"Boolean","logo":"CheckoutAndAccountsConfigurationBrandingLogoInput","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","position":"CheckoutAndAccountsConfigurationBrandingHeaderPosition"}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutSurface":{"o":{"f":{"components":"CheckoutAndAccountsConfigurationBrandingCheckoutComponents"}}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutSurfaceInput":{"i":{"components":"CheckoutAndAccountsConfigurationBrandingCheckoutComponentsInput"}}, +"CheckoutAndAccountsConfigurationBrandingChoiceList":{"o":{"f":{"group":"CheckoutAndAccountsConfigurationBrandingChoiceListGroup"}}}, +"CheckoutAndAccountsConfigurationBrandingChoiceListGroup":{"o":{"f":{"spacing":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingChoiceListGroupInput":{"i":{"spacing":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingChoiceListInput":{"i":{"group":"CheckoutAndAccountsConfigurationBrandingChoiceListGroupInput"}}, +"CheckoutAndAccountsConfigurationBrandingColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}, +"CheckoutAndAccountsConfigurationBrandingColors":{"o":{"f":{"base":"CheckoutAndAccountsConfigurationBrandingBaseColorRoles","control":"CheckoutAndAccountsConfigurationBrandingControlColorRoles","primaryButton":"CheckoutAndAccountsConfigurationBrandingPrimaryButtonColorRoles","secondaryButton":"CheckoutAndAccountsConfigurationBrandingSecondaryButtonColorRoles"}}}, +"CheckoutAndAccountsConfigurationBrandingColorsInput":{"i":{"base":"CheckoutAndAccountsConfigurationBrandingBaseColorRolesInput","control":"CheckoutAndAccountsConfigurationBrandingControlColorRolesInput","primaryButton":"CheckoutAndAccountsConfigurationBrandingPrimaryButtonColorRolesInput","secondaryButton":"CheckoutAndAccountsConfigurationBrandingSecondaryButtonColorRolesInput"}}, +"CheckoutAndAccountsConfigurationBrandingComponents":{"o":{"f":{"checkbox":"CheckoutAndAccountsConfigurationBrandingCheckbox","choiceList":"CheckoutAndAccountsConfigurationBrandingChoiceList","control":"CheckoutAndAccountsConfigurationBrandingControl","divider":"CheckoutAndAccountsConfigurationBrandingDividerStyle","favicon":"CheckoutAndAccountsConfigurationBrandingImageValue","footer":"CheckoutAndAccountsConfigurationBrandingFooter","header":"CheckoutAndAccountsConfigurationBrandingHeader","headingLevel1":"CheckoutAndAccountsConfigurationBrandingHeadingLevel","headingLevel2":"CheckoutAndAccountsConfigurationBrandingHeadingLevel","headingLevel3":"CheckoutAndAccountsConfigurationBrandingHeadingLevel","main":"CheckoutAndAccountsConfigurationBrandingMain","merchandiseThumbnail":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnail","primaryButton":"CheckoutAndAccountsConfigurationBrandingButton","secondaryButton":"CheckoutAndAccountsConfigurationBrandingButton","select":"CheckoutAndAccountsConfigurationBrandingSelect","shared":"CheckoutAndAccountsConfigurationBrandingShared","textField":"CheckoutAndAccountsConfigurationBrandingTextField"}}}, +"CheckoutAndAccountsConfigurationBrandingComponentsInput":{"i":{"checkbox":"CheckoutAndAccountsConfigurationBrandingCheckboxInput","choiceList":"CheckoutAndAccountsConfigurationBrandingChoiceListInput","control":"CheckoutAndAccountsConfigurationBrandingControlInput","divider":"CheckoutAndAccountsConfigurationBrandingDividerStyleInput","favicon":"CheckoutAndAccountsConfigurationBrandingImageInput","footer":"CheckoutAndAccountsConfigurationBrandingFooterInput","header":"CheckoutAndAccountsConfigurationBrandingHeaderInput","headingLevel1":"CheckoutAndAccountsConfigurationBrandingHeadingLevelInput","headingLevel2":"CheckoutAndAccountsConfigurationBrandingHeadingLevelInput","headingLevel3":"CheckoutAndAccountsConfigurationBrandingHeadingLevelInput","main":"CheckoutAndAccountsConfigurationBrandingMainInput","merchandiseThumbnail":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailInput","primaryButton":"CheckoutAndAccountsConfigurationBrandingButtonInput","secondaryButton":"CheckoutAndAccountsConfigurationBrandingButtonInput","select":"CheckoutAndAccountsConfigurationBrandingSelectInput","shared":"CheckoutAndAccountsConfigurationBrandingSharedInput","textField":"CheckoutAndAccountsConfigurationBrandingTextFieldInput"}}, +"CheckoutAndAccountsConfigurationBrandingContainerDivider":{"o":{"f":{"borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}}, +"CheckoutAndAccountsConfigurationBrandingContainerDividerInput":{"i":{"borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}, +"CheckoutAndAccountsConfigurationBrandingContent":{"o":{"f":{"divider":"CheckoutAndAccountsConfigurationBrandingContainerDivider"}}}, +"CheckoutAndAccountsConfigurationBrandingContentInput":{"i":{"divider":"CheckoutAndAccountsConfigurationBrandingContainerDividerInput"}}, +"CheckoutAndAccountsConfigurationBrandingControl":{"o":{"f":{"border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","labelPosition":"CheckoutAndAccountsConfigurationBrandingLabelPosition"}}}, +"CheckoutAndAccountsConfigurationBrandingControlColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","selected":"CheckoutAndAccountsConfigurationBrandingColorRoles","text":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingControlColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","selected":"CheckoutAndAccountsConfigurationBrandingColorRolesInput","text":"String"}}, +"CheckoutAndAccountsConfigurationBrandingControlInput":{"i":{"border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","labelPosition":"CheckoutAndAccountsConfigurationBrandingLabelPosition"}}, +"CheckoutAndAccountsConfigurationBrandingCornerRadius":{"e":["NONE","SMALL","BASE","LARGE"]}, +"CheckoutAndAccountsConfigurationBrandingCornerRadiusVariables":{"o":{"f":{"base":"Int","large":"Int","small":"Int"}}}, +"CheckoutAndAccountsConfigurationBrandingCornerRadiusVariablesInput":{"i":{"base":"Int","large":"Int","small":"Int"}}, +"CheckoutAndAccountsConfigurationBrandingCustomFont":{"o":{"f":{"genericFileId":"ID","sources":"String","weight":"Int"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomFontGroup":{"o":{"f":{"base":"CheckoutAndAccountsConfigurationBrandingCustomFont","bold":"CheckoutAndAccountsConfigurationBrandingCustomFont","loadingStrategy":"CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy","name":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomFontGroupInput":{"i":{"base":"CheckoutAndAccountsConfigurationBrandingCustomFontInput!","bold":"CheckoutAndAccountsConfigurationBrandingCustomFontInput!","loadingStrategy":"CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy"}}, +"CheckoutAndAccountsConfigurationBrandingCustomFontInput":{"i":{"genericFileId":"ID!","weight":"Int!"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsComponents":{"o":{"f":{"footer":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsFooter","header":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsHeader","main":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMain"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsComponentsInput":{"i":{"footer":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsFooterInput","header":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsHeaderInput","main":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainInput"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsFooter":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","colors":"CheckoutAndAccountsConfigurationBrandingColors","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsFooterInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsHeader":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","colors":"CheckoutAndAccountsConfigurationBrandingColors","logo":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsLogo","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsHeaderInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","logo":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsLogoInput","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsLogo":{"o":{"f":{"image":"CheckoutAndAccountsConfigurationBrandingImageValue","maxWidth":"Int"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsLogoInput":{"i":{"image":"CheckoutAndAccountsConfigurationBrandingImageInput","maxWidth":"Int"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMain":{"o":{"f":{"colors":"CheckoutAndAccountsConfigurationBrandingColors","section":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainSection"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainInput":{"i":{"colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","section":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainSectionInput"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainSection":{"o":{"f":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColors","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainSectionInput":{"i":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsSurface":{"o":{"f":{"components":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsComponents"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsSurfaceInput":{"i":{"components":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsComponentsInput"}}, +"CheckoutAndAccountsConfigurationBrandingDesignTokenColors":{"o":{"f":{"palette":"CheckoutAndAccountsConfigurationBrandingPalette"}}}, +"CheckoutAndAccountsConfigurationBrandingDesignTokens":{"o":{"f":{"colors":"CheckoutAndAccountsConfigurationBrandingDesignTokenColors","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadiusVariables","typography":"CheckoutAndAccountsConfigurationBrandingTypography"}}}, +"CheckoutAndAccountsConfigurationBrandingDesignTokensColorsInput":{"i":{"palette":"CheckoutAndAccountsConfigurationBrandingPaletteInput"}}, +"CheckoutAndAccountsConfigurationBrandingDesignTokensInput":{"i":{"colors":"CheckoutAndAccountsConfigurationBrandingDesignTokensColorsInput","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadiusVariablesInput","typography":"CheckoutAndAccountsConfigurationBrandingTypographyInput"}}, +"CheckoutAndAccountsConfigurationBrandingDividerStyle":{"o":{"f":{"borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth"}}}, +"CheckoutAndAccountsConfigurationBrandingDividerStyleInput":{"i":{"borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth"}}, +"CheckoutAndAccountsConfigurationBrandingExpressCheckout":{"o":{"f":{"button":"CheckoutAndAccountsConfigurationBrandingExpressCheckoutButton"}}}, +"CheckoutAndAccountsConfigurationBrandingExpressCheckoutButton":{"o":{"f":{"cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius"}}}, +"CheckoutAndAccountsConfigurationBrandingExpressCheckoutButtonInput":{"i":{"cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius"}}, +"CheckoutAndAccountsConfigurationBrandingExpressCheckoutInput":{"i":{"button":"CheckoutAndAccountsConfigurationBrandingExpressCheckoutButtonInput"}}, +"CheckoutAndAccountsConfigurationBrandingFontGroup":{"u":["CheckoutAndAccountsConfigurationBrandingCustomFontGroup","CheckoutAndAccountsConfigurationBrandingShopifyFontGroup"]}, +"CheckoutAndAccountsConfigurationBrandingFontGroupInput":{"i":{"customFontGroup":"CheckoutAndAccountsConfigurationBrandingCustomFontGroupInput","shopifyFontGroup":"CheckoutAndAccountsConfigurationBrandingShopifyFontGroupInput"}}, +"CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy":{"e":["AUTO","BLOCK","SWAP","FALLBACK","OPTIONAL"]}, +"CheckoutAndAccountsConfigurationBrandingFontSize":{"o":{"f":{"base":"Float","ratio":"Float"}}}, +"CheckoutAndAccountsConfigurationBrandingFontSizeInput":{"i":{"base":"Float","ratio":"Float"}}, +"CheckoutAndAccountsConfigurationBrandingFooter":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColors","content":"CheckoutAndAccountsConfigurationBrandingFooterContent","divided":"Boolean","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingFooterAlignment":{"e":["START","CENTER","END"]}, +"CheckoutAndAccountsConfigurationBrandingFooterContent":{"o":{"f":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}}, +"CheckoutAndAccountsConfigurationBrandingFooterContentInput":{"i":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}, +"CheckoutAndAccountsConfigurationBrandingFooterInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","content":"CheckoutAndAccountsConfigurationBrandingFooterContentInput","divided":"Boolean","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingFooterPosition":{"e":["END","INLINE"]}, +"CheckoutAndAccountsConfigurationBrandingHeader":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColors","divided":"Boolean","logo":"CheckoutAndAccountsConfigurationBrandingLogo","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingHeaderAlignment":{"e":["START","CENTER","END"]}, +"CheckoutAndAccountsConfigurationBrandingHeaderCartLink":{"o":{"f":{"contentType":"CheckoutAndAccountsConfigurationBrandingCartLinkContentType","image":"CheckoutAndAccountsConfigurationBrandingImageValue"}}}, +"CheckoutAndAccountsConfigurationBrandingHeaderCartLinkInput":{"i":{"contentType":"CheckoutAndAccountsConfigurationBrandingCartLinkContentType","image":"CheckoutAndAccountsConfigurationBrandingImageInput"}}, +"CheckoutAndAccountsConfigurationBrandingHeaderInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","divided":"Boolean","logo":"CheckoutAndAccountsConfigurationBrandingLogoInput","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingHeaderPosition":{"e":["INLINE","INLINE_SECONDARY","START"]}, +"CheckoutAndAccountsConfigurationBrandingHeadingLevel":{"o":{"f":{"typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyle"}}}, +"CheckoutAndAccountsConfigurationBrandingHeadingLevelInput":{"i":{"typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput"}}, +"CheckoutAndAccountsConfigurationBrandingImage":{"o":{"f":{"image":"Image"}}}, +"CheckoutAndAccountsConfigurationBrandingImageInput":{"i":{"mediaImageId":"ID"}}, +"CheckoutAndAccountsConfigurationBrandingImageValue":{"u":["CheckoutAndAccountsConfigurationBrandingImage"]}, +"CheckoutAndAccountsConfigurationBrandingInput":{"i":{"components":"CheckoutAndAccountsConfigurationBrandingComponentsInput","designTokens":"CheckoutAndAccountsConfigurationBrandingDesignTokensInput","surfaces":"CheckoutAndAccountsConfigurationBrandingSurfacesInput"}}, +"CheckoutAndAccountsConfigurationBrandingLabelPosition":{"e":["INSIDE","OUTSIDE"]}, +"CheckoutAndAccountsConfigurationBrandingLogo":{"o":{"f":{"image":"CheckoutAndAccountsConfigurationBrandingImageValue","maxWidth":"Int","visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}}, +"CheckoutAndAccountsConfigurationBrandingLogoInput":{"i":{"image":"CheckoutAndAccountsConfigurationBrandingImageInput","maxWidth":"Int","visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}, +"CheckoutAndAccountsConfigurationBrandingMain":{"o":{"f":{"colors":"CheckoutAndAccountsConfigurationBrandingColors","divider":"CheckoutAndAccountsConfigurationBrandingContainerDivider","section":"CheckoutAndAccountsConfigurationBrandingMainSection"}}}, +"CheckoutAndAccountsConfigurationBrandingMainInput":{"i":{"colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","divider":"CheckoutAndAccountsConfigurationBrandingContainerDividerInput","section":"CheckoutAndAccountsConfigurationBrandingMainSectionInput"}}, +"CheckoutAndAccountsConfigurationBrandingMainSection":{"o":{"f":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColors","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}}, +"CheckoutAndAccountsConfigurationBrandingMainSectionInput":{"i":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}, +"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnail":{"o":{"f":{"badge":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadge","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","fit":"CheckoutAndAccountsConfigurationBrandingObjectFit"}}}, +"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadge":{"o":{"f":{"background":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadgeBackground"}}}, +"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadgeBackground":{"e":["ACCENT","BASE"]}, +"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadgeInput":{"i":{"background":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadgeBackground"}}, +"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailInput":{"i":{"aspectRatio":"Float","badge":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadgeInput","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","fit":"CheckoutAndAccountsConfigurationBrandingObjectFit"}}, +"CheckoutAndAccountsConfigurationBrandingObjectFit":{"e":["CONTAIN","COVER"]}, +"CheckoutAndAccountsConfigurationBrandingOrderSummary":{"o":{"f":{"backgroundImage":"CheckoutAndAccountsConfigurationBrandingImageValue","colors":"CheckoutAndAccountsConfigurationBrandingColors","divider":"CheckoutAndAccountsConfigurationBrandingContainerDivider","section":"CheckoutAndAccountsConfigurationBrandingOrderSummarySection"}}}, +"CheckoutAndAccountsConfigurationBrandingOrderSummaryInput":{"i":{"backgroundImage":"CheckoutAndAccountsConfigurationBrandingImageInput","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","divider":"CheckoutAndAccountsConfigurationBrandingContainerDividerInput","section":"CheckoutAndAccountsConfigurationBrandingOrderSummarySectionInput"}}, +"CheckoutAndAccountsConfigurationBrandingOrderSummarySection":{"o":{"f":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColors","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}}, +"CheckoutAndAccountsConfigurationBrandingOrderSummarySectionInput":{"i":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}, +"CheckoutAndAccountsConfigurationBrandingPalette":{"o":{"f":{"color1":"String","color10":"String","color11":"String","color12":"String","color13":"String","color14":"String","color15":"String","color16":"String","color17":"String","color18":"String","color19":"String","color2":"String","color20":"String","color3":"String","color4":"String","color5":"String","color6":"String","color7":"String","color8":"String","color9":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingPaletteInput":{"i":{"color1":"String","color10":"String","color11":"String","color12":"String","color13":"String","color14":"String","color15":"String","color16":"String","color17":"String","color18":"String","color19":"String","color2":"String","color20":"String","color3":"String","color4":"String","color5":"String","color6":"String","color7":"String","color8":"String","color9":"String"}}, +"CheckoutAndAccountsConfigurationBrandingPrimaryButtonColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutAndAccountsConfigurationBrandingColorRoles","icon":"String","text":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingPrimaryButtonColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutAndAccountsConfigurationBrandingColorRolesInput","icon":"String","text":"String"}}, +"CheckoutAndAccountsConfigurationBrandingSecondaryButtonColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutAndAccountsConfigurationBrandingColorRoles","icon":"String","text":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingSecondaryButtonColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutAndAccountsConfigurationBrandingColorRolesInput","icon":"String","text":"String"}}, +"CheckoutAndAccountsConfigurationBrandingSelect":{"o":{"f":{"border":"CheckoutAndAccountsConfigurationBrandingBorder","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyle"}}}, +"CheckoutAndAccountsConfigurationBrandingSelectInput":{"i":{"border":"CheckoutAndAccountsConfigurationBrandingBorder","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput"}}, +"CheckoutAndAccountsConfigurationBrandingShadow":{"e":["SMALL_200","SMALL_100","BASE","LARGE_100","LARGE_200"]}, +"CheckoutAndAccountsConfigurationBrandingShared":{"o":{"f":{"colors":"CheckoutAndAccountsConfigurationBrandingSharedColors","cornerRadius":"CheckoutAndAccountsConfigurationBrandingSharedCornerRadius","typography":"CheckoutAndAccountsConfigurationBrandingSharedTypographyStyle"}}}, +"CheckoutAndAccountsConfigurationBrandingSharedColors":{"o":{"f":{"accent":"String","button":"String","control":"String","critical":"String","decorative":"String","info":"String","success":"String","warning":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingSharedColorsInput":{"i":{"accent":"String","button":"String","control":"String","critical":"String","decorative":"String","info":"String","success":"String","warning":"String"}}, +"CheckoutAndAccountsConfigurationBrandingSharedCornerRadius":{"e":["NONE"]}, +"CheckoutAndAccountsConfigurationBrandingSharedInput":{"i":{"colors":"CheckoutAndAccountsConfigurationBrandingSharedColorsInput","cornerRadius":"CheckoutAndAccountsConfigurationBrandingSharedCornerRadius","typography":"CheckoutAndAccountsConfigurationBrandingSharedTypographyStyleInput"}}, +"CheckoutAndAccountsConfigurationBrandingSharedTypographyStyle":{"o":{"f":{"kerning":"CheckoutAndAccountsConfigurationBrandingTypographyKerning","letterCase":"CheckoutAndAccountsConfigurationBrandingTypographyLetterCase"}}}, +"CheckoutAndAccountsConfigurationBrandingSharedTypographyStyleInput":{"i":{"kerning":"CheckoutAndAccountsConfigurationBrandingTypographyKerning","letterCase":"CheckoutAndAccountsConfigurationBrandingTypographyLetterCase"}}, +"CheckoutAndAccountsConfigurationBrandingShopifyFont":{"o":{"f":{"sources":"String","weight":"Int"}}}, +"CheckoutAndAccountsConfigurationBrandingShopifyFontGroup":{"o":{"f":{"base":"CheckoutAndAccountsConfigurationBrandingShopifyFont","bold":"CheckoutAndAccountsConfigurationBrandingShopifyFont","loadingStrategy":"CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy","name":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingShopifyFontGroupInput":{"i":{"baseFontHandle":"String!","boldFontHandle":"String!","loadingStrategy":"CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy"}}, +"CheckoutAndAccountsConfigurationBrandingSignInComponents":{"o":{"f":{"header":"CheckoutAndAccountsConfigurationBrandingSignInHeader","main":"CheckoutAndAccountsConfigurationBrandingSignInMain"}}}, +"CheckoutAndAccountsConfigurationBrandingSignInComponentsInput":{"i":{"header":"CheckoutAndAccountsConfigurationBrandingSignInHeaderInput","main":"CheckoutAndAccountsConfigurationBrandingSignInMainInput"}}, +"CheckoutAndAccountsConfigurationBrandingSignInHeader":{"o":{"f":{"logo":"CheckoutAndAccountsConfigurationBrandingSignInLogo","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingSignInHeaderInput":{"i":{"logo":"CheckoutAndAccountsConfigurationBrandingSignInLogoInput","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingSignInLogo":{"o":{"f":{"image":"CheckoutAndAccountsConfigurationBrandingImageValue","maxWidth":"Int"}}}, +"CheckoutAndAccountsConfigurationBrandingSignInLogoInput":{"i":{"image":"CheckoutAndAccountsConfigurationBrandingImageInput","maxWidth":"Int"}}, +"CheckoutAndAccountsConfigurationBrandingSignInMain":{"o":{"f":{"backgroundImage":"CheckoutAndAccountsConfigurationBrandingImageValue","colors":"CheckoutAndAccountsConfigurationBrandingColors","section":"CheckoutAndAccountsConfigurationBrandingMainSection"}}}, +"CheckoutAndAccountsConfigurationBrandingSignInMainInput":{"i":{"backgroundImage":"CheckoutAndAccountsConfigurationBrandingImageInput","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","section":"CheckoutAndAccountsConfigurationBrandingMainSectionInput"}}, +"CheckoutAndAccountsConfigurationBrandingSignInSurface":{"o":{"f":{"components":"CheckoutAndAccountsConfigurationBrandingSignInComponents"}}}, +"CheckoutAndAccountsConfigurationBrandingSignInSurfaceInput":{"i":{"components":"CheckoutAndAccountsConfigurationBrandingSignInComponentsInput"}}, +"CheckoutAndAccountsConfigurationBrandingSimpleBorder":{"e":["NONE","FULL"]}, +"CheckoutAndAccountsConfigurationBrandingSpacing":{"e":["NONE","EXTRA_TIGHT","TIGHT","BASE","LOOSE","EXTRA_LOOSE"]}, +"CheckoutAndAccountsConfigurationBrandingSpacingKeyword":{"e":["NONE","BASE","SMALL","SMALL_100","SMALL_200","SMALL_300","SMALL_400","SMALL_500","LARGE","LARGE_100","LARGE_200","LARGE_300","LARGE_400","LARGE_500"]}, +"CheckoutAndAccountsConfigurationBrandingSurfaces":{"o":{"f":{"checkout":"CheckoutAndAccountsConfigurationBrandingCheckoutSurface","customerAccounts":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsSurface","signIn":"CheckoutAndAccountsConfigurationBrandingSignInSurface"}}}, +"CheckoutAndAccountsConfigurationBrandingSurfacesInput":{"i":{"checkout":"CheckoutAndAccountsConfigurationBrandingCheckoutSurfaceInput","customerAccounts":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsSurfaceInput","signIn":"CheckoutAndAccountsConfigurationBrandingSignInSurfaceInput"}}, +"CheckoutAndAccountsConfigurationBrandingTextField":{"o":{"f":{"border":"CheckoutAndAccountsConfigurationBrandingBorder","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyle"}}}, +"CheckoutAndAccountsConfigurationBrandingTextFieldInput":{"i":{"border":"CheckoutAndAccountsConfigurationBrandingBorder","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput"}}, +"CheckoutAndAccountsConfigurationBrandingTypography":{"o":{"f":{"primary":"CheckoutAndAccountsConfigurationBrandingFontGroup","secondary":"CheckoutAndAccountsConfigurationBrandingFontGroup","size":"CheckoutAndAccountsConfigurationBrandingFontSize"}}}, +"CheckoutAndAccountsConfigurationBrandingTypographyFont":{"e":["PRIMARY","SECONDARY"]}, +"CheckoutAndAccountsConfigurationBrandingTypographyInput":{"i":{"primary":"CheckoutAndAccountsConfigurationBrandingFontGroupInput","secondary":"CheckoutAndAccountsConfigurationBrandingFontGroupInput","size":"CheckoutAndAccountsConfigurationBrandingFontSizeInput"}}, +"CheckoutAndAccountsConfigurationBrandingTypographyKerning":{"e":["BASE","LOOSE","EXTRA_LOOSE"]}, +"CheckoutAndAccountsConfigurationBrandingTypographyLetterCase":{"e":["LOWER","NONE","TITLE","UPPER"]}, +"CheckoutAndAccountsConfigurationBrandingTypographySize":{"e":["EXTRA_SMALL","SMALL","BASE","MEDIUM","LARGE","EXTRA_LARGE","EXTRA_EXTRA_LARGE"]}, +"CheckoutAndAccountsConfigurationBrandingTypographyStyle":{"o":{"f":{"font":"CheckoutAndAccountsConfigurationBrandingTypographyFont","kerning":"CheckoutAndAccountsConfigurationBrandingTypographyKerning","letterCase":"CheckoutAndAccountsConfigurationBrandingTypographyLetterCase","size":"CheckoutAndAccountsConfigurationBrandingTypographySize","weight":"CheckoutAndAccountsConfigurationBrandingTypographyWeight"}}}, +"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput":{"i":{"font":"CheckoutAndAccountsConfigurationBrandingTypographyFont","kerning":"CheckoutAndAccountsConfigurationBrandingTypographyKerning","letterCase":"CheckoutAndAccountsConfigurationBrandingTypographyLetterCase","size":"CheckoutAndAccountsConfigurationBrandingTypographySize","weight":"CheckoutAndAccountsConfigurationBrandingTypographyWeight"}}, +"CheckoutAndAccountsConfigurationBrandingTypographyWeight":{"e":["BASE","BOLD"]}, +"CheckoutAndAccountsConfigurationBrandingVisibility":{"e":["HIDDEN","VISIBLE"]}, +"CheckoutAndAccountsConfigurationConnection":{"o":{"f":{"edges":"[CheckoutAndAccountsConfigurationEdge!]!","nodes":"[CheckoutAndAccountsConfiguration!]!","pageInfo":"PageInfo!"}}}, +"CheckoutAndAccountsConfigurationEdge":{"o":{"f":{"cursor":"String!","node":"CheckoutAndAccountsConfiguration!"}}}, +"CheckoutAndAccountsConfigurationInput":{"i":{"branding":"CheckoutAndAccountsConfigurationBrandingInput","overrides":"[CheckoutAndAccountsConfigurationOverrideInput!]"}}, +"CheckoutAndAccountsConfigurationInterface":{"n":{"f":{"branding":"CheckoutAndAccountsConfigurationBranding","createdAt":"DateTime!","editedAt":"DateTime!","name":"String!","updatedAt":"DateTime!"},"t":["CheckoutAndAccountsConfiguration","CheckoutAndAccountsConfigurationOverride"]}}, +"CheckoutAndAccountsConfigurationOverride":{"o":{"f":{"branding":"CheckoutAndAccountsConfigurationBranding","createdAt":"DateTime!","editedAt":"DateTime!","id":"ID!","name":"String!","updatedAt":"DateTime!"},"t":["CheckoutAndAccountsConfigurationInterface","Node"]}}, +"CheckoutAndAccountsConfigurationOverrideInput":{"i":{"branding":"CheckoutAndAccountsConfigurationBrandingInput","id":"ID"}}, +"CheckoutAndAccountsConfigurationUpdatePayload":{"o":{"f":{"configuration":"CheckoutAndAccountsConfiguration","userErrors":"[CheckoutAndAccountsConfigurationUserError!]!"}}}, +"CheckoutAndAccountsConfigurationUserError":{"o":{"f":{"code":"CheckoutAndAccountsConfigurationUserErrorCode","field":"[String!]","message":"String!","reason":"String!"},"t":["DisplayableError"]}}, +"CheckoutAndAccountsConfigurationUserErrorCode":{"e":["INVALID","BLANK","INTERNAL_SERVER_ERROR","MISSING","NOT_FOUND","TRANSIENT"]}, +"CheckoutAndAccountsConfigurationsGraphQLSortKeys":{"e":["CREATED_AT","EDITED_AT","ID","IS_PUBLISHED"]}, +"CheckoutBranding":{"o":{"f":{"customizations":"CheckoutBrandingCustomizations","designSystem":"CheckoutBrandingDesignSystem"}}}, +"CheckoutBrandingBackground":{"e":["BASE","SUBDUED","TRANSPARENT"]}, +"CheckoutBrandingBackgroundStyle":{"e":["SOLID","NONE"]}, +"CheckoutBrandingBorder":{"e":["NONE","BLOCK_END","FULL"]}, +"CheckoutBrandingBorderStyle":{"e":["BASE","DASHED","DOTTED"]}, +"CheckoutBrandingBorderWidth":{"e":["BASE","LARGE_100","LARGE_200","LARGE"]}, +"CheckoutBrandingButton":{"o":{"f":{"background":"CheckoutBrandingBackgroundStyle","blockPadding":"CheckoutBrandingSpacing","border":"CheckoutBrandingSimpleBorder","cornerRadius":"CheckoutBrandingCornerRadius","inlinePadding":"CheckoutBrandingSpacing","typography":"CheckoutBrandingTypographyStyle"}}}, +"CheckoutBrandingButtonColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutBrandingColorRoles","icon":"String","text":"String"}}}, +"CheckoutBrandingButtonColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutBrandingColorRolesInput","icon":"String","text":"String"}}, +"CheckoutBrandingButtonInput":{"i":{"background":"CheckoutBrandingBackgroundStyle","blockPadding":"CheckoutBrandingSpacing","border":"CheckoutBrandingSimpleBorder","cornerRadius":"CheckoutBrandingCornerRadius","inlinePadding":"CheckoutBrandingSpacing","typography":"CheckoutBrandingTypographyStyleInput"}}, +"CheckoutBrandingBuyerJourney":{"o":{"f":{"visibility":"CheckoutBrandingVisibility"}}}, +"CheckoutBrandingBuyerJourneyInput":{"i":{"visibility":"CheckoutBrandingVisibility"}}, +"CheckoutBrandingCartLink":{"o":{"f":{"visibility":"CheckoutBrandingVisibility"}}}, +"CheckoutBrandingCartLinkContentType":{"e":["ICON","IMAGE","TEXT"]}, +"CheckoutBrandingCartLinkInput":{"i":{"visibility":"CheckoutBrandingVisibility"}}, +"CheckoutBrandingCheckbox":{"o":{"f":{"cornerRadius":"CheckoutBrandingCornerRadius"}}}, +"CheckoutBrandingCheckboxInput":{"i":{"cornerRadius":"CheckoutBrandingCornerRadius"}}, +"CheckoutBrandingChoiceList":{"o":{"f":{"group":"CheckoutBrandingChoiceListGroup"}}}, +"CheckoutBrandingChoiceListGroup":{"o":{"f":{"spacing":"CheckoutBrandingSpacingKeyword"}}}, +"CheckoutBrandingChoiceListGroupInput":{"i":{"spacing":"CheckoutBrandingSpacingKeyword"}}, +"CheckoutBrandingChoiceListInput":{"i":{"group":"CheckoutBrandingChoiceListGroupInput"}}, +"CheckoutBrandingColorGlobal":{"o":{"f":{"accent":"String","brand":"String","critical":"String","decorative":"String","info":"String","success":"String","warning":"String"}}}, +"CheckoutBrandingColorGlobalInput":{"i":{"accent":"String","brand":"String","critical":"String","decorative":"String","info":"String","success":"String","warning":"String"}}, +"CheckoutBrandingColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}}, +"CheckoutBrandingColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}, +"CheckoutBrandingColorScheme":{"o":{"f":{"base":"CheckoutBrandingColorRoles","control":"CheckoutBrandingControlColorRoles","primaryButton":"CheckoutBrandingButtonColorRoles","secondaryButton":"CheckoutBrandingButtonColorRoles"}}}, +"CheckoutBrandingColorSchemeInput":{"i":{"base":"CheckoutBrandingColorRolesInput","control":"CheckoutBrandingControlColorRolesInput","primaryButton":"CheckoutBrandingButtonColorRolesInput","secondaryButton":"CheckoutBrandingButtonColorRolesInput"}}, +"CheckoutBrandingColorSchemeSelection":{"e":["TRANSPARENT","COLOR_SCHEME1","COLOR_SCHEME2","COLOR_SCHEME3","COLOR_SCHEME4","COLOR_SCHEME5","COLOR_SCHEME6"]}, +"CheckoutBrandingColorSchemes":{"o":{"f":{"scheme1":"CheckoutBrandingColorScheme","scheme2":"CheckoutBrandingColorScheme","scheme3":"CheckoutBrandingColorScheme","scheme4":"CheckoutBrandingColorScheme","scheme5":"CheckoutBrandingColorScheme","scheme6":"CheckoutBrandingColorScheme"}}}, +"CheckoutBrandingColorSchemesInput":{"i":{"scheme1":"CheckoutBrandingColorSchemeInput","scheme2":"CheckoutBrandingColorSchemeInput","scheme3":"CheckoutBrandingColorSchemeInput","scheme4":"CheckoutBrandingColorSchemeInput","scheme5":"CheckoutBrandingColorSchemeInput","scheme6":"CheckoutBrandingColorSchemeInput"}}, +"CheckoutBrandingColorSelection":{"e":["TRANSPARENT"]}, +"CheckoutBrandingColors":{"o":{"f":{"global":"CheckoutBrandingColorGlobal","schemes":"CheckoutBrandingColorSchemes"}}}, +"CheckoutBrandingColorsInput":{"i":{"global":"CheckoutBrandingColorGlobalInput","schemes":"CheckoutBrandingColorSchemesInput"}}, +"CheckoutBrandingContainerDivider":{"o":{"f":{"borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","visibility":"CheckoutBrandingVisibility"}}}, +"CheckoutBrandingContainerDividerInput":{"i":{"borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","visibility":"CheckoutBrandingVisibility"}}, +"CheckoutBrandingContent":{"o":{"f":{"divider":"CheckoutBrandingContainerDivider"}}}, +"CheckoutBrandingContentInput":{"i":{"divider":"CheckoutBrandingContainerDividerInput"}}, +"CheckoutBrandingControl":{"o":{"f":{"border":"CheckoutBrandingSimpleBorder","color":"CheckoutBrandingColorSelection","cornerRadius":"CheckoutBrandingCornerRadius","labelPosition":"CheckoutBrandingLabelPosition"}}}, +"CheckoutBrandingControlColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","selected":"CheckoutBrandingColorRoles","text":"String"}}}, +"CheckoutBrandingControlColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","selected":"CheckoutBrandingColorRolesInput","text":"String"}}, +"CheckoutBrandingControlInput":{"i":{"border":"CheckoutBrandingSimpleBorder","color":"CheckoutBrandingColorSelection","cornerRadius":"CheckoutBrandingCornerRadius","labelPosition":"CheckoutBrandingLabelPosition"}}, +"CheckoutBrandingCornerRadius":{"e":["NONE","SMALL","BASE","LARGE"]}, +"CheckoutBrandingCornerRadiusVariables":{"o":{"f":{"base":"Int","large":"Int","small":"Int"}}}, +"CheckoutBrandingCornerRadiusVariablesInput":{"i":{"base":"Int","large":"Int","small":"Int"}}, +"CheckoutBrandingCustomFont":{"o":{"f":{"genericFileId":"ID","sources":"String","weight":"Int"},"t":["CheckoutBrandingFont"]}}, +"CheckoutBrandingCustomFontGroupInput":{"i":{"base":"CheckoutBrandingCustomFontInput!","bold":"CheckoutBrandingCustomFontInput!","loadingStrategy":"CheckoutBrandingFontLoadingStrategy"}}, +"CheckoutBrandingCustomFontInput":{"i":{"genericFileId":"ID!","weight":"Int!"}}, +"CheckoutBrandingCustomizations":{"o":{"f":{"buyerJourney":"CheckoutBrandingBuyerJourney","cartLink":"CheckoutBrandingCartLink","checkbox":"CheckoutBrandingCheckbox","choiceList":"CheckoutBrandingChoiceList","content":"CheckoutBrandingContent","control":"CheckoutBrandingControl","divider":"CheckoutBrandingDividerStyle","expressCheckout":"CheckoutBrandingExpressCheckout","favicon":"CheckoutBrandingImage","footer":"CheckoutBrandingFooter","global":"CheckoutBrandingGlobal","header":"CheckoutBrandingHeader","headingLevel1":"CheckoutBrandingHeadingLevel","headingLevel2":"CheckoutBrandingHeadingLevel","headingLevel3":"CheckoutBrandingHeadingLevel","main":"CheckoutBrandingMain","merchandiseThumbnail":"CheckoutBrandingMerchandiseThumbnail","orderSummary":"CheckoutBrandingOrderSummary","primaryButton":"CheckoutBrandingButton","secondaryButton":"CheckoutBrandingButton","select":"CheckoutBrandingSelect","textField":"CheckoutBrandingTextField"}}}, +"CheckoutBrandingCustomizationsInput":{"i":{"buyerJourney":"CheckoutBrandingBuyerJourneyInput","cartLink":"CheckoutBrandingCartLinkInput","checkbox":"CheckoutBrandingCheckboxInput","choiceList":"CheckoutBrandingChoiceListInput","content":"CheckoutBrandingContentInput","control":"CheckoutBrandingControlInput","divider":"CheckoutBrandingDividerStyleInput","expressCheckout":"CheckoutBrandingExpressCheckoutInput","favicon":"CheckoutBrandingImageInput","footer":"CheckoutBrandingFooterInput","global":"CheckoutBrandingGlobalInput","header":"CheckoutBrandingHeaderInput","headingLevel1":"CheckoutBrandingHeadingLevelInput","headingLevel2":"CheckoutBrandingHeadingLevelInput","headingLevel3":"CheckoutBrandingHeadingLevelInput","main":"CheckoutBrandingMainInput","merchandiseThumbnail":"CheckoutBrandingMerchandiseThumbnailInput","orderSummary":"CheckoutBrandingOrderSummaryInput","primaryButton":"CheckoutBrandingButtonInput","secondaryButton":"CheckoutBrandingButtonInput","select":"CheckoutBrandingSelectInput","textField":"CheckoutBrandingTextFieldInput"}}, +"CheckoutBrandingDesignSystem":{"o":{"f":{"colors":"CheckoutBrandingColors","cornerRadius":"CheckoutBrandingCornerRadiusVariables","typography":"CheckoutBrandingTypography"}}}, +"CheckoutBrandingDesignSystemInput":{"i":{"colors":"CheckoutBrandingColorsInput","cornerRadius":"CheckoutBrandingCornerRadiusVariablesInput","typography":"CheckoutBrandingTypographyInput"}}, +"CheckoutBrandingDividerStyle":{"o":{"f":{"borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth"}}}, +"CheckoutBrandingDividerStyleInput":{"i":{"borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth"}}, +"CheckoutBrandingExpressCheckout":{"o":{"f":{"button":"CheckoutBrandingExpressCheckoutButton"}}}, +"CheckoutBrandingExpressCheckoutButton":{"o":{"f":{"cornerRadius":"CheckoutBrandingCornerRadius"}}}, +"CheckoutBrandingExpressCheckoutButtonInput":{"i":{"cornerRadius":"CheckoutBrandingCornerRadius"}}, +"CheckoutBrandingExpressCheckoutInput":{"i":{"button":"CheckoutBrandingExpressCheckoutButtonInput"}}, +"CheckoutBrandingFont":{"n":{"f":{"sources":"String","weight":"Int"},"t":["CheckoutBrandingCustomFont","CheckoutBrandingShopifyFont"]}}, +"CheckoutBrandingFontGroup":{"o":{"f":{"base":"CheckoutBrandingFont","bold":"CheckoutBrandingFont","loadingStrategy":"CheckoutBrandingFontLoadingStrategy","name":"String"}}}, +"CheckoutBrandingFontGroupInput":{"i":{"customFontGroup":"CheckoutBrandingCustomFontGroupInput","shopifyFontGroup":"CheckoutBrandingShopifyFontGroupInput"}}, +"CheckoutBrandingFontLoadingStrategy":{"e":["AUTO","BLOCK","SWAP","FALLBACK","OPTIONAL"]}, +"CheckoutBrandingFontSize":{"o":{"f":{"base":"Float","ratio":"Float"}}}, +"CheckoutBrandingFontSizeInput":{"i":{"base":"Float","ratio":"Float"}}, +"CheckoutBrandingFooter":{"o":{"f":{"alignment":"CheckoutBrandingFooterAlignment","colorScheme":"CheckoutBrandingColorSchemeSelection","content":"CheckoutBrandingFooterContent","divided":"Boolean","padding":"CheckoutBrandingSpacingKeyword","position":"CheckoutBrandingFooterPosition"}}}, +"CheckoutBrandingFooterAlignment":{"e":["START","CENTER","END"]}, +"CheckoutBrandingFooterContent":{"o":{"f":{"visibility":"CheckoutBrandingVisibility"}}}, +"CheckoutBrandingFooterContentInput":{"i":{"visibility":"CheckoutBrandingVisibility"}}, +"CheckoutBrandingFooterInput":{"i":{"alignment":"CheckoutBrandingFooterAlignment","colorScheme":"CheckoutBrandingColorSchemeSelection","content":"CheckoutBrandingFooterContentInput","divided":"Boolean","padding":"CheckoutBrandingSpacingKeyword","position":"CheckoutBrandingFooterPosition"}}, +"CheckoutBrandingFooterPosition":{"e":["END","INLINE"]}, +"CheckoutBrandingGlobal":{"o":{"f":{"cornerRadius":"CheckoutBrandingGlobalCornerRadius","typography":"CheckoutBrandingTypographyStyleGlobal"}}}, +"CheckoutBrandingGlobalCornerRadius":{"e":["NONE"]}, +"CheckoutBrandingGlobalInput":{"i":{"cornerRadius":"CheckoutBrandingGlobalCornerRadius","typography":"CheckoutBrandingTypographyStyleGlobalInput"}}, +"CheckoutBrandingHeader":{"o":{"f":{"alignment":"CheckoutBrandingHeaderAlignment","banner":"CheckoutBrandingImage","cartLink":"CheckoutBrandingHeaderCartLink","colorScheme":"CheckoutBrandingColorSchemeSelection","divided":"Boolean","logo":"CheckoutBrandingLogo","padding":"CheckoutBrandingSpacingKeyword","position":"CheckoutBrandingHeaderPosition"}}}, +"CheckoutBrandingHeaderAlignment":{"e":["START","CENTER","END"]}, +"CheckoutBrandingHeaderCartLink":{"o":{"f":{"contentType":"CheckoutBrandingCartLinkContentType","image":"Image"}}}, +"CheckoutBrandingHeaderCartLinkInput":{"i":{"contentType":"CheckoutBrandingCartLinkContentType","image":"CheckoutBrandingImageInput"}}, +"CheckoutBrandingHeaderInput":{"i":{"alignment":"CheckoutBrandingHeaderAlignment","banner":"CheckoutBrandingImageInput","cartLink":"CheckoutBrandingHeaderCartLinkInput","colorScheme":"CheckoutBrandingColorSchemeSelection","divided":"Boolean","logo":"CheckoutBrandingLogoInput","padding":"CheckoutBrandingSpacingKeyword","position":"CheckoutBrandingHeaderPosition"}}, +"CheckoutBrandingHeaderPosition":{"e":["INLINE","INLINE_SECONDARY","START"]}, +"CheckoutBrandingHeadingLevel":{"o":{"f":{"typography":"CheckoutBrandingTypographyStyle"}}}, +"CheckoutBrandingHeadingLevelInput":{"i":{"typography":"CheckoutBrandingTypographyStyleInput"}}, +"CheckoutBrandingImage":{"o":{"f":{"image":"Image"}}}, +"CheckoutBrandingImageInput":{"i":{"mediaImageId":"ID"}}, +"CheckoutBrandingInput":{"i":{"customizations":"CheckoutBrandingCustomizationsInput","designSystem":"CheckoutBrandingDesignSystemInput"}}, +"CheckoutBrandingLabelPosition":{"e":["INSIDE","OUTSIDE"]}, +"CheckoutBrandingLogo":{"o":{"f":{"image":"Image","maxWidth":"Int","visibility":"CheckoutBrandingVisibility"}}}, +"CheckoutBrandingLogoInput":{"i":{"image":"CheckoutBrandingImageInput","maxWidth":"Int","visibility":"CheckoutBrandingVisibility"}}, +"CheckoutBrandingMain":{"o":{"f":{"backgroundImage":"CheckoutBrandingImage","colorScheme":"CheckoutBrandingColorSchemeSelection","divider":"CheckoutBrandingContainerDivider","section":"CheckoutBrandingMainSection"}}}, +"CheckoutBrandingMainInput":{"i":{"backgroundImage":"CheckoutBrandingImageInput","colorScheme":"CheckoutBrandingColorSchemeSelection","divider":"CheckoutBrandingContainerDividerInput","section":"CheckoutBrandingMainSectionInput"}}, +"CheckoutBrandingMainSection":{"o":{"f":{"background":"CheckoutBrandingBackground","border":"CheckoutBrandingSimpleBorder","borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","colorScheme":"CheckoutBrandingColorSchemeSelection","cornerRadius":"CheckoutBrandingCornerRadius","padding":"CheckoutBrandingSpacingKeyword","shadow":"CheckoutBrandingShadow"}}}, +"CheckoutBrandingMainSectionInput":{"i":{"background":"CheckoutBrandingBackground","border":"CheckoutBrandingSimpleBorder","borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","colorScheme":"CheckoutBrandingColorSchemeSelection","cornerRadius":"CheckoutBrandingCornerRadius","padding":"CheckoutBrandingSpacingKeyword","shadow":"CheckoutBrandingShadow"}}, +"CheckoutBrandingMerchandiseThumbnail":{"o":{"f":{"badge":"CheckoutBrandingMerchandiseThumbnailBadge","border":"CheckoutBrandingSimpleBorder","cornerRadius":"CheckoutBrandingCornerRadius","fit":"CheckoutBrandingObjectFit"}}}, +"CheckoutBrandingMerchandiseThumbnailBadge":{"o":{"f":{"background":"CheckoutBrandingMerchandiseThumbnailBadgeBackground"}}}, +"CheckoutBrandingMerchandiseThumbnailBadgeBackground":{"e":["ACCENT","BASE"]}, +"CheckoutBrandingMerchandiseThumbnailBadgeInput":{"i":{"background":"CheckoutBrandingMerchandiseThumbnailBadgeBackground"}}, +"CheckoutBrandingMerchandiseThumbnailInput":{"i":{"badge":"CheckoutBrandingMerchandiseThumbnailBadgeInput","border":"CheckoutBrandingSimpleBorder","cornerRadius":"CheckoutBrandingCornerRadius","fit":"CheckoutBrandingObjectFit"}}, +"CheckoutBrandingObjectFit":{"e":["CONTAIN","COVER"]}, +"CheckoutBrandingOrderSummary":{"o":{"f":{"backgroundImage":"CheckoutBrandingImage","colorScheme":"CheckoutBrandingColorSchemeSelection","divider":"CheckoutBrandingContainerDivider","section":"CheckoutBrandingOrderSummarySection"}}}, +"CheckoutBrandingOrderSummaryInput":{"i":{"backgroundImage":"CheckoutBrandingImageInput","colorScheme":"CheckoutBrandingColorSchemeSelection","divider":"CheckoutBrandingContainerDividerInput","section":"CheckoutBrandingOrderSummarySectionInput"}}, +"CheckoutBrandingOrderSummarySection":{"o":{"f":{"background":"CheckoutBrandingBackground","border":"CheckoutBrandingSimpleBorder","borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","colorScheme":"CheckoutBrandingColorSchemeSelection","cornerRadius":"CheckoutBrandingCornerRadius","padding":"CheckoutBrandingSpacingKeyword","shadow":"CheckoutBrandingShadow"}}}, +"CheckoutBrandingOrderSummarySectionInput":{"i":{"background":"CheckoutBrandingBackground","border":"CheckoutBrandingSimpleBorder","borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","colorScheme":"CheckoutBrandingColorSchemeSelection","cornerRadius":"CheckoutBrandingCornerRadius","padding":"CheckoutBrandingSpacingKeyword","shadow":"CheckoutBrandingShadow"}}, +"CheckoutBrandingSelect":{"o":{"f":{"border":"CheckoutBrandingBorder","typography":"CheckoutBrandingTypographyStyle"}}}, +"CheckoutBrandingSelectInput":{"i":{"border":"CheckoutBrandingBorder","typography":"CheckoutBrandingTypographyStyleInput"}}, +"CheckoutBrandingShadow":{"e":["SMALL_200","SMALL_100","BASE","LARGE_100","LARGE_200"]}, +"CheckoutBrandingShopifyFont":{"o":{"f":{"sources":"String","weight":"Int"},"t":["CheckoutBrandingFont"]}}, +"CheckoutBrandingShopifyFontGroupInput":{"i":{"baseWeight":"Int","boldWeight":"Int","loadingStrategy":"CheckoutBrandingFontLoadingStrategy","name":"String!"}}, +"CheckoutBrandingSimpleBorder":{"e":["NONE","FULL"]}, +"CheckoutBrandingSpacing":{"e":["NONE","EXTRA_TIGHT","TIGHT","BASE","LOOSE","EXTRA_LOOSE"]}, +"CheckoutBrandingSpacingKeyword":{"e":["NONE","BASE","SMALL","SMALL_100","SMALL_200","SMALL_300","SMALL_400","SMALL_500","LARGE","LARGE_100","LARGE_200","LARGE_300","LARGE_400","LARGE_500"]}, +"CheckoutBrandingTextField":{"o":{"f":{"border":"CheckoutBrandingBorder","typography":"CheckoutBrandingTypographyStyle"}}}, +"CheckoutBrandingTextFieldInput":{"i":{"border":"CheckoutBrandingBorder","typography":"CheckoutBrandingTypographyStyleInput"}}, +"CheckoutBrandingTypography":{"o":{"f":{"primary":"CheckoutBrandingFontGroup","secondary":"CheckoutBrandingFontGroup","size":"CheckoutBrandingFontSize"}}}, +"CheckoutBrandingTypographyFont":{"e":["PRIMARY","SECONDARY"]}, +"CheckoutBrandingTypographyInput":{"i":{"primary":"CheckoutBrandingFontGroupInput","secondary":"CheckoutBrandingFontGroupInput","size":"CheckoutBrandingFontSizeInput"}}, +"CheckoutBrandingTypographyKerning":{"e":["BASE","LOOSE","EXTRA_LOOSE"]}, +"CheckoutBrandingTypographyLetterCase":{"e":["LOWER","NONE","TITLE","UPPER"]}, +"CheckoutBrandingTypographySize":{"e":["EXTRA_SMALL","SMALL","BASE","MEDIUM","LARGE","EXTRA_LARGE","EXTRA_EXTRA_LARGE"]}, +"CheckoutBrandingTypographyStyle":{"o":{"f":{"font":"CheckoutBrandingTypographyFont","kerning":"CheckoutBrandingTypographyKerning","letterCase":"CheckoutBrandingTypographyLetterCase","size":"CheckoutBrandingTypographySize","weight":"CheckoutBrandingTypographyWeight"}}}, +"CheckoutBrandingTypographyStyleGlobal":{"o":{"f":{"kerning":"CheckoutBrandingTypographyKerning","letterCase":"CheckoutBrandingTypographyLetterCase"}}}, +"CheckoutBrandingTypographyStyleGlobalInput":{"i":{"kerning":"CheckoutBrandingTypographyKerning","letterCase":"CheckoutBrandingTypographyLetterCase"}}, +"CheckoutBrandingTypographyStyleInput":{"i":{"font":"CheckoutBrandingTypographyFont","kerning":"CheckoutBrandingTypographyKerning","letterCase":"CheckoutBrandingTypographyLetterCase","size":"CheckoutBrandingTypographySize","weight":"CheckoutBrandingTypographyWeight"}}, +"CheckoutBrandingTypographyWeight":{"e":["BASE","BOLD"]}, +"CheckoutBrandingUpsertPayload":{"o":{"f":{"checkoutBranding":"CheckoutBranding","userErrors":"[CheckoutBrandingUpsertUserError!]!"}}}, +"CheckoutBrandingUpsertUserError":{"o":{"f":{"code":"CheckoutBrandingUpsertUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CheckoutBrandingUpsertUserErrorCode":{"e":["INTERNAL_ERROR"]}, +"CheckoutBrandingVisibility":{"e":["HIDDEN","VISIBLE"]}, +"CheckoutProfile":{"o":{"f":{"createdAt":"DateTime!","editedAt":"DateTime!","id":"ID!","isPublished":"Boolean!","name":"String!","typOspPagesActive":"Boolean!","updatedAt":"DateTime!"},"t":["Node"]}}, +"CheckoutProfileConnection":{"o":{"f":{"edges":"[CheckoutProfileEdge!]!","nodes":"[CheckoutProfile!]!","pageInfo":"PageInfo!"}}}, +"CheckoutProfileEdge":{"o":{"f":{"cursor":"String!","node":"CheckoutProfile!"}}}, +"CheckoutProfileSortKeys":{"e":["CREATED_AT","EDITED_AT","ID","IS_PUBLISHED","UPDATED_AT"]}, +"ChildProductRelationInput":{"i":{"childProductId":"ID!","selectedParentOptionValues":"[SelectedVariantOptionInput!]!"}}, +"CodeDiscountSortKeys":{"e":["CREATED_AT","ENDS_AT","ID","RELEVANCE","STARTS_AT","TITLE","UPDATED_AT"]}, +"Collection":{"o":{"f":{"activeOperations":"CollectionOperations!","availablePublicationsCount":"Count","createdAt":"DateTime!","description":["String!",{"truncateAt":"Int"}],"descriptionHtml":"HTML!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"feedback":"ResourceFeedback","handle":"String!","hasProduct":["Boolean!",{"id":"ID!"}],"id":"ID!","image":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"legacyResourceId":"UnsignedInt64!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"ProductCollectionSortKeys="}],"productsCount":"Count","publicationCount":["Int!",{"onlyPublished":"Boolean="}],"publications":["CollectionPublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"publishedOnChannel":["Boolean!",{"channelId":"ID!"}],"publishedOnCurrentChannel":"Boolean!","publishedOnCurrentPublication":"Boolean!","publishedOnPublication":["Boolean!",{"publicationId":"ID!"}],"resourcePublications":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"resourcePublicationsCount":["Count",{"onlyPublished":"Boolean="}],"resourcePublicationsV2":["ResourcePublicationV2Connection!",{"after":"String","before":"String","catalogType":"CatalogType","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"ruleSet":"CollectionRuleSet","seo":"SEO!","sortOrder":"CollectionSortOrder!","sources":"[CollectionSource!]!","storefrontId":"StorefrontID!","subCollectionEligibility":"CollectionSubCollectionEligibility!","templateSuffix":"String","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"unpublishedChannels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unpublishedPublications":["PublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Node","Publishable"],"d":{"image(crop)":"Use `Image.url(transform: { crop:})` instead.","image(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","image(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","image(scale)":"Use `Image.url(transform: { scale:})` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","publicationCount":"Use `resourcePublicationsCount` instead.","publications":"Use `resourcePublications` instead.","publishedOnChannel":"Use `publishedOnPublication` instead.","publishedOnCurrentChannel":"Use `publishedOnCurrentPublication` instead.","publishedOnCurrentPublication":"Use `publishedOnPublication` instead.","ruleSet":"Use `sources` instead.","storefrontId":"Use `id` instead.","unpublishedChannels":"Use `unpublishedPublications` instead."}}}, +"CollectionAddProductsPayload":{"o":{"f":{"collection":"Collection","userErrors":"[UserError!]!"}}}, +"CollectionAddProductsV2Payload":{"o":{"f":{"job":"Job","userErrors":"[CollectionAddProductsV2UserError!]!"}}}, +"CollectionAddProductsV2UserError":{"o":{"f":{"code":"CollectionAddProductsV2UserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CollectionAddProductsV2UserErrorCode":{"e":["CANT_ADD_TO_SMART_COLLECTION","COLLECTION_DOES_NOT_EXIST"]}, +"CollectionConditionBasicMetafieldDefinition":{"o":{"f":{"description":"String","id":"ID!","key":"String!","name":"String!","namespace":"String!","ownerType":"MetafieldOwnerType!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!"},"t":["CollectionConditionMetafieldDefinitionInterface"]}}, +"CollectionConditionMatchType":{"e":["ANY","ALL"]}, +"CollectionConditionMetafieldDefinitionInterface":{"n":{"f":{"description":"String","id":"ID!","key":"String!","name":"String!","namespace":"String!","ownerType":"MetafieldOwnerType!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!"},"t":["CollectionConditionBasicMetafieldDefinition","CollectionConditionMetaobjectMetafieldDefinition"]}}, +"CollectionConditionMetaobjectMetafieldDefinition":{"o":{"f":{"description":"String","id":"ID!","key":"String!","metaobjectDefinition":"MetaobjectDefinition!","name":"String!","namespace":"String!","ownerType":"MetafieldOwnerType!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!"},"t":["CollectionConditionMetafieldDefinitionInterface"]}}, +"CollectionConditionsSource":{"o":{"f":{"app":"App","description":"String","exclusion":"CollectionSourceExclusion","id":"ID!","inclusion":"CollectionSourceInclusion!","products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"shareable":"Boolean!","targetType":"CollectionSourceTargetType!","title":"String!"},"t":["CollectionSource","Node"]}}, +"CollectionConditionsSourceConnection":{"o":{"f":{"edges":"[CollectionConditionsSourceEdge!]!","nodes":"[CollectionConditionsSource!]!","pageInfo":"PageInfo!"}}}, +"CollectionConditionsSourceCreatePayload":{"o":{"f":{"source":"CollectionConditionsSource","userErrors":"[UserError!]!"}}}, +"CollectionConditionsSourceDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[UserError!]!"}}}, +"CollectionConditionsSourceEdge":{"o":{"f":{"cursor":"String!","node":"CollectionConditionsSource!"}}}, +"CollectionConditionsSourceSortKeys":{"e":["ID","TITLE"]}, +"CollectionConditionsSourceUpdatePayload":{"o":{"f":{"source":"CollectionConditionsSource","userErrors":"[UserError!]!"}}}, +"CollectionConditionsSourcesByApp":{"o":{"f":{"app":"App!","sources":["CollectionConditionsSourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"CollectionConditionsSourceSortKeys="}]}}}, +"CollectionConditionsSourcesByAppConnection":{"o":{"f":{"edges":"[CollectionConditionsSourcesByAppEdge!]!","nodes":"[CollectionConditionsSourcesByApp!]!","pageInfo":"PageInfo!"}}}, +"CollectionConditionsSourcesByAppEdge":{"o":{"f":{"cursor":"String!","node":"CollectionConditionsSourcesByApp!"}}}, +"CollectionConnection":{"o":{"f":{"edges":"[CollectionEdge!]!","nodes":"[Collection!]!","pageInfo":"PageInfo!"}}}, +"CollectionCreateConditionsSourceInput":{"i":{"description":"String","exclusion":"CollectionCreateSourceExclusionInput","inclusion":"CollectionCreateSourceInclusionInput","targetType":"CollectionSourceTargetType=","title":"String!"}}, +"CollectionCreateInput":{"i":{"descriptionHtml":"String","handle":"String","image":"ImageInput","metafields":"[MetafieldInput!]","seo":"SEOInput","sortOrder":"CollectionSortOrder","sources":"[CollectionCreateSourceTargetInput!]","templateSuffix":"String","title":"String!"}}, +"CollectionCreatePayload":{"o":{"f":{"collection":"Collection","userErrors":"[UserError!]!"}}}, +"CollectionCreateSourceExclusionInput":{"i":{"conditions":"[CollectionSourceExclusionConditionInput!]=","matchType":"CollectionConditionMatchType","selections":"[CollectionExclusionProductSelectionInput!]="}}, +"CollectionCreateSourceInclusionInput":{"i":{"conditions":"[CollectionSourceInclusionConditionInput!]=","matchType":"CollectionConditionMatchType","selections":"[CollectionInclusionProductSelectionInput!]="}}, +"CollectionCreateSourceTargetInput":{"i":{"shareableSource":"CollectionShareableSourceInput","source":"CollectionCreateConditionsSourceInput","subCollections":"CollectionCreateSubCollectionsSourceInput"}}, +"CollectionCreateSubCollectionsSourceInput":{"i":{"collectionIds":"[ID!]!","description":"String","title":"String!"}}, +"CollectionDeleteInput":{"i":{"id":"ID!"}}, +"CollectionDeletePayload":{"o":{"f":{"deletedCollectionId":"ID","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"CollectionDuplicateInput":{"i":{"collectionId":"ID!","copyPublications":"Boolean=","newTitle":"String!"}}, +"CollectionDuplicateOperation":{"o":{"f":{"collectionRole":"CollectionDuplicateOperationRole!","job":"Job!"}}}, +"CollectionDuplicateOperationRole":{"e":["SOURCE","TARGET"]}, +"CollectionDuplicatePayload":{"o":{"f":{"collection":"Collection","job":"Job","userErrors":"[CollectionDuplicateUserError!]!"}}}, +"CollectionDuplicateUserError":{"o":{"f":{"code":"CollectionDuplicateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CollectionDuplicateUserErrorCode":{"e":["COLLECTION_NOT_FOUND","BLANK","TOO_LONG","TAKEN","INVALID","TOO_MANY_SUB_COLLECTION_INCLUSION_COLLECTIONS","TOO_MANY_SUB_COLLECTION_EXCLUSION_COLLECTIONS","TOO_MANY_CONDITION_BACKED_SOURCES"]}, +"CollectionEdge":{"o":{"f":{"cursor":"String!","node":"Collection!"}}}, +"CollectionExclusionProductSelection":{"o":{"f":{"product":"Product!"}}}, +"CollectionExclusionProductSelectionConnection":{"o":{"f":{"edges":"[CollectionExclusionProductSelectionEdge!]!","nodes":"[CollectionExclusionProductSelection!]!","pageInfo":"PageInfo!"}}}, +"CollectionExclusionProductSelectionEdge":{"o":{"f":{"cursor":"String!","node":"CollectionExclusionProductSelection!"}}}, +"CollectionExclusionProductSelectionInput":{"i":{"productId":"ID!"}}, +"CollectionIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"}}, +"CollectionInclusionProductSelection":{"o":{"f":{"product":"Product!","variantIds":"[ID!]"}}}, +"CollectionInclusionProductSelectionConnection":{"o":{"f":{"edges":"[CollectionInclusionProductSelectionEdge!]!","nodes":"[CollectionInclusionProductSelection!]!","pageInfo":"PageInfo!"}}}, +"CollectionInclusionProductSelectionEdge":{"o":{"f":{"cursor":"String!","node":"CollectionInclusionProductSelection!"}}}, +"CollectionInclusionProductSelectionInput":{"i":{"productId":"ID!","variantIds":"[ID!]"}}, +"CollectionInput":{"i":{"f":{"descriptionHtml":"String","handle":"String","id":"ID","image":"ImageInput","metafields":"[MetafieldInput!]","products":"[ID!]","publications":"[CollectionPublicationInput!]","redirectNewHandle":"Boolean=","ruleSet":"CollectionRuleSetInput","seo":"SEOInput","sortOrder":"CollectionSortOrder","templateSuffix":"String","title":"String"},"d":{"publications":"Use PublishablePublish instead."}}}, +"CollectionOperations":{"o":{"f":{"duplicate":"[CollectionDuplicateOperation!]!"}}}, +"CollectionPublication":{"o":{"f":{"channel":"Channel!","collection":"Collection!","isPublished":"Boolean!","publication":"Publication!","publishDate":"DateTime!"},"d":{"channel":"Use `publication` instead."}}}, +"CollectionPublicationConnection":{"o":{"f":{"edges":"[CollectionPublicationEdge!]!","nodes":"[CollectionPublication!]!","pageInfo":"PageInfo!"}}}, +"CollectionPublicationEdge":{"o":{"f":{"cursor":"String!","node":"CollectionPublication!"}}}, +"CollectionPublicationInput":{"i":{"f":{"channelHandle":"String","channelId":"ID","publicationId":"ID"},"d":{"channelHandle":"Use publicationId instead.","channelId":"Use publicationId instead."}}}, +"CollectionPublishInput":{"i":{"collectionPublications":"[CollectionPublicationInput!]!","id":"ID!"}}, +"CollectionPublishPayload":{"o":{"f":{"collection":"Collection","collectionPublications":"[CollectionPublication!]","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"CollectionRemoveProductsPayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"CollectionReorderProductsPayload":{"o":{"f":{"job":"Job","userErrors":"[CollectionReorderProductsUserError!]!"}}}, +"CollectionReorderProductsUserError":{"o":{"f":{"code":"CollectionReorderProductsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CollectionReorderProductsUserErrorCode":{"e":["TOO_MANY_ATTEMPTS_TO_REORDER_PRODUCTS","COLLECTION_NOT_FOUND","MANUALLY_SORTED_COLLECTION","INVALID_MOVE"]}, +"CollectionRule":{"o":{"f":{"column":"CollectionRuleColumn!","condition":"String!","conditionObject":"CollectionRuleConditionObject","relation":"CollectionRuleRelation!"}}}, +"CollectionRuleCategoryCondition":{"o":{"f":{"value":"TaxonomyCategory!"}}}, +"CollectionRuleColumn":{"e":["TAG","TITLE","TYPE","PRODUCT_TAXONOMY_NODE_ID","PRODUCT_CATEGORY_ID","PRODUCT_CATEGORY_ID_WITH_DESCENDANTS","VENDOR","VARIANT_PRICE","IS_PRICE_REDUCED","VARIANT_COMPARE_AT_PRICE","VARIANT_WEIGHT","VARIANT_INVENTORY","VARIANT_TITLE","PRODUCT_METAFIELD_DEFINITION","VARIANT_METAFIELD_DEFINITION"]}, +"CollectionRuleConditionObject":{"u":["CollectionRuleCategoryCondition","CollectionRuleMetafieldCondition","CollectionRuleProductCategoryCondition","CollectionRuleTextCondition"]}, +"CollectionRuleConditions":{"o":{"f":{"allowedRelations":"[CollectionRuleRelation!]!","defaultRelation":"CollectionRuleRelation!","ruleObject":"CollectionRuleConditionsRuleObject","ruleType":"CollectionRuleColumn!"}}}, +"CollectionRuleConditionsRuleObject":{"u":["CollectionRuleMetafieldCondition"]}, +"CollectionRuleInput":{"i":{"column":"CollectionRuleColumn!","condition":"String!","conditionObjectId":"ID","relation":"CollectionRuleRelation!"}}, +"CollectionRuleMetafieldCondition":{"o":{"f":{"metafieldDefinition":"MetafieldDefinition!"}}}, +"CollectionRuleProductCategoryCondition":{"o":{"f":{"value":"ProductTaxonomyNode!"}}}, +"CollectionRuleRelation":{"e":["CONTAINS","ENDS_WITH","EQUALS","GREATER_THAN","IS_NOT_SET","IS_SET","LESS_THAN","NOT_CONTAINS","NOT_EQUALS","STARTS_WITH"]}, +"CollectionRuleSet":{"o":{"f":{"appliedDisjunctively":"Boolean!","rules":"[CollectionRule!]!"}}}, +"CollectionRuleSetInput":{"i":{"appliedDisjunctively":"Boolean!","rules":"[CollectionRuleInput!]"}}, +"CollectionRuleTextCondition":{"o":{"f":{"value":"String!"}}}, +"CollectionShareableSourceInput":{"i":{"sourceId":"ID!"}}, +"CollectionSortKeys":{"e":["ID","RELEVANCE","TITLE","UPDATED_AT"]}, +"CollectionSortOrder":{"e":["ALPHA_ASC","ALPHA_DESC","BEST_SELLING","MOST_RELEVANT","CREATED","CREATED_DESC","MANUAL","PRICE_ASC","PRICE_DESC"]}, +"CollectionSource":{"n":{"f":{"app":"App","description":"String","id":"ID!","title":"String!"},"t":["CollectionConditionsSource","CollectionSubCollectionsSource"]}}, +"CollectionSourceExclusion":{"o":{"f":{"conditions":"[CollectionSourceExclusionCondition!]!","matchType":"CollectionConditionMatchType","selections":["CollectionExclusionProductSelectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"CollectionSourceExclusionCondition":{"n":{"f":{"id":"ID!"},"t":["CollectionSourceExclusionConditionCollection","CollectionSourceExclusionConditionProductCategory","CollectionSourceExclusionConditionProductTag","CollectionSourceExclusionConditionProductType","CollectionSourceExclusionConditionProductVendor","CollectionSourceExclusionConditionUnknown"]}}, +"CollectionSourceExclusionConditionCollection":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","values":"[Collection!]!"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionCollectionInput":{"i":{"values":"[ID!]!"}}, +"CollectionSourceExclusionConditionInput":{"i":{"collection":"CollectionSourceExclusionConditionCollectionInput","productCategory":"CollectionSourceExclusionConditionProductCategoryInput","productTag":"CollectionSourceExclusionConditionProductTagInput","productType":"CollectionSourceExclusionConditionProductTypeInput","productVendor":"CollectionSourceExclusionConditionProductVendorInput"}}, +"CollectionSourceExclusionConditionProductCategory":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductCategoryRelation!","values":"[CollectionSourceExclusionConditionProductCategoryValue!]!"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionProductCategoryInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductCategoryRelation!","values":"[CollectionSourceExclusionConditionProductCategoryValueInput!]!"}}, +"CollectionSourceExclusionConditionProductCategoryRelation":{"e":["EQUALS"]}, +"CollectionSourceExclusionConditionProductCategoryValue":{"o":{"f":{"category":"TaxonomyCategory!","includeDescendants":"Boolean!"}}}, +"CollectionSourceExclusionConditionProductCategoryValueInput":{"i":{"categoryId":"ID!","includeDescendants":"Boolean="}}, +"CollectionSourceExclusionConditionProductTag":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductTagRelation!","values":"[String!]!"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionProductTagInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductTagRelation!","values":"[String!]!"}}, +"CollectionSourceExclusionConditionProductTagRelation":{"e":["TAGGED_WITH"]}, +"CollectionSourceExclusionConditionProductType":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductTypeRelation!","values":"[String!]!"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionProductTypeInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductTypeRelation!","values":"[String!]!"}}, +"CollectionSourceExclusionConditionProductTypeRelation":{"e":["EQUALS","CONTAINS"]}, +"CollectionSourceExclusionConditionProductVendor":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductVendorRelation!","values":"[String!]!"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionProductVendorInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductVendorRelation!","values":"[String!]!"}}, +"CollectionSourceExclusionConditionProductVendorRelation":{"e":["EQUALS","CONTAINS"]}, +"CollectionSourceExclusionConditionUnknown":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType","relation":"String","values":"[String!]"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionUpdateCollectionInput":{"i":{"values":"[ID!]!"}}, +"CollectionSourceExclusionConditionUpdateInput":{"i":{"collection":"CollectionSourceExclusionConditionUpdateCollectionInput","productCategory":"CollectionSourceExclusionConditionUpdateProductCategoryInput","productTag":"CollectionSourceExclusionConditionUpdateProductTagInput","productType":"CollectionSourceExclusionConditionUpdateProductTypeInput","productVendor":"CollectionSourceExclusionConditionUpdateProductVendorInput"}}, +"CollectionSourceExclusionConditionUpdateProductCategoryInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductCategoryRelation","values":"[CollectionSourceExclusionConditionProductCategoryValueInput!]"}}, +"CollectionSourceExclusionConditionUpdateProductTagInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductTagRelation","values":"[String!]"}}, +"CollectionSourceExclusionConditionUpdateProductTypeInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductTypeRelation","values":"[String!]"}}, +"CollectionSourceExclusionConditionUpdateProductVendorInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductVendorRelation","values":"[String!]"}}, +"CollectionSourceInclusion":{"o":{"f":{"conditions":"[CollectionSourceInclusionCondition!]!","matchType":"CollectionConditionMatchType","selections":["CollectionInclusionProductSelectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"CollectionSourceInclusionCondition":{"n":{"f":{"id":"ID!"},"t":["CollectionSourceInclusionConditionMetafieldBoolean","CollectionSourceInclusionConditionMetafieldDecimal","CollectionSourceInclusionConditionMetafieldInt","CollectionSourceInclusionConditionMetafieldInteger","CollectionSourceInclusionConditionMetafieldMetaobject","CollectionSourceInclusionConditionMetafieldMetaobjectList","CollectionSourceInclusionConditionMetafieldString","CollectionSourceInclusionConditionMetafieldStringList","CollectionSourceInclusionConditionProductCategory","CollectionSourceInclusionConditionProductStatus","CollectionSourceInclusionConditionProductTag","CollectionSourceInclusionConditionProductTitle","CollectionSourceInclusionConditionProductType","CollectionSourceInclusionConditionProductVendor","CollectionSourceInclusionConditionUnknown","CollectionSourceInclusionConditionVariantCompareAtPrice","CollectionSourceInclusionConditionVariantInventory","CollectionSourceInclusionConditionVariantPrice","CollectionSourceInclusionConditionVariantTitle","CollectionSourceInclusionConditionVariantWeight"]}}, +"CollectionSourceInclusionConditionInput":{"i":{"f":{"metafieldBoolean":"CollectionSourceInclusionConditionMetafieldBooleanInput","metafieldDecimal":"CollectionSourceInclusionConditionMetafieldDecimalInput","metafieldInt":"CollectionSourceInclusionConditionMetafieldIntInput","metafieldInteger":"CollectionSourceInclusionConditionMetafieldIntegerInput","metafieldMetaobject":"CollectionSourceInclusionConditionMetafieldMetaobjectInput","metafieldMetaobjectList":"CollectionSourceInclusionConditionMetafieldMetaobjectListInput","metafieldString":"CollectionSourceInclusionConditionMetafieldStringInput","metafieldStringList":"CollectionSourceInclusionConditionMetafieldStringListInput","productCategory":"CollectionSourceInclusionConditionProductCategoryInput","productStatus":"CollectionSourceInclusionConditionProductStatusInput","productTag":"CollectionSourceInclusionConditionProductTagInput","productTitle":"CollectionSourceInclusionConditionProductTitleInput","productType":"CollectionSourceInclusionConditionProductTypeInput","productVendor":"CollectionSourceInclusionConditionProductVendorInput","variantCompareAtPrice":"CollectionSourceInclusionConditionVariantCompareAtPriceInput","variantInventory":"CollectionSourceInclusionConditionVariantInventoryInput","variantPrice":"CollectionSourceInclusionConditionVariantPriceInput","variantTitle":"CollectionSourceInclusionConditionVariantTitleInput","variantWeight":"CollectionSourceInclusionConditionVariantWeightInput"},"d":{"metafieldInteger":"Use `metafieldInt` instead. Integer metafields support values beyond the range of GraphQL's 32-bit `Int`. Removed as of the 2027-01 release."}}}, +"CollectionSourceInclusionConditionMetafield":{"n":{"f":{"definition":"MetafieldDefinition!","id":"ID!"},"t":["CollectionSourceInclusionConditionMetafieldBoolean","CollectionSourceInclusionConditionMetafieldDecimal","CollectionSourceInclusionConditionMetafieldInt","CollectionSourceInclusionConditionMetafieldInteger","CollectionSourceInclusionConditionMetafieldMetaobject","CollectionSourceInclusionConditionMetafieldMetaobjectList","CollectionSourceInclusionConditionMetafieldString","CollectionSourceInclusionConditionMetafieldStringList"]}}, +"CollectionSourceInclusionConditionMetafieldBoolean":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldBooleanRelation!","value":"Boolean!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldBooleanInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldBooleanRelation!","value":"Boolean!"}}, +"CollectionSourceInclusionConditionMetafieldBooleanRelation":{"e":["EQUALS"]}, +"CollectionSourceInclusionConditionMetafieldDecimal":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldDecimalRelation!","value":"Decimal!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldDecimalInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldDecimalRelation!","value":"Decimal!"}}, +"CollectionSourceInclusionConditionMetafieldDecimalRelation":{"e":["EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceInclusionConditionMetafieldInt":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldIntRelation!","value":"String!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldIntInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldIntRelation!","value":"String!"}}, +"CollectionSourceInclusionConditionMetafieldIntRelation":{"e":["EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceInclusionConditionMetafieldInteger":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldIntegerRelation!","value":"Int!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"],"d":{"relation":"Use `CollectionSourceInclusionConditionMetafieldInt.relation` instead. That type replaces this one entirely and supports integer metafield values beyond the range of GraphQL's 32-bit `Int`.","value":"Use `CollectionSourceInclusionConditionMetafieldInt.value` instead. That type replaces this one entirely and supports integer metafield values beyond the range of GraphQL's 32-bit `Int`."}}}, +"CollectionSourceInclusionConditionMetafieldIntegerInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldIntegerRelation!","value":"Int!"}}, +"CollectionSourceInclusionConditionMetafieldIntegerRelation":{"e":["EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceInclusionConditionMetafieldMetaobject":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectRelation!","value":"Metaobject!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldMetaobjectInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectRelation!","value":"ID!"}}, +"CollectionSourceInclusionConditionMetafieldMetaobjectList":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectListRelation!","values":"[Metaobject!]!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldMetaobjectListInput":{"i":{"definitionId":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectListRelation!","values":"[ID!]!"}}, +"CollectionSourceInclusionConditionMetafieldMetaobjectListRelation":{"e":["INCLUDES"]}, +"CollectionSourceInclusionConditionMetafieldMetaobjectRelation":{"e":["EQUALS"]}, +"CollectionSourceInclusionConditionMetafieldString":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldStringRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldStringInput":{"i":{"definitionId":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldStringRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionMetafieldStringList":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldStringListRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldStringListInput":{"i":{"definitionId":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldStringListRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionMetafieldStringListRelation":{"e":["INCLUDES"]}, +"CollectionSourceInclusionConditionMetafieldStringRelation":{"e":["EQUALS"]}, +"CollectionSourceInclusionConditionProductCategory":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductCategoryRelation!","values":"[CollectionSourceInclusionConditionProductCategoryValue!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductCategoryInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductCategoryRelation!","values":"[CollectionSourceInclusionConditionProductCategoryValueInput!]!"}}, +"CollectionSourceInclusionConditionProductCategoryRelation":{"e":["EQUALS","NOT_EQUALS"]}, +"CollectionSourceInclusionConditionProductCategoryValue":{"o":{"f":{"category":"TaxonomyCategory!","includeDescendants":"Boolean!"}}}, +"CollectionSourceInclusionConditionProductCategoryValueInput":{"i":{"categoryId":"ID!","includeDescendants":"Boolean!"}}, +"CollectionSourceInclusionConditionProductStatus":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductStatusRelation!","values":"[ProductStatus!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductStatusInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductStatusRelation!","values":"[ProductStatus!]!"}}, +"CollectionSourceInclusionConditionProductStatusRelation":{"e":["EQUALS","NOT_EQUALS"]}, +"CollectionSourceInclusionConditionProductTag":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTagRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductTagInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTagRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionProductTagRelation":{"e":["TAGGED_WITH","NOT_TAGGED_WITH"]}, +"CollectionSourceInclusionConditionProductTitle":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTitleRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductTitleInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTitleRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionProductTitleRelation":{"e":["EQUALS","NOT_EQUALS","CONTAINS","DOES_NOT_CONTAIN","STARTS_WITH","ENDS_WITH"]}, +"CollectionSourceInclusionConditionProductType":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTypeRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductTypeInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTypeRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionProductTypeRelation":{"e":["EQUALS","NOT_EQUALS","STARTS_WITH","ENDS_WITH","CONTAINS","DOES_NOT_CONTAIN"]}, +"CollectionSourceInclusionConditionProductVendor":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductVendorRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductVendorInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductVendorRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionProductVendorRelation":{"e":["EQUALS","NOT_EQUALS","STARTS_WITH","ENDS_WITH","CONTAINS","DOES_NOT_CONTAIN"]}, +"CollectionSourceInclusionConditionUnknown":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType","relation":"String","values":"[String!]"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionUpdateInput":{"i":{"f":{"metafieldBoolean":"CollectionSourceInclusionConditionUpdateMetafieldBooleanInput","metafieldDecimal":"CollectionSourceInclusionConditionUpdateMetafieldDecimalInput","metafieldInt":"CollectionSourceInclusionConditionUpdateMetafieldIntInput","metafieldInteger":"CollectionSourceInclusionConditionUpdateMetafieldIntegerInput","metafieldMetaobject":"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectInput","metafieldMetaobjectList":"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectListInput","metafieldString":"CollectionSourceInclusionConditionUpdateMetafieldStringInput","metafieldStringList":"CollectionSourceInclusionConditionUpdateMetafieldStringListInput","productCategory":"CollectionSourceInclusionConditionUpdateProductCategoryInput","productStatus":"CollectionSourceInclusionConditionUpdateProductStatusInput","productTag":"CollectionSourceInclusionConditionUpdateProductTagInput","productTitle":"CollectionSourceInclusionConditionUpdateProductTitleInput","productType":"CollectionSourceInclusionConditionUpdateProductTypeInput","productVendor":"CollectionSourceInclusionConditionUpdateProductVendorInput","variantCompareAtPrice":"CollectionSourceInclusionConditionUpdateVariantCompareAtPriceInput","variantInventory":"CollectionSourceInclusionConditionUpdateVariantInventoryInput","variantPrice":"CollectionSourceInclusionConditionUpdateVariantPriceInput","variantTitle":"CollectionSourceInclusionConditionUpdateVariantTitleInput","variantWeight":"CollectionSourceInclusionConditionUpdateVariantWeightInput"},"d":{"metafieldInteger":"Use `metafieldInt` instead. Integer metafields support values beyond the range of GraphQL's 32-bit `Int`. Removed as of the 2027-01 release."}}}, +"CollectionSourceInclusionConditionUpdateMetafieldBooleanInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldBooleanRelation","value":"Boolean"}}, +"CollectionSourceInclusionConditionUpdateMetafieldDecimalInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldDecimalRelation","value":"Decimal"}}, +"CollectionSourceInclusionConditionUpdateMetafieldIntInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldIntRelation","value":"String"}}, +"CollectionSourceInclusionConditionUpdateMetafieldIntegerInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldIntegerRelation","value":"Int"}}, +"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectRelation","value":"ID"}}, +"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectListInput":{"i":{"definitionId":"ID","matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectListRelation","values":"[ID!]"}}, +"CollectionSourceInclusionConditionUpdateMetafieldStringInput":{"i":{"definitionId":"ID","matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionMetafieldStringRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateMetafieldStringListInput":{"i":{"definitionId":"ID","matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionMetafieldStringListRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateProductCategoryInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductCategoryRelation","values":"[CollectionSourceInclusionConditionProductCategoryValueInput!]"}}, +"CollectionSourceInclusionConditionUpdateProductStatusInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductStatusRelation","values":"[ProductStatus!]"}}, +"CollectionSourceInclusionConditionUpdateProductTagInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductTagRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateProductTitleInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductTitleRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateProductTypeInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductTypeRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateProductVendorInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductVendorRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateVariantCompareAtPriceInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantCompareAtPriceRelation","value":"MoneyInput"}}, +"CollectionSourceInclusionConditionUpdateVariantInventoryInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantInventoryRelation","value":"Int"}}, +"CollectionSourceInclusionConditionUpdateVariantPriceInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantPriceRelation","value":"MoneyInput"}}, +"CollectionSourceInclusionConditionUpdateVariantTitleInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionVariantTitleRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateVariantWeightInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantWeightRelation","value":"WeightInput"}}, +"CollectionSourceInclusionConditionVariantCompareAtPrice":{"o":{"f":{"id":"ID!","relation":"CollectionSourceInclusionConditionVariantCompareAtPriceRelation!","value":"MoneyV2"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionVariantCompareAtPriceInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantCompareAtPriceRelation!","value":"MoneyInput"}}, +"CollectionSourceInclusionConditionVariantCompareAtPriceRelation":{"e":["EQUALS","NOT_EQUALS","GREATER_THAN","LESS_THAN","IS_SET","IS_NOT_SET"]}, +"CollectionSourceInclusionConditionVariantInventory":{"o":{"f":{"id":"ID!","relation":"CollectionSourceInclusionConditionVariantInventoryRelation!","value":"Int!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionVariantInventoryInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantInventoryRelation!","value":"Int!"}}, +"CollectionSourceInclusionConditionVariantInventoryRelation":{"e":["EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceInclusionConditionVariantPrice":{"o":{"f":{"id":"ID!","relation":"CollectionSourceInclusionConditionVariantPriceRelation!","value":"MoneyV2!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionVariantPriceInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantPriceRelation!","value":"MoneyInput!"}}, +"CollectionSourceInclusionConditionVariantPriceRelation":{"e":["EQUALS","NOT_EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceInclusionConditionVariantTitle":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionVariantTitleRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionVariantTitleInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionVariantTitleRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionVariantTitleRelation":{"e":["EQUALS","NOT_EQUALS","STARTS_WITH","ENDS_WITH","CONTAINS","DOES_NOT_CONTAIN"]}, +"CollectionSourceInclusionConditionVariantWeight":{"o":{"f":{"id":"ID!","relation":"CollectionSourceInclusionConditionVariantWeightRelation!","value":"Weight!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionVariantWeightInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantWeightRelation!","value":"WeightInput!"}}, +"CollectionSourceInclusionConditionVariantWeightRelation":{"e":["EQUALS","NOT_EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceTargetType":{"e":["PRODUCTS","VARIANTS"]}, +"CollectionSubCollectionEligibility":{"o":{"f":{"exclusion":"CollectionSubCollectionEligibilityState!","inclusion":"CollectionSubCollectionEligibilityState!"}}}, +"CollectionSubCollectionEligibilityState":{"o":{"f":{"eligible":"Boolean!","ineligibleReason":"SubCollectionIneligibleReason"}}}, +"CollectionSubCollectionsSource":{"o":{"f":{"app":"App","collections":"[Collection!]!","description":"String","id":"ID!","title":"String!"},"t":["CollectionSource","Node"]}}, +"CollectionUnpublishInput":{"i":{"collectionPublications":"[CollectionPublicationInput!]!","id":"ID!"}}, +"CollectionUnpublishPayload":{"o":{"f":{"collection":"Collection","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"CollectionUpdateConditionsSourceInput":{"i":{"description":"String","exclusion":"CollectionUpdateSourceExclusionInput","id":"ID!","inclusion":"CollectionUpdateSourceInclusionInput","title":"String"}}, +"CollectionUpdateInput":{"i":{"descriptionHtml":"String","handle":"String","id":"ID","image":"ImageInput","metafields":"[MetafieldInput!]","redirectNewHandle":"Boolean=","seo":"SEOInput","sortOrder":"CollectionSortOrder","sourcesToCreate":"[CollectionCreateSourceTargetInput!]","sourcesToDelete":"[ID!]","sourcesToUpdate":"[CollectionUpdateSourceTargetInput!]","templateSuffix":"String","title":"String"}}, +"CollectionUpdatePayload":{"o":{"f":{"collection":"Collection","job":"Job","userErrors":"[UserError!]!"}}}, +"CollectionUpdateSourceExclusionConditionInput":{"i":{"condition":"CollectionSourceExclusionConditionUpdateInput!","id":"ID!"}}, +"CollectionUpdateSourceExclusionInput":{"i":{"conditionsToCreate":"[CollectionSourceExclusionConditionInput!]","conditionsToDelete":"[ID!]","conditionsToUpdate":"[CollectionUpdateSourceExclusionConditionInput!]","matchType":"CollectionConditionMatchType","selectionsToAdd":"[CollectionExclusionProductSelectionInput!]","selectionsToRemove":"[CollectionExclusionProductSelectionInput!]"}}, +"CollectionUpdateSourceInclusionConditionInput":{"i":{"condition":"CollectionSourceInclusionConditionUpdateInput!","id":"ID!"}}, +"CollectionUpdateSourceInclusionInput":{"i":{"conditionsToCreate":"[CollectionSourceInclusionConditionInput!]","conditionsToDelete":"[ID!]","conditionsToUpdate":"[CollectionUpdateSourceInclusionConditionInput!]","matchType":"CollectionConditionMatchType","selectionsToAdd":"[CollectionInclusionProductSelectionInput!]","selectionsToRemove":"[CollectionInclusionProductSelectionInput!]"}}, +"CollectionUpdateSourceTargetInput":{"i":{"condition":"CollectionUpdateConditionsSourceInput","subCollections":"CollectionUpdateSubCollectionsSourceInput"}}, +"CollectionUpdateSubCollectionsSourceInput":{"i":{"collectionIds":"[ID!]","description":"String","id":"ID!","title":"String"}}, +"Color":"s", +"ColumnDataType":{"e":["UNSPECIFIED","MONEY","PERCENT","INTEGER","FLOAT","DECIMAL","STRING","BOOLEAN","TIMESTAMP","MINUTE_TIMESTAMP","HOUR_TIMESTAMP","DAY_TIMESTAMP","WEEK_TIMESTAMP","MONTH_TIMESTAMP","QUARTER_TIMESTAMP","YEAR_TIMESTAMP","DAY_OF_WEEK","HOUR_OF_DAY","IDENTITY","MONTH_OF_YEAR","WEEK_OF_YEAR","SECOND_TIMESTAMP","ARRAY","MILLISECOND_DURATION","SECOND_DURATION","MINUTE_DURATION","HOUR_DURATION","DAY_DURATION","CUMULATIVE","GEO_COORDINATE","ENTITY","COLOR","STRING_IDENTITY","RATING","UNITLESS_SCALAR","MULTIPLIER"]}, +"CombinedListing":{"o":{"f":{"combinedListingChildren":["CombinedListingChildConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"parentProduct":"Product!"}}}, +"CombinedListingChild":{"o":{"f":{"parentVariant":"ProductVariant!","product":"Product!"}}}, +"CombinedListingChildConnection":{"o":{"f":{"edges":"[CombinedListingChildEdge!]!","nodes":"[CombinedListingChild!]!","pageInfo":"PageInfo!"}}}, +"CombinedListingChildEdge":{"o":{"f":{"cursor":"String!","node":"CombinedListingChild!"}}}, +"CombinedListingUpdatePayload":{"o":{"f":{"product":"Product","userErrors":"[CombinedListingUpdateUserError!]!"}}}, +"CombinedListingUpdateUserError":{"o":{"f":{"code":"CombinedListingUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CombinedListingUpdateUserErrorCode":{"e":["CANNOT_HAVE_DUPLICATED_PRODUCTS","CANNOT_HAVE_PARENT_AS_CHILD","CANNOT_HAVE_REPEATED_OPTION_VALUES","CANNOT_HAVE_REPEATED_OPTIONS","CANT_ADD_OPTIONS_VALUES_IF_ALREADY_EXISTS","COMBINED_LISTINGS_NOT_ENABLED","EDIT_AND_REMOVE_ON_SAME_PRODUCTS","FAILED_TO_ADD_PRODUCTS","FAILED_TO_REMOVE_PRODUCTS","FAILED_TO_UPDATE_PRODUCTS","LINKED_METAFIELD_CANNOT_BE_CHANGED","LINKED_METAFIELD_VALUE_MISSING","LINKED_METAFIELDS_CANNOT_BE_REPEATED","LINKED_OPTIONS_NOT_SUPPORTED_FOR_SHOP","MISSING_OPTION_VALUES","MUST_HAVE_SELECTED_OPTION_VALUES","OPTION_NAME_CANNOT_BE_BLANK","OPTION_NAME_CONTAINS_INVALID_CHARACTERS","OPTION_NOT_FOUND","OPTIONS_MUST_BE_EQUAL_TO_THE_OTHER_COMPONENTS","OPTION_VALUES_CANNOT_BE_BLANK","OPTION_VALUES_CANNOT_BE_EMPTY","OPTION_VALUES_MUST_BE_COMPLETE","PARENT_PRODUCT_CANNOT_BE_COMBINED_LISTING_CHILD","PARENT_PRODUCT_MUST_BE_A_COMBINED_LISTING","PARENT_PRODUCT_MUST_HAVE_CATEGORY","PARENT_PRODUCT_NOT_FOUND","PRODUCT_IS_ALREADY_A_CHILD","PRODUCT_MEMBERSHIP_NOT_FOUND","PRODUCT_NOT_FOUND","TITLE_TOO_LONG","TOO_MANY_VARIANTS","TOO_MANY_PRODUCTS","UNEXPECTED_ERROR"]}, +"CombinedListingsRole":{"e":["PARENT","CHILD"]}, +"Comment":{"o":{"f":{"article":"Article","author":"CommentAuthor!","body":"String!","bodyHtml":"HTML!","createdAt":"DateTime!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","ip":"String","isPublished":"Boolean!","publishedAt":"DateTime","status":"CommentStatus!","updatedAt":"DateTime","userAgent":"String"},"t":["HasEvents","Node"]}}, +"CommentApprovePayload":{"o":{"f":{"comment":"Comment","userErrors":"[CommentApproveUserError!]!"}}}, +"CommentApproveUserError":{"o":{"f":{"code":"CommentApproveUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CommentApproveUserErrorCode":{"e":["NOT_FOUND"]}, +"CommentAuthor":{"o":{"f":{"email":"String!","name":"String!"}}}, +"CommentConnection":{"o":{"f":{"edges":"[CommentEdge!]!","nodes":"[Comment!]!","pageInfo":"PageInfo!"}}}, +"CommentDeletePayload":{"o":{"f":{"deletedCommentId":"ID","userErrors":"[CommentDeleteUserError!]!"}}}, +"CommentDeleteUserError":{"o":{"f":{"code":"CommentDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CommentDeleteUserErrorCode":{"e":["NOT_FOUND"]}, +"CommentEdge":{"o":{"f":{"cursor":"String!","node":"Comment!"}}}, +"CommentEvent":{"o":{"f":{"action":"String!","appTitle":"String","attachments":"[CommentEventAttachment!]!","attributeToApp":"Boolean!","attributeToUser":"Boolean!","author":"StaffMember!","canDelete":"Boolean!","canEdit":"Boolean!","createdAt":"DateTime!","criticalAlert":"Boolean!","edited":"Boolean!","embed":"CommentEventEmbed","id":"ID!","message":"FormattedString!","rawMessage":"String!","subject":"CommentEventSubject"},"t":["Event","Node"]}}, +"CommentEventAttachment":{"o":{"f":{"fileExtension":"String","id":"ID!","image":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"name":"String!","size":"Int!","url":"URL!"},"d":{"image(crop)":"Use `Image.url(transform: { crop:})` instead.","image(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","image(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","image(scale)":"Use `Image.url(transform: { scale:})` instead."}}}, +"CommentEventEmbed":{"u":["Customer","DraftOrder","InventoryTransfer","Order","Product","ProductVariant"]}, +"CommentEventSubject":{"n":{"f":{"hasTimelineComment":"Boolean!","id":"ID!"},"t":["Company","CompanyLocation","Customer","DraftOrder","InventoryTransfer","Order"]}}, +"CommentNotSpamPayload":{"o":{"f":{"comment":"Comment","userErrors":"[CommentNotSpamUserError!]!"}}}, +"CommentNotSpamUserError":{"o":{"f":{"code":"CommentNotSpamUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CommentNotSpamUserErrorCode":{"e":["NOT_FOUND"]}, +"CommentPolicy":{"e":["AUTO_PUBLISHED","CLOSED","MODERATED"]}, +"CommentSortKeys":{"e":["CREATED_AT","ID"]}, +"CommentSpamPayload":{"o":{"f":{"comment":"Comment","userErrors":"[CommentSpamUserError!]!"}}}, +"CommentSpamUserError":{"o":{"f":{"code":"CommentSpamUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CommentSpamUserErrorCode":{"e":["NOT_FOUND"]}, +"CommentStatus":{"e":["SPAM","REMOVED","PUBLISHED","UNAPPROVED","PENDING"]}, +"CompaniesDeletePayload":{"o":{"f":{"deletedCompanyIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"Company":{"o":{"f":{"contactCount":"Int!","contactRoles":["CompanyContactRoleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"CompanyContactRoleSortKeys="}],"contacts":["CompanyContactConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyContactSortKeys="}],"contactsCount":"Count","createdAt":"DateTime!","customerSince":"DateTime!","defaultCursor":"String!","defaultRole":"CompanyContactRole","draftOrders":["DraftOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DraftOrderSortKeys="}],"events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"externalId":"String","hasTimelineComment":"Boolean!","id":"ID!","lifetimeDuration":"String!","locations":["CompanyLocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyLocationSortKeys="}],"locationsCount":"Count","mainContact":"CompanyContact","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","note":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"ordersCount":"Count","totalSpent":"MoneyV2!","updatedAt":"DateTime!"},"t":["CommentEventSubject","HasEvents","HasMetafieldDefinitions","HasMetafields","Navigable","Node"],"d":{"contactCount":"Use `contactsCount` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"CompanyAddress":{"o":{"f":{"address1":"String!","address2":"String","city":"String","companyName":"String!","country":"String","countryCode":"CountryCode!","createdAt":"DateTime!","firstName":"String","formattedAddress":["[String!]!",{"withCompanyName":"Boolean=","withName":"Boolean="}],"formattedArea":"String","id":"ID!","lastName":"String","phone":"String","province":"String","recipient":"String","updatedAt":"DateTime!","zip":"String","zoneCode":"String"},"t":["Node"]}}, +"CompanyAddressDeletePayload":{"o":{"f":{"deletedAddressId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyAddressInput":{"i":{"address1":"String","address2":"String","city":"String","countryCode":"CountryCode","firstName":"String","lastName":"String","phone":"String","recipient":"String","zip":"String","zoneCode":"String"}}, +"CompanyAddressType":{"e":["BILLING","SHIPPING"]}, +"CompanyAssignCustomerAsContactPayload":{"o":{"f":{"companyContact":"CompanyContact","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyAssignMainContactPayload":{"o":{"f":{"company":"Company","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyConnection":{"o":{"f":{"edges":"[CompanyEdge!]!","nodes":"[Company!]!","pageInfo":"PageInfo!"}}}, +"CompanyContact":{"o":{"f":{"company":"Company!","createdAt":"DateTime!","customer":"Customer!","draftOrders":["DraftOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DraftOrderSortKeys="}],"id":"ID!","isMainContact":"Boolean!","lifetimeDuration":"String!","locale":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"roleAssignments":["CompanyContactRoleAssignmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyContactRoleAssignmentSortKeys="}],"title":"String","updatedAt":"DateTime!"},"t":["Node"]}}, +"CompanyContactAssignRolePayload":{"o":{"f":{"companyContactRoleAssignment":"CompanyContactRoleAssignment","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactAssignRolesPayload":{"o":{"f":{"roleAssignments":"[CompanyContactRoleAssignment!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactConnection":{"o":{"f":{"edges":"[CompanyContactEdge!]!","nodes":"[CompanyContact!]!","pageInfo":"PageInfo!"}}}, +"CompanyContactCreatePayload":{"o":{"f":{"companyContact":"CompanyContact","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactDeletePayload":{"o":{"f":{"deletedCompanyContactId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactEdge":{"o":{"f":{"cursor":"String!","node":"CompanyContact!"}}}, +"CompanyContactInput":{"i":{"email":"String","firstName":"String","lastName":"String","locale":"String","phone":"String","title":"String"}}, +"CompanyContactRemoveFromCompanyPayload":{"o":{"f":{"removedCompanyContactId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactRevokeRolePayload":{"o":{"f":{"revokedCompanyContactRoleAssignmentId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactRevokeRolesPayload":{"o":{"f":{"revokedRoleAssignmentIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactRole":{"o":{"f":{"id":"ID!","name":"String!","note":"String"},"t":["Node"]}}, +"CompanyContactRoleAssign":{"i":{"companyContactRoleId":"ID!","companyLocationId":"ID!"}}, +"CompanyContactRoleAssignment":{"o":{"f":{"company":"Company!","companyContact":"CompanyContact!","companyLocation":"CompanyLocation!","createdAt":"DateTime!","id":"ID!","role":"CompanyContactRole!","updatedAt":"DateTime!"},"t":["Node"]}}, +"CompanyContactRoleAssignmentConnection":{"o":{"f":{"edges":"[CompanyContactRoleAssignmentEdge!]!","nodes":"[CompanyContactRoleAssignment!]!","pageInfo":"PageInfo!"}}}, +"CompanyContactRoleAssignmentEdge":{"o":{"f":{"cursor":"String!","node":"CompanyContactRoleAssignment!"}}}, +"CompanyContactRoleAssignmentSortKeys":{"e":["CREATED_AT","ID","LOCATION_NAME","UPDATED_AT"]}, +"CompanyContactRoleConnection":{"o":{"f":{"edges":"[CompanyContactRoleEdge!]!","nodes":"[CompanyContactRole!]!","pageInfo":"PageInfo!"}}}, +"CompanyContactRoleEdge":{"o":{"f":{"cursor":"String!","node":"CompanyContactRole!"}}}, +"CompanyContactRoleSortKeys":{"e":["CREATED_AT","ID","UPDATED_AT"]}, +"CompanyContactSendWelcomeEmailPayload":{"o":{"f":{"companyContact":"CompanyContact","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactSortKeys":{"e":["COMPANY_ID","CREATED_AT","EMAIL","ID","NAME","NAME_EMAIL","RELEVANCE","TITLE","UPDATED_AT"]}, +"CompanyContactUpdatePayload":{"o":{"f":{"companyContact":"CompanyContact","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactsDeletePayload":{"o":{"f":{"deletedCompanyContactIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyCreateInput":{"i":{"company":"CompanyInput!","companyContact":"CompanyContactInput","companyLocation":"CompanyLocationInput"}}, +"CompanyCreatePayload":{"o":{"f":{"company":"Company","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyDeletePayload":{"o":{"f":{"deletedCompanyId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyEdge":{"o":{"f":{"cursor":"String!","node":"Company!"}}}, +"CompanyInput":{"i":{"customerSince":"DateTime","externalId":"String","name":"String","note":"String"}}, +"CompanyLocation":{"o":{"f":{"billingAddress":"CompanyAddress","buyerExperienceConfiguration":"BuyerExperienceConfiguration","catalogs":["CatalogConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"catalogsCount":["Count",{"limit":"Int="}],"company":"Company!","createdAt":"DateTime!","currency":"CurrencyCode!","defaultCursor":"String!","draftOrders":["DraftOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DraftOrderSortKeys="}],"events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"externalId":"String","hasTimelineComment":"Boolean!","id":"ID!","inCatalog":["Boolean!",{"catalogId":"ID!"}],"locale":"String","market":"Market!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","note":"String","orderCount":"Int!","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"ordersCount":"Count","phone":"String","roleAssignments":["CompanyContactRoleAssignmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyContactRoleAssignmentSortKeys="}],"shippingAddress":"CompanyAddress","staffMemberAssignments":["CompanyLocationStaffMemberAssignmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyLocationStaffMemberAssignmentSortKeys="}],"storeCreditAccounts":["StoreCreditAccountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String"}],"taxExemptions":"[TaxExemption!]!","taxRegistrationId":"String","taxSettings":"CompanyLocationTaxSettings!","totalSpent":"MoneyV2!","updatedAt":"DateTime!"},"t":["CommentEventSubject","HasEvents","HasMetafieldDefinitions","HasMetafields","HasStoreCreditAccounts","Navigable","Node"],"d":{"market":"This `market` field will be removed in a future version of the API.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","orderCount":"Use `ordersCount` instead.","taxExemptions":"Use `taxSettings` instead.","taxRegistrationId":"Use `taxSettings` instead."}}}, +"CompanyLocationAssignAddressPayload":{"o":{"f":{"addresses":"[CompanyAddress!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationAssignRolesPayload":{"o":{"f":{"roleAssignments":"[CompanyContactRoleAssignment!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationAssignStaffMembersPayload":{"o":{"f":{"companyLocationStaffMemberAssignments":"[CompanyLocationStaffMemberAssignment!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationAssignTaxExemptionsPayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationCatalog":{"o":{"f":{"companyLocations":["CompanyLocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyLocationSortKeys="}],"companyLocationsCount":"Count","id":"ID!","operations":"[ResourceOperation!]!","priceList":"PriceList","publication":"Publication","status":"CatalogStatus!","title":"String!"},"t":["Catalog","Node"]}}, +"CompanyLocationConnection":{"o":{"f":{"edges":"[CompanyLocationEdge!]!","nodes":"[CompanyLocation!]!","pageInfo":"PageInfo!"}}}, +"CompanyLocationCreatePayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationCreateTaxRegistrationPayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationDeletePayload":{"o":{"f":{"deletedCompanyLocationId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationEdge":{"o":{"f":{"cursor":"String!","node":"CompanyLocation!"}}}, +"CompanyLocationInput":{"i":{"billingAddress":"CompanyAddressInput","billingSameAsShipping":"Boolean","buyerExperienceConfiguration":"BuyerExperienceConfigurationInput","externalId":"String","locale":"String","name":"String","note":"String","phone":"String","shippingAddress":"CompanyAddressInput","taxExempt":"Boolean","taxExemptions":"[TaxExemption!]","taxRegistrationId":"String"}}, +"CompanyLocationRemoveStaffMembersPayload":{"o":{"f":{"deletedCompanyLocationStaffMemberAssignmentIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationRevokeRolesPayload":{"o":{"f":{"revokedRoleAssignmentIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationRevokeTaxExemptionsPayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationRevokeTaxRegistrationPayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationRoleAssign":{"i":{"companyContactId":"ID!","companyContactRoleId":"ID!"}}, +"CompanyLocationSortKeys":{"e":["COMPANY_AND_LOCATION_NAME","COMPANY_ID","CREATED_AT","ID","NAME","RELEVANCE","UPDATED_AT"]}, +"CompanyLocationStaffMemberAssignment":{"o":{"f":{"companyLocation":"CompanyLocation!","id":"ID!","staffMember":"StaffMember!"},"t":["Node"]}}, +"CompanyLocationStaffMemberAssignmentConnection":{"o":{"f":{"edges":"[CompanyLocationStaffMemberAssignmentEdge!]!","nodes":"[CompanyLocationStaffMemberAssignment!]!","pageInfo":"PageInfo!"}}}, +"CompanyLocationStaffMemberAssignmentEdge":{"o":{"f":{"cursor":"String!","node":"CompanyLocationStaffMemberAssignment!"}}}, +"CompanyLocationStaffMemberAssignmentSortKeys":{"e":["CREATED_AT","ID","UPDATED_AT"]}, +"CompanyLocationTaxSettings":{"o":{"f":{"taxExempt":"Boolean!","taxExemptions":"[TaxExemption!]!","taxRegistrationId":"String"}}}, +"CompanyLocationTaxSettingsUpdatePayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationUpdateInput":{"i":{"buyerExperienceConfiguration":"BuyerExperienceConfigurationInput","externalId":"String","locale":"String","name":"String","note":"String","phone":"String"}}, +"CompanyLocationUpdatePayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationsCondition":{"o":{"f":{"applicationLevel":"MarketConditionApplicationType","companyLocations":["CompanyLocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"CompanyLocationsDeletePayload":{"o":{"f":{"deletedCompanyLocationIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyRevokeMainContactPayload":{"o":{"f":{"company":"Company","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanySortKeys":{"e":["CREATED_AT","ID","NAME","ORDER_COUNT","SINCE_DATE","TOTAL_SPENT","UPDATED_AT"]}, +"CompanyUpdatePayload":{"o":{"f":{"company":"Company","userErrors":"[BusinessCustomerUserError!]!"}}}, +"ComponentizedProductsBundleConsolidatedOption":{"o":{"f":{"name":"String!","selections":"[ComponentizedProductsBundleConsolidatedOptionSelection!]!"}}}, +"ComponentizedProductsBundleConsolidatedOptionSelection":{"o":{"f":{"components":"[ComponentizedProductsBundleConsolidatedOptionSelectionComponent!]!","value":"String!"}}}, +"ComponentizedProductsBundleConsolidatedOptionSelectionComponent":{"o":{"f":{"optionId":"ID!","value":"String!"}}}, +"ConsentPolicy":{"o":{"f":{"consentRequired":"Boolean","countryCode":"PrivacyCountryCode","dataSaleOptOutRequired":"Boolean","id":"ID!","regionCode":"String","shopId":"ID!"},"t":["Node"]}}, +"ConsentPolicyError":{"o":{"f":{"code":"ConsentPolicyErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ConsentPolicyErrorCode":{"e":["COUNTRY_CODE_REQUIRED","REGION_CODE_REQUIRED","REGION_CODE_MUST_MATCH_COUNTRY_CODE","SHOPIFY_COOKIE_BANNER_NOT_DISABLED","UNSUPORTED_CONSENT_POLICY"]}, +"ConsentPolicyInput":{"i":{"consentRequired":"Boolean","countryCode":"PrivacyCountryCode","dataSaleOptOutRequired":"Boolean","regionCode":"String"}}, +"ConsentPolicyRegion":{"o":{"f":{"countryCode":"PrivacyCountryCode","regionCode":"String"}}}, +"ConsentPolicyUpdatePayload":{"o":{"f":{"updatedPolicies":"[ConsentPolicy!]","userErrors":"[ConsentPolicyError!]!"}}}, +"ContextualPricingContext":{"i":{"companyLocationId":"ID","country":"CountryCode","locationId":"ID"}}, +"ContextualPublicationContext":{"i":{"companyLocationId":"ID","country":"CountryCode","locationId":"ID"}}, +"CookieBanner":{"o":{"f":{"autoManaged":"Boolean!","enabled":"Boolean!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["HasPublishedTranslations"]}}, +"Count":{"o":{"f":{"count":"Int!","precision":"CountPrecision!"}}}, +"CountPrecision":{"e":["EXACT","AT_LEAST"]}, +"CountriesInShippingZones":{"o":{"f":{"countryCodes":"[CountryCode!]!","includeRestOfWorld":"Boolean!"}}}, +"CountryCode":{"e":["AF","AX","AL","DZ","AD","AO","AI","AG","AR","AM","AW","AC","AU","AT","AZ","BS","BH","BD","BB","BY","BE","BZ","BJ","BM","BT","BO","BA","BW","BV","BR","IO","BN","BG","BF","BI","KH","CA","CV","BQ","KY","CF","TD","CL","CN","CX","CC","CO","KM","CG","CD","CK","CR","HR","CU","CW","CY","CZ","CI","DK","DJ","DM","DO","EC","EG","SV","GQ","ER","EE","SZ","ET","FK","FO","FJ","FI","FR","GF","PF","TF","GA","GM","GE","DE","GH","GI","GR","GL","GD","GP","GT","GG","GN","GW","GY","HT","HM","VA","HN","HK","HU","IS","IN","ID","IR","IQ","IE","IM","IL","IT","JM","JP","JE","JO","KZ","KE","KI","KP","XK","KW","KG","LA","LV","LB","LS","LR","LY","LI","LT","LU","MO","MG","MW","MY","MV","ML","MT","MQ","MR","MU","YT","MX","MD","MC","MN","ME","MS","MA","MZ","MM","NA","NR","NP","NL","AN","NC","NZ","NI","NE","NG","NU","NF","MK","NO","OM","PK","PS","PA","PG","PY","PE","PH","PN","PL","PT","QA","CM","RE","RO","RU","RW","BL","SH","KN","LC","MF","PM","WS","SM","ST","SA","SN","RS","SC","SL","SG","SX","SK","SI","SB","SO","ZA","GS","KR","SS","ES","LK","VC","SD","SR","SJ","SE","CH","SY","TW","TJ","TZ","TH","TL","TG","TK","TO","TT","TA","TN","TR","TM","TC","TV","UG","UA","AE","GB","US","UM","UY","UZ","VU","VE","VN","VG","WF","EH","YE","ZM","ZW","ZZ"]}, +"CountryHarmonizedSystemCode":{"o":{"f":{"countryCode":"CountryCode!","harmonizedSystemCode":"String!"}}}, +"CountryHarmonizedSystemCodeConnection":{"o":{"f":{"edges":"[CountryHarmonizedSystemCodeEdge!]!","nodes":"[CountryHarmonizedSystemCode!]!","pageInfo":"PageInfo!"}}}, +"CountryHarmonizedSystemCodeEdge":{"o":{"f":{"cursor":"String!","node":"CountryHarmonizedSystemCode!"}}}, +"CountryHarmonizedSystemCodeInput":{"i":{"countryCode":"CountryCode","harmonizedSystemCode":"String!"}}, +"CreateMediaInput":{"i":{"alt":"String","mediaContentType":"MediaContentType!","originalSource":"String!"}}, +"CropRegion":{"e":["CENTER","TOP","BOTTOM","LEFT","RIGHT"]}, +"CurrencyCode":{"e":{"v":["USD","EUR","GBP","CAD","AFN","ALL","DZD","AOA","ARS","AMD","AWG","AUD","BBD","AZN","BDT","BSD","BHD","BIF","BYN","BZD","BMD","BTN","BAM","BRL","BOB","BWP","BND","BGN","MMK","KHR","CVE","XCG","KYD","XAF","CLP","CNY","COP","KMF","CDF","CRC","HRK","CZK","DKK","DJF","DOP","XCD","EGP","ERN","ETB","FKP","XPF","FJD","GIP","GMD","GHS","GTQ","GYD","GEL","GNF","HTG","HNL","HKD","HUF","ISK","INR","IDR","ILS","IRR","IQD","JMD","JPY","JEP","JOD","KZT","KES","KID","KWD","KGS","LAK","LVL","LBP","LSL","LRD","LYD","LTL","MGA","MKD","MOP","MWK","MVR","MRU","MXN","MYR","MUR","MDL","MAD","MNT","MZN","NAD","NPR","ANG","NZD","NIO","NGN","NOK","OMR","PAB","PKR","PGK","PYG","PEN","PHP","PLN","QAR","RON","RUB","RWF","WST","SHP","SAR","RSD","SCR","SLL","SGD","SDG","SOS","SYP","ZAR","KRW","SSP","SBD","LKR","SRD","SZL","SEK","CHF","TWD","THB","TJS","TZS","TOP","TTD","TND","TRY","TMT","UGX","UAH","AED","UYU","UZS","VUV","VES","VND","XOF","YER","ZMW","USDC","BYR","STD","STN","VED","VEF","XXX"],"d":{"ANG":"Use `XCG` instead.","BYR":"Use `BYN` instead.","STD":"Use `STN` instead.","VEF":"Use `VES` instead."}}}, +"CurrencyExchangeAdjustment":{"o":{"f":{"adjustment":"MoneyV2!","finalAmountSet":"MoneyV2!","id":"ID!","originalAmountSet":"MoneyV2!"},"t":["Node"]}}, +"CurrencyFormats":{"o":{"f":{"moneyFormat":"FormattedString!","moneyInEmailsFormat":"String!","moneyWithCurrencyFormat":"FormattedString!","moneyWithCurrencyInEmailsFormat":"String!"}}}, +"CurrencySetting":{"o":{"f":{"currencyCode":"CurrencyCode!","currencyName":"String!","enabled":"Boolean!","manualRate":"Decimal","rateUpdatedAt":"DateTime"}}}, +"CurrencySettingConnection":{"o":{"f":{"edges":"[CurrencySettingEdge!]!","nodes":"[CurrencySetting!]!","pageInfo":"PageInfo!"}}}, +"CurrencySettingEdge":{"o":{"f":{"cursor":"String!","node":"CurrencySetting!"}}}, +"CustomShippingPackageInput":{"i":{"default":"Boolean=","dimensions":"ObjectDimensionsInput","name":"String","type":"ShippingPackageType","weight":"WeightInput"}}, +"Customer":{"o":{"f":{"addresses":["[MailingAddress!]!",{"first":"Int"}],"addressesV2":["MailingAddressConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"amountSpent":"MoneyV2!","canDelete":"Boolean!","companyContactProfiles":"[CompanyContact!]!","createdAt":"DateTime!","dataSaleOptOut":"Boolean!","defaultAddress":"MailingAddress","defaultEmailAddress":"CustomerEmailAddress","defaultPhoneNumber":"CustomerPhoneNumber","displayName":"String!","email":"String","emailMarketingConsent":"CustomerEmailMarketingConsentState","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"firstName":"String","hasTimelineComment":"Boolean!","id":"ID!","identityProviderSubjects":"[IdentityProviderSubject!]!","image":["Image!",{"size":"Int"}],"lastName":"String","lastOrder":"Order","legacyResourceId":"UnsignedInt64!","lifetimeDuration":"String!","locale":"String!","market":"Market","mergeable":"CustomerMergeable!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"multipassIdentifier":"String","note":"String","numberOfOrders":"UnsignedInt64!","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"paymentMethods":["CustomerPaymentMethodConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","showRevoked":"Boolean="}],"phone":"String","productSubscriberStatus":"CustomerProductSubscriberStatus!","smsMarketingConsent":"CustomerSmsMarketingConsentState","state":"CustomerState!","statistics":"CustomerStatistics!","storeCreditAccounts":["StoreCreditAccountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String"}],"subscriptionContracts":["SubscriptionContractConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"tags":"[String!]!","taxExempt":"Boolean!","taxExemptions":"[TaxExemption!]!","taxSettings":"TaxSettings!","unsubscribeUrl":"URL!","updatedAt":"DateTime!","validEmailAddress":"Boolean!","verifiedEmail":"Boolean!"},"t":["CommentEventSubject","HasEvents","HasMetafieldDefinitions","HasMetafields","HasStoreCreditAccounts","LegacyInteroperability","Node"],"d":{"addresses":"Limited to 250 addresses. Use `addressesV2` for paginated access to all addresses.","email":"Use `defaultEmailAddress.emailAddress` instead.","emailMarketingConsent":"Use `defaultEmailAddress.marketingState`, `defaultEmailAddress.marketingOptInLevel`, `defaultEmailAddress.marketingUpdatedAt`, and `defaultEmailAddress.sourceLocation` instead.","hasTimelineComment":"To query for comments on the timeline, use the `events` connection and a 'query' argument containing `verb:comment`, or look for a 'CommentEvent' in the `__typename` of `events`.","image(size)":"Use `maxWidth` or `maxHeight` on `Image.transformedSrc` instead.","market":"This `market` field will be removed in a future version of the API.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","phone":"Use `defaultPhoneNumber.phoneNumber` instead.","smsMarketingConsent":"Use `defaultPhoneNumber.marketingState`, `defaultPhoneNumber.marketingOptInLevel`, `defaultPhoneNumber.marketingUpdatedAt`, `defaultPhoneNumber.marketingCollectedFrom`, and `defaultPhoneNumber.sourceLocation` instead.","unsubscribeUrl":"Use `defaultEmailAddress.marketingUnsubscribeUrl` instead.","validEmailAddress":"Use `defaultEmailAddress.validFormat` instead."}}}, +"CustomerAccountAppExtensionPage":{"o":{"f":{"appExtensionUuid":"String","defaultCursor":"String!","handle":"String!","id":"ID!","title":"String!"},"t":["CustomerAccountPage","Navigable","Node"]}}, +"CustomerAccountNativePage":{"o":{"f":{"defaultCursor":"String!","handle":"String!","id":"ID!","pageType":"CustomerAccountNativePagePageType!","title":"String!"},"t":["CustomerAccountPage","Navigable","Node"]}}, +"CustomerAccountNativePagePageType":{"e":["NATIVE_ORDERS","NATIVE_SETTINGS","NATIVE_PROFILE","UNKNOWN"]}, +"CustomerAccountPage":{"n":{"f":{"defaultCursor":"String!","handle":"String!","id":"ID!","title":"String!"},"t":["CustomerAccountAppExtensionPage","CustomerAccountNativePage"]}}, +"CustomerAccountPageConnection":{"o":{"f":{"edges":"[CustomerAccountPageEdge!]!","nodes":"[CustomerAccountPage!]!","pageInfo":"PageInfo!"}}}, +"CustomerAccountPageEdge":{"o":{"f":{"cursor":"String!","node":"CustomerAccountPage!"}}}, +"CustomerAccountsV2":{"o":{"f":{"customerAccountsVersion":"CustomerAccountsVersion!","loginLinksVisibleOnStorefrontAndCheckout":"Boolean!","loginRequiredAtCheckout":"Boolean!","url":"URL"}}}, +"CustomerAccountsVersion":{"e":["CLASSIC","NEW_CUSTOMER_ACCOUNTS"]}, +"CustomerAddTaxExemptionsPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerAddressCreatePayload":{"o":{"f":{"address":"MailingAddress","userErrors":"[UserError!]!"}}}, +"CustomerAddressDeletePayload":{"o":{"f":{"deletedAddressId":"ID","userErrors":"[UserError!]!"}}}, +"CustomerAddressUpdatePayload":{"o":{"f":{"address":"MailingAddress","userErrors":"[UserError!]!"}}}, +"CustomerCancelDataErasureErrorCode":{"e":["DOES_NOT_EXIST","FAILED_TO_CANCEL","NOT_BEING_ERASED","UNAUTHORIZED_CANCELLATION"]}, +"CustomerCancelDataErasurePayload":{"o":{"f":{"customerId":"ID","userErrors":"[CustomerCancelDataErasureUserError!]!"}}}, +"CustomerCancelDataErasureUserError":{"o":{"f":{"code":"CustomerCancelDataErasureErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerConnection":{"o":{"f":{"edges":"[CustomerEdge!]!","nodes":"[Customer!]!","pageInfo":"PageInfo!"}}}, +"CustomerConsentCollectedFrom":{"e":["SHOPIFY","OTHER"]}, +"CustomerCreatePayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerCreditCard":{"o":{"f":{"billingAddress":"CustomerCreditCardBillingAddress","brand":"String!","expiresSoon":"Boolean!","expiryMonth":"Int!","expiryYear":"Int!","firstDigits":"String","isRevocable":"Boolean!","lastDigits":"String!","maskedNumber":"String!","name":"String!","source":"String","virtualLastDigits":"String"}}}, +"CustomerCreditCardBillingAddress":{"o":{"f":{"address1":"String","city":"String","country":"String","countryCode":"CountryCode","firstName":"String","lastName":"String","province":"String","provinceCode":"String","zip":"String"}}}, +"CustomerDeleteInput":{"i":{"id":"ID!"}}, +"CustomerDeletePayload":{"o":{"f":{"deletedCustomerId":"ID","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"CustomerEdge":{"o":{"f":{"cursor":"String!","node":"Customer!"}}}, +"CustomerEmailAddress":{"o":{"f":{"emailAddress":"String!","marketingOptInLevel":"CustomerMarketingOptInLevel","marketingState":"CustomerEmailAddressMarketingState!","marketingUnsubscribeUrl":"URL!","marketingUpdatedAt":"DateTime","openTrackingLevel":"CustomerEmailAddressOpenTrackingLevel!","openTrackingUrl":"URL!","sourceLocation":"Location","validFormat":"Boolean!"}}}, +"CustomerEmailAddressMarketingState":{"e":["INVALID","NOT_SUBSCRIBED","PENDING","SUBSCRIBED","UNSUBSCRIBED"]}, +"CustomerEmailAddressOpenTrackingLevel":{"e":["UNKNOWN","OPTED_IN","OPTED_OUT"]}, +"CustomerEmailMarketingConsentInput":{"i":{"consentUpdatedAt":"DateTime","marketingOptInLevel":"CustomerMarketingOptInLevel","marketingState":"CustomerEmailMarketingState!","sourceLocationId":"ID"}}, +"CustomerEmailMarketingConsentState":{"o":{"f":{"consentUpdatedAt":"DateTime","marketingOptInLevel":"CustomerMarketingOptInLevel","marketingState":"CustomerEmailMarketingState!","sourceLocation":"Location"}}}, +"CustomerEmailMarketingConsentUpdateInput":{"i":{"customerId":"ID!","emailMarketingConsent":"CustomerEmailMarketingConsentInput!"}}, +"CustomerEmailMarketingConsentUpdatePayload":{"o":{"f":{"customer":"Customer","userErrors":"[CustomerEmailMarketingConsentUpdateUserError!]!"}}}, +"CustomerEmailMarketingConsentUpdateUserError":{"o":{"f":{"code":"CustomerEmailMarketingConsentUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerEmailMarketingConsentUpdateUserErrorCode":{"e":["INVALID","INCLUSION","INTERNAL_ERROR","MISSING_ARGUMENT"]}, +"CustomerEmailMarketingState":{"e":["NOT_SUBSCRIBED","PENDING","SUBSCRIBED","UNSUBSCRIBED","REDACTED","INVALID"]}, +"CustomerGenerateAccountActivationUrlPayload":{"o":{"f":{"accountActivationUrl":"URL","userErrors":"[UserError!]!"}}}, +"CustomerIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","emailAddress":"String","id":"ID","phoneNumber":"String"}}, +"CustomerInput":{"i":{"f":{"addresses":"[MailingAddressInput!]","email":"String","emailMarketingConsent":"CustomerEmailMarketingConsentInput","firstName":"String","id":"ID","lastName":"String","locale":"String","metafields":"[MetafieldInput!]","multipassIdentifier":"String","note":"String","phone":"String","smsMarketingConsent":"CustomerSmsMarketingConsentInput","tags":"[String!]","taxExempt":"Boolean","taxExemptions":"[TaxExemption!]","whatsAppMarketingConsent":"CustomerMarketingConsentInput"},"d":{"addresses":"Use the dedicated address mutations (`customerAddressCreate`, `customerAddressUpdate`, `customerAddressDelete`) instead."}}}, +"CustomerJourney":{"o":{"f":{"customerOrderIndex":"Int!","daysToConversion":"Int!","firstVisit":"CustomerVisit!","lastVisit":"CustomerVisit","moments":"[CustomerMoment!]!"}}}, +"CustomerJourneySummary":{"o":{"f":{"customerOrderIndex":"Int","daysToConversion":"Int","firstVisit":"CustomerVisit","lastVisit":"CustomerVisit","moments":["CustomerMomentConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"momentsCount":"Count","ready":"Boolean!"}}}, +"CustomerMarketingConsent":{"n":{"f":{"collectedFrom":"CustomerConsentCollectedFrom","optInLevel":"CustomerMarketingOptInLevel","sourceLocation":"Location","state":"CustomerMarketingConsentState!","updatedAt":"DateTime"},"t":["CustomerSmsMarketingConsent","CustomerWhatsAppMarketingConsent"]}}, +"CustomerMarketingConsentError":{"o":{"f":{"code":"CustomerMarketingConsentErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerMarketingConsentErrorCode":{"e":["INVALID","INCLUSION","INTERNAL_ERROR","MISSING_ARGUMENT"]}, +"CustomerMarketingConsentInput":{"i":{"optInLevel":"CustomerMarketingOptInLevel","sourceLocationId":"ID","state":"CustomerMarketingConsentState!","updatedAt":"DateTime"}}, +"CustomerMarketingConsentState":{"e":["NEVER_SUBSCRIBED","PENDING","SUBSCRIBED","UNSUBSCRIBED","REDACTED"]}, +"CustomerMarketingOptInLevel":{"e":["SINGLE_OPT_IN","CONFIRMED_OPT_IN","UNKNOWN"]}, +"CustomerMergeError":{"o":{"f":{"errorFields":"[CustomerMergeErrorFieldType!]!","message":"String!"}}}, +"CustomerMergeErrorCode":{"e":["INTERNAL_ERROR","INVALID_CUSTOMER","INVALID_CUSTOMER_ID","CUSTOMER_HAS_GIFT_CARDS","MISSING_OVERRIDE_ATTRIBUTE","OVERRIDE_ATTRIBUTE_INVALID"]}, +"CustomerMergeErrorFieldType":{"e":["DELETED_AT","REDACTED_AT","SUBSCRIPTIONS","MERGE_IN_PROGRESS","GIFT_CARDS","OVERRIDE_FIELDS","STORE_CREDIT","COMPANY_CONTACT","CUSTOMER_PAYMENT_METHODS","PENDING_DATA_REQUEST","MULTIPASS_IDENTIFIER"]}, +"CustomerMergeOverrideFields":{"i":{"customerIdOfDefaultAddressToKeep":"ID","customerIdOfEmailToKeep":"ID","customerIdOfFirstNameToKeep":"ID","customerIdOfLastNameToKeep":"ID","customerIdOfPhoneNumberToKeep":"ID","note":"String","tags":"[String!]"}}, +"CustomerMergePayload":{"o":{"f":{"job":"Job","resultingCustomerId":"ID","userErrors":"[CustomerMergeUserError!]!"}}}, +"CustomerMergePreview":{"o":{"f":{"alternateFields":"CustomerMergePreviewAlternateFields","blockingFields":"CustomerMergePreviewBlockingFields","customerMergeErrors":"[CustomerMergeError!]","defaultFields":"CustomerMergePreviewDefaultFields","resultingCustomerId":"ID"}}}, +"CustomerMergePreviewAlternateFields":{"o":{"f":{"defaultAddress":"MailingAddress","email":"CustomerEmailAddress","firstName":"String","lastName":"String","phoneNumber":"CustomerPhoneNumber"}}}, +"CustomerMergePreviewBlockingFields":{"o":{"f":{"note":"String","tags":"[String!]!"}}}, +"CustomerMergePreviewDefaultFields":{"o":{"f":{"addresses":["MailingAddressConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"defaultAddress":"MailingAddress","discountNodeCount":"UnsignedInt64!","discountNodes":["DiscountNodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"DiscountSortKeys="}],"displayName":"String!","draftOrderCount":"UnsignedInt64!","draftOrders":["DraftOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"DraftOrderSortKeys="}],"email":"CustomerEmailAddress","firstName":"String","giftCardCount":"UnsignedInt64!","giftCards":["GiftCardConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"GiftCardSortKeys="}],"lastName":"String","metafieldCount":"UnsignedInt64!","note":"String","orderCount":"UnsignedInt64!","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"phoneNumber":"CustomerPhoneNumber","tags":"[String!]!"}}}, +"CustomerMergeRequest":{"o":{"f":{"customerMergeErrors":"[CustomerMergeError!]!","jobId":"ID","resultingCustomerId":"ID!","status":"CustomerMergeRequestStatus!"}}}, +"CustomerMergeRequestStatus":{"e":["REQUESTED","IN_PROGRESS","COMPLETED","FAILED"]}, +"CustomerMergeUserError":{"o":{"f":{"code":"CustomerMergeErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerMergeable":{"o":{"f":{"errorFields":"[CustomerMergeErrorFieldType!]!","isMergeable":"Boolean!","mergeInProgress":"CustomerMergeRequest","reason":"String"}}}, +"CustomerMoment":{"n":{"f":{"occurredAt":"DateTime!"},"t":["CustomerVisit"]}}, +"CustomerMomentConnection":{"o":{"f":{"edges":"[CustomerMomentEdge!]!","nodes":"[CustomerMoment!]!","pageInfo":"PageInfo!"}}}, +"CustomerMomentEdge":{"o":{"f":{"cursor":"String!","node":"CustomerMoment!"}}}, +"CustomerPaymentInstrument":{"u":["BankAccount","CustomerCreditCard","CustomerPaypalBillingAgreement","CustomerShopPayAgreement"]}, +"CustomerPaymentInstrumentBillingAddress":{"o":{"f":{"address1":"String","city":"String","country":"String","countryCode":"CountryCode","name":"String","province":"String","provinceCode":"String","zip":"String"}}}, +"CustomerPaymentMethod":{"o":{"f":{"customer":"Customer","id":"ID!","instrument":"CustomerPaymentInstrument","mandates":["PaymentMandateResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"revokedAt":"DateTime","revokedReason":"CustomerPaymentMethodRevocationReason","subscriptionContracts":["SubscriptionContractConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Node"]}}, +"CustomerPaymentMethodConnection":{"o":{"f":{"edges":"[CustomerPaymentMethodEdge!]!","nodes":"[CustomerPaymentMethod!]!","pageInfo":"PageInfo!"}}}, +"CustomerPaymentMethodCreateFromDuplicationDataPayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","userErrors":"[CustomerPaymentMethodCreateFromDuplicationDataUserError!]!"}}}, +"CustomerPaymentMethodCreateFromDuplicationDataUserError":{"o":{"f":{"code":"CustomerPaymentMethodCreateFromDuplicationDataUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerPaymentMethodCreateFromDuplicationDataUserErrorCode":{"e":["TOO_MANY_REQUESTS","CUSTOMER_DOES_NOT_EXIST","INVALID_ENCRYPTED_DUPLICATION_DATA"]}, +"CustomerPaymentMethodCreditCardCreatePayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","processing":"Boolean","userErrors":"[UserError!]!"}}}, +"CustomerPaymentMethodCreditCardUpdatePayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","processing":"Boolean","userErrors":"[UserError!]!"}}}, +"CustomerPaymentMethodEdge":{"o":{"f":{"cursor":"String!","node":"CustomerPaymentMethod!"}}}, +"CustomerPaymentMethodGetDuplicationDataPayload":{"o":{"f":{"encryptedDuplicationData":"String","userErrors":"[CustomerPaymentMethodGetDuplicationDataUserError!]!"}}}, +"CustomerPaymentMethodGetDuplicationDataUserError":{"o":{"f":{"code":"CustomerPaymentMethodGetDuplicationDataUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerPaymentMethodGetDuplicationDataUserErrorCode":{"e":["PAYMENT_METHOD_DOES_NOT_EXIST","INVALID_INSTRUMENT","TOO_MANY_REQUESTS","CUSTOMER_DOES_NOT_EXIST","SAME_SHOP","INVALID_ORGANIZATION_SHOP"]}, +"CustomerPaymentMethodGetUpdateUrlPayload":{"o":{"f":{"updatePaymentMethodUrl":"URL","userErrors":"[CustomerPaymentMethodGetUpdateUrlUserError!]!"}}}, +"CustomerPaymentMethodGetUpdateUrlUserError":{"o":{"f":{"code":"CustomerPaymentMethodGetUpdateUrlUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerPaymentMethodGetUpdateUrlUserErrorCode":{"e":["PAYMENT_METHOD_DOES_NOT_EXIST","INVALID_INSTRUMENT","TOO_MANY_REQUESTS","CUSTOMER_DOES_NOT_EXIST"]}, +"CustomerPaymentMethodPaypalBillingAgreementCreatePayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","userErrors":"[CustomerPaymentMethodUserError!]!"}}}, +"CustomerPaymentMethodPaypalBillingAgreementUpdatePayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","userErrors":"[CustomerPaymentMethodUserError!]!"}}}, +"CustomerPaymentMethodRemoteCreatePayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","userErrors":"[CustomerPaymentMethodRemoteUserError!]!"}}}, +"CustomerPaymentMethodRemoteInput":{"i":{"authorizeNetCustomerPaymentProfile":"RemoteAuthorizeNetCustomerPaymentProfileInput","braintreePaymentMethod":"RemoteBraintreePaymentMethodInput","stripePaymentMethod":"RemoteStripePaymentMethodInput"}}, +"CustomerPaymentMethodRemoteUserError":{"o":{"f":{"code":"CustomerPaymentMethodRemoteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerPaymentMethodRemoteUserErrorCode":{"e":["INVALID","PRESENT","TAKEN","EXACTLY_ONE_REMOTE_REFERENCE_REQUIRED","AUTHORIZE_NET_NOT_ENABLED_FOR_SUBSCRIPTIONS","BRAINTREE_NOT_ENABLED_FOR_SUBSCRIPTIONS"]}, +"CustomerPaymentMethodRevocationReason":{"e":["AUTHORIZE_NET_GATEWAY_NOT_ENABLED","AUTHORIZE_NET_RETURNED_NO_PAYMENT_METHOD","FAILED_TO_UPDATE_CREDIT_CARD","STRIPE_API_AUTHENTICATION_ERROR","STRIPE_API_INVALID_REQUEST_ERROR","STRIPE_GATEWAY_NOT_ENABLED","STRIPE_RETURNED_NO_PAYMENT_METHOD","STRIPE_PAYMENT_METHOD_NOT_CARD","BRAINTREE_API_AUTHENTICATION_ERROR","BRAINTREE_GATEWAY_NOT_ENABLED","BRAINTREE_RETURNED_NO_PAYMENT_METHOD","BRAINTREE_PAYMENT_METHOD_NOT_CARD","PAYMENT_METHOD_VERIFICATION_FAILED","THREE_D_SECURE_FLOW_IN_VERIFICATION_NOT_IMPLEMENTED","MANUALLY_REVOKED","FAILED_TO_RETRIEVE_BILLING_ADDRESS","MERGED","CUSTOMER_REDACTED","TOO_MANY_CONSECUTIVE_FAILURES","CVV_ATTEMPTS_LIMIT_EXCEEDED"]}, +"CustomerPaymentMethodRevokePayload":{"o":{"f":{"revokedCustomerPaymentMethodId":"ID","userErrors":"[UserError!]!"}}}, +"CustomerPaymentMethodSendUpdateEmailPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerPaymentMethodUserError":{"o":{"f":{"code":"CustomerPaymentMethodUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerPaymentMethodUserErrorCode":{"e":["INVALID","PRESENT","TAKEN"]}, +"CustomerPaypalBillingAgreement":{"o":{"f":{"billingAddress":"CustomerPaymentInstrumentBillingAddress","inactive":"Boolean!","isRevocable":"Boolean!","paypalAccountEmail":"String"}}}, +"CustomerPhoneNumber":{"o":{"f":{"marketingCollectedFrom":"CustomerConsentCollectedFrom","marketingOptInLevel":"CustomerMarketingOptInLevel","marketingState":"CustomerSmsMarketingState!","marketingUpdatedAt":"DateTime","phoneNumber":"String!","smsMarketingConsent":"CustomerSmsMarketingConsent!","sourceLocation":"Location","whatsAppMarketingConsent":"CustomerWhatsAppMarketingConsent!"},"d":{"marketingCollectedFrom":"Use `smsMarketingConsent.collectedFrom` instead.","marketingOptInLevel":"Use `smsMarketingConsent.optInLevel` instead.","marketingState":"Use `smsMarketingConsent.state` instead.","marketingUpdatedAt":"Use `smsMarketingConsent.updatedAt` instead.","sourceLocation":"Use `smsMarketingConsent.sourceLocation` instead."}}}, +"CustomerPredictedSpendTier":{"e":["HIGH","MEDIUM","LOW"]}, +"CustomerProductSubscriberStatus":{"e":["ACTIVE","CANCELLED","EXPIRED","FAILED","NEVER_SUBSCRIBED","PAUSED"]}, +"CustomerRemoveTaxExemptionsPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerReplaceTaxExemptionsPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerRequestDataErasureErrorCode":{"e":["DOES_NOT_EXIST","FAILED_TO_REQUEST"]}, +"CustomerRequestDataErasurePayload":{"o":{"f":{"customerId":"ID","userErrors":"[CustomerRequestDataErasureUserError!]!"}}}, +"CustomerRequestDataErasureUserError":{"o":{"f":{"code":"CustomerRequestDataErasureErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerRfmGroup":{"e":["CHAMPIONS","LOYAL","ACTIVE","NEW","PROMISING","NEEDS_ATTENTION","ALMOST_LOST","PREVIOUSLY_LOYAL","AT_RISK","DORMANT","PROSPECTS"]}, +"CustomerSavedSearchSortKeys":{"e":["ID","NAME"]}, +"CustomerSegmentMember":{"o":{"f":{"amountSpent":"MoneyV2","defaultAddress":"MailingAddress","defaultEmailAddress":"CustomerEmailAddress","defaultPhoneNumber":"CustomerPhoneNumber","displayName":"String!","firstName":"String","id":"ID!","lastName":"String","lastOrderId":"ID","mergeable":"CustomerMergeable!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"note":"String","numberOfOrders":"UnsignedInt64"},"t":["HasMetafields"]}}, +"CustomerSegmentMemberConnection":{"o":{"f":{"edges":"[CustomerSegmentMemberEdge!]!","pageInfo":"PageInfo!","statistics":"SegmentStatistics!","totalCount":"Int!"}}}, +"CustomerSegmentMemberEdge":{"o":{"f":{"cursor":"String!","node":"CustomerSegmentMember!"}}}, +"CustomerSegmentMembersQuery":{"o":{"f":{"currentCount":"Int!","done":"Boolean!","id":"ID!"},"t":["JobResult","Node"]}}, +"CustomerSegmentMembersQueryCreatePayload":{"o":{"f":{"customerSegmentMembersQuery":"CustomerSegmentMembersQuery","userErrors":"[CustomerSegmentMembersQueryUserError!]!"}}}, +"CustomerSegmentMembersQueryInput":{"i":{"query":"String","reverse":"Boolean=","segmentId":"ID","sortKey":"String"}}, +"CustomerSegmentMembersQueryUserError":{"o":{"f":{"code":"CustomerSegmentMembersQueryUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerSegmentMembersQueryUserErrorCode":{"e":["INVALID"]}, +"CustomerSendAccountInviteEmailPayload":{"o":{"f":{"customer":"Customer","userErrors":"[CustomerSendAccountInviteEmailUserError!]!"}}}, +"CustomerSendAccountInviteEmailUserError":{"o":{"f":{"code":"CustomerSendAccountInviteEmailUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerSendAccountInviteEmailUserErrorCode":{"e":["INVALID"]}, +"CustomerSetIdentifiers":{"i":{"customId":"UniqueMetafieldValueInput","email":"String","id":"ID","phone":"String"}}, +"CustomerSetInput":{"i":{"f":{"addresses":"[MailingAddressInput!]","email":"String","firstName":"String","id":"ID","lastName":"String","locale":"String","note":"String","phone":"String","tags":"[String!]","taxExempt":"Boolean","taxExemptions":"[TaxExemption!]"},"d":{"addresses":"Use the dedicated address mutations (`customerAddressCreate`, `customerAddressUpdate`, `customerAddressDelete`) instead.","id":"To update a customer use `identifier` argument instead."}}}, +"CustomerSetPayload":{"o":{"f":{"customer":"Customer","userErrors":"[CustomerSetUserError!]!"}}}, +"CustomerSetUserError":{"o":{"f":{"code":"CustomerSetUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerSetUserErrorCode":{"e":["INVALID","INCLUSION","TAKEN","TOO_LONG","TOO_SHORT","PRESENT","BLANK","ID_NOT_ALLOWED","MISSING_FIELD_REQUIRED","INPUT_MISMATCH","NOT_FOUND","METAFIELD_MISMATCH"]}, +"CustomerShopPayAgreement":{"o":{"f":{"billingAddress":"CustomerCreditCardBillingAddress","expiresSoon":"Boolean!","expiryMonth":"Int!","expiryYear":"Int!","inactive":"Boolean!","isRevocable":"Boolean!","lastDigits":"String!","maskedNumber":"String!","name":"String!"}}}, +"CustomerSmsMarketingConsent":{"o":{"f":{"collectedFrom":"CustomerConsentCollectedFrom","optInLevel":"CustomerMarketingOptInLevel","sourceLocation":"Location","state":"CustomerMarketingConsentState!","updatedAt":"DateTime"},"t":["CustomerMarketingConsent"]}}, +"CustomerSmsMarketingConsentError":{"o":{"f":{"code":"CustomerSmsMarketingConsentErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerSmsMarketingConsentErrorCode":{"e":["INVALID","INCLUSION","INTERNAL_ERROR","MISSING_ARGUMENT"]}, +"CustomerSmsMarketingConsentInput":{"i":{"consentUpdatedAt":"DateTime","marketingOptInLevel":"CustomerMarketingOptInLevel","marketingState":"CustomerSmsMarketingState!","sourceLocationId":"ID"}}, +"CustomerSmsMarketingConsentState":{"o":{"f":{"consentCollectedFrom":"CustomerConsentCollectedFrom","consentUpdatedAt":"DateTime","marketingOptInLevel":"CustomerMarketingOptInLevel!","marketingState":"CustomerSmsMarketingState!","sourceLocation":"Location"}}}, +"CustomerSmsMarketingConsentUpdateInput":{"i":{"customerId":"ID!","smsMarketingConsent":"CustomerSmsMarketingConsentInput!"}}, +"CustomerSmsMarketingConsentUpdatePayload":{"o":{"f":{"customer":"Customer","userErrors":"[CustomerSmsMarketingConsentError!]!"}}}, +"CustomerSmsMarketingState":{"e":["NOT_SUBSCRIBED","PENDING","SUBSCRIBED","UNSUBSCRIBED","REDACTED"]}, +"CustomerSortKeys":{"e":["CREATED_AT","ID","LOCATION","NAME","RELEVANCE","UPDATED_AT"]}, +"CustomerState":{"e":["DECLINED","DISABLED","ENABLED","INVITED"]}, +"CustomerStatistics":{"o":{"f":{"predictedSpendTier":"CustomerPredictedSpendTier","rfmGroup":"CustomerRfmGroup"}}}, +"CustomerUpdateDefaultAddressPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerUpdatePayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerVisit":{"o":{"f":{"id":"ID!","landingPage":"URL","landingPageHtml":"HTML","marketingEvent":"MarketingEvent","occurredAt":"DateTime!","referralCode":"String","referralInfoHtml":"FormattedString!","referrerUrl":"URL","source":"String!","sourceDescription":"String","sourceType":"MarketingTactic","utmParameters":"UTMParameters"},"t":["CustomerMoment","Node"]}}, +"CustomerVisitProductInfo":{"o":{"f":{"product":"Product","quantity":"Int!","variant":"ProductVariant"}}}, +"CustomerVisitProductInfoConnection":{"o":{"f":{"edges":"[CustomerVisitProductInfoEdge!]!","nodes":"[CustomerVisitProductInfo!]!","pageInfo":"PageInfo!"}}}, +"CustomerVisitProductInfoEdge":{"o":{"f":{"cursor":"String!","node":"CustomerVisitProductInfo!"}}}, +"CustomerWhatsAppMarketingConsent":{"o":{"f":{"collectedFrom":"CustomerConsentCollectedFrom","optInLevel":"CustomerMarketingOptInLevel","sourceLocation":"Location","state":"CustomerMarketingConsentState!","updatedAt":"DateTime"},"t":["CustomerMarketingConsent"]}}, +"CustomerWhatsAppMarketingConsentUpdateInput":{"i":{"customerId":"ID!","whatsAppMarketingConsent":"CustomerMarketingConsentInput!"}}, +"CustomerWhatsAppMarketingConsentUpdatePayload":{"o":{"f":{"customerPhoneNumber":"CustomerPhoneNumber","userErrors":"[CustomerMarketingConsentError!]!"}}}, +"DataSaleOptOutPage":{"o":{"f":{"autoManaged":"Boolean!"}}}, +"DataSaleOptOutPayload":{"o":{"f":{"customerId":"ID","userErrors":"[DataSaleOptOutUserError!]!"}}}, +"DataSaleOptOutUserError":{"o":{"f":{"code":"DataSaleOptOutUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DataSaleOptOutUserErrorCode":{"e":["FAILED"]}, +"Date":"s", +"DateTime":"s", +"DayOfTheWeek":{"e":["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]}, +"Decimal":"s", +"DelegateAccessToken":{"o":{"f":{"accessScopes":"[String!]!","accessToken":"String!","createdAt":"DateTime!","expiresIn":"Int"}}}, +"DelegateAccessTokenCreatePayload":{"o":{"f":{"delegateAccessToken":"DelegateAccessToken","shop":"Shop!","userErrors":"[DelegateAccessTokenCreateUserError!]!"}}}, +"DelegateAccessTokenCreateUserError":{"o":{"f":{"code":"DelegateAccessTokenCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DelegateAccessTokenCreateUserErrorCode":{"e":["EMPTY_ACCESS_SCOPE","DELEGATE_ACCESS_TOKEN","NEGATIVE_EXPIRES_IN","EXPIRES_AFTER_PARENT","REFRESH_TOKEN","PERSISTENCE_FAILED","UNKNOWN_SCOPES"]}, +"DelegateAccessTokenDestroyPayload":{"o":{"f":{"shop":"Shop!","status":"Boolean","userErrors":"[DelegateAccessTokenDestroyUserError!]!"}}}, +"DelegateAccessTokenDestroyUserError":{"o":{"f":{"code":"DelegateAccessTokenDestroyUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DelegateAccessTokenDestroyUserErrorCode":{"e":["PERSISTENCE_FAILED","ACCESS_TOKEN_NOT_FOUND","CAN_ONLY_DELETE_DELEGATE_TOKENS","ACCESS_DENIED"]}, +"DelegateAccessTokenInput":{"i":{"delegateAccessScope":"[String!]!","expiresIn":"Int"}}, +"DeletionEvent":{"o":{"f":{"occurredAt":"DateTime!","subjectId":"ID!","subjectType":"DeletionEventSubjectType!"}}}, +"DeletionEventConnection":{"o":{"f":{"edges":"[DeletionEventEdge!]!","nodes":"[DeletionEvent!]!","pageInfo":"PageInfo!"}}}, +"DeletionEventEdge":{"o":{"f":{"cursor":"String!","node":"DeletionEvent!"}}}, +"DeletionEventSortKeys":{"e":["CREATED_AT","ID"]}, +"DeletionEventSubjectType":{"e":["COLLECTION","PRODUCT"]}, +"DeliveryAvailableService":{"o":{"f":{"countries":"DeliveryCountryCodesOrRestOfWorld!","name":"String!"}}}, +"DeliveryBrandedPromise":{"o":{"f":{"handle":"String!","name":"String!"}}}, +"DeliveryCarrierCalculatedOptionDefinition":{"o":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!","rateGroups":["DeliveryCarrierCalculatedRateGroupConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinition"]}}, +"DeliveryCarrierCalculatedOptionDefinitionCreateInput":{"i":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyInput","isActive":"Boolean=","rateGroups":"[DeliveryCarrierCalculatedRateGroupCreateInput!]!"}}, +"DeliveryCarrierCalculatedOptionDefinitionUpdateInput":{"i":{"currency":"CurrencyCode","description":"String","freeDeliveryMinimumValue":"MoneyInput","id":"ID!","isActive":"Boolean","rateGroupsToCreate":"[DeliveryCarrierCalculatedRateGroupCreateInput!]","rateGroupsToDelete":"[ID!]","rateGroupsToUpdate":"[DeliveryCarrierCalculatedRateGroupUpdateInput!]"}}, +"DeliveryCarrierCalculatedRateGroup":{"o":{"f":{"absoluteAdjustment":"MoneyV2","autoIncludeNewServices":"Boolean!","carrierService":"DeliveryCarrierService!","conditions":"DeliveryRateGroupConditions!","id":"ID!","percentageAdjustment":"Int","serviceConfiguration":"[DeliveryCarrierCalculatedRateGroupService!]!"},"t":["DeliveryOptionDefinitionRateGroup"]}}, +"DeliveryCarrierCalculatedRateGroupConnection":{"o":{"f":{"edges":"[DeliveryCarrierCalculatedRateGroupEdge!]!","nodes":"[DeliveryCarrierCalculatedRateGroup!]!","pageInfo":"PageInfo!"}}}, +"DeliveryCarrierCalculatedRateGroupCreateInput":{"i":{"absoluteAdjustment":"MoneyInput","autoIncludeNewServices":"Boolean","carrierServiceId":"ID!","conditions":"DeliveryRateConditionsCreateInput","percentageAdjustment":"Int","serviceConfiguration":"[DeliveryCarrierCalculatedRateGroupServiceInput!]"}}, +"DeliveryCarrierCalculatedRateGroupEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryCarrierCalculatedRateGroup!"}}}, +"DeliveryCarrierCalculatedRateGroupService":{"o":{"f":{"name":"String!","status":"DeliveryCarrierCalculatedRateGroupServiceStatus!"}}}, +"DeliveryCarrierCalculatedRateGroupServiceInput":{"i":{"name":"String!","status":"DeliveryCarrierCalculatedRateGroupServiceStatus!"}}, +"DeliveryCarrierCalculatedRateGroupServiceStatus":{"e":["INCLUDED","EXCLUDED"]}, +"DeliveryCarrierCalculatedRateGroupUpdateInput":{"i":{"absoluteAdjustment":"MoneyInput","autoIncludeNewServices":"Boolean","carrierServiceId":"ID","conditions":"DeliveryRateConditionsUpdateInput","id":"ID!","percentageAdjustment":"Int","serviceConfiguration":"[DeliveryCarrierCalculatedRateGroupServiceInput!]"}}, +"DeliveryCarrierService":{"o":{"f":{"active":"Boolean!","availableServicesForCountries":["[DeliveryAvailableService!]!",{"countryCodes":"[CountryCode!]","origins":"[ID!]","restOfWorld":"Boolean!"}],"callbackUrl":"URL","createdAt":"DateTime!","formattedName":"String","icon":"Image!","id":"ID!","name":"String","supportsServiceDiscovery":"Boolean!"},"t":["Node"]}}, +"DeliveryCarrierServiceAndLocations":{"o":{"f":{"carrierService":"DeliveryCarrierService!","locations":"[Location!]!"}}}, +"DeliveryCarrierServiceConnection":{"o":{"f":{"edges":"[DeliveryCarrierServiceEdge!]!","nodes":"[DeliveryCarrierService!]!","pageInfo":"PageInfo!"}}}, +"DeliveryCarrierServiceCreateInput":{"i":{"active":"Boolean!","callbackUrl":"URL!","name":"String!","supportsServiceDiscovery":"Boolean!"}}, +"DeliveryCarrierServiceEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryCarrierService!"}}}, +"DeliveryCarrierServiceUpdateInput":{"i":{"active":"Boolean","callbackUrl":"URL","id":"ID!","name":"String","supportsServiceDiscovery":"Boolean"}}, +"DeliveryCondition":{"o":{"f":{"conditionCriteria":"DeliveryConditionCriteria!","field":"DeliveryConditionField!","id":"ID!","operator":"DeliveryConditionOperator!"},"t":["Node"]}}, +"DeliveryConditionCriteria":{"u":["MoneyV2","Weight"]}, +"DeliveryConditionField":{"e":["TOTAL_WEIGHT","TOTAL_PRICE"]}, +"DeliveryConditionOperator":{"e":["GREATER_THAN_OR_EQUAL_TO","LESS_THAN_OR_EQUAL_TO"]}, +"DeliveryCountry":{"o":{"f":{"code":"DeliveryCountryCodeOrRestOfWorld!","id":"ID!","name":"String!","provinces":"[DeliveryProvince!]!","translatedName":"String!"},"t":["Node"]}}, +"DeliveryCountryAndZone":{"o":{"f":{"country":"DeliveryCountry!","zone":"String!"}}}, +"DeliveryCountryCodeOrRestOfWorld":{"o":{"f":{"countryCode":"CountryCode","restOfWorld":"Boolean!"}}}, +"DeliveryCountryCodesOrRestOfWorld":{"o":{"f":{"countryCodes":"[CountryCode!]!","restOfWorld":"Boolean!"}}}, +"DeliveryCountryInput":{"i":{"code":"CountryCode","includeAllProvinces":"Boolean","provinces":"[DeliveryProvinceInput!]","restOfWorld":"Boolean"}}, +"DeliveryCustomization":{"o":{"f":{"enabled":"Boolean!","errorHistory":"FunctionsErrorHistory","functionId":"String!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"shopifyFunction":"ShopifyFunction!","title":"String!"},"t":["HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"DeliveryCustomizationActivationPayload":{"o":{"f":{"ids":"[String!]","userErrors":"[DeliveryCustomizationError!]!"}}}, +"DeliveryCustomizationConnection":{"o":{"f":{"edges":"[DeliveryCustomizationEdge!]!","nodes":"[DeliveryCustomization!]!","pageInfo":"PageInfo!"}}}, +"DeliveryCustomizationCreatePayload":{"o":{"f":{"deliveryCustomization":"DeliveryCustomization","userErrors":"[DeliveryCustomizationError!]!"}}}, +"DeliveryCustomizationDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[DeliveryCustomizationError!]!"}}}, +"DeliveryCustomizationEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryCustomization!"}}}, +"DeliveryCustomizationError":{"o":{"f":{"code":"DeliveryCustomizationErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DeliveryCustomizationErrorCode":{"e":["INVALID","FUNCTION_NOT_FOUND","DELIVERY_CUSTOMIZATION_NOT_FOUND","DELIVERY_CUSTOMIZATION_FUNCTION_NOT_ELIGIBLE","UNAUTHORIZED_APP_SCOPE","MAXIMUM_ACTIVE_DELIVERY_CUSTOMIZATIONS","MAXIMUM_DELIVERY_CUSTOMIZATIONS","CUSTOM_APP_FUNCTION_NOT_ELIGIBLE","FUNCTION_DOES_NOT_IMPLEMENT","FUNCTION_PENDING_DELETION","FUNCTION_ID_CANNOT_BE_CHANGED","REQUIRED_INPUT_FIELD","INVALID_METAFIELDS","MISSING_FUNCTION_IDENTIFIER","MULTIPLE_FUNCTION_IDENTIFIERS"]}, +"DeliveryCustomizationInput":{"i":{"f":{"enabled":"Boolean","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]=","title":"String"},"d":{"functionId":"Use `functionHandle` instead."}}}, +"DeliveryCustomizationUpdatePayload":{"o":{"f":{"deliveryCustomization":"DeliveryCustomization","userErrors":"[DeliveryCustomizationError!]!"}}}, +"DeliveryFlatRate":{"o":{"f":{"id":"ID!","price":"MoneyV2!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"},"t":["DeliveryRate"]}}, +"DeliveryFlatRateCreateInput":{"i":{"price":"MoneyInput!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryFlatRateGroup":{"o":{"f":{"conditions":"DeliveryRateGroupConditions!","id":"ID!","rate":"DeliveryFlatRate!"},"t":["DeliveryOptionDefinitionRateGroup"]}}, +"DeliveryFlatRateGroupConnection":{"o":{"f":{"edges":"[DeliveryFlatRateGroupEdge!]!","nodes":"[DeliveryFlatRateGroup!]!","pageInfo":"PageInfo!"}}}, +"DeliveryFlatRateGroupCreateInput":{"i":{"conditions":"DeliveryRateConditionsCreateInput","rate":"DeliveryFlatRateCreateInput!"}}, +"DeliveryFlatRateGroupEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryFlatRateGroup!"}}}, +"DeliveryFlatRateGroupUpdateInput":{"i":{"conditions":"DeliveryRateConditionsUpdateInput","id":"ID!","rate":"DeliveryFlatRateUpdateInput"}}, +"DeliveryFlatRateOptionDefinition":{"o":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!","name":"String!","rateGroups":["DeliveryFlatRateGroupConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinition"]}}, +"DeliveryFlatRateOptionDefinitionCreateInput":{"i":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyInput","isActive":"Boolean=","name":"String!","rateGroups":"[DeliveryFlatRateGroupCreateInput!]"}}, +"DeliveryFlatRateOptionDefinitionUpdateInput":{"i":{"currency":"CurrencyCode","description":"String","freeDeliveryMinimumValue":"MoneyInput","id":"ID!","isActive":"Boolean","name":"String","rateGroupsToCreate":"[DeliveryFlatRateGroupCreateInput!]","rateGroupsToDelete":"[ID!]","rateGroupsToUpdate":"[DeliveryFlatRateGroupUpdateInput!]"}}, +"DeliveryFlatRateUpdateInput":{"i":{"price":"MoneyInput","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryLocalPickupSettings":{"o":{"f":{"instructions":"String!","pickupTime":"DeliveryLocalPickupTime!"}}}, +"DeliveryLocalPickupTime":{"e":{"v":["ONE_HOUR","TWO_HOURS","FOUR_HOURS","TWENTY_FOUR_HOURS","TWO_TO_FOUR_DAYS","FIVE_OR_MORE_DAYS","CUSTOM"],"d":{"CUSTOM":"Custom pickup time is no longer supported."}}}, +"DeliveryLocationGroup":{"o":{"f":{"id":"ID!","locations":["LocationConnection!",{"after":"String","before":"String","first":"Int","includeInactive":"Boolean=","includeLegacy":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","sortKey":"LocationSortKeys="}],"locationsCount":"Count"},"t":["Node"]}}, +"DeliveryLocationGroupZone":{"o":{"f":{"methodDefinitionCounts":"DeliveryMethodDefinitionCounts!","methodDefinitions":["DeliveryMethodDefinitionConnection!",{"after":"String","before":"String","eligible":"Boolean","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"MethodDefinitionSortKeys=","type":"DeliveryMethodDefinitionType"}],"zone":"DeliveryZone!"}}}, +"DeliveryLocationGroupZoneConnection":{"o":{"f":{"edges":"[DeliveryLocationGroupZoneEdge!]!","nodes":"[DeliveryLocationGroupZone!]!","pageInfo":"PageInfo!"}}}, +"DeliveryLocationGroupZoneEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryLocationGroupZone!"}}}, +"DeliveryLocationGroupZoneInput":{"i":{"countries":"[DeliveryCountryInput!]","id":"ID","methodDefinitionsToCreate":"[DeliveryMethodDefinitionInput!]","methodDefinitionsToUpdate":"[DeliveryMethodDefinitionInput!]","name":"String"}}, +"DeliveryLocationLocalPickupEnableInput":{"i":{"instructions":"String","locationId":"ID!","pickupTime":"DeliveryLocalPickupTime!"}}, +"DeliveryLocationLocalPickupSettingsError":{"o":{"f":{"code":"DeliveryLocationLocalPickupSettingsErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DeliveryLocationLocalPickupSettingsErrorCode":{"e":["ACTIVE_LOCATION_NOT_FOUND","CUSTOM_PICKUP_TIME_NOT_ALLOWED","GENERIC_ERROR"]}, +"DeliveryMethod":{"o":{"f":{"additionalInformation":"DeliveryMethodAdditionalInformation","brandedPromise":"DeliveryBrandedPromise","id":"ID!","maxDeliveryDateTime":"DateTime","methodType":"DeliveryMethodType!","minDeliveryDateTime":"DateTime","presentedName":"String","serviceCode":"String","sourceReference":"String"},"t":["Node"]}}, +"DeliveryMethodAdditionalInformation":{"o":{"f":{"instructions":"String","phone":"String"}}}, +"DeliveryMethodDefinition":{"o":{"f":{"active":"Boolean!","description":"String","id":"ID!","methodConditions":"[DeliveryCondition!]!","name":"String!","rateProvider":"DeliveryRateProvider!"},"t":["Node"]}}, +"DeliveryMethodDefinitionConnection":{"o":{"f":{"edges":"[DeliveryMethodDefinitionEdge!]!","nodes":"[DeliveryMethodDefinition!]!","pageInfo":"PageInfo!"}}}, +"DeliveryMethodDefinitionCounts":{"o":{"f":{"participantDefinitionsCount":"Int!","rateDefinitionsCount":"Int!"}}}, +"DeliveryMethodDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryMethodDefinition!"}}}, +"DeliveryMethodDefinitionInput":{"i":{"active":"Boolean","conditionsToUpdate":"[DeliveryUpdateConditionInput!]","description":"String","id":"ID","name":"String","participant":"DeliveryParticipantInput","priceConditionsToCreate":"[DeliveryPriceConditionInput!]","rateDefinition":"DeliveryRateDefinitionInput","weightConditionsToCreate":"[DeliveryWeightConditionInput!]"}}, +"DeliveryMethodDefinitionType":{"e":["MERCHANT","PARTICIPANT"]}, +"DeliveryMethodType":{"e":["SHIPPING","PICK_UP","NONE","RETAIL","LOCAL","PICKUP_POINT"]}, +"DeliveryOptionDefinition":{"n":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!"},"t":["DeliveryCarrierCalculatedOptionDefinition","DeliveryFlatRateOptionDefinition","DeliveryValueBasedOptionDefinition","DeliveryWeightBasedOptionDefinition"]}}, +"DeliveryOptionDefinitionConnection":{"o":{"f":{"edges":"[DeliveryOptionDefinitionEdge!]!","nodes":"[DeliveryOptionDefinition!]!","pageInfo":"PageInfo!"}}}, +"DeliveryOptionDefinitionCreateInput":{"i":{"carrierCalculated":"DeliveryCarrierCalculatedOptionDefinitionCreateInput","flatRate":"DeliveryFlatRateOptionDefinitionCreateInput","valueBased":"DeliveryValueBasedOptionDefinitionCreateInput","weightBased":"DeliveryWeightBasedOptionDefinitionCreateInput"}}, +"DeliveryOptionDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryOptionDefinition!"}}}, +"DeliveryOptionDefinitionRateGroup":{"n":{"f":{"conditions":"DeliveryRateGroupConditions!","id":"ID!"},"t":["DeliveryCarrierCalculatedRateGroup","DeliveryFlatRateGroup","DeliveryValueBasedRateGroup","DeliveryWeightBasedRateGroup"]}}, +"DeliveryOptionDefinitionUpdateInput":{"i":{"carrierCalculated":"DeliveryCarrierCalculatedOptionDefinitionUpdateInput","flatRate":"DeliveryFlatRateOptionDefinitionUpdateInput","valueBased":"DeliveryValueBasedOptionDefinitionUpdateInput","weightBased":"DeliveryWeightBasedOptionDefinitionUpdateInput"}}, +"DeliveryParticipant":{"o":{"f":{"adaptToNewServicesFlag":"Boolean!","carrierService":"DeliveryCarrierService!","fixedFee":"MoneyV2","id":"ID!","participantServices":"[DeliveryParticipantService!]!","percentageOfRateFee":"Float!"},"t":["Node"]}}, +"DeliveryParticipantInput":{"i":{"adaptToNewServices":"Boolean","carrierServiceId":"ID","fixedFee":"MoneyInput","id":"ID","participantServices":"[DeliveryParticipantServiceInput!]","percentageOfRateFee":"Float"}}, +"DeliveryParticipantService":{"o":{"f":{"active":"Boolean!","name":"String!"}}}, +"DeliveryParticipantServiceInput":{"i":{"active":"Boolean!","name":"String!"}}, +"DeliveryPriceConditionInput":{"i":{"criteria":"MoneyInput","operator":"DeliveryConditionOperator"}}, +"DeliveryProductVariantsCount":{"o":{"f":{"capped":"Boolean!","count":"Int!"}}}, +"DeliveryProfile":{"o":{"f":{"activeMethodDefinitionsCount":"Int!","coversAllItems":"Boolean!","createdAt":"DateTime!","default":"Boolean!","id":"ID!","locationsWithoutRatesCount":"Int!","name":"String!","originLocationCount":"Int!","productVariantsCount":"Count","productVariantsCountV2":"DeliveryProductVariantsCount!","profileItems":["DeliveryProfileItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"ProfileItemSortKeys="}],"profileLocationGroups":["[DeliveryProfileLocationGroup!]!",{"locationGroupId":"ID"}],"sellingPlanGroups":["SellingPlanGroupConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unassignedLocations":"[Location!]!","unassignedLocationsPaginated":["LocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"version":"Int!","zoneCountryCount":"Int!"},"t":["Node"],"d":{"productVariantsCountV2":"Use `productVariantsCount` instead.","profileItems(sortKey)":"Profile item sorting is no longer supported."}}}, +"DeliveryProfileConnection":{"o":{"f":{"edges":"[DeliveryProfileEdge!]!","nodes":"[DeliveryProfile!]!","pageInfo":"PageInfo!"}}}, +"DeliveryProfileCreatePayload":{"o":{"f":{"profile":"DeliveryProfile","userErrors":"[UserError!]!"}}}, +"DeliveryProfileEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryProfile!"}}}, +"DeliveryProfileInput":{"i":{"conditionsToDelete":"[ID!]","coversAllItems":"Boolean","locationGroupsToCreate":"[DeliveryProfileLocationGroupInput!]","locationGroupsToDelete":"[ID!]","locationGroupsToUpdate":"[DeliveryProfileLocationGroupInput!]","methodDefinitionsToDelete":"[ID!]","name":"String","profileLocationGroups":"[DeliveryProfileLocationGroupInput!]","sellingPlanGroupsToAssociate":"[ID!]","sellingPlanGroupsToDissociate":"[ID!]","variantsToAssociate":"[ID!]","variantsToDissociate":"[ID!]","zonesToDelete":"[ID!]"}}, +"DeliveryProfileItem":{"o":{"f":{"id":"ID!","product":"Product!","variants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"ProductVariantSortKeys="}]},"t":["Node"],"d":{"variants(sortKey)":"Profile item variant sorting is no longer supported."}}}, +"DeliveryProfileItemConnection":{"o":{"f":{"edges":"[DeliveryProfileItemEdge!]!","nodes":"[DeliveryProfileItem!]!","pageInfo":"PageInfo!"}}}, +"DeliveryProfileItemEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryProfileItem!"}}}, +"DeliveryProfileLocationGroup":{"o":{"f":{"countriesInAnyZone":"[DeliveryCountryAndZone!]!","locationGroup":"DeliveryLocationGroup!","locationGroupZones":["DeliveryLocationGroupZoneConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"DeliveryProfileLocationGroupInput":{"i":{"id":"ID","locations":"[ID!]","locationsToAdd":"[ID!]","locationsToRemove":"[ID!]","zonesToCreate":"[DeliveryLocationGroupZoneInput!]","zonesToUpdate":"[DeliveryLocationGroupZoneInput!]"}}, +"DeliveryProfileRemovePayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"DeliveryProfileUpdatePayload":{"o":{"f":{"profile":"DeliveryProfile","userErrors":"[UserError!]!"}}}, +"DeliveryPromiseParticipant":{"o":{"f":{"id":"ID!","owner":"DeliveryPromiseParticipantOwner","ownerType":"DeliveryPromiseParticipantOwnerType!"},"t":["Node"]}}, +"DeliveryPromiseParticipantConnection":{"o":{"f":{"edges":"[DeliveryPromiseParticipantEdge!]!","nodes":"[DeliveryPromiseParticipant!]!","pageInfo":"PageInfo!"}}}, +"DeliveryPromiseParticipantEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryPromiseParticipant!"}}}, +"DeliveryPromiseParticipantOwner":{"u":["ProductVariant"]}, +"DeliveryPromiseParticipantOwnerType":{"e":["PRODUCTVARIANT"]}, +"DeliveryPromiseParticipantsUpdatePayload":{"o":{"f":{"promiseParticipants":"[DeliveryPromiseParticipant!]","userErrors":"[UserError!]!"}}}, +"DeliveryPromiseProvider":{"o":{"f":{"active":"Boolean!","fulfillmentDelay":"Int","id":"ID!","location":"Location!","timeZone":"String!"},"t":["Node"]}}, +"DeliveryPromiseProviderUpsertPayload":{"o":{"f":{"deliveryPromiseProvider":"DeliveryPromiseProvider","userErrors":"[DeliveryPromiseProviderUpsertUserError!]!"}}}, +"DeliveryPromiseProviderUpsertUserError":{"o":{"f":{"code":"DeliveryPromiseProviderUpsertUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DeliveryPromiseProviderUpsertUserErrorCode":{"e":["NOT_FOUND","TOO_LONG","MUST_BELONG_TO_APP","INVALID_TIME_ZONE"]}, +"DeliveryPromiseSetting":{"o":{"f":{"deliveryDatesEnabled":"Boolean!","processingTime":"String"}}}, +"DeliveryProvince":{"o":{"f":{"code":"String!","id":"ID!","name":"String!","translatedName":"String!"},"t":["Node"]}}, +"DeliveryProvinceInput":{"i":{"code":"String!"}}, +"DeliveryRate":{"n":{"f":{"price":"MoneyV2!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"},"t":["DeliveryFlatRate","DeliveryValueBasedRate","DeliveryWeightBasedRate"]}}, +"DeliveryRateConditionsCreateInput":{"i":{"collectionsToAdd":"[ID!]","originLocationsToAdd":"[ID!]"}}, +"DeliveryRateConditionsUpdateInput":{"i":{"collectionsToAdd":"[ID!]","collectionsToRemove":"[ID!]","originLocationsToAdd":"[ID!]","originLocationsToRemove":"[ID!]","resetToAllProducts":"Boolean"}}, +"DeliveryRateDefinition":{"o":{"f":{"id":"ID!","price":"MoneyV2!"},"t":["Node"]}}, +"DeliveryRateDefinitionInput":{"i":{"id":"ID","price":"MoneyInput!"}}, +"DeliveryRateGroupConditions":{"o":{"f":{"collections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collectionsCount":"Count","originLocations":["LocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"originLocationsCount":"Count!"}}}, +"DeliveryRateProvider":{"u":["DeliveryParticipant","DeliveryRateDefinition"]}, +"DeliverySettingUpdatePayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"DeliveryShippingOriginAssignPayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"DeliveryUpdateConditionInput":{"i":{"criteria":"Float","criteriaUnit":"String","field":"DeliveryConditionField","id":"ID!","operator":"DeliveryConditionOperator"}}, +"DeliveryValueBasedOptionDefinition":{"o":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!","name":"String!","rateGroups":["DeliveryValueBasedRateGroupConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinition"]}}, +"DeliveryValueBasedOptionDefinitionCreateInput":{"i":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyInput","isActive":"Boolean=","name":"String!","rateGroups":"[DeliveryValueBasedRateGroupCreateInput!]!"}}, +"DeliveryValueBasedOptionDefinitionUpdateInput":{"i":{"currency":"CurrencyCode","description":"String","freeDeliveryMinimumValue":"MoneyInput","id":"ID!","isActive":"Boolean","name":"String","rateGroupsToCreate":"[DeliveryValueBasedRateGroupCreateInput!]","rateGroupsToDelete":"[ID!]","rateGroupsToUpdate":"[DeliveryValueBasedRateGroupUpdateInput!]"}}, +"DeliveryValueBasedRate":{"o":{"f":{"id":"ID!","maxValue":"MoneyV2","minValue":"MoneyV2!","price":"MoneyV2!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"},"t":["DeliveryRate"]}}, +"DeliveryValueBasedRateConnection":{"o":{"f":{"edges":"[DeliveryValueBasedRateEdge!]!","nodes":"[DeliveryValueBasedRate!]!","pageInfo":"PageInfo!"}}}, +"DeliveryValueBasedRateCreateInput":{"i":{"maxValue":"MoneyInput","minValue":"MoneyInput!","price":"MoneyInput!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryValueBasedRateEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryValueBasedRate!"}}}, +"DeliveryValueBasedRateGroup":{"o":{"f":{"conditions":"DeliveryRateGroupConditions!","id":"ID!","rates":["DeliveryValueBasedRateConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinitionRateGroup"]}}, +"DeliveryValueBasedRateGroupConnection":{"o":{"f":{"edges":"[DeliveryValueBasedRateGroupEdge!]!","nodes":"[DeliveryValueBasedRateGroup!]!","pageInfo":"PageInfo!"}}}, +"DeliveryValueBasedRateGroupCreateInput":{"i":{"conditions":"DeliveryRateConditionsCreateInput!","rates":"[DeliveryValueBasedRateCreateInput!]!"}}, +"DeliveryValueBasedRateGroupEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryValueBasedRateGroup!"}}}, +"DeliveryValueBasedRateGroupUpdateInput":{"i":{"conditions":"DeliveryRateConditionsUpdateInput","id":"ID!","ratesToCreate":"[DeliveryValueBasedRateCreateInput!]","ratesToDelete":"[ID!]","ratesToUpdate":"[DeliveryValueBasedRateUpdateInput!]"}}, +"DeliveryValueBasedRateUpdateInput":{"i":{"id":"ID!","maxValue":"MoneyInput","minValue":"MoneyInput","price":"MoneyInput","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryWeightBasedOptionDefinition":{"o":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!","name":"String!","rateGroups":["DeliveryWeightBasedRateGroupConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinition"]}}, +"DeliveryWeightBasedOptionDefinitionCreateInput":{"i":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyInput","isActive":"Boolean=","name":"String!","rateGroups":"[DeliveryWeightBasedRateGroupCreateInput!]!"}}, +"DeliveryWeightBasedOptionDefinitionUpdateInput":{"i":{"currency":"CurrencyCode","description":"String","freeDeliveryMinimumValue":"MoneyInput","id":"ID!","isActive":"Boolean","name":"String","rateGroupsToCreate":"[DeliveryWeightBasedRateGroupCreateInput!]","rateGroupsToDelete":"[ID!]","rateGroupsToUpdate":"[DeliveryWeightBasedRateGroupUpdateInput!]"}}, +"DeliveryWeightBasedRate":{"o":{"f":{"id":"ID!","maxWeight":"Weight","minWeight":"Weight!","price":"MoneyV2!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"},"t":["DeliveryRate"]}}, +"DeliveryWeightBasedRateConnection":{"o":{"f":{"edges":"[DeliveryWeightBasedRateEdge!]!","nodes":"[DeliveryWeightBasedRate!]!","pageInfo":"PageInfo!"}}}, +"DeliveryWeightBasedRateCreateInput":{"i":{"maxWeight":"WeightInput","minWeight":"WeightInput!","price":"MoneyInput!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryWeightBasedRateEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryWeightBasedRate!"}}}, +"DeliveryWeightBasedRateGroup":{"o":{"f":{"conditions":"DeliveryRateGroupConditions!","id":"ID!","rates":["DeliveryWeightBasedRateConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinitionRateGroup"]}}, +"DeliveryWeightBasedRateGroupConnection":{"o":{"f":{"edges":"[DeliveryWeightBasedRateGroupEdge!]!","nodes":"[DeliveryWeightBasedRateGroup!]!","pageInfo":"PageInfo!"}}}, +"DeliveryWeightBasedRateGroupCreateInput":{"i":{"conditions":"DeliveryRateConditionsCreateInput!","rates":"[DeliveryWeightBasedRateCreateInput!]!"}}, +"DeliveryWeightBasedRateGroupEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryWeightBasedRateGroup!"}}}, +"DeliveryWeightBasedRateGroupUpdateInput":{"i":{"conditions":"DeliveryRateConditionsUpdateInput","id":"ID!","ratesToCreate":"[DeliveryWeightBasedRateCreateInput!]","ratesToDelete":"[ID!]","ratesToUpdate":"[DeliveryWeightBasedRateUpdateInput!]"}}, +"DeliveryWeightBasedRateUpdateInput":{"i":{"id":"ID!","maxWeight":"WeightInput","minWeight":"WeightInput","price":"MoneyInput","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryWeightConditionInput":{"i":{"criteria":"WeightInput","operator":"DeliveryConditionOperator"}}, +"DeliveryZone":{"o":{"f":{"countries":"[DeliveryCountry!]!","id":"ID!","name":"String!"},"t":["Node"]}}, +"DepositConfiguration":{"u":["DepositPercentage"]}, +"DepositInput":{"i":{"percentage":"Float!"}}, +"DepositPercentage":{"o":{"f":{"percentage":"Float!"}}}, +"DigitalWallet":{"e":["APPLE_PAY","ANDROID_PAY","GOOGLE_PAY","SHOPIFY_PAY","FACEBOOK_PAY","AMAZON_PAY"]}, +"Discount":{"u":["DiscountAutomaticApp","DiscountAutomaticBasic","DiscountAutomaticBxgy","DiscountAutomaticFreeShipping","DiscountCodeApp","DiscountCodeBasic","DiscountCodeBxgy","DiscountCodeFreeShipping"]}, +"DiscountAllocation":{"o":{"f":{"allocatedAmount":"MoneyV2!","allocatedAmountSet":"MoneyBag!","discountApplication":"DiscountApplication!"},"d":{"allocatedAmount":"Use `allocatedAmountSet` instead."}}}, +"DiscountAllocationConnection":{"o":{"f":{"edges":"[DiscountAllocationEdge!]!","nodes":"[DiscountAllocation!]!","pageInfo":"PageInfo!"}}}, +"DiscountAllocationEdge":{"o":{"f":{"cursor":"String!","node":"DiscountAllocation!"}}}, +"DiscountAmount":{"o":{"f":{"amount":"MoneyV2!","appliesOnEachItem":"Boolean!"}}}, +"DiscountAmountInput":{"i":{"amount":"Decimal","appliesOnEachItem":"Boolean"}}, +"DiscountApplication":{"n":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","index":"Int!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["AutomaticDiscountApplication","DiscountCodeApplication","ManualDiscountApplication","ScriptDiscountApplication"]}}, +"DiscountApplicationAllocationMethod":{"e":{"v":["ACROSS","EACH","ONE"],"d":{"ONE":"Use ACROSS instead."}}}, +"DiscountApplicationConnection":{"o":{"f":{"edges":"[DiscountApplicationEdge!]!","nodes":"[DiscountApplication!]!","pageInfo":"PageInfo!"}}}, +"DiscountApplicationEdge":{"o":{"f":{"cursor":"String!","node":"DiscountApplication!"}}}, +"DiscountApplicationLevel":{"e":["ORDER","LINE"]}, +"DiscountApplicationTargetSelection":{"e":["ALL","ENTITLED","EXPLICIT"]}, +"DiscountApplicationTargetType":{"e":["LINE_ITEM","SHIPPING_LINE"]}, +"DiscountAutomatic":{"u":["DiscountAutomaticApp","DiscountAutomaticBasic","DiscountAutomaticBxgy","DiscountAutomaticFreeShipping"]}, +"DiscountAutomaticActivatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticApp":{"o":{"f":{"appDiscountType":"AppDiscountType!","appliesOnOneTimePurchase":"Boolean!","appliesOnSubscription":"Boolean!","asyncUsageCount":"Int!","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","discountClass":"DiscountClass!","discountClasses":"[DiscountClass!]!","discountId":"ID!","endsAt":"DateTime","errorHistory":"FunctionsErrorHistory","recurringCycleLimit":"Int!","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"startsAt":"DateTime!","status":"DiscountStatus!","tags":"[String!]!","title":"String!","updatedAt":"DateTime!"},"t":["HasRollouts"],"d":{"discountClass":"Use `discountClasses` instead."}}}, +"DiscountAutomaticAppCreatePayload":{"o":{"f":{"automaticAppDiscount":"DiscountAutomaticApp","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticAppInput":{"i":{"f":{"appliesOnOneTimePurchase":"Boolean=","appliesOnSubscription":"Boolean=","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","discountClasses":"[DiscountClass!]","endsAt":"DateTime","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]=","recurringCycleLimit":"Int=","startsAt":"DateTime","tags":"[String!]","title":"String"},"d":{"functionId":"Use `functionHandle` instead."}}}, +"DiscountAutomaticAppUpdatePayload":{"o":{"f":{"automaticAppDiscount":"DiscountAutomaticApp","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticBasic":{"o":{"f":{"asyncUsageCount":"Int!","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerGets":"DiscountCustomerGets!","discountClass":"MerchandiseDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","minimumRequirement":"DiscountMinimumRequirement","recurringCycleLimit":"Int!","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shortSummary":"String!","startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","updatedAt":"DateTime!","usageCount":"Int!"},"t":["HasRollouts"],"d":{"discountClass":"Use `discountClasses` instead.","usageCount":"Use `asyncUsageCount` instead."}}}, +"DiscountAutomaticBasicCreatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticBasicInput":{"i":{"combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerGets":"DiscountCustomerGetsInput","endsAt":"DateTime","minimumRequirement":"DiscountMinimumRequirementInput","recurringCycleLimit":"Int","startsAt":"DateTime","tags":"[String!]","title":"String"}}, +"DiscountAutomaticBasicUpdatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticBulkDeletePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticBxgy":{"o":{"f":{"asyncUsageCount":"Int!","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerBuys":"DiscountCustomerBuys!","customerGets":"DiscountCustomerGets!","discountClass":"MerchandiseDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","updatedAt":"DateTime!","usageCount":"Int!","usesPerOrderLimit":"Int"},"t":["HasEvents","HasRollouts","Node"],"d":{"discountClass":"Use `discountClasses` instead.","id":"Use DiscountAutomaticNode.id instead.","usageCount":"Use `asyncUsageCount` instead."}}}, +"DiscountAutomaticBxgyCreatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticBxgyInput":{"i":{"combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerBuys":"DiscountCustomerBuysInput","customerGets":"DiscountCustomerGetsInput","endsAt":"DateTime","startsAt":"DateTime","tags":"[String!]","title":"String","usesPerOrderLimit":"UnsignedInt64"}}, +"DiscountAutomaticBxgyUpdatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticConnection":{"o":{"f":{"edges":"[DiscountAutomaticEdge!]!","nodes":"[DiscountAutomatic!]!","pageInfo":"PageInfo!"}}}, +"DiscountAutomaticDeactivatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticDeletePayload":{"o":{"f":{"deletedAutomaticDiscountId":"ID","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticEdge":{"o":{"f":{"cursor":"String!","node":"DiscountAutomatic!"}}}, +"DiscountAutomaticFreeShipping":{"o":{"f":{"appliesOnOneTimePurchase":"Boolean!","appliesOnSubscription":"Boolean!","asyncUsageCount":"Int!","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","destinationSelection":"DiscountShippingDestinationSelection!","discountClass":"ShippingDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","hasTimelineComment":"Boolean!","maximumShippingPrice":"MoneyV2","minimumRequirement":"DiscountMinimumRequirement","recurringCycleLimit":"Int!","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shortSummary":"String!","startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","totalSales":"MoneyV2","updatedAt":"DateTime!"},"t":["HasRollouts"],"d":{"discountClass":"Use `discountClasses` instead."}}}, +"DiscountAutomaticFreeShippingCreatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticFreeShippingInput":{"i":{"appliesOnOneTimePurchase":"Boolean","appliesOnSubscription":"Boolean","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","destination":"DiscountShippingDestinationSelectionInput","endsAt":"DateTime","maximumShippingPrice":"Decimal","minimumRequirement":"DiscountMinimumRequirementInput","recurringCycleLimit":"Int","startsAt":"DateTime","tags":"[String!]","title":"String"}}, +"DiscountAutomaticFreeShippingUpdatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticNode":{"o":{"f":{"automaticDiscount":"DiscountAutomatic!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"DiscountAutomaticNodeConnection":{"o":{"f":{"edges":"[DiscountAutomaticNodeEdge!]!","nodes":"[DiscountAutomaticNode!]!","pageInfo":"PageInfo!"}}}, +"DiscountAutomaticNodeEdge":{"o":{"f":{"cursor":"String!","node":"DiscountAutomaticNode!"}}}, +"DiscountBulkTagsAddPayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountBulkTagsRemovePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountBuyerSelection":{"e":["ALL"]}, +"DiscountBuyerSelectionAll":{"o":{"f":{"all":"DiscountBuyerSelection!"}}}, +"DiscountClass":{"e":["PRODUCT","ORDER","SHIPPING"]}, +"DiscountCode":{"u":["DiscountCodeApp","DiscountCodeBasic","DiscountCodeBxgy","DiscountCodeFreeShipping"]}, +"DiscountCodeActivatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeApp":{"o":{"f":{"appDiscountType":"AppDiscountType!","appliesOnOneTimePurchase":"Boolean!","appliesOnSubscription":"Boolean!","appliesOncePerCustomer":"Boolean!","asyncUsageCount":"Int!","codes":["DiscountRedeemCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DiscountCodeSortKeys="}],"codesCount":"Count","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerSelection":"DiscountCustomerSelection!","discountClass":"DiscountClass!","discountClasses":"[DiscountClass!]!","discountId":"ID!","endsAt":"DateTime","errorHistory":"FunctionsErrorHistory","hasTimelineComment":"Boolean!","recurringCycleLimit":"Int","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shareableUrls":"[DiscountShareableUrl!]!","startsAt":"DateTime!","status":"DiscountStatus!","tags":"[String!]!","title":"String!","totalSales":"MoneyV2","updatedAt":"DateTime!","usageLimit":"Int"},"t":["HasRollouts"],"d":{"customerSelection":"Use `context` instead.","discountClass":"Use `discountClasses` instead."}}}, +"DiscountCodeAppCreatePayload":{"o":{"f":{"codeAppDiscount":"DiscountCodeApp","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeAppInput":{"i":{"f":{"appliesOnOneTimePurchase":"Boolean=","appliesOnSubscription":"Boolean=","appliesOncePerCustomer":"Boolean","code":"String","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerSelection":"DiscountCustomerSelectionInput","discountClasses":"[DiscountClass!]","endsAt":"DateTime","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]=","recurringCycleLimit":"Int=","startsAt":"DateTime","tags":"[String!]","title":"String","usageLimit":"Int"},"d":{"customerSelection":"Use `context` instead.","functionId":"Use `functionHandle` instead."}}}, +"DiscountCodeAppUpdatePayload":{"o":{"f":{"codeAppDiscount":"DiscountCodeApp","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","code":"String!","index":"Int!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["DiscountApplication"]}}, +"DiscountCodeBasic":{"o":{"f":{"appliesOncePerCustomer":"Boolean!","asyncUsageCount":"Int!","codes":["DiscountRedeemCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DiscountCodeSortKeys="}],"codesCount":"Count","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerGets":"DiscountCustomerGets!","customerSelection":"DiscountCustomerSelection!","discountClass":"MerchandiseDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","hasTimelineComment":"Boolean!","minimumRequirement":"DiscountMinimumRequirement","recurringCycleLimit":"Int","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shareableUrls":"[DiscountShareableUrl!]!","shortSummary":"String!","startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","totalSales":"MoneyV2","updatedAt":"DateTime!","usageLimit":"Int"},"t":["HasRollouts"],"d":{"customerSelection":"Use `context` instead.","discountClass":"Use `discountClasses` instead."}}}, +"DiscountCodeBasicCreatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBasicInput":{"i":{"f":{"appliesOncePerCustomer":"Boolean","code":"String","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerGets":"DiscountCustomerGetsInput","customerSelection":"DiscountCustomerSelectionInput","endsAt":"DateTime","minimumRequirement":"DiscountMinimumRequirementInput","recurringCycleLimit":"Int","startsAt":"DateTime","tags":"[String!]","title":"String","usageLimit":"Int"},"d":{"customerSelection":"Use `context` instead."}}}, +"DiscountCodeBasicUpdatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBulkActivatePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBulkDeactivatePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBulkDeletePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBxgy":{"o":{"f":{"appliesOncePerCustomer":"Boolean!","asyncUsageCount":"Int!","codes":["DiscountRedeemCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DiscountCodeSortKeys="}],"codesCount":"Count","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerBuys":"DiscountCustomerBuys!","customerGets":"DiscountCustomerGets!","customerSelection":"DiscountCustomerSelection!","discountClass":"MerchandiseDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","hasTimelineComment":"Boolean!","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shareableUrls":"[DiscountShareableUrl!]!","startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","totalSales":"MoneyV2","updatedAt":"DateTime!","usageLimit":"Int","usesPerOrderLimit":"Int"},"t":["HasRollouts"],"d":{"customerSelection":"Use `context` instead.","discountClass":"Use `discountClasses` instead."}}}, +"DiscountCodeBxgyCreatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBxgyInput":{"i":{"f":{"appliesOncePerCustomer":"Boolean","code":"String","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerBuys":"DiscountCustomerBuysInput","customerGets":"DiscountCustomerGetsInput","customerSelection":"DiscountCustomerSelectionInput","endsAt":"DateTime","startsAt":"DateTime","tags":"[String!]","title":"String","usageLimit":"Int","usesPerOrderLimit":"Int"},"d":{"customerSelection":"Use `context` instead."}}}, +"DiscountCodeBxgyUpdatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeDeactivatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeDeletePayload":{"o":{"f":{"deletedCodeDiscountId":"ID","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeFreeShipping":{"o":{"f":{"appliesOnOneTimePurchase":"Boolean!","appliesOnSubscription":"Boolean!","appliesOncePerCustomer":"Boolean!","asyncUsageCount":"Int!","codes":["DiscountRedeemCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DiscountCodeSortKeys="}],"codesCount":"Count","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerSelection":"DiscountCustomerSelection!","destinationSelection":"DiscountShippingDestinationSelection!","discountClass":"ShippingDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","hasTimelineComment":"Boolean!","maximumShippingPrice":"MoneyV2","minimumRequirement":"DiscountMinimumRequirement","recurringCycleLimit":"Int","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shareableUrls":"[DiscountShareableUrl!]!","shortSummary":"String!","startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","totalSales":"MoneyV2","updatedAt":"DateTime!","usageLimit":"Int"},"t":["HasRollouts"],"d":{"customerSelection":"Use `context` instead.","discountClass":"Use `discountClasses` instead."}}}, +"DiscountCodeFreeShippingCreatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeFreeShippingInput":{"i":{"f":{"appliesOnOneTimePurchase":"Boolean","appliesOnSubscription":"Boolean","appliesOncePerCustomer":"Boolean","code":"String","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerSelection":"DiscountCustomerSelectionInput","destination":"DiscountShippingDestinationSelectionInput","endsAt":"DateTime","maximumShippingPrice":"Decimal","minimumRequirement":"DiscountMinimumRequirementInput","recurringCycleLimit":"Int","startsAt":"DateTime","tags":"[String!]","title":"String","usageLimit":"Int"},"d":{"customerSelection":"Use `context` instead."}}}, +"DiscountCodeFreeShippingUpdatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeNode":{"o":{"f":{"codeDiscount":"DiscountCode!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"DiscountCodeNodeConnection":{"o":{"f":{"edges":"[DiscountCodeNodeEdge!]!","nodes":"[DiscountCodeNode!]!","pageInfo":"PageInfo!"}}}, +"DiscountCodeNodeEdge":{"o":{"f":{"cursor":"String!","node":"DiscountCodeNode!"}}}, +"DiscountCodeRedeemCodeBulkDeletePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeSortKeys":{"e":["CODE","CREATED_AT","ID","RELEVANCE"]}, +"DiscountCollections":{"o":{"f":{"collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"DiscountCollectionsInput":{"i":{"add":"[ID!]","remove":"[ID!]"}}, +"DiscountCombinesWith":{"o":{"f":{"orderDiscounts":"Boolean!","productDiscounts":"Boolean!","productDiscountsWithTagsOnSameCartLine":"[String!]","shippingDiscounts":"Boolean!"}}}, +"DiscountCombinesWithInput":{"i":{"orderDiscounts":"Boolean=","productDiscounts":"Boolean=","productDiscountsWithTagsOnSameCartLine":"ProductDiscountsWithTagsOnSameCartLineInput","shippingDiscounts":"Boolean="}}, +"DiscountContext":{"u":["DiscountBuyerSelectionAll","DiscountContextUnknown","DiscountCustomerSegments","DiscountCustomers","DiscountMarkets"]}, +"DiscountContextInput":{"i":{"all":"DiscountBuyerSelection","customerSegments":"DiscountCustomerSegmentsInput","customers":"DiscountCustomersInput","markets":"DiscountMarketsInput"}}, +"DiscountContextUnknown":{"o":{"f":{"contextType":"String!"}}}, +"DiscountCountries":{"o":{"f":{"countries":"[CountryCode!]!","includeRestOfWorld":"Boolean!"},"d":{"includeRestOfWorld":"This field is being retired. Discounts that set `includeRestOfWorld: true` will be converted to an explicit list of countries, and `countries` will then return every country where the discount applies."}}}, +"DiscountCountriesInput":{"i":{"f":{"add":"[CountryCode!]","includeRestOfWorld":"Boolean=","remove":"[CountryCode!]"},"d":{"includeRestOfWorld":"This field is being retired. Use `add` to specify each country where the discount should apply."}}}, +"DiscountCountryAll":{"o":{"f":{"allCountries":"Boolean!"}}}, +"DiscountCustomerAll":{"o":{"f":{"allCustomers":"Boolean!"}}}, +"DiscountCustomerBuys":{"o":{"f":{"isOneTimePurchase":"Boolean!","isSubscription":"Boolean!","items":"DiscountItems!","value":"DiscountCustomerBuysValue!"}}}, +"DiscountCustomerBuysInput":{"i":{"isOneTimePurchase":"Boolean=","isSubscription":"Boolean=","items":"DiscountItemsInput","value":"DiscountCustomerBuysValueInput"}}, +"DiscountCustomerBuysValue":{"u":["DiscountPurchaseAmount","DiscountQuantity"]}, +"DiscountCustomerBuysValueInput":{"i":{"amount":"Decimal","quantity":"UnsignedInt64"}}, +"DiscountCustomerGets":{"o":{"f":{"appliesOnOneTimePurchase":"Boolean!","appliesOnSubscription":"Boolean!","items":"DiscountItems!","value":"DiscountCustomerGetsValue!"}}}, +"DiscountCustomerGetsInput":{"i":{"appliesOnOneTimePurchase":"Boolean","appliesOnSubscription":"Boolean","items":"DiscountItemsInput","value":"DiscountCustomerGetsValueInput"}}, +"DiscountCustomerGetsValue":{"u":["DiscountAmount","DiscountOnQuantity","DiscountPercentage"]}, +"DiscountCustomerGetsValueInput":{"i":{"discountAmount":"DiscountAmountInput","discountOnQuantity":"DiscountOnQuantityInput","percentage":"Float"}}, +"DiscountCustomerSegments":{"o":{"f":{"segments":"[Segment!]!"}}}, +"DiscountCustomerSegmentsInput":{"i":{"add":"[ID!]","remove":"[ID!]"}}, +"DiscountCustomerSelection":{"u":["DiscountCustomerAll","DiscountCustomerSegments","DiscountCustomerSelectionUnknown","DiscountCustomers"]}, +"DiscountCustomerSelectionInput":{"i":{"all":"Boolean","customerSegments":"DiscountCustomerSegmentsInput","customers":"DiscountCustomersInput"}}, +"DiscountCustomerSelectionUnknown":{"o":{"f":{"customerSelectionType":"String!"}}}, +"DiscountCustomers":{"o":{"f":{"customers":"[Customer!]!"}}}, +"DiscountCustomersInput":{"i":{"add":"[ID!]","remove":"[ID!]"}}, +"DiscountEffect":{"u":["DiscountAmount","DiscountPercentage"]}, +"DiscountEffectInput":{"i":{"amount":"Decimal","percentage":"Float"}}, +"DiscountErrorCode":{"e":["BLANK","PRESENT","EQUAL_TO","GREATER_THAN","GREATER_THAN_OR_EQUAL_TO","INVALID","LESS_THAN_OR_EQUAL_TO","LESS_THAN","TAKEN","TOO_LONG","TOO_SHORT","INTERNAL_ERROR","TOO_MANY_ARGUMENTS","MISSING_ARGUMENT","ACTIVE_PERIOD_OVERLAP","END_DATE_BEFORE_START_DATE","EXCEEDED_MAX","MINIMUM_SUBTOTAL_AND_QUANTITY_RANGE_BOTH_PRESENT","VALUE_OUTSIDE_RANGE","CONFLICT","IMPLICIT_DUPLICATE","DUPLICATE","INCLUSION","INVALID_COMBINES_WITH_FOR_DISCOUNT_CLASS","INVALID_DISCOUNT_CLASS_FOR_PRICE_RULE","DISCOUNT_NOT_COMPATIBLE_WITH_CONDITION_TYPES","MAX_APP_DISCOUNTS","APPLIES_ON_NOTHING","RECURRING_CYCLE_LIMIT_NOT_A_VALID_INTEGER","MULTIPLE_RECURRING_CYCLE_LIMIT_FOR_NON_SUBSCRIPTION_ITEMS","MISSING_FUNCTION_IDENTIFIER","MULTIPLE_FUNCTION_IDENTIFIERS","INVALID_TAG_LENGTH","TOO_MANY_TAGS","TOO_MANY_PRODUCT_DISCOUNTS_WITH_TAGS_ON_SAME_CART_LINE","INVALID_PRODUCT_DISCOUNTS_WITH_TAGS_ON_SAME_CART_LINE_FOR_DISCOUNT_CLASS","INVALID_PRODUCT_DISCOUNTS_WITH_TAGS_ON_SAME_CART_LINE_WITHOUT_PRODUCT_DISCOUNTS","INVALID_PRODUCT_DISCOUNTS_FALSE_WITH_EXISTING_TAGS_ON_SAME_CART_LINE","PRODUCT_DISCOUNTS_WITH_TAGS_ON_SAME_CART_LINE_NOT_ENTITLED"]}, +"DiscountItems":{"u":["AllDiscountItems","DiscountCollections","DiscountProducts"]}, +"DiscountItemsInput":{"i":{"all":"Boolean","collections":"DiscountCollectionsInput","products":"DiscountProductsInput"}}, +"DiscountMarkets":{"o":{"f":{"markets":["MarketConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"marketsCount":"Int!"}}}, +"DiscountMarketsInput":{"i":{"add":"[ID!]","remove":"[ID!]"}}, +"DiscountMinimumQuantity":{"o":{"f":{"greaterThanOrEqualToQuantity":"UnsignedInt64!"}}}, +"DiscountMinimumQuantityInput":{"i":{"greaterThanOrEqualToQuantity":"UnsignedInt64"}}, +"DiscountMinimumRequirement":{"u":["DiscountMinimumQuantity","DiscountMinimumSubtotal"]}, +"DiscountMinimumRequirementInput":{"i":{"quantity":"DiscountMinimumQuantityInput","subtotal":"DiscountMinimumSubtotalInput"}}, +"DiscountMinimumSubtotal":{"o":{"f":{"greaterThanOrEqualToSubtotal":"MoneyV2!"}}}, +"DiscountMinimumSubtotalInput":{"i":{"greaterThanOrEqualToSubtotal":"Decimal"}}, +"DiscountNode":{"o":{"f":{"discount":"Discount!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"DiscountNodeConnection":{"o":{"f":{"edges":"[DiscountNodeEdge!]!","nodes":"[DiscountNode!]!","pageInfo":"PageInfo!"}}}, +"DiscountNodeEdge":{"o":{"f":{"cursor":"String!","node":"DiscountNode!"}}}, +"DiscountOnQuantity":{"o":{"f":{"effect":"DiscountEffect!","quantity":"DiscountQuantity!"}}}, +"DiscountOnQuantityInput":{"i":{"effect":"DiscountEffectInput","quantity":"UnsignedInt64"}}, +"DiscountPercentage":{"o":{"f":{"percentage":"Float!"}}}, +"DiscountProducts":{"o":{"f":{"productVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"DiscountProductsInput":{"i":{"productVariantsToAdd":"[ID!]","productVariantsToRemove":"[ID!]","productsToAdd":"[ID!]","productsToRemove":"[ID!]"}}, +"DiscountPurchaseAmount":{"o":{"f":{"amount":"Decimal!"}}}, +"DiscountQuantity":{"o":{"f":{"quantity":"UnsignedInt64!"}}}, +"DiscountRedeemCode":{"o":{"f":{"asyncUsageCount":"Int!","code":"String!","createdAt":"DateTime!","createdBy":"App","id":"ID!"}}}, +"DiscountRedeemCodeBulkAddPayload":{"o":{"f":{"bulkCreation":"DiscountRedeemCodeBulkCreation","userErrors":"[DiscountUserError!]!"}}}, +"DiscountRedeemCodeBulkCreation":{"o":{"f":{"codes":["DiscountRedeemCodeBulkCreationCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"codesCount":"Int!","createdAt":"DateTime!","discountCode":"DiscountCodeNode","done":"Boolean!","failedCount":"Int!","id":"ID!","importedCount":"Int!"},"t":["Node"]}}, +"DiscountRedeemCodeBulkCreationCode":{"o":{"f":{"code":"String!","discountRedeemCode":"DiscountRedeemCode","errors":"[DiscountUserError!]!"}}}, +"DiscountRedeemCodeBulkCreationCodeConnection":{"o":{"f":{"edges":"[DiscountRedeemCodeBulkCreationCodeEdge!]!","nodes":"[DiscountRedeemCodeBulkCreationCode!]!","pageInfo":"PageInfo!"}}}, +"DiscountRedeemCodeBulkCreationCodeEdge":{"o":{"f":{"cursor":"String!","node":"DiscountRedeemCodeBulkCreationCode!"}}}, +"DiscountRedeemCodeConnection":{"o":{"f":{"edges":"[DiscountRedeemCodeEdge!]!","nodes":"[DiscountRedeemCode!]!","pageInfo":"PageInfo!"}}}, +"DiscountRedeemCodeEdge":{"o":{"f":{"cursor":"String!","node":"DiscountRedeemCode!"}}}, +"DiscountRedeemCodeInput":{"i":{"code":"String!"}}, +"DiscountShareableUrl":{"o":{"f":{"targetItemImage":"Image","targetType":"DiscountShareableUrlTargetType!","title":"String!","url":"URL!"}}}, +"DiscountShareableUrlTargetType":{"e":["HOME","PRODUCT","COLLECTION"]}, +"DiscountShippingDestinationSelection":{"u":["DiscountCountries","DiscountCountryAll"]}, +"DiscountShippingDestinationSelectionInput":{"i":{"all":"Boolean=","countries":"DiscountCountriesInput"}}, +"DiscountSortKeys":{"e":["CREATED_AT","ENDS_AT","ID","RELEVANCE","STARTS_AT","TITLE","UPDATED_AT"]}, +"DiscountStatus":{"e":["ACTIVE","EXPIRED","SCHEDULED"]}, +"DiscountTagSortKeys":{"e":["ID","TITLE"]}, +"DiscountTargetType":{"e":["LINE_ITEM","SHIPPING_LINE"]}, +"DiscountType":{"e":["MANUAL","CODE_DISCOUNT","AUTOMATIC_DISCOUNT"]}, +"DiscountUserError":{"o":{"f":{"code":"DiscountErrorCode","extraInfo":"String","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DisplayableError":{"n":{"f":{"field":"[String!]","message":"String!"},"t":["AbandonmentEmailStateUpdateUserError","AbandonmentUpdateActivitiesDeliveryStatusesUserError","AnalyticsAnnotationCreateUserError","AnalyticsAnnotationDeleteUserError","AnalyticsAnnotationUpdateUserError","AnalyticsTargetCreateUserError","AnalyticsTargetUpdateUserError","AnalyticsTargetsDeleteUserError","AppRevokeAccessScopesAppRevokeScopeError","AppSubscriptionTrialExtendUserError","AppUninstallAppUninstallError","ArticleCreateUserError","ArticleDeleteUserError","ArticleUpdateUserError","BillingAttemptUserError","BlogCreateUserError","BlogDeleteUserError","BlogUpdateUserError","BulkMutationUserError","BulkOperationUserError","BulkProductResourceFeedbackCreateUserError","BusinessCustomerUserError","CarrierServiceCreateUserError","CarrierServiceDeleteUserError","CarrierServiceUpdateUserError","CartTransformCreateUserError","CartTransformDeleteUserError","CashDrawerCreateUserError","CashDrawerFindOrCreateUserError","CashDrawerUpdateUserError","CashManagementReasonCodeCreateUserError","CashManagementReasonCodeDeleteUserError","CatalogUserError","ChannelCreateUserError","ChannelDeleteUserError","ChannelFullSyncUserError","ChannelUpdateUserError","CheckoutAndAccountsConfigurationUserError","CheckoutBrandingUpsertUserError","CollectionAddProductsV2UserError","CollectionDuplicateUserError","CollectionReorderProductsUserError","CombinedListingUpdateUserError","CommentApproveUserError","CommentDeleteUserError","CommentNotSpamUserError","CommentSpamUserError","ConsentPolicyError","CustomerCancelDataErasureUserError","CustomerEmailMarketingConsentUpdateUserError","CustomerMarketingConsentError","CustomerMergeUserError","CustomerPaymentMethodCreateFromDuplicationDataUserError","CustomerPaymentMethodGetDuplicationDataUserError","CustomerPaymentMethodGetUpdateUrlUserError","CustomerPaymentMethodRemoteUserError","CustomerPaymentMethodUserError","CustomerRequestDataErasureUserError","CustomerSegmentMembersQueryUserError","CustomerSendAccountInviteEmailUserError","CustomerSetUserError","CustomerSmsMarketingConsentError","DataSaleOptOutUserError","DelegateAccessTokenCreateUserError","DelegateAccessTokenDestroyUserError","DeliveryCustomizationError","DeliveryLocationLocalPickupSettingsError","DeliveryPromiseProviderUpsertUserError","DiscountUserError","DisputeEvidenceUpdateUserError","ErrorsServerPixelUserError","ErrorsWebPixelUserError","FilesUserError","FulfillmentConstraintRuleCreateUserError","FulfillmentConstraintRuleDeleteUserError","FulfillmentConstraintRuleUpdateUserError","FulfillmentOrderCancelError","FulfillmentOrderHoldUserError","FulfillmentOrderLineItemsPreparedForPickupUserError","FulfillmentOrderMergeUserError","FulfillmentOrderMoveFulfillmentOrderMoveUserError","FulfillmentOrderReleaseHoldUserError","FulfillmentOrderReportProgressUserError","FulfillmentOrderRescheduleUserError","FulfillmentOrderSplitUserError","FulfillmentOrdersRerouteUserError","FulfillmentOrdersSetFulfillmentDeadlineUserError","GiftCardDeactivateUserError","GiftCardProductSetUserError","GiftCardSendNotificationToCustomerUserError","GiftCardSendNotificationToRecipientUserError","GiftCardTransactionUserError","GiftCardUserError","InventoryAdjustQuantitiesUserError","InventoryBulkToggleActivationUserError","InventoryMoveQuantitiesUserError","InventorySetOnHandQuantitiesUserError","InventorySetQuantitiesUserError","InventoryShipmentAddItemsUserError","InventoryShipmentCreateInTransitUserError","InventoryShipmentCreateUserError","InventoryShipmentDeleteUserError","InventoryShipmentMarkInTransitUserError","InventoryShipmentReceiveUserError","InventoryShipmentRemoveItemsUserError","InventoryShipmentSetBarcodeUserError","InventoryShipmentSetTrackingUserError","InventoryShipmentUpdateItemQuantitiesUserError","InventoryTransferCancelUserError","InventoryTransferCreateAsReadyToShipUserError","InventoryTransferCreateUserError","InventoryTransferDeleteUserError","InventoryTransferDuplicateUserError","InventoryTransferEditUserError","InventoryTransferMarkAsReadyToShipUserError","InventoryTransferRemoveItemsUserError","InventoryTransferSetItemsUserError","LocationActivateUserError","LocationAddUserError","LocationDeactivateUserError","LocationDeleteUserError","LocationEditUserError","MarketCurrencySettingsUserError","MarketUserError","MarketingActivityUserError","MediaUserError","MenuCreateUserError","MenuDeleteUserError","MenuUpdateUserError","MetafieldDefinitionCreateUserError","MetafieldDefinitionDeleteUserError","MetafieldDefinitionPinUserError","MetafieldDefinitionUnpinUserError","MetafieldDefinitionUpdateUserError","MetafieldsSetUserError","MetaobjectUserError","MobilePlatformApplicationUserError","OnlineStoreThemeFilesUserErrors","OrderAttributionDefinitionDeleteUserError","OrderAttributionDefinitionUpsertUserError","OrderCancelUserError","OrderCreateMandatePaymentUserError","OrderCreateManualPaymentOrderCreateManualPaymentError","OrderCreateUserError","OrderCustomerRemoveUserError","OrderCustomerSetUserError","OrderDeleteUserError","OrderEditAddShippingLineUserError","OrderEditRemoveDiscountUserError","OrderEditRemoveShippingLineUserError","OrderEditUpdateDiscountUserError","OrderEditUpdateShippingLineUserError","OrderInvoiceSendUserError","OrderRiskAssessmentCreateUserError","PageCreateUserError","PageDeleteUserError","PageUpdateUserError","PaymentCustomizationError","PaymentReminderSendUserError","PaymentScheduleCaptureUserError","PaymentTermsCreateUserError","PaymentTermsDeleteUserError","PaymentTermsUpdateUserError","PointOfSaleDeviceAssignToCashDrawerUserError","PointOfSaleDevicePaymentSessionCloseUserError","PointOfSaleDevicePaymentSessionCountUserError","PointOfSaleDevicePaymentSessionOpenUserError","PreviewInstallUserError","PriceListFixedPricesByProductBulkUpdateUserError","PriceListPriceUserError","PriceListUserError","PrivacyFeaturesDisableUserError","ProductBundleMutationUserError","ProductChangeStatusUserError","ProductFeedCreateUserError","ProductFeedDeleteUserError","ProductFullSyncUserError","ProductOptionUpdateUserError","ProductOptionsCreateUserError","ProductOptionsDeleteUserError","ProductOptionsReorderUserError","ProductSetUserError","ProductVariantRelationshipBulkUpdateUserError","ProductVariantsBulkCreateUserError","ProductVariantsBulkDeleteUserError","ProductVariantsBulkReorderUserError","ProductVariantsBulkUpdateUserError","PubSubWebhookSubscriptionCreateUserError","PubSubWebhookSubscriptionUpdateUserError","PublicationUserError","QuantityPricingByVariantUserError","QuantityRuleUserError","RequestedOrderEditCreateUserError","RequestedOrderEditDeclineUserError","RequestedOrderEditResolveUserError","ReturnUserError","SellingPlanGroupUserError","ShippingLabelPurchaseError","ShippingLabelPurchaseUserError","ShopPolicyUserError","ShopResourceFeedbackCreateUserError","ShopifyPaymentsPayoutAlternateCurrencyCreateUserError","StandardMetafieldDefinitionEnableUserError","StoreCreditAccountCreditUserError","StoreCreditAccountDebitUserError","SubscriptionBillingCycleBulkUserError","SubscriptionBillingCycleContractEditCalculateUserError","SubscriptionBillingCycleSkipUserError","SubscriptionBillingCycleUnskipUserError","SubscriptionBillingCycleUserError","SubscriptionContractCalculationCommitUserError","SubscriptionContractCreateCalculateUserError","SubscriptionContractStatusUpdateUserError","SubscriptionContractUpdateCalculateUserError","SubscriptionContractUserError","SubscriptionDraftUserError","TaxAppConfigureUserError","TaxSummaryCreateUserError","ThemeCreateUserError","ThemeDeleteUserError","ThemeDuplicateUserError","ThemePublishUserError","ThemeUpdateUserError","TransactionVoidUserError","TranslationUserError","UrlRedirectBulkDeleteByIdsUserError","UrlRedirectBulkDeleteBySavedSearchUserError","UrlRedirectBulkDeleteBySearchUserError","UrlRedirectImportUserError","UrlRedirectUserError","UserError","ValidationUserError"]}}, +"DisputeEvidenceUpdatePayload":{"o":{"f":{"disputeEvidence":"ShopifyPaymentsDisputeEvidence","userErrors":"[DisputeEvidenceUpdateUserError!]!"}}}, +"DisputeEvidenceUpdateUserError":{"o":{"f":{"code":"DisputeEvidenceUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DisputeEvidenceUpdateUserErrorCode":{"e":["DISPUTE_EVIDENCE_NOT_FOUND","EVIDENCE_ALREADY_ACCEPTED","EVIDENCE_PAST_DUE_DATE","EVIDENCE_UNDER_REVIEW","FILES_SIZE_EXCEEDED_LIMIT","FILE_NOT_FOUND","TOO_LARGE","INVALID"]}, +"DisputeStatus":{"e":{"v":["ACCEPTED","LOST","NEEDS_RESPONSE","PREVENTED","UNDER_REVIEW","WON","CHARGE_REFUNDED"],"d":{"CHARGE_REFUNDED":"CHARGE_REFUNDED is no longer supported."}}}, +"DisputeType":{"e":["CHARGEBACK","INQUIRY"]}, +"Distance":{"o":{"f":{"unit":"DistanceUnit!","value":"Float!"}}}, +"DistanceUnit":{"e":["KILOMETERS","MILES"]}, +"Domain":{"o":{"f":{"createdAt":"DateTime!","host":"String!","id":"ID!","localization":"DomainLocalization","marketWebPresence":"MarketWebPresence","sslEnabled":"Boolean!","url":"URL!"},"t":["Node"]}}, +"DomainLocalization":{"o":{"f":{"alternateLocales":"[String!]!","country":"String","defaultLocale":"String!"}}}, +"DraftOrder":{"o":{"f":{"acceptAutomaticDiscounts":"Boolean","allVariantPricesOverridden":"Boolean!","allowDiscountCodesInCheckout":"Boolean!","amountDueLaterSet":"MoneyBag!","amountDueNowSet":"MoneyBag!","anyVariantPricesOverridden":"Boolean!","appliedDiscount":"DraftOrderAppliedDiscount","billingAddress":"MailingAddress","billingAddressMatchesShippingAddress":"Boolean!","completedAt":"DateTime","createdAt":"DateTime!","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer","defaultCursor":"String!","deposit":"DepositConfiguration","discountCodes":"[String!]!","email":"String","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"hasTimelineComment":"Boolean!","id":"ID!","invoiceEmailTemplateSubject":"String!","invoiceSentAt":"DateTime","invoiceUrl":"URL","legacyResourceId":"UnsignedInt64!","lineItems":["DraftOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"lineItemsSubtotalPrice":"MoneyBag!","localizationExtensions":["LocalizationExtensionConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizationExtensionPurpose!]","reverse":"Boolean="}],"localizedFields":["LocalizedFieldConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizedFieldPurpose!]","reverse":"Boolean="}],"marketName":"String!","marketRegionCountryCode":"CountryCode!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","note2":"String","order":"Order","paymentTerms":"PaymentTerms","phone":"String","platformDiscounts":"[DraftOrderPlatformDiscount!]!","poNumber":"String","presentmentCurrencyCode":"CurrencyCode!","purchasingEntity":"PurchasingEntity","ready":"Boolean!","reserveInventoryUntil":"DateTime","shippingAddress":"MailingAddress","shippingLine":"ShippingLine","status":"DraftOrderStatus!","subtotalPrice":"Money!","subtotalPriceSet":"MoneyBag!","tags":"[String!]!","taxExempt":"Boolean!","taxLines":"[TaxLine!]!","taxesIncluded":"Boolean!","totalDiscountsSet":"MoneyBag!","totalLineItemsPriceSet":"MoneyBag!","totalPrice":"Money!","totalPriceSet":"MoneyBag!","totalQuantityOfLineItems":"Int!","totalShippingPrice":"Money!","totalShippingPriceSet":"MoneyBag!","totalTax":"Money!","totalTaxSet":"MoneyBag!","totalWeight":"UnsignedInt64!","transformerFingerprint":"String","updatedAt":"DateTime!","visibleToCustomer":"Boolean!","warnings":"[DraftOrderWarning!]!"},"t":["CommentEventSubject","HasEvents","HasLocalizationExtensions","HasLocalizedFields","HasMetafields","LegacyInteroperability","Navigable","Node"],"d":{"localizationExtensions":"This connection will be removed in a future version. Use `localizedFields` instead.","marketName":"This field is now incompatible with Markets.","marketRegionCountryCode":"This field is now incompatible with Markets.","subtotalPrice":"Use `subtotalPriceSet` instead.","totalPrice":"Use `totalPriceSet` instead.","totalShippingPrice":"Use `totalShippingPriceSet` instead.","totalTax":"Use `totalTaxSet` instead."}}}, +"DraftOrderAppliedDiscount":{"o":{"f":{"amount":"Money!","amountSet":"MoneyBag!","amountV2":"MoneyV2!","description":"String!","title":"String","value":"Float!","valueType":"DraftOrderAppliedDiscountType!"},"d":{"amount":"Use `amountSet` instead.","amountV2":"Use `amountSet` instead."}}}, +"DraftOrderAppliedDiscountInput":{"i":{"f":{"amount":"Money","amountWithCurrency":"MoneyInput","description":"String","title":"String","value":"Float!","valueType":"DraftOrderAppliedDiscountType!"},"d":{"amount":"Please use `amountWithCurrency` instead."}}}, +"DraftOrderAppliedDiscountType":{"e":["FIXED_AMOUNT","PERCENTAGE"]}, +"DraftOrderAvailableDeliveryOptions":{"o":{"f":{"availableLocalDeliveryRates":"[DraftOrderShippingRate!]!","availableLocalPickupOptions":"[PickupInStoreLocation!]!","availableShippingRates":"[DraftOrderShippingRate!]!","pageInfo":"PageInfo!"}}}, +"DraftOrderAvailableDeliveryOptionsInput":{"i":{"acceptAutomaticDiscounts":"Boolean","appliedDiscount":"DraftOrderAppliedDiscountInput","discountCodes":"[String!]","lineItems":"[DraftOrderLineItemInput!]","marketRegionCountryCode":"CountryCode","purchasingEntity":"PurchasingEntityInput","shippingAddress":"MailingAddressInput"}}, +"DraftOrderBulkAddTagsPayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"DraftOrderBulkDeletePayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"DraftOrderBulkRemoveTagsPayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"DraftOrderBundleAddedWarning":{"o":{"f":{"errorCode":"String!","field":"String!","message":"String!"},"t":["DraftOrderWarning"]}}, +"DraftOrderCalculatePayload":{"o":{"f":{"calculatedDraftOrder":"CalculatedDraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderCompletePayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderConnection":{"o":{"f":{"edges":"[DraftOrderEdge!]!","nodes":"[DraftOrder!]!","pageInfo":"PageInfo!"}}}, +"DraftOrderCreateFromOrderPayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderCreatePayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderDeleteInput":{"i":{"id":"ID!"}}, +"DraftOrderDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[UserError!]!"}}}, +"DraftOrderDiscountNotAppliedWarning":{"o":{"f":{"discountCode":"String","discountTitle":"String","errorCode":"String!","field":"String!","message":"String!"},"t":["DraftOrderWarning"]}}, +"DraftOrderDuplicatePayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderEdge":{"o":{"f":{"cursor":"String!","node":"DraftOrder!"}}}, +"DraftOrderInput":{"i":{"f":{"acceptAutomaticDiscounts":"Boolean","allowDiscountCodesInCheckout":"Boolean","appliedDiscount":"DraftOrderAppliedDiscountInput","billingAddress":"MailingAddressInput","customAttributes":"[AttributeInput!]","customerId":"ID","deposit":"DepositInput","discountCodes":"[String!]","email":"String","lineItems":"[DraftOrderLineItemInput!]","localizationExtensions":"[LocalizationExtensionInput!]","localizedFields":"[LocalizedFieldInput!]","marketRegionCountryCode":"CountryCode","metafields":"[MetafieldInput!]","note":"String","paymentTerms":"PaymentTermsInput","phone":"String","poNumber":"String","presentmentCurrencyCode":"CurrencyCode","purchasingEntity":"PurchasingEntityInput","reserveInventoryUntil":"DateTime","sessionToken":"String","shippingAddress":"MailingAddressInput","shippingLine":"ShippingLineInput","sourceName":"String","tags":"[String!]","taxExempt":"Boolean","transformerFingerprint":"String","useCustomerDefaultAddress":"Boolean","visibleToCustomer":"Boolean"},"d":{"customerId":"Use `purchasingEntity` instead, which can be used for either a D2C or B2B customer.","localizationExtensions":"This field will be removed in a future version. Use `localizedFields` instead.","marketRegionCountryCode":"This field is now incompatible with Markets."}}}, +"DraftOrderInvoicePreviewPayload":{"o":{"f":{"previewHtml":"HTML","previewSubject":"HTML","userErrors":"[UserError!]!"}}}, +"DraftOrderInvoiceSendPayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderLineItem":{"o":{"f":{"appliedDiscount":"DraftOrderAppliedDiscount","approximateDiscountedUnitPriceSet":"MoneyBag!","bundleComponents":"[DraftOrderLineItem!]!","components":"[DraftOrderLineItem!]!","custom":"Boolean!","customAttributes":"[Attribute!]!","customAttributesV2":"[TypedAttribute!]!","discountedTotal":"Money!","discountedTotalSet":"MoneyBag!","discountedUnitPrice":"Money!","discountedUnitPriceSet":"MoneyBag!","fulfillmentService":"FulfillmentService","grams":"Int","id":"ID!","image":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"isGiftCard":"Boolean!","name":"String!","originalTotal":"Money!","originalTotalSet":"MoneyBag!","originalUnitPrice":"Money!","originalUnitPriceSet":"MoneyBag!","originalUnitPriceWithCurrency":"MoneyV2","priceOverride":"MoneyV2","product":"Product","quantity":"Int!","requiresShipping":"Boolean!","sku":"String","taxLines":"[TaxLine!]!","taxable":"Boolean!","title":"String!","totalDiscount":"Money!","totalDiscountSet":"MoneyBag!","uuid":"String!","variant":"ProductVariant","variantTitle":"String","vendor":"String","weight":"Weight"},"t":["Node"],"d":{"bundleComponents":"Use `components` instead.","discountedTotal":"Use `discountedTotalSet` instead.","discountedUnitPrice":"Use `approximateDiscountedUnitPriceSet` instead.","discountedUnitPriceSet":"Use `approximateDiscountedUnitPriceSet` instead.","grams":"Use `weight` instead.","image(crop)":"Use `Image.url(transform: { crop:})` instead.","image(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","image(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","image(scale)":"Use `Image.url(transform: { scale:})` instead.","originalTotal":"Use `originalTotalSet` instead.","originalUnitPrice":"Use `originalUnitPriceWithCurrency` instead.","totalDiscount":"Use `totalDiscountSet` instead."}}}, +"DraftOrderLineItemComponentInput":{"i":{"quantity":"Int!","uuid":"String","variantId":"ID"}}, +"DraftOrderLineItemConnection":{"o":{"f":{"edges":"[DraftOrderLineItemEdge!]!","nodes":"[DraftOrderLineItem!]!","pageInfo":"PageInfo!"}}}, +"DraftOrderLineItemEdge":{"o":{"f":{"cursor":"String!","node":"DraftOrderLineItem!"}}}, +"DraftOrderLineItemInput":{"i":{"f":{"appliedDiscount":"DraftOrderAppliedDiscountInput","bundleComponents":"[BundlesDraftOrderBundleLineItemComponentInput!]","components":"[DraftOrderLineItemComponentInput!]","customAttributes":"[AttributeInput!]","generatePriceOverride":"Boolean","grams":"Int","originalUnitPrice":"Money","originalUnitPriceWithCurrency":"MoneyInput","priceOverride":"MoneyInput","quantity":"Int!","requiresShipping":"Boolean","sku":"String","taxable":"Boolean","title":"String","uuid":"String","variantId":"ID","weight":"WeightInput"},"d":{"bundleComponents":"Use `components` instead.","grams":"`weight` should be used instead, allowing different units to be used.","originalUnitPrice":"`originalUnitPriceWithCurrency` should be used instead, where currency can be specified."}}}, +"DraftOrderMarketRegionCountryCodeNotSupportedWarning":{"o":{"f":{"errorCode":"String!","field":"String!","message":"String!"},"t":["DraftOrderWarning"]}}, +"DraftOrderPlatformDiscount":{"o":{"f":{"allocations":"[DraftOrderPlatformDiscountAllocation!]!","automaticDiscount":"Boolean!","bxgyDiscount":"Boolean!","code":"String","discountClass":"DiscountClass!","discountClasses":"[DiscountClass!]!","discountNode":"DiscountNode","id":"ID","presentationLevel":"String!","shortSummary":"String!","summary":"String!","title":"String!","totalAmount":"MoneyV2!","totalAmountPriceSet":"MoneyBag!"},"d":{"discountClass":"Use `discountClasses` instead."}}}, +"DraftOrderPlatformDiscountAllocation":{"o":{"f":{"id":"ID","quantity":"Int","reductionAmount":"MoneyV2!","reductionAmountSet":"MoneyBag!","target":"DraftOrderPlatformDiscountAllocationTarget"}}}, +"DraftOrderPlatformDiscountAllocationTarget":{"u":["CalculatedDraftOrderLineItem","DraftOrderLineItem","ShippingLine"]}, +"DraftOrderShippingRate":{"o":{"f":{"code":"String!","handle":"String!","price":"MoneyV2!","source":"String!","title":"String!"}}}, +"DraftOrderSortKeys":{"e":["CUSTOMER_NAME","ID","NUMBER","RELEVANCE","STATUS","TOTAL_PRICE","UPDATED_AT"]}, +"DraftOrderStatus":{"e":["COMPLETED","INVOICE_SENT","OPEN"]}, +"DraftOrderTag":{"o":{"f":{"handle":"String!","id":"ID!","title":"String!"},"t":["Node"]}}, +"DraftOrderUpdatePayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderWarning":{"n":{"f":{"errorCode":"String!","field":"String!","message":"String!"},"t":["DraftOrderBundleAddedWarning","DraftOrderDiscountNotAppliedWarning","DraftOrderMarketRegionCountryCodeNotSupportedWarning"]}}, +"Duty":{"o":{"f":{"countryCodeOfOrigin":"CountryCode","harmonizedSystemCode":"String","id":"ID!","price":"MoneyBag!","taxLines":"[TaxLine!]!"},"t":["Node"]}}, +"DutySale":{"o":{"f":{"actionType":"SaleActionType!","duty":"Duty!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"EditableProperty":{"o":{"f":{"locked":"Boolean!","reason":"FormattedString"}}}, +"EmailInput":{"i":{"bcc":"[String!]","body":"String","customMessage":"String","from":"String","subject":"String","to":"String"}}, +"EntitlementsType":{"o":{"f":{"b2b":"B2BType!","markets":"MarketsType!"}}}, +"ErrorsServerPixelUserError":{"o":{"f":{"code":"ErrorsServerPixelUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ErrorsServerPixelUserErrorCode":{"e":["NOT_FOUND","ALREADY_EXISTS","PUB_SUB_ERROR","NEEDS_CONFIGURATION_TO_CONNECT"]}, +"ErrorsWebPixelUserError":{"o":{"f":{"code":"ErrorsWebPixelUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ErrorsWebPixelUserErrorCode":{"e":{"v":["BLANK","TAKEN","NOT_FOUND","INVALID_SETTINGS","UNABLE_TO_DELETE","NO_EXTENSION","INVALID_CONFIGURATION_JSON","INVALID_SETTINGS_DEFINITION","UNEXPECTED_ERROR","INVALID_RUNTIME_CONTEXT"],"d":{"UNABLE_TO_DELETE":"`UNABLE_TO_DELETE` is deprecated. Use `UNEXPECTED_ERROR` instead."}}}, +"Event":{"n":{"f":{"action":"String!","appTitle":"String","attributeToApp":"Boolean!","attributeToUser":"Boolean!","createdAt":"DateTime!","criticalAlert":"Boolean!","id":"ID!","message":"FormattedString!"},"t":["BasicEvent","CommentEvent"]}}, +"EventBridgeServerPixelUpdatePayload":{"o":{"f":{"serverPixel":"ServerPixel","userErrors":"[ErrorsServerPixelUserError!]!"}}}, +"EventBridgeWebhookSubscriptionCreatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"EventBridgeWebhookSubscriptionInput":{"i":{"arn":"ARN","filter":"String","format":"WebhookSubscriptionFormat","includeFields":"[String!]","metafieldNamespaces":"[String!]","metafields":"[HasMetafieldsMetafieldIdentifierInput!]","name":"String"}}, +"EventBridgeWebhookSubscriptionUpdatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"EventConnection":{"o":{"f":{"edges":"[EventEdge!]!","nodes":"[Event!]!","pageInfo":"PageInfo!"}}}, +"EventEdge":{"o":{"f":{"cursor":"String!","node":"Event!"}}}, +"EventSortKeys":{"e":["CREATED_AT","ID"]}, +"EventSubjectType":{"e":["COMPANY_LOCATION","COMPANY","CUSTOMER","DRAFT_ORDER","INVENTORY_TRANSFER","COLLECTION","PRODUCT","PRODUCT_VARIANT","ARTICLE","BLOG","COMMENT","PAGE","DISCOUNT_AUTOMATIC_BXGY","DISCOUNT_AUTOMATIC_NODE","DISCOUNT_CODE_NODE","DISCOUNT_NODE","PRICE_RULE","ORDER","UNKNOWN"]}, +"ExchangeLineItem":{"o":{"f":{"id":"ID!","lineItem":"LineItem","lineItems":"[LineItem!]","processableQuantity":"Int!","processedQuantity":"Int!","productId":"ID","quantity":"Int!","title":"String","unprocessedQuantity":"Int!","variantId":"ID","variantSku":"String","variantTitle":"String"},"t":["Node"],"d":{"lineItem":"Use `lineItems` instead."}}}, +"ExchangeLineItemAppliedDiscountInput":{"i":{"description":"String","value":"ExchangeLineItemAppliedDiscountValueInput!"}}, +"ExchangeLineItemAppliedDiscountValueInput":{"i":{"amount":"MoneyInput","percentage":"Float"}}, +"ExchangeLineItemConnection":{"o":{"f":{"edges":"[ExchangeLineItemEdge!]!","nodes":"[ExchangeLineItem!]!","pageInfo":"PageInfo!"}}}, +"ExchangeLineItemEdge":{"o":{"f":{"cursor":"String!","node":"ExchangeLineItem!"}}}, +"ExchangeLineItemInput":{"i":{"appliedDiscount":"ExchangeLineItemAppliedDiscountInput","giftCardCodes":"[String!]","quantity":"Int!","variantId":"ID"}}, +"ExchangeLineItemRemoveFromReturnInput":{"i":{"exchangeLineItemId":"ID!","quantity":"Int!"}}, +"ExchangeV2":{"o":{"f":{"additions":"ExchangeV2Additions!","completedAt":"DateTime","createdAt":"DateTime!","id":"ID!","location":"Location","mirrored":"Boolean!","note":"String","refunds":"[Refund!]!","returns":"ExchangeV2Returns!","staffMember":"StaffMember","totalAmountProcessedSet":"MoneyBag!","totalPriceSet":"MoneyBag!","transactions":"[OrderTransaction!]!"},"t":["Node"]}}, +"ExchangeV2Additions":{"o":{"f":{"lineItems":"[ExchangeV2LineItem!]!","subtotalPriceSet":"MoneyBag!","taxLines":"[TaxLine!]!","totalPriceSet":"MoneyBag!"}}}, +"ExchangeV2Connection":{"o":{"f":{"edges":"[ExchangeV2Edge!]!","nodes":"[ExchangeV2!]!","pageInfo":"PageInfo!"}}}, +"ExchangeV2Edge":{"o":{"f":{"cursor":"String!","node":"ExchangeV2!"}}}, +"ExchangeV2LineItem":{"o":{"f":{"customAttributes":"[Attribute!]!","discountedTotalSet":"MoneyBag!","discountedUnitPriceSet":"MoneyBag!","fulfillmentService":"FulfillmentService","giftCard":"Boolean!","giftCards":"[GiftCard!]!","isGiftCard":"Boolean!","lineItem":"LineItem","name":"String!","originalTotalSet":"MoneyBag!","originalUnitPriceSet":"MoneyBag!","quantity":"Int!","requiresShipping":"Boolean!","sku":"String","taxLines":"[TaxLine!]!","taxable":"Boolean!","title":"String!","variant":"ProductVariant","variantTitle":"String","vendor":"String"}}}, +"ExchangeV2Returns":{"o":{"f":{"lineItems":"[ExchangeV2LineItem!]!","orderDiscountAmountSet":"MoneyBag!","shippingRefundAmountSet":"MoneyBag!","subtotalPriceSet":"MoneyBag!","taxLines":"[TaxLine!]!","tipRefundAmountSet":"MoneyBag!","totalPriceSet":"MoneyBag!"}}}, +"ExternalVideo":{"o":{"f":{"alt":"String","createdAt":"DateTime!","embedUrl":"URL!","embeddedUrl":"URL!","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","host":"MediaHost!","id":"ID!","mediaContentType":"MediaContentType!","mediaErrors":"[MediaError!]!","mediaWarnings":"[MediaWarning!]!","originUrl":"URL!","preview":"MediaPreviewImage","status":"MediaStatus!","updatedAt":"DateTime!"},"t":["File","Media","Node"],"d":{"embeddedUrl":"Use `originUrl` instead."}}}, +"FailedRequirement":{"o":{"f":{"action":"NavigationItem","message":"String!"}}}, +"Fee":{"n":{"f":{"id":"ID!"},"t":["RestockingFee","ReturnShippingFee"]}}, +"FeeSale":{"o":{"f":{"actionType":"SaleActionType!","fee":"Fee","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"File":{"n":{"f":{"alt":"String","createdAt":"DateTime!","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","id":"ID!","preview":"MediaPreviewImage","updatedAt":"DateTime!"},"t":["ExternalVideo","GenericFile","MediaImage","Model3d","Video"]}}, +"FileAcknowledgeUpdateFailedPayload":{"o":{"f":{"files":"[File!]","userErrors":"[FilesUserError!]!"}}}, +"FileConnection":{"o":{"f":{"edges":"[FileEdge!]!","nodes":"[File!]!","pageInfo":"PageInfo!"}}}, +"FileContentType":{"e":["IMAGE","FILE","VIDEO","EXTERNAL_VIDEO","MODEL_3D"]}, +"FileCreateInput":{"i":{"alt":"String","contentType":"FileContentType","duplicateResolutionMode":"FileCreateInputDuplicateResolutionMode=","filename":"String","originalSource":"String!"}}, +"FileCreateInputDuplicateResolutionMode":{"e":["APPEND_UUID","RAISE_ERROR","REPLACE"]}, +"FileCreatePayload":{"o":{"f":{"files":"[File!]","userErrors":"[FilesUserError!]!"}}}, +"FileDeletePayload":{"o":{"f":{"deletedFileIds":"[ID!]","userErrors":"[FilesUserError!]!"}}}, +"FileEdge":{"o":{"f":{"cursor":"String!","node":"File!"}}}, +"FileError":{"o":{"f":{"code":"FileErrorCode!","details":"String","message":"String!"}}}, +"FileErrorCode":{"e":["UNKNOWN","INVALID_SIGNED_URL","IMAGE_DOWNLOAD_FAILURE","IMAGE_PROCESSING_FAILURE","MEDIA_TIMEOUT_ERROR","EXTERNAL_VIDEO_NOT_FOUND","EXTERNAL_VIDEO_UNLISTED","EXTERNAL_VIDEO_INVALID_ASPECT_RATIO","EXTERNAL_VIDEO_EMBED_DISABLED","EXTERNAL_VIDEO_EMBED_NOT_FOUND_OR_TRANSCODING","GENERIC_FILE_DOWNLOAD_FAILURE","GENERIC_FILE_INVALID_SIZE","VIDEO_METADATA_READ_ERROR","VIDEO_INVALID_FILETYPE_ERROR","VIDEO_MIN_WIDTH_ERROR","VIDEO_MAX_WIDTH_ERROR","VIDEO_MIN_HEIGHT_ERROR","VIDEO_MAX_HEIGHT_ERROR","VIDEO_MIN_DURATION_ERROR","VIDEO_MAX_DURATION_ERROR","VIDEO_VALIDATION_ERROR","MODEL3D_VALIDATION_ERROR","MODEL3D_THUMBNAIL_GENERATION_ERROR","MODEL3D_THUMBNAIL_REGENERATION_ERROR","MODEL3D_GLB_TO_USDZ_CONVERSION_ERROR","MODEL3D_GLB_OUTPUT_CREATION_ERROR","MODEL3D_PROCESSING_FAILURE","UNSUPPORTED_IMAGE_FILE_TYPE","INVALID_IMAGE_FILE_SIZE","INVALID_IMAGE_ASPECT_RATIO","INVALID_IMAGE_RESOLUTION","FILE_STORAGE_LIMIT_EXCEEDED","DUPLICATE_FILENAME_ERROR"]}, +"FileSetInput":{"i":{"alt":"String","contentType":"FileContentType","duplicateResolutionMode":"FileCreateInputDuplicateResolutionMode=","filename":"String","id":"ID","originalSource":"String"}}, +"FileSortKeys":{"e":["CREATED_AT","FILENAME","ID","ORIGINAL_UPLOAD_SIZE","RELEVANCE","UPDATED_AT"]}, +"FileStatus":{"e":["UPLOADED","PROCESSING","READY","FAILED"]}, +"FileUpdateInput":{"i":{"alt":"String","filename":"String","id":"ID!","originalSource":"String","previewImageSource":"String","referencesToAdd":"[ID!]","referencesToRemove":"[ID!]"}}, +"FileUpdatePayload":{"o":{"f":{"files":"[File!]","userErrors":"[FilesUserError!]!"}}}, +"FilesErrorCode":{"e":["INVALID","FILE_DOES_NOT_EXIST","FILE_LOCKED","UNSUPPORTED_MEDIA_TYPE_FOR_FILENAME_UPDATE","TOO_MANY_ARGUMENTS","BLANK_SEARCH","MISSING_ARGUMENTS","INVALID_QUERY","PRODUCT_SUSPENDED","INVALID_FILENAME_EXTENSION","INVALID_FILENAME","FILENAME_ALREADY_EXISTS","UNACCEPTABLE_UNVERIFIED_TRIAL_ASSET","UNACCEPTABLE_ASSET","UNACCEPTABLE_TRIAL_ASSET","ALT_VALUE_LIMIT_EXCEEDED","NON_READY_STATE","INVALID_FAILED_MEDIA_STATE","NON_IMAGE_MEDIA_PER_SHOP_LIMIT_EXCEEDED","MISMATCHED_FILENAME_AND_ORIGINAL_SOURCE","INVALID_DUPLICATE_MODE_FOR_TYPE","INVALID_IMAGE_SOURCE_URL","MISSING_FILENAME_FOR_DUPLICATE_MODE_REPLACE","PRODUCT_MEDIA_LIMIT_EXCEEDED","UNSUPPORTED_FILE_REFERENCE","REFERENCE_TARGET_DOES_NOT_EXIST","TOO_MANY_FILE_REFERENCE","INVALID_DUPLICATE_RESOLUTION_MODE","MEDIA_CANNOT_BE_MODIFIED"]}, +"FilesUserError":{"o":{"f":{"code":"FilesErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FilterOption":{"o":{"f":{"label":"String!","value":"String!"}}}, +"FinanceAppAccessPolicy":{"o":{"f":{"access":"[BankingFinanceAppAccess!]!"}}}, +"FinanceKycInformation":{"o":{"f":{"businessAddress":"ShopifyPaymentsAddressBasic","businessType":"ShopifyPaymentsBusinessType","industry":"ShopifyPaymentsMerchantCategoryCode","legalName":"String","shopOwner":"FinancialKycShopOwner!","taxIdentification":"ShopifyPaymentsTaxIdentification"}}}, +"FinancialKycShopOwner":{"o":{"f":{"email":"String!","firstName":"String","id":"ID!","lastName":"String","phone":"String"}}}, +"FinancialSummaryDiscountAllocation":{"o":{"f":{"approximateAllocatedAmountPerItem":"MoneyBag!","discountApplication":"FinancialSummaryDiscountApplication!"}}}, +"FinancialSummaryDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!"}}}, +"Float":"s", +"FlowGenerateSignaturePayload":{"o":{"f":{"payload":"String","signature":"String","targetUrl":"URL","userErrors":"[UserError!]!"}}}, +"FlowTriggerReceivePayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"FormattedString":"s", +"Fulfillment":{"o":{"f":{"createdAt":"DateTime!","deliveredAt":"DateTime","displayStatus":"FulfillmentDisplayStatus","estimatedDeliveryAt":"DateTime","events":["FulfillmentEventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"FulfillmentEventSortKeys="}],"fulfillmentLineItems":["FulfillmentLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"fulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"id":"ID!","inTransitAt":"DateTime","legacyResourceId":"UnsignedInt64!","location":"Location","name":"String!","order":"Order!","originAddress":"FulfillmentOriginAddress","requiresShipping":"Boolean!","service":"FulfillmentService","shippingLabel":"ShippingLabel","status":"FulfillmentStatus!","totalQuantity":"Int!","trackingInfo":["[FulfillmentTrackingInfo!]!",{"first":"Int"}],"updatedAt":"DateTime!"},"t":["LegacyInteroperability","Node"]}}, +"FulfillmentCancelPayload":{"o":{"f":{"fulfillment":"Fulfillment","userErrors":"[UserError!]!"}}}, +"FulfillmentConnection":{"o":{"f":{"edges":"[FulfillmentEdge!]!","nodes":"[Fulfillment!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentConstraintRule":{"o":{"f":{"deliveryMethodTypes":"[DeliveryMethodType!]!","function":"ShopifyFunction!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["HasMetafields","Node"]}}, +"FulfillmentConstraintRuleCreatePayload":{"o":{"f":{"fulfillmentConstraintRule":"FulfillmentConstraintRule","userErrors":"[FulfillmentConstraintRuleCreateUserError!]!"}}}, +"FulfillmentConstraintRuleCreateUserError":{"o":{"f":{"code":"FulfillmentConstraintRuleCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentConstraintRuleCreateUserErrorCode":{"e":["INPUT_INVALID","FUNCTION_NOT_FOUND","FUNCTION_ALREADY_REGISTERED","FUNCTION_DOES_NOT_IMPLEMENT","CUSTOM_APP_FUNCTION_NOT_ELIGIBLE","FUNCTION_PENDING_DELETION","MULTIPLE_FUNCTION_IDENTIFIERS","MISSING_FUNCTION_IDENTIFIER","MAXIMUM_FULFILLMENT_CONSTRAINT_RULES_REACHED"]}, +"FulfillmentConstraintRuleDeletePayload":{"o":{"f":{"success":"Boolean","userErrors":"[FulfillmentConstraintRuleDeleteUserError!]!"}}}, +"FulfillmentConstraintRuleDeleteUserError":{"o":{"f":{"code":"FulfillmentConstraintRuleDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentConstraintRuleDeleteUserErrorCode":{"e":["NOT_FOUND","UNAUTHORIZED_APP_SCOPE"]}, +"FulfillmentConstraintRuleUpdatePayload":{"o":{"f":{"fulfillmentConstraintRule":"FulfillmentConstraintRule","userErrors":"[FulfillmentConstraintRuleUpdateUserError!]!"}}}, +"FulfillmentConstraintRuleUpdateUserError":{"o":{"f":{"code":"FulfillmentConstraintRuleUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentConstraintRuleUpdateUserErrorCode":{"e":["NOT_FOUND","UNAUTHORIZED_APP_SCOPE"]}, +"FulfillmentCreatePayload":{"o":{"f":{"fulfillment":"Fulfillment","userErrors":"[UserError!]!"}}}, +"FulfillmentCreateV2Payload":{"o":{"f":{"fulfillment":"Fulfillment","userErrors":"[UserError!]!"}}}, +"FulfillmentDisplayStatus":{"e":["ATTEMPTED_DELIVERY","CANCELED","CONFIRMED","DELAYED","DELIVERED","FAILURE","FULFILLED","CARRIER_PICKED_UP","IN_TRANSIT","LABEL_PRINTED","LABEL_PURCHASED","LABEL_VOIDED","MARKED_AS_FULFILLED","NOT_DELIVERED","OUT_FOR_DELIVERY","READY_FOR_PICKUP","PICKED_UP","SUBMITTED"]}, +"FulfillmentEdge":{"o":{"f":{"cursor":"String!","node":"Fulfillment!"}}}, +"FulfillmentEvent":{"o":{"f":{"address1":"String","city":"String","country":"String","createdAt":"DateTime!","estimatedDeliveryAt":"DateTime","happenedAt":"DateTime!","id":"ID!","latitude":"Float","longitude":"Float","message":"String","province":"String","status":"FulfillmentEventStatus!","zip":"String"},"t":["Node"]}}, +"FulfillmentEventConnection":{"o":{"f":{"edges":"[FulfillmentEventEdge!]!","nodes":"[FulfillmentEvent!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentEventCreatePayload":{"o":{"f":{"fulfillmentEvent":"FulfillmentEvent","userErrors":"[UserError!]!"}}}, +"FulfillmentEventEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentEvent!"}}}, +"FulfillmentEventInput":{"i":{"address1":"String","city":"String","country":"String","estimatedDeliveryAt":"DateTime","fulfillmentId":"ID!","happenedAt":"DateTime","latitude":"Float","longitude":"Float","message":"String","province":"String","status":"FulfillmentEventStatus!","zip":"String"}}, +"FulfillmentEventSortKeys":{"e":["HAPPENED_AT","ID"]}, +"FulfillmentEventStatus":{"e":["LABEL_PURCHASED","LABEL_PRINTED","READY_FOR_PICKUP","CONFIRMED","IN_TRANSIT","OUT_FOR_DELIVERY","ATTEMPTED_DELIVERY","DELAYED","DELIVERED","FAILURE","CARRIER_PICKED_UP"]}, +"FulfillmentHold":{"o":{"f":{"displayReason":"String!","handle":"String","heldByApp":"App","heldByRequestingApp":"Boolean!","id":"ID!","reason":"FulfillmentHoldReason!","reasonNotes":"String"},"t":["Node"]}}, +"FulfillmentHoldReason":{"e":["AWAITING_PAYMENT","HIGH_RISK_OF_FRAUD","INCORRECT_ADDRESS","INVENTORY_OUT_OF_STOCK","UNKNOWN_DELIVERY_DATE","ONLINE_STORE_POST_PURCHASE_CROSS_SELL","AWAITING_RETURN_ITEMS","OTHER"]}, +"FulfillmentInput":{"i":{"lineItemsByFulfillmentOrder":"[FulfillmentOrderLineItemsInput!]!","notifyCustomer":"Boolean=","originAddress":"FulfillmentOriginAddressInput","trackingInfo":"FulfillmentTrackingInput"}}, +"FulfillmentLineItem":{"o":{"f":{"createdAt":"DateTime!","discountedTotal":"Money!","discountedTotalSet":"MoneyBag!","id":"ID!","lineItem":"LineItem!","originalTotal":"Money!","originalTotalSet":"MoneyBag!","quantity":"Int"},"t":["Node"],"d":{"discountedTotal":"Use `discountedTotalSet` instead.","originalTotal":"Use `originalTotalSet` instead."}}}, +"FulfillmentLineItemConnection":{"o":{"f":{"edges":"[FulfillmentLineItemEdge!]!","nodes":"[FulfillmentLineItem!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentLineItemEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentLineItem!"}}}, +"FulfillmentOrder":{"o":{"f":{"assignedLocation":"FulfillmentOrderAssignedLocation!","channelId":"ID","createdAt":"DateTime!","deliveryMethod":"DeliveryMethod","destination":"FulfillmentOrderDestination","fulfillAt":"DateTime","fulfillBy":"DateTime","fulfillmentHolds":"[FulfillmentHold!]!","fulfillmentOrdersForMerge":["FulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"fulfillments":["FulfillmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"id":"ID!","internationalDuties":"FulfillmentOrderInternationalDuties","lineItems":["FulfillmentOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"locationsForMove":["FulfillmentOrderLocationForMoveConnection!",{"after":"String","before":"String","first":"Int","last":"Int","lineItemIds":"[ID!]=","locationIds":"[ID!]","query":"String","reverse":"Boolean="}],"merchantRequests":["FulfillmentOrderMerchantRequestConnection!",{"after":"String","before":"String","first":"Int","kind":"FulfillmentOrderMerchantRequestKind","last":"Int","reverse":"Boolean="}],"order":"Order!","orderId":"ID!","orderName":"String!","orderProcessedAt":"DateTime!","remainingLineItemsWeight":"Weight","requestStatus":"FulfillmentOrderRequestStatus!","status":"FulfillmentOrderStatus!","supportedActions":"[FulfillmentOrderSupportedAction!]!","updatedAt":"DateTime!"},"t":["Node"],"d":{"channelId":"Use [`order.attribution.handle`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttribution#field-OrderAttribution.fields.handle) instead."}}}, +"FulfillmentOrderAcceptCancellationRequestPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderAcceptFulfillmentRequestPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderAction":{"e":["CREATE_FULFILLMENT","REQUEST_FULFILLMENT","CANCEL_FULFILLMENT_ORDER","MOVE","REQUEST_CANCELLATION","MARK_AS_OPEN","RELEASE_HOLD","HOLD","EXTERNAL","SPLIT","MERGE","REPORT_PROGRESS"]}, +"FulfillmentOrderAssignedLocation":{"o":{"f":{"address1":"String","address2":"String","city":"String","countryCode":"CountryCode!","location":"Location","name":"String!","phone":"String","province":"String","zip":"String"}}}, +"FulfillmentOrderAssignmentStatus":{"e":["CANCELLATION_REQUESTED","FULFILLMENT_REQUESTED","FULFILLMENT_ACCEPTED","FULFILLMENT_UNSUBMITTED"]}, +"FulfillmentOrderCancelError":{"o":{"f":{"code":"FulfillmentOrderCancelErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderCancelErrorCode":{"e":["FULFILLMENT_ORDER_HAS_MANUALLY_REPORTED_PROGRESS"]}, +"FulfillmentOrderCancelPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","replacementFulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderCancelError!]!"}}}, +"FulfillmentOrderClosePayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderConnection":{"o":{"f":{"edges":"[FulfillmentOrderEdge!]!","nodes":"[FulfillmentOrder!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentOrderDestination":{"o":{"f":{"address1":"String","address2":"String","city":"String","company":"String","countryCode":"CountryCode","email":"String","firstName":"String","id":"ID!","lastName":"String","location":"Location","phone":"String","province":"String","zip":"String"},"t":["Node"]}}, +"FulfillmentOrderEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentOrder!"}}}, +"FulfillmentOrderHoldInput":{"i":{"externalId":"String","fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]=","handle":"String=","notifyMerchant":"Boolean=","reason":"FulfillmentHoldReason!","reasonNotes":"String"}}, +"FulfillmentOrderHoldPayload":{"o":{"f":{"fulfillmentHold":"FulfillmentHold","fulfillmentOrder":"FulfillmentOrder","remainingFulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderHoldUserError!]!"}}}, +"FulfillmentOrderHoldUserError":{"o":{"f":{"code":"FulfillmentOrderHoldUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderHoldUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND","TAKEN","GREATER_THAN_ZERO","FULFILLMENT_ORDER_HOLD_LIMIT_REACHED","DUPLICATE_FULFILLMENT_HOLD_HANDLE","INVALID_LINE_ITEM_QUANTITY","FULFILLMENT_ORDER_NOT_SPLITTABLE","DUPLICATED_FULFILLMENT_ORDER_LINE_ITEMS"]}, +"FulfillmentOrderInternationalDuties":{"o":{"f":{"incoterm":"String!"}}}, +"FulfillmentOrderLineItem":{"o":{"f":{"financialSummaries":"[FulfillmentOrderLineItemFinancialSummary!]!","id":"ID!","image":"Image","inventoryItemId":"ID","lineItem":"LineItem!","originalUnitPriceSet":"MoneyBag!","productTitle":"String!","remainingQuantity":"Int!","requiresShipping":"Boolean!","shippingLine":"ShippingLine","sku":"String","totalQuantity":"Int!","variant":"ProductVariant","variantTitle":"String","vendor":"String","warnings":"[FulfillmentOrderLineItemWarning!]!","weight":"Weight"},"t":["Node"],"d":{"originalUnitPriceSet":"Use `financialSummaries` instead."}}}, +"FulfillmentOrderLineItemConnection":{"o":{"f":{"edges":"[FulfillmentOrderLineItemEdge!]!","nodes":"[FulfillmentOrderLineItem!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentOrderLineItemEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentOrderLineItem!"}}}, +"FulfillmentOrderLineItemFinancialSummary":{"o":{"f":{"approximateDiscountedUnitPriceSet":"MoneyBag!","discountAllocations":"[FinancialSummaryDiscountAllocation!]!","originalUnitPriceSet":"MoneyBag!","quantity":"Int!"}}}, +"FulfillmentOrderLineItemInput":{"i":{"id":"ID!","quantity":"Int!"}}, +"FulfillmentOrderLineItemWarning":{"o":{"f":{"description":"String","title":"String"}}}, +"FulfillmentOrderLineItemsInput":{"i":{"fulfillmentOrderId":"ID!","fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]"}}, +"FulfillmentOrderLineItemsPreparedForPickupInput":{"i":{"lineItemsByFulfillmentOrder":"[PreparedFulfillmentOrderLineItemsInput!]!"}}, +"FulfillmentOrderLineItemsPreparedForPickupPayload":{"o":{"f":{"userErrors":"[FulfillmentOrderLineItemsPreparedForPickupUserError!]!"}}}, +"FulfillmentOrderLineItemsPreparedForPickupUserError":{"o":{"f":{"code":"FulfillmentOrderLineItemsPreparedForPickupUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderLineItemsPreparedForPickupUserErrorCode":{"e":["NO_LINE_ITEMS_TO_PREPARE_FOR_FULFILLMENT_ORDER","FULFILLMENT_ORDER_INVALID","UNABLE_TO_PREPARE_QUANTITY"]}, +"FulfillmentOrderLocationForMove":{"o":{"f":{"availableLineItems":["FulfillmentOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"availableLineItemsCount":"Count","location":"Location!","message":"String","movable":"Boolean!","unavailableLineItems":["FulfillmentOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unavailableLineItemsCount":"Count"}}}, +"FulfillmentOrderLocationForMoveConnection":{"o":{"f":{"edges":"[FulfillmentOrderLocationForMoveEdge!]!","nodes":"[FulfillmentOrderLocationForMove!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentOrderLocationForMoveEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentOrderLocationForMove!"}}}, +"FulfillmentOrderMerchantRequest":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder!","id":"ID!","kind":"FulfillmentOrderMerchantRequestKind!","message":"String","requestOptions":"JSON","responseData":"JSON","sentAt":"DateTime!"},"t":["Node"]}}, +"FulfillmentOrderMerchantRequestConnection":{"o":{"f":{"edges":"[FulfillmentOrderMerchantRequestEdge!]!","nodes":"[FulfillmentOrderMerchantRequest!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentOrderMerchantRequestEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentOrderMerchantRequest!"}}}, +"FulfillmentOrderMerchantRequestKind":{"e":["FULFILLMENT_REQUEST","CANCELLATION_REQUEST"]}, +"FulfillmentOrderMergeInput":{"i":{"mergeIntents":"[FulfillmentOrderMergeInputMergeIntent!]!"}}, +"FulfillmentOrderMergeInputMergeIntent":{"i":{"fulfillmentOrderId":"ID!","fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]"}}, +"FulfillmentOrderMergePayload":{"o":{"f":{"fulfillmentOrderMerges":"[FulfillmentOrderMergeResult!]","userErrors":"[FulfillmentOrderMergeUserError!]!"}}}, +"FulfillmentOrderMergeResult":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder!"}}}, +"FulfillmentOrderMergeUserError":{"o":{"f":{"code":"FulfillmentOrderMergeUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderMergeUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND","GREATER_THAN","INVALID_LINE_ITEM_QUANTITY"]}, +"FulfillmentOrderMoveFulfillmentOrderMoveUserError":{"o":{"f":{"code":"FulfillmentOrderMoveFulfillmentOrderMoveUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderMoveFulfillmentOrderMoveUserErrorCode":{"e":["CANNOT_MOVE_FULFILLMENT_ORDER_WITH_REPORTED_PROGRESS"]}, +"FulfillmentOrderMovePayload":{"o":{"f":{"movedFulfillmentOrder":"FulfillmentOrder","originalFulfillmentOrder":"FulfillmentOrder","remainingFulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderMoveFulfillmentOrderMoveUserError!]!"}}}, +"FulfillmentOrderOpenPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderRejectCancellationRequestPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderRejectFulfillmentRequestPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderRejectionReason":{"e":["INCORRECT_ADDRESS","INVENTORY_OUT_OF_STOCK","INELIGIBLE_PRODUCT","UNDELIVERABLE_DESTINATION","INTERNATIONAL_SHIPPING_UNAVAILABLE","INCORRECT_PRODUCT_INFO","MISSING_CUSTOMS_INFO","INVALID_SKU","PAYMENT_DECLINED","PACKAGE_PREFERENCE_NOT_SET","INVALID_CONTACT_INFORMATION","ORDER_TOO_LARGE","MERCHANT_BLOCKED_OR_SUSPENDED","OTHER"]}, +"FulfillmentOrderReleaseHoldPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderReleaseHoldUserError!]!"}}}, +"FulfillmentOrderReleaseHoldUserError":{"o":{"f":{"code":"FulfillmentOrderReleaseHoldUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderReleaseHoldUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND","INVALID_ACCESS"]}, +"FulfillmentOrderReportProgressInput":{"i":{"reasonNotes":"String"}}, +"FulfillmentOrderReportProgressPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderReportProgressUserError!]!"}}}, +"FulfillmentOrderReportProgressUserError":{"o":{"f":{"code":"FulfillmentOrderReportProgressUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderReportProgressUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND","FULFILLMENT_ORDER_STATUS_INVALID","FULFILLMENT_ORDER_CONTAINS_PICKED_ITEMS","FULFILLMENT_ORDER_INVALID_DELIVERY_METHOD","FULFILLMENT_ORDER_INVALID_FULFILLMENT_SERVICE_OWNERSHIP","FULFILLMENT_ORDER_UNSUPPORTED_ACTION","MARKETPLACE_APP_NOT_ELIGIBLE"]}, +"FulfillmentOrderRequestStatus":{"e":["UNSUBMITTED","SUBMITTED","ACCEPTED","REJECTED","CANCELLATION_REQUESTED","CANCELLATION_ACCEPTED","CANCELLATION_REJECTED","CLOSED"]}, +"FulfillmentOrderReschedulePayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderRescheduleUserError!]!"}}}, +"FulfillmentOrderRescheduleUserError":{"o":{"f":{"code":"FulfillmentOrderRescheduleUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderRescheduleUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND"]}, +"FulfillmentOrderSortKeys":{"e":["ID","UPDATED_AT"]}, +"FulfillmentOrderSplitInput":{"i":{"fulfillmentOrderId":"ID!","fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]!"}}, +"FulfillmentOrderSplitPayload":{"o":{"f":{"fulfillmentOrderSplits":"[FulfillmentOrderSplitResult!]","userErrors":"[FulfillmentOrderSplitUserError!]!"}}}, +"FulfillmentOrderSplitResult":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder!","remainingFulfillmentOrder":"FulfillmentOrder!","replacementFulfillmentOrder":"FulfillmentOrder"}}}, +"FulfillmentOrderSplitUserError":{"o":{"f":{"code":"FulfillmentOrderSplitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderSplitUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND","GREATER_THAN","INVALID_LINE_ITEM_QUANTITY","NO_LINE_ITEMS_PROVIDED_TO_SPLIT"]}, +"FulfillmentOrderStatus":{"e":["OPEN","IN_PROGRESS","CANCELLED","INCOMPLETE","CLOSED","SCHEDULED","ON_HOLD"]}, +"FulfillmentOrderSubmitCancellationRequestPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderSubmitFulfillmentRequestPayload":{"o":{"f":{"originalFulfillmentOrder":"FulfillmentOrder","submittedFulfillmentOrder":"FulfillmentOrder","unsubmittedFulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderSupportedAction":{"o":{"f":{"action":"FulfillmentOrderAction!","externalUrl":"URL"}}}, +"FulfillmentOrdersReroutePayload":{"o":{"f":{"movedFulfillmentOrders":"[FulfillmentOrder!]","userErrors":"[FulfillmentOrdersRerouteUserError!]!"}}}, +"FulfillmentOrdersRerouteUserError":{"o":{"f":{"code":"FulfillmentOrdersRerouteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrdersRerouteUserErrorCode":{"e":["NO_FULFILLMENT_ORDER_IDS","FULFILLMENT_ORDER_NOT_FOUND","FULFILLMENT_ORDERS_NOT_FROM_THE_SAME_ORDER","FULFILLMENT_ORDERS_STATE_NOT_SUPPORTED","CANNOT_REASSIGN_LOCATION_FOR_FULFILLMENT_ORDERS","DELIVERY_METHOD_TYPE_NOT_SUPPORTED","SINGLE_LOCATION_SHOP_NOT_SUPPORTED","FULFILLMENT_ORDERS_MUST_BELONG_TO_SAME_LOCATION","CANNOT_MOVE_FULFILLMENT_ORDER_WITH_REPORTED_PROGRESS"]}, +"FulfillmentOrdersSetFulfillmentDeadlinePayload":{"o":{"f":{"success":"Boolean","userErrors":"[FulfillmentOrdersSetFulfillmentDeadlineUserError!]!"}}}, +"FulfillmentOrdersSetFulfillmentDeadlineUserError":{"o":{"f":{"code":"FulfillmentOrdersSetFulfillmentDeadlineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrdersSetFulfillmentDeadlineUserErrorCode":{"e":["FULFILLMENT_ORDERS_NOT_FOUND"]}, +"FulfillmentOriginAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","countryCode":"String!","provinceCode":"String","zip":"String"}}}, +"FulfillmentOriginAddressInput":{"i":{"address1":"String","address2":"String","city":"String","countryCode":"String!","provinceCode":"String","zip":"String"}}, +"FulfillmentService":{"o":{"f":{"callbackUrl":"URL","createdAt":"DateTime!","fulfillmentOrdersOptIn":"Boolean!","handle":"String!","id":"ID!","inventoryManagement":"Boolean!","location":"Location","requiresShippingMethod":"Boolean!","serviceName":"String!","trackingSupport":"Boolean!","type":"FulfillmentServiceType!"},"d":{"fulfillmentOrdersOptIn":"Migration period ended. All correctly functioning fulfillment services have `fulfillmentOrdersOptIn` set to `true`."}}}, +"FulfillmentServiceCreatePayload":{"o":{"f":{"fulfillmentService":"FulfillmentService","userErrors":"[UserError!]!"}}}, +"FulfillmentServiceDeleteInventoryAction":{"e":["DELETE","KEEP","TRANSFER"]}, +"FulfillmentServiceDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[UserError!]!"}}}, +"FulfillmentServiceType":{"e":["GIFT_CARD","MANUAL","THIRD_PARTY"]}, +"FulfillmentServiceUpdatePayload":{"o":{"f":{"fulfillmentService":"FulfillmentService","userErrors":"[UserError!]!"}}}, +"FulfillmentStatus":{"e":{"v":["PENDING","OPEN","SUCCESS","CANCELLED","ERROR","FAILURE"],"d":{"OPEN":"This is a legacy status and is due to be deprecated.","PENDING":"This is a legacy status and is due to be deprecated."}}}, +"FulfillmentTrackingInfo":{"o":{"f":{"company":"String","number":"String","url":"URL"}}}, +"FulfillmentTrackingInfoUpdatePayload":{"o":{"f":{"fulfillment":"Fulfillment","userErrors":"[UserError!]!"}}}, +"FulfillmentTrackingInfoUpdateV2Payload":{"o":{"f":{"fulfillment":"Fulfillment","userErrors":"[UserError!]!"}}}, +"FulfillmentTrackingInput":{"i":{"company":"String","number":"String","numbers":"[String!]","url":"URL","urls":"[URL!]"}}, +"FulfillmentV2Input":{"i":{"lineItemsByFulfillmentOrder":"[FulfillmentOrderLineItemsInput!]!","notifyCustomer":"Boolean=","originAddress":"FulfillmentOriginAddressInput","trackingInfo":"FulfillmentTrackingInput"}}, +"FullSyncTraceInfo":{"o":{"f":{"country":"CountryCode!","language":"LanguageCode!","operationId":"ID"}}}, +"FunctionsAppBridge":{"o":{"f":{"createPath":"String!","detailsPath":"String!"}}}, +"FunctionsErrorHistory":{"o":{"f":{"errorsFirstOccurredAt":"DateTime!","firstOccurredAt":"DateTime!","hasBeenSharedSinceLastError":"Boolean!","hasSharedRecentErrors":"Boolean!"}}}, +"GenericFile":{"o":{"f":{"alt":"String","createdAt":"DateTime!","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","id":"ID!","mimeType":"String","originalFileSize":"Int","preview":"MediaPreviewImage","updatedAt":"DateTime!","url":"URL"},"t":["File","Node"]}}, +"GiftCard":{"o":{"f":{"balance":"MoneyV2!","createdAt":"DateTime!","crossCurrencyRedemptionStrategy":"GiftCardCrossCurrencyRedemptionStrategy!","customer":"Customer","deactivatedAt":"DateTime","enabled":"Boolean!","expiresOn":"Date","id":"ID!","initialValue":"MoneyV2!","isRedeemable":"Boolean!","lastCharacters":"String!","lineItem":"LineItem","maskedCode":"String!","note":"String","order":"Order","recipientAttributes":"GiftCardRecipient","templateSuffix":"String","transactions":["GiftCardTransactionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["Node"]}}, +"GiftCardCashOutTransaction":{"o":{"f":{"amount":"MoneyV2!","giftCard":"GiftCard!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"note":"String","processedAt":"DateTime!"},"t":["GiftCardTransaction","HasMetafields","Node"]}}, +"GiftCardConfiguration":{"o":{"f":{"expirationConfiguration":"GiftCardExpirationConfiguration","issueLimit":"MoneyV2!","purchaseLimit":"MoneyV2!"}}}, +"GiftCardConfigurationExpirationUnit":{"e":["DAYS","MONTHS","YEARS"]}, +"GiftCardConnection":{"o":{"f":{"edges":"[GiftCardEdge!]!","nodes":"[GiftCard!]!","pageInfo":"PageInfo!"}}}, +"GiftCardCreateInput":{"i":{"f":{"code":"String","crossCurrencyRedemptionStrategy":"GiftCardCrossCurrencyRedemptionStrategy","customerId":"ID","expiresOn":"Date","initialAmount":"MoneyInput","initialValue":"Decimal","note":"String","recipientAttributes":"GiftCardRecipientInput","templateSuffix":"String"},"d":{"initialValue":"Use `initialAmount` instead."}}}, +"GiftCardCreatePayload":{"o":{"f":{"giftCard":"GiftCard","giftCardCode":"String","userErrors":"[GiftCardUserError!]!"}}}, +"GiftCardCreditInput":{"i":{"creditAmount":"MoneyInput!","note":"String","processedAt":"DateTime"}}, +"GiftCardCreditPayload":{"o":{"f":{"giftCardCreditTransaction":"GiftCardCreditTransaction","userErrors":"[GiftCardTransactionUserError!]!"}}}, +"GiftCardCreditTransaction":{"o":{"f":{"amount":"MoneyV2!","giftCard":"GiftCard!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"note":"String","processedAt":"DateTime!"},"t":["GiftCardTransaction","HasMetafields","Node"]}}, +"GiftCardCrossCurrencyRedemptionStrategy":{"e":["NONE","MARKET_FX","SPOT_FX"]}, +"GiftCardDeactivatePayload":{"o":{"f":{"giftCard":"GiftCard","userErrors":"[GiftCardDeactivateUserError!]!"}}}, +"GiftCardDeactivateUserError":{"o":{"f":{"code":"GiftCardDeactivateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"GiftCardDeactivateUserErrorCode":{"e":["GIFT_CARD_NOT_FOUND"]}, +"GiftCardDebitInput":{"i":{"debitAmount":"MoneyInput!","note":"String","processedAt":"DateTime"}}, +"GiftCardDebitPayload":{"o":{"f":{"giftCardDebitTransaction":"GiftCardDebitTransaction","userErrors":"[GiftCardTransactionUserError!]!"}}}, +"GiftCardDebitTransaction":{"o":{"f":{"amount":"MoneyV2!","giftCard":"GiftCard!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"note":"String","processedAt":"DateTime!"},"t":["GiftCardTransaction","HasMetafields","Node"]}}, +"GiftCardEdge":{"o":{"f":{"cursor":"String!","node":"GiftCard!"}}}, +"GiftCardErrorCode":{"e":["TOO_BIG","TOO_LONG","TOO_SHORT","TAKEN","INVALID","INTERNAL_ERROR","MISSING_ARGUMENT","GREATER_THAN","GIFT_CARD_LIMIT_EXCEEDED","CUSTOMER_NOT_FOUND","RECIPIENT_NOT_FOUND"]}, +"GiftCardExpirationConfiguration":{"o":{"f":{"expirationUnit":"GiftCardConfigurationExpirationUnit!","expirationValue":"Int!"}}}, +"GiftCardProductSetInput":{"i":{"collections":"[ID!]","crossCurrencyRedeemable":"Boolean","descriptionHtml":"String","files":"[FileSetInput!]","giftCardTemplateSuffix":"String","handle":"String","issuanceCurrency":"CurrencyCode","metafields":"[MetafieldInput!]","productOptions":"[OptionSetInput!]","productType":"String","redirectNewHandle":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","variants":"[GiftCardProductVariantSetInput!]","vendor":"String"}}, +"GiftCardProductSetPayload":{"o":{"f":{"product":"Product","productSetOperation":"ProductSetOperation","userErrors":"[GiftCardProductSetUserError!]!"}}}, +"GiftCardProductSetUserError":{"o":{"f":{"code":"GiftCardProductSetUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"GiftCardProductSetUserErrorCode":{"e":["ID_NOT_ALLOWED","MISSING_FIELD_REQUIRED","INPUT_MISMATCH","NOT_FOUND","METAFIELD_MISMATCH","GENERIC_ERROR","INVALID_METAFIELD","INVALID_VARIANT","PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","PRODUCT_VARIANT_DOES_NOT_EXIST","OPTION_DOES_NOT_EXIST","OPTION_VALUE_DOES_NOT_EXIST","OPTIONS_OVER_LIMIT","OPTION_VALUES_OVER_LIMIT","OPTION_VALUES_MISSING","DUPLICATED_OPTION_NAME","DUPLICATED_OPTION_VALUE","VARIANTS_OVER_LIMIT","PRODUCT_OPTIONS_INPUT_MISSING","VARIANTS_INPUT_MISSING","GIFT_CARDS_NOT_ACTIVATED","GIFT_CARD_ATTRIBUTE_CANNOT_BE_CHANGED","INVALID_PRODUCT","INVALID_INPUT","JOB_ERROR","CAPABILITY_VIOLATION","CANNOT_COMBINE_LINKED_AND_NONLINKED_OPTION_VALUES","INVALID_METAFIELD_VALUE_FOR_LINKED_OPTION","DUPLICATE_LINKED_OPTION","DUPLICATED_METAFIELD_VALUE","LINKED_OPTIONS_NOT_SUPPORTED_FOR_SHOP","LINKED_METAFIELD_DEFINITION_NOT_FOUND","DUPLICATED_VALUE","HANDLE_NOT_UNIQUE","INCOMPATIBLE_BARCODE_FIELDS","BLANK_BARCODE_VALUE","TOO_MANY_BARCODES","BARCODE_VALUE_TOO_LONG","DUPLICATE_BARCODE_VALUE","INVALID_BARCODE_TYPE","INVALID_BARCODE_SEPARATORS","INVALID_BARCODE_LENGTH","INVALID_BARCODE_PREFIX","INVALID_BARCODE_CHARACTERS","BARCODE_CHECKSUM_VALIDATION_FAILED","PRODUCT_MUST_BE_GIFT_CARD"]}, +"GiftCardProductSettings":{"o":{"f":{"crossCurrencyRedeemable":"Boolean!","issuanceCurrency":"CurrencyCode"}}}, +"GiftCardProductVariantSetInput":{"i":{"f":{"barcode":"String","barcodes":"[BarcodeInput!]","file":"FileSetInput","id":"ID","metafields":"[MetafieldInput!]","optionValues":"[VariantOptionValueInput!]!","position":"Int","price":"Money","published":"Boolean","sku":"String"},"d":{"barcode":"Use `barcodes` instead."}}}, +"GiftCardRecipient":{"o":{"f":{"message":"String","preferredName":"String","recipient":"Customer!","sendNotificationAt":"DateTime"}}}, +"GiftCardRecipientInput":{"i":{"id":"ID!","message":"String","preferredName":"String","sendNotificationAt":"DateTime"}}, +"GiftCardSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineItem":"LineItem!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"GiftCardSendNotificationToCustomerPayload":{"o":{"f":{"giftCard":"GiftCard","userErrors":"[GiftCardSendNotificationToCustomerUserError!]!"}}}, +"GiftCardSendNotificationToCustomerUserError":{"o":{"f":{"code":"GiftCardSendNotificationToCustomerUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"GiftCardSendNotificationToCustomerUserErrorCode":{"e":["INVALID","CUSTOMER_NOT_FOUND","GIFT_CARD_NOT_FOUND"]}, +"GiftCardSendNotificationToRecipientPayload":{"o":{"f":{"giftCard":"GiftCard","userErrors":"[GiftCardSendNotificationToRecipientUserError!]!"}}}, +"GiftCardSendNotificationToRecipientUserError":{"o":{"f":{"code":"GiftCardSendNotificationToRecipientUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"GiftCardSendNotificationToRecipientUserErrorCode":{"e":["INVALID","RECIPIENT_NOT_FOUND","GIFT_CARD_NOT_FOUND"]}, +"GiftCardSortKeys":{"e":["AMOUNT_SPENT","BALANCE","CODE","CREATED_AT","CUSTOMER_NAME","DISABLED_AT","EXPIRES_ON","ID","INITIAL_VALUE","UPDATED_AT"]}, +"GiftCardTransaction":{"n":{"f":{"amount":"MoneyV2!","giftCard":"GiftCard!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"note":"String","processedAt":"DateTime!"},"t":["GiftCardCashOutTransaction","GiftCardCreditTransaction","GiftCardDebitTransaction"]}}, +"GiftCardTransactionConnection":{"o":{"f":{"edges":"[GiftCardTransactionEdge!]!","nodes":"[GiftCardTransaction!]!","pageInfo":"PageInfo!"}}}, +"GiftCardTransactionEdge":{"o":{"f":{"cursor":"String!","node":"GiftCardTransaction!"}}}, +"GiftCardTransactionUserError":{"o":{"f":{"code":"GiftCardTransactionUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"GiftCardTransactionUserErrorCode":{"e":["INVALID","INTERNAL_ERROR","GIFT_CARD_LIMIT_EXCEEDED","GIFT_CARD_NOT_FOUND","NEGATIVE_OR_ZERO_AMOUNT","INSUFFICIENT_FUNDS","MISMATCHING_CURRENCY"]}, +"GiftCardUpdateInput":{"i":{"crossCurrencyRedemptionStrategy":"GiftCardCrossCurrencyRedemptionStrategy","customerId":"ID","expiresOn":"Date","note":"String","recipientAttributes":"GiftCardRecipientInput","templateSuffix":"String"}}, +"GiftCardUpdatePayload":{"o":{"f":{"giftCard":"GiftCard","userErrors":"[UserError!]!"}}}, +"GiftCardUserError":{"o":{"f":{"code":"GiftCardErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"HTML":"s", +"HasCompareDigest":{"n":{"f":{"compareDigest":"String!"},"t":["Metafield"]}}, +"HasEvents":{"n":{"f":{"events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}]},"t":["Article","Blog","Collection","Comment","Company","CompanyLocation","Customer","DiscountAutomaticBxgy","DiscountAutomaticNode","DiscountCodeNode","DiscountNode","DraftOrder","InventoryTransfer","Order","Page","Product","ProductVariant"]}}, +"HasLocalizationExtensions":{"n":{"f":{"localizationExtensions":["LocalizationExtensionConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizationExtensionPurpose!]","reverse":"Boolean="}]},"t":["DraftOrder","Order"],"d":{"localizationExtensions":"This connection will be removed in a future version. Use `localizedFields` instead."}}}, +"HasLocalizedFields":{"n":{"f":{"localizedFields":["LocalizedFieldConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizedFieldPurpose!]","reverse":"Boolean="}]},"t":["DraftOrder","Order"]}}, +"HasMetafieldDefinitions":{"n":{"f":{"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}]},"t":["Article","Blog","Collection","Company","CompanyLocation","Customer","DeliveryCustomization","DiscountAutomaticNode","DiscountCodeNode","DiscountNode","InventoryTransfer","Location","Market","Order","Page","PaymentCustomization","Product","ProductVariant","SellingPlan","Shop","Validation"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"HasMetafields":{"n":{"f":{"metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["AppInstallation","Article","Blog","CartTransform","Collection","Company","CompanyLocation","Customer","CustomerSegmentMember","DeliveryCustomization","DiscountAutomaticNode","DiscountCodeNode","DiscountNode","DraftOrder","FulfillmentConstraintRule","GiftCardCashOutTransaction","GiftCardCreditTransaction","GiftCardDebitTransaction","Image","InventoryTransfer","Location","Market","MediaImage","Order","Page","PaymentCustomization","Product","ProductVariant","SellingPlan","Shop","Validation"]}}, +"HasMetafieldsMetafieldIdentifierInput":{"i":{"key":"String!","namespace":"String"}}, +"HasPublishedTranslations":{"n":{"f":{"translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["Article","Blog","Collection","CookieBanner","Image","Link","MediaImage","Menu","Metafield","OnlineStoreTheme","Page","Product","ProductOption","ProductOptionValue","ProductVariant","SellingPlan","SellingPlanGroup","Shop","ShopPolicy"]}}, +"HasRollouts":{"n":{"f":{"rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}]},"t":["DiscountAutomaticApp","DiscountAutomaticBasic","DiscountAutomaticBxgy","DiscountAutomaticFreeShipping","DiscountCodeApp","DiscountCodeBasic","DiscountCodeBxgy","DiscountCodeFreeShipping"]}}, +"HasStoreCreditAccounts":{"n":{"f":{"storeCreditAccounts":["StoreCreditAccountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String"}]},"t":["CompanyLocation","Customer"]}}, +"ID":"s", +"IdentityProviderSubject":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","providerName":"String","subject":"String!","updatedAt":"DateTime!"},"t":["Node"]}}, +"Image":{"o":{"f":{"altText":"String","height":"Int","id":"ID","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"originalSrc":"URL!","src":"URL!","thumbhash":"String","transformedSrc":["URL!",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","preferredContentType":"ImageContentType","scale":"Int="}],"translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"url":["URL!",{"transform":"ImageTransformInput"}],"width":"Int"},"t":["HasMetafields","HasPublishedTranslations"],"d":{"originalSrc":"Use `url` instead.","src":"Use `url` instead.","transformedSrc":"Use `url(transform:)` instead"}}}, +"ImageConnection":{"o":{"f":{"edges":"[ImageEdge!]!","nodes":"[Image!]!","pageInfo":"PageInfo!"}}}, +"ImageContentType":{"e":["PNG","JPG","WEBP"]}, +"ImageEdge":{"o":{"f":{"cursor":"String!","node":"Image!"}}}, +"ImageInput":{"i":{"altText":"String","id":"ID","src":"String"}}, +"ImageTransformInput":{"i":{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","preferredContentType":"ImageContentType","scale":"Int="}}, +"ImageUploadParameter":{"o":{"f":{"name":"String!","value":"String!"}}}, +"InclusiveDutiesPricingStrategy":{"e":["ADD_DUTIES_AT_CHECKOUT","INCLUDE_DUTIES_IN_PRICE"]}, +"InclusiveTaxPricingStrategy":{"e":["ADD_TAXES_AT_CHECKOUT","INCLUDES_TAXES_IN_PRICE","INCLUDES_TAXES_IN_PRICE_BASED_ON_COUNTRY"]}, +"IncomingRequestLineItemInput":{"i":{"fulfillmentOrderLineItemId":"ID!","message":"String"}}, +"Int":"s", +"InventoryActivatePayload":{"o":{"f":{"inventoryLevel":"InventoryLevel","userErrors":"[UserError!]!"}}}, +"InventoryAdjustQuantitiesInput":{"i":{"changes":"[InventoryChangeInput!]!","name":"String!","reason":"String!","referenceDocumentUri":"String"}}, +"InventoryAdjustQuantitiesPayload":{"o":{"f":{"inventoryAdjustmentGroup":"InventoryAdjustmentGroup","userErrors":"[InventoryAdjustQuantitiesUserError!]!"}}}, +"InventoryAdjustQuantitiesUserError":{"o":{"f":{"code":"InventoryAdjustQuantitiesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryAdjustQuantitiesUserErrorCode":{"e":["INTERNAL_LEDGER_DOCUMENT","INVALID_AVAILABLE_DOCUMENT","INVALID_INVENTORY_ITEM","INVALID_LEDGER_DOCUMENT","INVALID_LOCATION","INVALID_QUANTITY_DOCUMENT","INVALID_QUANTITY_NAME","INVALID_QUANTITY_TOO_LOW","INVALID_QUANTITY_TOO_HIGH","INVALID_REASON","INVALID_REFERENCE_DOCUMENT","SERVICE_UNAVAILABLE","CHANGE_FROM_QUANTITY_STALE","ADJUST_QUANTITIES_FAILED","MAX_ONE_LEDGER_DOCUMENT","NON_MUTABLE_INVENTORY_ITEM","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED"]}, +"InventoryAdjustmentGroup":{"o":{"f":{"app":"App","changes":["[InventoryChange!]!",{"inventoryItemIds":"[ID!]","locationIds":"[ID!]","quantityNames":"[String!]"}],"createdAt":"DateTime!","id":"ID!","reason":"String!","referenceDocumentUri":"String","staffMember":"StaffMember"},"t":["Node"]}}, +"InventoryAdjustmentInput":{"i":{"adjustment":"Int","changeFromQuantity":"Int","locationId":"ID!"}}, +"InventoryBulkToggleActivationInput":{"i":{"activate":"Boolean!","locationId":"ID!"}}, +"InventoryBulkToggleActivationPayload":{"o":{"f":{"inventoryItem":"InventoryItem","inventoryLevels":"[InventoryLevel!]","userErrors":"[InventoryBulkToggleActivationUserError!]!"}}}, +"InventoryBulkToggleActivationUserError":{"o":{"f":{"code":"InventoryBulkToggleActivationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryBulkToggleActivationUserErrorCode":{"e":{"v":["GENERIC_ERROR","CANNOT_DEACTIVATE_FROM_ONLY_LOCATION","COMMITTED_AND_INCOMING_INVENTORY_AT_LOCATION","INCOMING_INVENTORY_AT_LOCATION","COMMITTED_INVENTORY_AT_LOCATION","RESERVED_INVENTORY_AT_LOCATION","FAILED_TO_UNSTOCK_FROM_LOCATION","INVENTORY_MANAGED_BY_3RD_PARTY","INVENTORY_MANAGED_BY_SHOPIFY","FAILED_TO_STOCK_AT_LOCATION","MISSING_SKU","LOCATION_NOT_FOUND","INVENTORY_ITEM_NOT_FOUND"],"d":{"COMMITTED_AND_INCOMING_INVENTORY_AT_LOCATION":"This error code is deprecated. Both INCOMING_INVENTORY_AT_LOCATION and COMMITTED_INVENTORY_AT_LOCATION codes will be returned as individual errors instead."}}}, +"InventoryChange":{"o":{"f":{"delta":"Int!","item":"InventoryItem","ledgerDocumentUri":"String","location":"Location","name":"String!","quantityAfterChange":"Int"}}}, +"InventoryChangeInput":{"i":{"changeFromQuantity":"Int","delta":"Int!","inventoryItemId":"ID!","ledgerDocumentUri":"String","locationId":"ID!"}}, +"InventoryDeactivatePayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"InventoryItem":{"o":{"f":{"countryCodeOfOrigin":"CountryCode","countryHarmonizedSystemCodes":["CountryHarmonizedSystemCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"createdAt":"DateTime!","duplicateSkuCount":"Int!","harmonizedSystemCode":"String","id":"ID!","inventoryHistoryUrl":"URL","inventoryLevel":["InventoryLevel",{"includeInactive":"Boolean=","locationId":"ID!"}],"inventoryLevels":["InventoryLevelConnection!",{"after":"String","before":"String","first":"Int","includeInactive":"Boolean=","last":"Int","query":"String","reverse":"Boolean="}],"legacyResourceId":"UnsignedInt64!","locationsCount":"Count","measurement":"InventoryItemMeasurement!","provinceCodeOfOrigin":"String","requiresShipping":"Boolean!","sku":"String","tracked":"Boolean!","trackedEditable":"EditableProperty!","unitCost":"MoneyV2","updatedAt":"DateTime!","variant":"ProductVariant!","variants":["ProductVariantConnection",{"after":"String","before":"String","first":"Int","last":"Int"}]},"t":["LegacyInteroperability","Node"],"d":{"variant":"Use `variants` instead."}}}, +"InventoryItemConnection":{"o":{"f":{"edges":"[InventoryItemEdge!]!","nodes":"[InventoryItem!]!","pageInfo":"PageInfo!"}}}, +"InventoryItemEdge":{"o":{"f":{"cursor":"String!","node":"InventoryItem!"}}}, +"InventoryItemInput":{"i":{"cost":"Decimal","countryCodeOfOrigin":"CountryCode","countryHarmonizedSystemCodes":"[CountryHarmonizedSystemCodeInput!]","harmonizedSystemCode":"String","measurement":"InventoryItemMeasurementInput","provinceCodeOfOrigin":"String","requiresShipping":"Boolean","sku":"String","tracked":"Boolean"}}, +"InventoryItemMeasurement":{"o":{"f":{"id":"ID!","weight":"Weight"},"t":["Node"]}}, +"InventoryItemMeasurementInput":{"i":{"shippingPackageId":"ID","weight":"WeightInput"}}, +"InventoryItemUpdatePayload":{"o":{"f":{"inventoryItem":"InventoryItem","userErrors":"[UserError!]!"}}}, +"InventoryLevel":{"o":{"f":{"canDeactivate":"Boolean!","createdAt":"DateTime!","deactivationAlert":"String","id":"ID!","isActive":"Boolean!","item":"InventoryItem!","location":"Location!","quantities":["[InventoryQuantity!]!",{"names":"[String!]!"}],"scheduledChanges":["InventoryScheduledChangeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ScheduledChangeSortKeys="}],"updatedAt":"DateTime!"},"t":["Node"],"d":{"scheduledChanges":"Scheduled changes will be phased out in a future version."}}}, +"InventoryLevelConnection":{"o":{"f":{"edges":"[InventoryLevelEdge!]!","nodes":"[InventoryLevel!]!","pageInfo":"PageInfo!"}}}, +"InventoryLevelEdge":{"o":{"f":{"cursor":"String!","node":"InventoryLevel!"}}}, +"InventoryLevelInput":{"i":{"availableQuantity":"Int!","locationId":"ID!"}}, +"InventoryMoveQuantitiesInput":{"i":{"changes":"[InventoryMoveQuantityChange!]!","reason":"String!","referenceDocumentUri":"String!"}}, +"InventoryMoveQuantitiesPayload":{"o":{"f":{"inventoryAdjustmentGroup":"InventoryAdjustmentGroup","userErrors":"[InventoryMoveQuantitiesUserError!]!"}}}, +"InventoryMoveQuantitiesUserError":{"o":{"f":{"code":"InventoryMoveQuantitiesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryMoveQuantitiesUserErrorCode":{"e":["INTERNAL_LEDGER_DOCUMENT","INVALID_AVAILABLE_DOCUMENT","INVALID_INVENTORY_ITEM","INVALID_LEDGER_DOCUMENT","INVALID_LOCATION","INVALID_QUANTITY_DOCUMENT","INVALID_QUANTITY_NAME","INVALID_QUANTITY_NEGATIVE","INVALID_QUANTITY_TOO_HIGH","INVALID_REASON","INVALID_REFERENCE_DOCUMENT","SERVICE_UNAVAILABLE","CHANGE_FROM_QUANTITY_STALE","MOVE_QUANTITIES_FAILED","DIFFERENT_LOCATIONS","SAME_QUANTITY_NAME","MAXIMUM_LEDGER_DOCUMENT_URIS","NON_MUTABLE_INVENTORY_ITEM","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED"]}, +"InventoryMoveQuantityChange":{"i":{"from":"InventoryMoveQuantityTerminalInput!","inventoryItemId":"ID!","quantity":"Int!","to":"InventoryMoveQuantityTerminalInput!"}}, +"InventoryMoveQuantityTerminalInput":{"i":{"changeFromQuantity":"Int","ledgerDocumentUri":"String","locationId":"ID!","name":"String!"}}, +"InventoryProperties":{"o":{"f":{"quantityNames":"[InventoryQuantityName!]!"}}}, +"InventoryPurchaseOrder":{"o":{"f":{"archivedAt":"DateTime","currency":"CurrencyCode!","dateCreated":"DateTime!","destination":"LocationSnapshot","id":"ID!","lineItems":["InventoryPurchaseOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","lineItemId":"ID","query":"String","reverse":"Boolean=","sortKey":"PurchaseOrderLineItemSortKeys="}],"name":"String!","orderedAt":"DateTime","origin":"InventorySupplierSnapshot","status":"InventoryPurchaseOrderStatus!","transfers":["InventoryTransferConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Node"]}}, +"InventoryPurchaseOrderConnection":{"o":{"f":{"edges":"[InventoryPurchaseOrderEdge!]!","nodes":"[InventoryPurchaseOrder!]!","pageInfo":"PageInfo!"}}}, +"InventoryPurchaseOrderEdge":{"o":{"f":{"cursor":"String!","node":"InventoryPurchaseOrder!"}}}, +"InventoryPurchaseOrderLineItem":{"o":{"f":{"id":"ID!","inventoryItem":"InventoryItem","purchaseOrder":"InventoryPurchaseOrder","subtotal":"MoneyV2","supplierSku":"String","taxPercent":"Decimal","title":"String","totalCost":"MoneyV2","totalQuantity":"Int!","unitCost":"MoneyV2","variantTitle":"String"},"t":["Node"]}}, +"InventoryPurchaseOrderLineItemConnection":{"o":{"f":{"edges":"[InventoryPurchaseOrderLineItemEdge!]!","nodes":"[InventoryPurchaseOrderLineItem!]!","pageInfo":"PageInfo!"}}}, +"InventoryPurchaseOrderLineItemEdge":{"o":{"f":{"cursor":"String!","node":"InventoryPurchaseOrderLineItem!"}}}, +"InventoryPurchaseOrderStatus":{"e":["DRAFT","ORDERED"]}, +"InventoryQuantity":{"o":{"f":{"id":"ID!","name":"String!","quantity":"Int!","updatedAt":"DateTime"},"t":["Node"]}}, +"InventoryQuantityInput":{"i":{"changeFromQuantity":"Int","inventoryItemId":"ID!","locationId":"ID!","quantity":"Int!"}}, +"InventoryQuantityName":{"o":{"f":{"belongsTo":"[String!]!","comprises":"[String!]!","displayName":"String","isInUse":"Boolean!","name":"String!"}}}, +"InventoryScheduledChange":{"o":{"f":{"expectedAt":"DateTime!","fromName":"String!","inventoryLevel":"InventoryLevel!","ledgerDocumentUri":"URL!","quantity":"Int!","toName":"String!"}}}, +"InventoryScheduledChangeConnection":{"o":{"f":{"edges":"[InventoryScheduledChangeEdge!]!","nodes":"[InventoryScheduledChange!]!","pageInfo":"PageInfo!"}}}, +"InventoryScheduledChangeEdge":{"o":{"f":{"cursor":"String!","node":"InventoryScheduledChange!"}}}, +"InventorySetOnHandQuantitiesInput":{"i":{"reason":"String!","referenceDocumentUri":"String","setQuantities":"[InventorySetQuantityInput!]!"}}, +"InventorySetOnHandQuantitiesPayload":{"o":{"f":{"inventoryAdjustmentGroup":"InventoryAdjustmentGroup","userErrors":"[InventorySetOnHandQuantitiesUserError!]!"}}}, +"InventorySetOnHandQuantitiesUserError":{"o":{"f":{"code":"InventorySetOnHandQuantitiesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventorySetOnHandQuantitiesUserErrorCode":{"e":["INVALID_INVENTORY_ITEM","INVALID_LOCATION","INVALID_QUANTITY_NEGATIVE","INVALID_REASON","INVALID_REFERENCE_DOCUMENT","CHANGE_FROM_QUANTITY_STALE","SET_ON_HAND_QUANTITIES_FAILED","NON_MUTABLE_INVENTORY_ITEM","INVALID_QUANTITY_TOO_HIGH","COMPARE_QUANTITY_STALE","SERVICE_UNAVAILABLE","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED"]}, +"InventorySetQuantitiesInput":{"i":{"name":"String!","quantities":"[InventoryQuantityInput!]!","reason":"String!","referenceDocumentUri":"String"}}, +"InventorySetQuantitiesPayload":{"o":{"f":{"inventoryAdjustmentGroup":"InventoryAdjustmentGroup","userErrors":"[InventorySetQuantitiesUserError!]!"}}}, +"InventorySetQuantitiesUserError":{"o":{"f":{"code":"InventorySetQuantitiesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventorySetQuantitiesUserErrorCode":{"e":["INVALID_INVENTORY_ITEM","INVALID_LOCATION","INVALID_QUANTITY_NEGATIVE","INVALID_REASON","INVALID_REFERENCE_DOCUMENT","INVALID_QUANTITY_TOO_HIGH","INVALID_QUANTITY_TOO_LOW","COMPARE_QUANTITY_REQUIRED","COMPARE_QUANTITY_STALE","CHANGE_FROM_QUANTITY_STALE","INVALID_NAME","NO_DUPLICATE_INVENTORY_ITEM_ID_GROUP_ID_PAIR","NON_MUTABLE_INVENTORY_ITEM","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED"]}, +"InventorySetQuantityInput":{"i":{"changeFromQuantity":"Int","inventoryItemId":"ID!","locationId":"ID!","quantity":"Int!"}}, +"InventoryShipment":{"o":{"f":{"barcode":"String","dateCreated":"DateTime","dateReceived":"DateTime","dateShipped":"DateTime","id":"ID!","lineItemTotalQuantity":"Int!","lineItems":["InventoryShipmentLineItemConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ShipmentLineItemSortKeys="}],"lineItemsCount":["Count",{"limit":"Int=","query":"String"}],"name":"String!","status":"InventoryShipmentStatus!","totalAcceptedQuantity":"Int!","totalCanceledQuantity":"Int!","totalReceivedQuantity":"Int!","totalRejectedQuantity":"Int!","tracking":"InventoryShipmentTracking"},"t":["Node"]}}, +"InventoryShipmentAddItemsPayload":{"o":{"f":{"addedItems":"[InventoryShipmentLineItem!]","inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentAddItemsUserError!]!"}}}, +"InventoryShipmentAddItemsUserError":{"o":{"f":{"code":"InventoryShipmentAddItemsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentAddItemsUserErrorCode":{"e":["LOCATION_NOT_FOUND","INVALID_SHIPMENT_STATUS","DUPLICATE_ITEM","INVALID_QUANTITY","ITEM_NOT_FOUND","INVENTORY_STATE_NOT_ACTIVE","UNTRACKED_ITEM","SHIPMENT_NOT_FOUND","LOCATION_NOT_ACTIVE","ACTIVATION_FAILED","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH"]}, +"InventoryShipmentConnection":{"o":{"f":{"edges":"[InventoryShipmentEdge!]!","nodes":"[InventoryShipment!]!","pageInfo":"PageInfo!"}}}, +"InventoryShipmentCreateInTransitPayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentCreateInTransitUserError!]!"}}}, +"InventoryShipmentCreateInTransitUserError":{"o":{"f":{"code":"InventoryShipmentCreateInTransitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentCreateInTransitUserErrorCode":{"e":["BARCODE_DUPLICATE","BARCODE_TOO_LONG","DUPLICATE_ITEM","INVALID_QUANTITY","ITEM_NOT_FOUND","INVALID_TRANSFER_STATUS","UNTRACKED_ITEM","EMPTY_SHIPMENT_INPUT","ITEMS_EMPTY","TRANSFER_NOT_FOUND","INVALID_URL","INVALID_SHIPMENT_INPUT","INVALID_ITEM","INVENTORY_STATE_NOT_ACTIVE","LOCATION_NOT_ACTIVE","SHIPMENT_NOT_FOUND","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH"]}, +"InventoryShipmentCreateInput":{"i":{"barcode":"String","dateCreated":"DateTime","lineItems":"[InventoryShipmentLineItemInput!]!","movementId":"ID!","trackingInput":"InventoryShipmentTrackingInput"}}, +"InventoryShipmentCreatePayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentCreateUserError!]!"}}}, +"InventoryShipmentCreateUserError":{"o":{"f":{"code":"InventoryShipmentCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentCreateUserErrorCode":{"e":["BARCODE_DUPLICATE","BARCODE_TOO_LONG","EMPTY_SHIPMENT_INPUT","ITEM_NOT_FOUND","TRANSFER_NOT_FOUND","INVALID_TRANSFER_STATUS","BUNDLED_ITEM","INVALID_QUANTITY","UNTRACKED_ITEM","DUPLICATE_ITEM","INVALID_SHIPMENT_INPUT","INVALID_ITEM","INVALID_URL","LOCATION_NOT_ACTIVE","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","IDEMPOTENCY_RECORD_NOT_FOUND"]}, +"InventoryShipmentDeletePayload":{"o":{"f":{"id":"ID","userErrors":"[InventoryShipmentDeleteUserError!]!"}}}, +"InventoryShipmentDeleteUserError":{"o":{"f":{"code":"InventoryShipmentDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentDeleteUserErrorCode":{"e":["SHIPMENT_NOT_FOUND","INVALID_SHIPMENT_STATUS"]}, +"InventoryShipmentEdge":{"o":{"f":{"cursor":"String!","node":"InventoryShipment!"}}}, +"InventoryShipmentLineItem":{"o":{"f":{"acceptedQuantity":"Int!","canceledQuantity":"Int!","id":"ID!","inventoryItem":"InventoryItem","quantity":"Int!","rejectedQuantity":"Int!","unreceivedQuantity":"Int!"},"t":["Node"]}}, +"InventoryShipmentLineItemConnection":{"o":{"f":{"edges":"[InventoryShipmentLineItemEdge!]!","nodes":"[InventoryShipmentLineItem!]!","pageInfo":"PageInfo!"}}}, +"InventoryShipmentLineItemEdge":{"o":{"f":{"cursor":"String!","node":"InventoryShipmentLineItem!"}}}, +"InventoryShipmentLineItemInput":{"i":{"inventoryItemId":"ID!","quantity":"Int!"}}, +"InventoryShipmentMarkInTransitPayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentMarkInTransitUserError!]!"}}}, +"InventoryShipmentMarkInTransitUserError":{"o":{"f":{"code":"InventoryShipmentMarkInTransitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentMarkInTransitUserErrorCode":{"e":["SHIPMENT_NOT_FOUND","INVALID_SHIPMENT_STATUS","ITEM_NOT_FOUND","INVENTORY_STATE_NOT_ACTIVE","UNTRACKED_ITEM","INVALID_QUANTITY","ITEMS_EMPTY","LOCATION_NOT_ACTIVE","ACTIVATION_FAILED"]}, +"InventoryShipmentReceiveItemInput":{"i":{"quantity":"Int!","reason":"InventoryShipmentReceiveLineItemReason!","shipmentLineItemId":"ID!"}}, +"InventoryShipmentReceiveLineItemReason":{"e":["ACCEPTED","REJECTED","CANCELED"]}, +"InventoryShipmentReceivePayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentReceiveUserError!]!"}}}, +"InventoryShipmentReceiveUserError":{"o":{"f":{"code":"InventoryShipmentReceiveUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentReceiveUserErrorCode":{"e":["LOCATION_NOT_FOUND","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","INTERNAL_ERROR","INVALID_SHIPMENT_INPUT","INVALID_SHIPMENT_STATUS","INVENTORY_STATE_NOT_ACTIVE","SHIPMENT_NOT_FOUND","INVALID_QUANTITY","ITEM_NOT_FOUND","LOCATION_NOT_ACTIVE"]}, +"InventoryShipmentRemoveItemsPayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentRemoveItemsUserError!]!"}}}, +"InventoryShipmentRemoveItemsUserError":{"o":{"f":{"code":"InventoryShipmentRemoveItemsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentRemoveItemsUserErrorCode":{"e":["LOCATION_NOT_FOUND","INTERNAL_ERROR","SHIPMENT_NOT_FOUND","ITEM_NOT_FOUND","INVALID_SHIPMENT_STATUS","LOCATION_NOT_ACTIVE"]}, +"InventoryShipmentSetBarcodePayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentSetBarcodeUserError!]!"}}}, +"InventoryShipmentSetBarcodeUserError":{"o":{"f":{"code":"InventoryShipmentSetBarcodeUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentSetBarcodeUserErrorCode":{"e":["SHIPMENT_NOT_FOUND","BARCODE_DUPLICATE","BARCODE_TOO_LONG"]}, +"InventoryShipmentSetTrackingPayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentSetTrackingUserError!]!"}}}, +"InventoryShipmentSetTrackingUserError":{"o":{"f":{"code":"InventoryShipmentSetTrackingUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentSetTrackingUserErrorCode":{"e":["SHIPMENT_NOT_FOUND","INVALID_URL"]}, +"InventoryShipmentSortKeys":{"e":["ID","STATUS"]}, +"InventoryShipmentStatus":{"e":["DRAFT","IN_TRANSIT","PARTIALLY_RECEIVED","RECEIVED","OTHER"]}, +"InventoryShipmentTracking":{"o":{"f":{"arrivesAt":"DateTime","company":"String","trackingNumber":"String","trackingUrl":"URL"}}}, +"InventoryShipmentTrackingInput":{"i":{"arrivesAt":"DateTime","company":"String","trackingNumber":"String","trackingUrl":"URL"}}, +"InventoryShipmentUpdateItemQuantitiesInput":{"i":{"quantity":"Int!","shipmentLineItemId":"ID!"}}, +"InventoryShipmentUpdateItemQuantitiesPayload":{"o":{"f":{"shipment":"InventoryShipment","updatedLineItems":"[InventoryShipmentLineItem!]","userErrors":"[InventoryShipmentUpdateItemQuantitiesUserError!]!"}}}, +"InventoryShipmentUpdateItemQuantitiesUserError":{"o":{"f":{"code":"InventoryShipmentUpdateItemQuantitiesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentUpdateItemQuantitiesUserErrorCode":{"e":["LOCATION_NOT_FOUND","SHIPMENT_NOT_FOUND","ITEM_NOT_FOUND","INVALID_QUANTITY","INVALID_SHIPMENT_STATUS","LOCATION_NOT_ACTIVE"]}, +"InventorySupplierSnapshot":{"o":{"f":{"supplierName":"String"}}}, +"InventoryTransfer":{"o":{"f":{"dateCreated":"DateTime","destination":"LocationSnapshot","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"hasTimelineComment":"Boolean!","id":"ID!","lineItems":["InventoryTransferLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"lineItemsCount":["Count",{"limit":"Int=","query":"String"}],"metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","note":"String","origin":"LocationSnapshot","receivedQuantity":"Int!","referenceName":"String","shipments":["InventoryShipmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"status":"InventoryTransferStatus!","tags":"[String!]!","totalQuantity":"Int!"},"t":["CommentEventSubject","HasEvents","HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"InventoryTransferCancelPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferCancelUserError!]!"}}}, +"InventoryTransferCancelUserError":{"o":{"f":{"code":"InventoryTransferCancelUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferCancelUserErrorCode":{"e":["INVALID_TRANSFER_STATUS","SHIPMENT_EXISTS","TRANSFER_NOT_FOUND"]}, +"InventoryTransferConnection":{"o":{"f":{"edges":"[InventoryTransferEdge!]!","nodes":"[InventoryTransfer!]!","pageInfo":"PageInfo!"}}}, +"InventoryTransferCreateAsReadyToShipInput":{"i":{"dateCreated":"DateTime","destinationLocationId":"ID","lineItems":"[InventoryTransferLineItemInput!]!=","metafields":"[MetafieldInput!]","note":"String","originLocationId":"ID","referenceName":"String","tags":"[String!]"}}, +"InventoryTransferCreateAsReadyToShipPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferCreateAsReadyToShipUserError!]!"}}}, +"InventoryTransferCreateAsReadyToShipUserError":{"o":{"f":{"code":"InventoryTransferCreateAsReadyToShipUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferCreateAsReadyToShipUserErrorCode":{"e":["TRANSFER_NOT_FOUND","ITEMS_EMPTY","INVALID_TRANSFER_STATUS","LOCATION_NOT_ACTIVE","LOCATION_NOT_FOUND","TRANSFER_ORIGIN_CANNOT_BE_THE_SAME_AS_DESTINATION","TAG_EXCEEDS_MAX_LENGTH","INVALID_TAG","LOCATION_REQUIRED","INVALID_METAFIELDS","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","BUNDLED_ITEM","UNTRACKED_ITEM","ITEM_NOT_FOUND","INVALID_QUANTITY","DUPLICATE_ITEM","INVENTORY_STATE_NOT_ACTIVE"]}, +"InventoryTransferCreateInput":{"i":{"dateCreated":"DateTime","destinationLocationId":"ID","lineItems":"[InventoryTransferLineItemInput!]!=","metafields":"[MetafieldInput!]","note":"String","originLocationId":"ID","referenceName":"String","tags":"[String!]"}}, +"InventoryTransferCreatePayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferCreateUserError!]!"}}}, +"InventoryTransferCreateUserError":{"o":{"f":{"code":"InventoryTransferCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferCreateUserErrorCode":{"e":["TRANSFER_NOT_FOUND","LOCATION_NOT_FOUND","LOCATION_NOT_ACTIVE","TRANSFER_ORIGIN_CANNOT_BE_THE_SAME_AS_DESTINATION","TAG_EXCEEDS_MAX_LENGTH","INVALID_TAG","INVALID_METAFIELDS","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","BUNDLED_ITEM","UNTRACKED_ITEM","ITEM_NOT_FOUND","INVALID_QUANTITY","DUPLICATE_ITEM","INVENTORY_STATE_NOT_ACTIVE"]}, +"InventoryTransferDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[InventoryTransferDeleteUserError!]!"}}}, +"InventoryTransferDeleteUserError":{"o":{"f":{"code":"InventoryTransferDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferDeleteUserErrorCode":{"e":["INVALID_STATE","INVALID_TRANSFER_STATUS","TRANSFER_NOT_FOUND"]}, +"InventoryTransferDuplicatePayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferDuplicateUserError!]!"}}}, +"InventoryTransferDuplicateUserError":{"o":{"f":{"code":"InventoryTransferDuplicateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferDuplicateUserErrorCode":{"e":["TRANSFER_NOT_FOUND","INVALID_QUANTITY","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH"]}, +"InventoryTransferEdge":{"o":{"f":{"cursor":"String!","node":"InventoryTransfer!"}}}, +"InventoryTransferEditInput":{"i":{"dateCreated":"Date","destinationId":"ID","metafields":"[MetafieldInput!]","note":"String","originId":"ID","referenceName":"String","tags":"[String!]"}}, +"InventoryTransferEditPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferEditUserError!]!"}}}, +"InventoryTransferEditUserError":{"o":{"f":{"code":"InventoryTransferEditUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferEditUserErrorCode":{"e":["INTERNAL_ERROR","TRANSFER_NOT_FOUND","TRANSFER_LOCATION_IMMUTABLE","TRANSFER_ORIGIN_CANNOT_BE_THE_SAME_AS_DESTINATION","LOCATION_NOT_ACTIVE","LOCATION_NOT_FOUND","INVENTORY_STATE_NOT_ACTIVE","TAG_EXCEEDS_MAX_LENGTH","INVALID_TAG","INVALID_METAFIELDS"]}, +"InventoryTransferLineItem":{"o":{"f":{"id":"ID!","inventoryItem":"InventoryItem","pickedForShipmentQuantity":"Int!","processableQuantity":"Int!","shippableQuantity":"Int!","shippedQuantity":"Int!","title":"String","totalQuantity":"Int!"},"t":["Node"]}}, +"InventoryTransferLineItemConnection":{"o":{"f":{"edges":"[InventoryTransferLineItemEdge!]!","nodes":"[InventoryTransferLineItem!]!","pageInfo":"PageInfo!"}}}, +"InventoryTransferLineItemEdge":{"o":{"f":{"cursor":"String!","node":"InventoryTransferLineItem!"}}}, +"InventoryTransferLineItemInput":{"i":{"inventoryItemId":"ID!","quantity":"Int!"}}, +"InventoryTransferLineItemUpdate":{"o":{"f":{"deltaQuantity":"Int","inventoryItemId":"ID","newQuantity":"Int"}}}, +"InventoryTransferMarkAsReadyToShipPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferMarkAsReadyToShipUserError!]!"}}}, +"InventoryTransferMarkAsReadyToShipUserError":{"o":{"f":{"code":"InventoryTransferMarkAsReadyToShipUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferMarkAsReadyToShipUserErrorCode":{"e":["TRANSFER_NOT_FOUND","ITEMS_EMPTY","INVALID_TRANSFER_STATUS","LOCATION_REQUIRED","INVALID_ITEM","LOCATION_NOT_ACTIVE","LOCATION_NOT_FOUND"]}, +"InventoryTransferRemoveItemsInput":{"i":{"id":"ID!","transferLineItemIds":"[ID!]"}}, +"InventoryTransferRemoveItemsPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","removedQuantities":"[InventoryTransferLineItemUpdate!]","userErrors":"[InventoryTransferRemoveItemsUserError!]!"}}}, +"InventoryTransferRemoveItemsUserError":{"o":{"f":{"code":"InventoryTransferRemoveItemsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferRemoveItemsUserErrorCode":{"e":["TRANSFER_NOT_FOUND","CANT_REMOVE_ALL_ITEMS_FROM_READY_TO_SHIP_TRANSFER","ITEM_NOT_FOUND","ALL_QUANTITY_SHIPPED","ITEM_PRESENT_ON_DRAFT_SHIPMENT_WITH_ZERO_QUANTITY","INVALID_TRANSFER_STATUS","LOCATION_NOT_FOUND"]}, +"InventoryTransferSetItemsInput":{"i":{"id":"ID!","lineItems":"[InventoryTransferLineItemInput!]!"}}, +"InventoryTransferSetItemsPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","updatedLineItems":"[InventoryTransferLineItemUpdate!]","userErrors":"[InventoryTransferSetItemsUserError!]!"}}}, +"InventoryTransferSetItemsUserError":{"o":{"f":{"code":"InventoryTransferSetItemsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferSetItemsUserErrorCode":{"e":["TRANSFER_NOT_FOUND","INVALID_TRANSFER_STATUS","LOCATION_NOT_FOUND","LOCATION_NOT_ACTIVE","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","BUNDLED_ITEM","UNTRACKED_ITEM","ITEM_NOT_FOUND","INVALID_QUANTITY","DUPLICATE_ITEM","INVENTORY_STATE_NOT_ACTIVE"]}, +"InventoryTransferStatus":{"e":["DRAFT","READY_TO_SHIP","IN_PROGRESS","TRANSFERRED","CANCELED","OTHER"]}, +"InvoiceReturnOutcome":{"o":{"f":{"amount":"MoneyBag!"}}}, +"JSON":"s", +"Job":{"o":{"f":{"done":"Boolean!","id":"ID!","query":"QueryRoot"}}}, +"JobResult":{"n":{"f":{"done":"Boolean!","id":"ID!"},"t":["CustomerSegmentMembersQuery","OrderCancelJobResult","OrderCreateMandatePaymentJobResult","ShippingLabelPurchaseResult"]}}, +"LanguageCode":{"e":["AF","AK","AM","AR","AS","AZ","BE","BG","BM","BN","BO","BR","BS","CA","CE","CKB","CS","CY","DA","DE","DZ","EE","EL","EN","EO","ES","ET","EU","FA","FF","FI","FIL","FO","FR","FY","GA","GD","GL","GU","GV","HA","HE","HI","HR","HU","HY","IA","ID","IG","II","IS","IT","JA","JV","KA","KI","KK","KL","KM","KN","KO","KS","KU","KW","KY","LB","LG","LN","LO","LT","LU","LV","MG","MI","MK","ML","MN","MR","MS","MT","MY","NB","ND","NE","NL","NN","NO","OM","OR","OS","PA","PL","PS","PT_BR","PT_PT","QU","RM","RN","RO","RU","RW","SA","SC","SD","SE","SG","SI","SK","SL","SN","SO","SQ","SR","SU","SV","SW","TA","TE","TG","TH","TI","TK","TO","TR","TT","UG","UK","UR","UZ","VI","WO","XH","YI","YO","ZH_CN","ZH_TW","ZU","ZH","PT","CU","VO"]}, +"LegacyInteroperability":{"n":{"f":{"legacyResourceId":"UnsignedInt64!"},"t":["Customer","DraftOrder","Fulfillment","InventoryItem","Location","MarketingEvent","Metafield","Order","Product","ProductVariant","Refund","SavedSearch","ScriptTag","ShopifyPaymentsDispute","ShopifyPaymentsPayout","WebhookSubscription"]}}, +"LengthUnit":{"e":["MILLIMETERS","CENTIMETERS","METERS","INCHES","FEET","YARDS"]}, +"LimitedPendingOrderCount":{"o":{"f":{"atMax":"Boolean!","count":"Int!"}}}, +"LineItem":{"o":{"f":{"canRestock":"Boolean!","contract":"SubscriptionContract","createdAt":"DateTime!","currentQuantity":"Int!","customAttributes":"[Attribute!]!","discountAllocations":"[DiscountAllocation!]!","discountedTotal":"Money!","discountedTotalSet":["MoneyBag!",{"withCodeDiscounts":"Boolean="}],"discountedUnitPrice":"Money!","discountedUnitPriceAfterAllDiscountsSet":"MoneyBag!","discountedUnitPriceSet":"MoneyBag!","duties":"[Duty!]!","fulfillableQuantity":"Int!","fulfillmentService":"FulfillmentService","fulfillmentStatus":"String!","id":"ID!","image":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"isGiftCard":"Boolean!","lineItemGroup":"LineItemGroup","merchantEditable":"Boolean!","name":"String!","nonFulfillableQuantity":"Int!","originalTotal":"Money!","originalTotalSet":"MoneyBag!","originalUnitPrice":"Money!","originalUnitPriceSet":"MoneyBag!","priceAfterAllDiscountsBeforeTaxesSet":"MoneyBag!","product":"Product","quantity":"Int!","refundableQuantity":"Int!","requiresShipping":"Boolean!","restockable":"Boolean!","sellingPlan":"LineItemSellingPlan","sku":"String","staffMember":"StaffMember","suggestedReturnReasonDefinitions":["ReturnReasonDefinitionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"taxLines":["[TaxLine!]!",{"first":"Int"}],"taxable":"Boolean!","title":"String!","totalDiscount":"Money!","totalDiscountSet":"MoneyBag!","unfulfilledDiscountedTotal":"Money!","unfulfilledDiscountedTotalSet":"MoneyBag!","unfulfilledOriginalTotal":"Money!","unfulfilledOriginalTotalSet":"MoneyBag!","unfulfilledQuantity":"Int!","variant":"ProductVariant","variantTitle":"String","vendor":"String","weight":"Weight"},"t":["Node"],"d":{"canRestock":"Use `restockable` instead.","discountedTotal":"Use `discountedTotalSet` instead.","discountedUnitPrice":"Use `discountedUnitPriceSet` instead.","fulfillableQuantity":"Use [FulfillmentOrderLineItem#remainingQuantity](https://shopify.dev/api/admin-graphql/latest/objects/FulfillmentOrderLineItem#field-fulfillmentorderlineitem-remainingquantity) instead.","fulfillmentService":"The [relationship between a product variant and a fulfillment service was changed](/changelog/fulfillment-service-sku-sharing). A [ProductVariant](/api/admin-graphql/latest/objects/ProductVariant) can be stocked by multiple fulfillment services. As a result, we recommend that you use the [inventoryItem field](/api/admin-graphql/latest/objects/ProductVariant#field-productvariant-inventoryitem) if you need to determine where a product variant is stocked.\n\nIf you need to determine whether a product is a gift card, then you should continue to use this field until an alternative is available.\n\nAltering the locations which stock a product variant won't change the value of this field for existing orders.\n\nLearn about [managing inventory quantities and states](/apps/fulfillment/inventory-management-apps/quantities-states).","fulfillmentStatus":"Use [FulfillmentOrderLineItem#remainingQuantity](https://shopify.dev/api/admin-graphql/latest/objects/FulfillmentOrderLineItem#field-fulfillmentorderlineitem-remainingquantity) instead","image(crop)":"Use `Image.url(transform: { crop:})` instead.","image(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","image(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","image(scale)":"Use `Image.url(transform: { scale:})` instead.","originalTotal":"Use `originalTotalSet` instead.","originalUnitPrice":"Use `originalUnitPriceSet` instead.","totalDiscount":"Use `totalDiscountSet` instead.","unfulfilledDiscountedTotal":"Use `unfulfilledDiscountedTotalSet` instead.","unfulfilledOriginalTotal":"Use `unfulfilledOriginalTotalSet` instead."}}}, +"LineItemConnection":{"o":{"f":{"edges":"[LineItemEdge!]!","nodes":"[LineItem!]!","pageInfo":"PageInfo!"}}}, +"LineItemEdge":{"o":{"f":{"cursor":"String!","node":"LineItem!"}}}, +"LineItemGroup":{"o":{"f":{"customAttributes":"[Attribute!]!","id":"ID!","productId":"ID","quantity":"Int!","title":"String!","variantId":"ID","variantSku":"String"},"t":["Node"]}}, +"LineItemSellingPlan":{"o":{"f":{"name":"String!","sellingPlanId":"ID"}}}, +"Link":{"o":{"f":{"label":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"url":"URL!"},"t":["HasPublishedTranslations"]}}, +"LinkedMetafield":{"o":{"f":{"key":"String","namespace":"String"}}}, +"LinkedMetafieldCreateInput":{"i":{"key":"String!","namespace":"String!","values":"[String!]"}}, +"LinkedMetafieldInput":{"i":{"key":"String!","namespace":"String!","values":"[String!]!"}}, +"LinkedMetafieldUpdateInput":{"i":{"key":"String!","namespace":"String!"}}, +"LocalPaymentMethodsPaymentDetails":{"o":{"f":{"paymentDescriptor":"String","paymentMethodName":"String"},"t":["BasePaymentDetails"]}}, +"Locale":{"o":{"f":{"isoCode":"String!","name":"String!"}}}, +"LocalizableContentType":{"e":["JSON_STRING","JSON","LINK","LIST_LINK","LIST_MULTI_LINE_TEXT_FIELD","LIST_SINGLE_LINE_TEXT_FIELD","LIST_URL","MULTI_LINE_TEXT_FIELD","RICH_TEXT_FIELD","SINGLE_LINE_TEXT_FIELD","STRING","URL","FILE_REFERENCE","LIST_FILE_REFERENCE","HTML","URI","INLINE_RICH_TEXT"]}, +"LocalizationExtension":{"o":{"f":{"countryCode":"CountryCode!","key":"LocalizationExtensionKey!","purpose":"LocalizationExtensionPurpose!","title":"String!","value":"String!"}}}, +"LocalizationExtensionConnection":{"o":{"f":{"edges":"[LocalizationExtensionEdge!]!","nodes":"[LocalizationExtension!]!","pageInfo":"PageInfo!"}}}, +"LocalizationExtensionEdge":{"o":{"f":{"cursor":"String!","node":"LocalizationExtension!"}}}, +"LocalizationExtensionInput":{"i":{"key":"LocalizationExtensionKey!","value":"String!"}}, +"LocalizationExtensionKey":{"e":["TAX_CREDENTIAL_BR","SHIPPING_CREDENTIAL_BR","TAX_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CN","TAX_CREDENTIAL_CO","TAX_CREDENTIAL_TYPE_CO","SHIPPING_CREDENTIAL_CO","SHIPPING_CREDENTIAL_TYPE_CO","TAX_CREDENTIAL_CR","SHIPPING_CREDENTIAL_CR","TAX_CREDENTIAL_EC","SHIPPING_CREDENTIAL_EC","TAX_CREDENTIAL_GT","SHIPPING_CREDENTIAL_GT","TAX_CREDENTIAL_ID","SHIPPING_CREDENTIAL_ID","TAX_CREDENTIAL_IT","TAX_EMAIL_IT","TAX_CREDENTIAL_MY","SHIPPING_CREDENTIAL_MY","SHIPPING_CREDENTIAL_MX","TAX_CREDENTIAL_MX","TAX_CREDENTIAL_TYPE_MX","TAX_CREDENTIAL_USE_MX","TAX_CREDENTIAL_PY","SHIPPING_CREDENTIAL_PY","TAX_CREDENTIAL_PE","SHIPPING_CREDENTIAL_PE","TAX_CREDENTIAL_PT","SHIPPING_CREDENTIAL_PT","SHIPPING_CREDENTIAL_KR","TAX_CREDENTIAL_ES","SHIPPING_CREDENTIAL_ES","SHIPPING_CREDENTIAL_TW","TAX_CREDENTIAL_TR","SHIPPING_CREDENTIAL_TR"]}, +"LocalizationExtensionPurpose":{"e":["SHIPPING","TAX"]}, +"LocalizedField":{"o":{"f":{"countryCode":"CountryCode!","key":"LocalizedFieldKey!","purpose":"LocalizedFieldPurpose!","title":"String!","value":"String!"}}}, +"LocalizedFieldConnection":{"o":{"f":{"edges":"[LocalizedFieldEdge!]!","nodes":"[LocalizedField!]!","pageInfo":"PageInfo!"}}}, +"LocalizedFieldEdge":{"o":{"f":{"cursor":"String!","node":"LocalizedField!"}}}, +"LocalizedFieldInput":{"i":{"key":"LocalizedFieldKey!","value":"String!"}}, +"LocalizedFieldKey":{"e":["TAX_CREDENTIAL_BR","SHIPPING_CREDENTIAL_BR","TAX_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CN","TAX_CREDENTIAL_CO","TAX_CREDENTIAL_TYPE_CO","SHIPPING_CREDENTIAL_CO","SHIPPING_CREDENTIAL_TYPE_CO","TAX_CREDENTIAL_CR","SHIPPING_CREDENTIAL_CR","TAX_CREDENTIAL_EC","SHIPPING_CREDENTIAL_EC","TAX_CREDENTIAL_GT","SHIPPING_CREDENTIAL_GT","TAX_CREDENTIAL_ID","SHIPPING_CREDENTIAL_ID","TAX_CREDENTIAL_IT","TAX_EMAIL_IT","TAX_CREDENTIAL_MY","SHIPPING_CREDENTIAL_MY","SHIPPING_CREDENTIAL_MX","TAX_CREDENTIAL_MX","TAX_CREDENTIAL_TYPE_MX","TAX_CREDENTIAL_USE_MX","TAX_CREDENTIAL_PY","SHIPPING_CREDENTIAL_PY","TAX_CREDENTIAL_PE","SHIPPING_CREDENTIAL_PE","TAX_CREDENTIAL_PT","SHIPPING_CREDENTIAL_PT","SHIPPING_CREDENTIAL_KR","TAX_CREDENTIAL_ES","SHIPPING_CREDENTIAL_ES","SHIPPING_CREDENTIAL_TW","TAX_CREDENTIAL_TR","SHIPPING_CREDENTIAL_TR"]}, +"LocalizedFieldPurpose":{"e":["SHIPPING","TAX"]}, +"Location":{"o":{"f":{"activatable":"Boolean!","address":"LocationAddress!","addressVerified":"Boolean!","createdAt":"DateTime!","deactivatable":"Boolean!","deactivatedAt":"String","deletable":"Boolean!","fulfillmentService":"FulfillmentService","fulfillsOnlineOrders":"Boolean!","hasActiveInventory":"Boolean!","hasUnfulfilledOrders":"Boolean!","id":"ID!","inventoryLevel":["InventoryLevel",{"includeInactive":"Boolean=","inventoryItemId":"ID!"}],"inventoryLevels":["InventoryLevelConnection!",{"after":"String","before":"String","first":"Int","includeInactive":"Boolean=","last":"Int","query":"String","reverse":"Boolean="}],"isActive":"Boolean!","isFulfillmentService":"Boolean!","isPrimary":"Boolean!","legacyResourceId":"UnsignedInt64!","localPickupSettingsV2":"DeliveryLocalPickupSettings","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","shipsInventory":"Boolean!","suggestedAddresses":"[LocationSuggestedAddress!]!","updatedAt":"DateTime!"},"t":["HasMetafieldDefinitions","HasMetafields","LegacyInteroperability","Node"],"d":{"isPrimary":"The concept of a primary location is deprecated, shipsInventory can be used to get a fallback location","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"LocationActivatePayload":{"o":{"f":{"location":"Location","locationActivateUserErrors":"[LocationActivateUserError!]!"}}}, +"LocationActivateUserError":{"o":{"f":{"code":"LocationActivateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"LocationActivateUserErrorCode":{"e":["GENERIC_ERROR","LOCATION_LIMIT","HAS_ONGOING_RELOCATION","LOCATION_NOT_FOUND","HAS_NON_UNIQUE_NAME","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH"]}, +"LocationAddAddressInput":{"i":{"address1":"String","address2":"String","city":"String","countryCode":"CountryCode!","phone":"String","provinceCode":"String","zip":"String"}}, +"LocationAddInput":{"i":{"address":"LocationAddAddressInput!","fulfillsOnlineOrders":"Boolean=","metafields":"[MetafieldInput!]","name":"String!"}}, +"LocationAddPayload":{"o":{"f":{"location":"Location","userErrors":"[LocationAddUserError!]!"}}}, +"LocationAddUserError":{"o":{"f":{"code":"LocationAddUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"LocationAddUserErrorCode":{"e":["INVALID","TOO_LONG","TAKEN","BLANK","INVALID_US_ZIPCODE","GENERIC_ERROR","INVALID_TYPE","INVALID_VALUE","APP_NOT_AUTHORIZED","UNSTRUCTURED_RESERVED_NAMESPACE","DISALLOWED_OWNER_TYPE","INCLUSION","PRESENT","TOO_SHORT","CAPABILITY_VIOLATION","INTERNAL_ERROR"]}, +"LocationAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","country":"String","countryCode":"String","formatted":"[String!]!","latitude":"Float","longitude":"Float","phone":"String","province":"String","provinceCode":"String","zip":"String"}}}, +"LocationConnection":{"o":{"f":{"edges":"[LocationEdge!]!","nodes":"[Location!]!","pageInfo":"PageInfo!"}}}, +"LocationDeactivatePayload":{"o":{"f":{"location":"Location","locationDeactivateUserErrors":"[LocationDeactivateUserError!]!"}}}, +"LocationDeactivateUserError":{"o":{"f":{"code":"LocationDeactivateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"LocationDeactivateUserErrorCode":{"e":["LOCATION_NOT_FOUND","PERMANENTLY_BLOCKED_FROM_DEACTIVATION_ERROR","TEMPORARILY_BLOCKED_FROM_DEACTIVATION_ERROR","HAS_ACTIVE_RETAIL_SUBSCRIPTIONS","DESTINATION_LOCATION_IS_THE_SAME_LOCATION","DESTINATION_LOCATION_NOT_FOUND_OR_INACTIVE","DESTINATION_LOCATION_NOT_SHOPIFY_MANAGED","HAS_ACTIVE_INVENTORY_ERROR","HAS_FULFILLMENT_ORDERS_ERROR","HAS_INCOMING_FROM_EXTERNAL_DOCUMENT_SOURCES","HAS_INCOMING_MOVEMENTS_ERROR","HAS_OPEN_PURCHASE_ORDERS_ERROR","FAILED_TO_RELOCATE_ACTIVE_INVENTORIES","FAILED_TO_RELOCATE_OPEN_PURCHASE_ORDERS","FAILED_TO_RELOCATE_INCOMING_MOVEMENTS","CANNOT_DISABLE_ONLINE_ORDER_FULFILLMENT","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH"]}, +"LocationDeletePayload":{"o":{"f":{"deletedLocationId":"ID","locationDeleteUserErrors":"[LocationDeleteUserError!]!"}}}, +"LocationDeleteUserError":{"o":{"f":{"code":"LocationDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"LocationDeleteUserErrorCode":{"e":["LOCATION_NOT_FOUND","LOCATION_IS_ACTIVE","GENERIC_ERROR","LOCATION_HAS_INVENTORY","LOCATION_HAS_PENDING_ORDERS","LOCATION_HAS_ACTIVE_RETAIL_SUBSCRIPTION"]}, +"LocationEdge":{"o":{"f":{"cursor":"String!","node":"Location!"}}}, +"LocationEditAddressInput":{"i":{"address1":"String","address2":"String","city":"String","countryCode":"CountryCode","phone":"String","provinceCode":"String","zip":"String"}}, +"LocationEditInput":{"i":{"address":"LocationEditAddressInput","fulfillsOnlineOrders":"Boolean","metafields":"[MetafieldInput!]","name":"String"}}, +"LocationEditPayload":{"o":{"f":{"location":"Location","userErrors":"[LocationEditUserError!]!"}}}, +"LocationEditUserError":{"o":{"f":{"code":"LocationEditUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"LocationEditUserErrorCode":{"e":["TOO_LONG","BLANK","NOT_FOUND","INVALID","TAKEN","INVALID_US_ZIPCODE","GENERIC_ERROR","CANNOT_DISABLE_ONLINE_ORDER_FULFILLMENT","CANNOT_MODIFY_ONLINE_ORDER_FULFILLMENT_FOR_FS_LOCATION","INVALID_TYPE","INVALID_VALUE","APP_NOT_AUTHORIZED","UNSTRUCTURED_RESERVED_NAMESPACE","DISALLOWED_OWNER_TYPE","INCLUSION","PRESENT","TOO_SHORT","CAPABILITY_VIOLATION","INTERNAL_ERROR"]}, +"LocationIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","id":"ID"}}, +"LocationLocalPickupDisablePayload":{"o":{"f":{"locationId":"ID","userErrors":"[DeliveryLocationLocalPickupSettingsError!]!"}}}, +"LocationLocalPickupEnablePayload":{"o":{"f":{"localPickupSettings":"DeliveryLocalPickupSettings","userErrors":"[DeliveryLocationLocalPickupSettingsError!]!"}}}, +"LocationSnapshot":{"o":{"f":{"address":"LocationAddress!","location":"Location","name":"String!","snapshottedAt":"DateTime!"}}}, +"LocationSortKeys":{"e":["ID","NAME","RELEVANCE"]}, +"LocationSuggestedAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","country":"String","countryCode":"CountryCode","formatted":"[String!]!","province":"String","provinceCode":"String","zip":"String"}}}, +"LocationsCondition":{"o":{"f":{"applicationLevel":"MarketConditionApplicationType","locations":["LocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"MailingAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","company":"String","coordinatesValidated":"Boolean!","country":"String","countryCode":"String","countryCodeV2":"CountryCode","firstName":"String","formatted":["[String!]!",{"withCompany":"Boolean=","withName":"Boolean="}],"formattedArea":"String","id":"ID!","lastName":"String","latitude":"Float","longitude":"Float","name":"String","phone":"String","province":"String","provinceCode":"String","timeZone":"String","validationResultSummary":"MailingAddressValidationResult","zip":"String"},"t":["Node"],"d":{"countryCode":"Use `countryCodeV2` instead."}}}, +"MailingAddressConnection":{"o":{"f":{"edges":"[MailingAddressEdge!]!","nodes":"[MailingAddress!]!","pageInfo":"PageInfo!"}}}, +"MailingAddressEdge":{"o":{"f":{"cursor":"String!","node":"MailingAddress!"}}}, +"MailingAddressInput":{"i":{"f":{"address1":"String","address2":"String","city":"String","company":"String","country":"String","countryCode":"CountryCode","firstName":"String","id":"ID","lastName":"String","phone":"String","province":"String","provinceCode":"String","zip":"String"},"d":{"country":"Use `countryCode` instead.","id":"Not needed for 90% of mutations, and provided separately where it is needed.","province":"Use `provinceCode` instead."}}}, +"MailingAddressValidationResult":{"e":["NO_ISSUES","ERROR","WARNING"]}, +"MandateResourceType":{"e":["CREDENTIAL_ON_FILE","CHECKOUT","DRAFT_ORDER","ORDER","SUBSCRIPTIONS"]}, +"ManualDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","description":"String","index":"Int!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","title":"String!","value":"PricingValue!"},"t":["DiscountApplication"]}}, +"Market":{"o":{"f":{"assignedCustomization":["Boolean!",{"customizationId":"ID!"}],"catalogs":["MarketCatalogConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"catalogsCount":"Count","childMarkets":["MarketConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"childMarketsCount":"Count","conditions":"MarketConditions","currencySettings":"MarketCurrencySettings","delivery":"MarketDeliveryConfigurations!","discounts":["DiscountNodeConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountsCount":"Count","enabled":"Boolean!","handle":"String!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","parentMarkets":["MarketConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"parentMarketsCount":"Count","priceInclusions":"MarketPriceInclusions","priceList":"PriceList","primary":"Boolean!","regions":["MarketRegionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"returnPolicyProfile":"ReturnPolicyProfile","status":"MarketStatus!","type":"MarketType!","webPresence":"MarketWebPresence","webPresences":["MarketWebPresenceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["HasMetafieldDefinitions","HasMetafields","Node"],"d":{"enabled":"Use `status` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","priceList":"Use `catalogs` instead.","primary":"This field is deprecated and will be removed in the future.","regions":"This field is deprecated and will be removed in the future. Use `conditions.regionConditions` instead.","webPresence":"Use `webPresences` instead."}}}, +"MarketCatalog":{"o":{"f":{"id":"ID!","markets":["MarketConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","status":"MarketStatus=","type":"MarketType="}],"marketsCount":["Count",{"limit":"Int","query":"String","status":"MarketStatus=","type":"MarketType="}],"operations":"[ResourceOperation!]!","priceList":"PriceList","publication":"Publication","status":"CatalogStatus!","title":"String!"},"t":["Catalog","Node"]}}, +"MarketCatalogConnection":{"o":{"f":{"edges":"[MarketCatalogEdge!]!","nodes":"[MarketCatalog!]!","pageInfo":"PageInfo!"}}}, +"MarketCatalogEdge":{"o":{"f":{"cursor":"String!","node":"MarketCatalog!"}}}, +"MarketConditionApplicationType":{"e":["SPECIFIED","ALL"]}, +"MarketConditionType":{"e":["REGION","LOCATION","COMPANY_LOCATION","CHANNEL"]}, +"MarketConditions":{"o":{"f":{"channelsCondition":"ChannelsCondition","companyLocationsCondition":"CompanyLocationsCondition","conditionTypes":"[MarketConditionType!]!","locationsCondition":"LocationsCondition","regionsCondition":"RegionsCondition"}}}, +"MarketConditionsChannelsInput":{"i":{"channelIds":"[ID!]"}}, +"MarketConditionsCompanyLocationsInput":{"i":{"applicationLevel":"MarketConditionApplicationType","companyLocationIds":"[ID!]"}}, +"MarketConditionsInput":{"i":{"channelsCondition":"MarketConditionsChannelsInput","companyLocationsCondition":"MarketConditionsCompanyLocationsInput","locationsCondition":"MarketConditionsLocationsInput","regionsCondition":"MarketConditionsRegionsInput"}}, +"MarketConditionsLocationsInput":{"i":{"applicationLevel":"MarketConditionApplicationType","locationIds":"[ID!]"}}, +"MarketConditionsRegionInput":{"i":{"countryCode":"CountryCode!","subdivision":"String"}}, +"MarketConditionsRegionsInput":{"i":{"applicationLevel":"MarketConditionApplicationType","regionIds":"[ID!]","regions":"[MarketConditionsRegionInput!]"}}, +"MarketConditionsUpdateInput":{"i":{"conditionsToAdd":"MarketConditionsInput","conditionsToDelete":"MarketConditionsInput"}}, +"MarketConnection":{"o":{"f":{"edges":"[MarketEdge!]!","nodes":"[Market!]!","pageInfo":"PageInfo!"}}}, +"MarketCreateInput":{"i":{"f":{"catalogs":"[ID!]","conditions":"MarketConditionsInput","currencySettings":"MarketCurrencySettingsUpdateInput","delivery":"MarketDeliveryConfigurationsCreateInput","discounts":"[ID!]","enabled":"Boolean","handle":"String","makeDuplicateRegionMarketsDraft":"Boolean","makeDuplicateUniqueMarketsDraft":"Boolean","name":"String!","priceInclusions":"MarketPriceInclusionsInput","regions":"[MarketRegionCreateInput!]","returnPolicyProfileId":"ID","status":"MarketStatus","webPresences":"[ID!]"},"d":{"enabled":"Use `status` instead.","makeDuplicateRegionMarketsDraft":"Use `makeDuplicateUniqueMarketsDraft` instead.","regions":"Use `conditions` instead."}}}, +"MarketCreatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketCurrencySettings":{"o":{"f":{"baseCurrency":"CurrencySetting!","localCurrencies":"Boolean!","roundingEnabled":"Boolean!"}}}, +"MarketCurrencySettingsUpdateInput":{"i":{"baseCurrency":"CurrencyCode","baseCurrencyManualRate":"Decimal","localCurrencies":"Boolean","roundingEnabled":"Boolean"}}, +"MarketCurrencySettingsUpdatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketCurrencySettingsUserError!]!"},"d":{"market":"Use `marketCreate` and `marketUpdate` mutations instead."}}}, +"MarketCurrencySettingsUserError":{"o":{"f":{"code":"MarketCurrencySettingsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MarketCurrencySettingsUserErrorCode":{"e":["MARKET_NOT_FOUND","MANAGED_MARKET","UNIFIED_MARKETS_ENABLED","MULTIPLE_CURRENCIES_NOT_SUPPORTED","NO_LOCAL_CURRENCIES_ON_SINGLE_COUNTRY_MARKET","UNSUPPORTED_CURRENCY","PRIMARY_MARKET_USES_SHOP_CURRENCY","ADAPTIVE_PRICING_REQUIRES_LOCAL_CURRENCIES"]}, +"MarketDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[MarketUserError!]!"}}}, +"MarketDeliveryConfigurations":{"o":{"f":{"shipping":"ShippingConfiguration"}}}, +"MarketDeliveryConfigurationsCreateInput":{"i":{"shipping":"ShippingConfigurationCreateInput"}}, +"MarketDeliveryConfigurationsUpdateInput":{"i":{"removeShipping":"Boolean","shipping":"ShippingConfigurationUpdateInput"}}, +"MarketEdge":{"o":{"f":{"cursor":"String!","node":"Market!"}}}, +"MarketLocalizableContent":{"o":{"f":{"digest":"String","key":"String!","value":"String"}}}, +"MarketLocalizableResource":{"o":{"f":{"marketLocalizableContent":"[MarketLocalizableContent!]!","marketLocalizations":["[MarketLocalization!]!",{"marketId":"ID!"}],"resourceId":"ID!"}}}, +"MarketLocalizableResourceConnection":{"o":{"f":{"edges":"[MarketLocalizableResourceEdge!]!","nodes":"[MarketLocalizableResource!]!","pageInfo":"PageInfo!"}}}, +"MarketLocalizableResourceEdge":{"o":{"f":{"cursor":"String!","node":"MarketLocalizableResource!"}}}, +"MarketLocalizableResourceType":{"e":["METAFIELD","METAOBJECT"]}, +"MarketLocalization":{"o":{"f":{"key":"String!","market":"Market!","outdated":"Boolean!","updatedAt":"DateTime","value":"String"}}}, +"MarketLocalizationRegisterInput":{"i":{"key":"String!","marketId":"ID!","marketLocalizableContentDigest":"String!","value":"String!"}}, +"MarketLocalizationsRegisterPayload":{"o":{"f":{"marketLocalizations":"[MarketLocalization!]","userErrors":"[TranslationUserError!]!"}}}, +"MarketLocalizationsRemovePayload":{"o":{"f":{"marketLocalizations":"[MarketLocalization!]","userErrors":"[TranslationUserError!]!"}}}, +"MarketPriceInclusions":{"o":{"f":{"adaptivePricingEnabled":"Boolean!","inclusiveDutiesPricingStrategy":"InclusiveDutiesPricingStrategy!","inclusiveTaxPricingStrategy":"InclusiveTaxPricingStrategy!"}}}, +"MarketPriceInclusionsInput":{"i":{"adaptivePricingEnabled":"Boolean","dutiesPricingStrategy":"InclusiveDutiesPricingStrategy","taxPricingStrategy":"InclusiveTaxPricingStrategy"}}, +"MarketRegion":{"n":{"f":{"id":"ID!","name":"String!"},"t":["MarketRegionCountry","MarketRegionSubdivision"]}}, +"MarketRegionConnection":{"o":{"f":{"edges":"[MarketRegionEdge!]!","nodes":"[MarketRegion!]!","pageInfo":"PageInfo!"}}}, +"MarketRegionCountry":{"o":{"f":{"code":"CountryCode!","currency":"CurrencySetting!","id":"ID!","name":"String!"},"t":["MarketRegion","Node"]}}, +"MarketRegionCreateInput":{"i":{"countryCode":"CountryCode!"}}, +"MarketRegionDeletePayload":{"o":{"f":{"deletedId":"ID","market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketRegionEdge":{"o":{"f":{"cursor":"String!","node":"MarketRegion!"}}}, +"MarketRegionSubdivision":{"o":{"f":{"code":"String!","country":"MarketRegionSubdivisionCountry!","id":"ID!","name":"String!"},"t":["MarketRegion","Node"]}}, +"MarketRegionSubdivisionCountry":{"o":{"f":{"code":"CountryCode!","name":"String!"}}}, +"MarketRegionsCreatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketRegionsDeletePayload":{"o":{"f":{"deletedIds":"[ID!]","userErrors":"[MarketUserError!]!"}}}, +"MarketRelationship":{"o":{"f":{"childMarket":"Market!","id":"ID!","parentMarket":"Market"},"t":["Node"]}}, +"MarketRelationshipConnection":{"o":{"f":{"edges":"[MarketRelationshipEdge!]!","nodes":"[MarketRelationship!]!","pageInfo":"PageInfo!"}}}, +"MarketRelationshipEdge":{"o":{"f":{"cursor":"String!","node":"MarketRelationship!"}}}, +"MarketRelationshipsStatus":{"o":{"f":{"version":"String!"}}}, +"MarketStatus":{"e":["ACTIVE","DRAFT"]}, +"MarketType":{"e":["NONE","REGION","LOCATION","COMPANY_LOCATION","CHANNEL"]}, +"MarketUpdateInput":{"i":{"f":{"catalogsToAdd":"[ID!]","catalogsToDelete":"[ID!]","conditions":"MarketConditionsUpdateInput","currencySettings":"MarketCurrencySettingsUpdateInput","delivery":"MarketDeliveryConfigurationsUpdateInput","discountsToAdd":"[ID!]","discountsToDelete":"[ID!]","enabled":"Boolean","handle":"String","makeDuplicateRegionMarketsDraft":"Boolean","makeDuplicateUniqueMarketsDraft":"Boolean","name":"String","priceInclusions":"MarketPriceInclusionsInput","removeCurrencySettings":"Boolean","removePriceInclusions":"Boolean","removeReturnPolicyProfile":"Boolean","returnPolicyProfileId":"ID","status":"MarketStatus","webPresencesToAdd":"[ID!]","webPresencesToDelete":"[ID!]"},"d":{"enabled":"Use `status` instead.","makeDuplicateRegionMarketsDraft":"Use `makeDuplicateUniqueMarketsDraft` instead."}}}, +"MarketUpdatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketUserError":{"o":{"f":{"code":"MarketUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MarketUserErrorCode":{"e":{"v":["INVALID","TAKEN","TOO_LONG","TOO_SHORT","BLANK","INCLUSION","MARKET_NOT_FOUND","REGION_NOT_FOUND","PROVINCE_DOES_NOT_EXIST","SUBDIVISION_DOES_NOT_EXIST","WEB_PRESENCE_NOT_FOUND","CANNOT_ADD_REGIONS_TO_PRIMARY_MARKET","CANNOT_DELETE_ONLY_REGION","REQUIRES_EXACTLY_ONE_OPTION","CANNOT_DELETE_PRIMARY_MARKET","CANNOT_DELETE_SUBDIVISION_MARKET","EXCEEDS_MAX_MULTI_CONTEXT_MARKETS","DOMAIN_NOT_FOUND","SUBFOLDER_SUFFIX_MUST_CONTAIN_ONLY_LETTERS","SUBFOLDER_SUFFIX_MUST_BE_AT_LEAST_2_LETTERS","SUBFOLDER_SUFFIX_CANNOT_BE_SCRIPT_CODE","NO_LANGUAGES","NO_LOCAL_CURRENCIES_ON_SINGLE_COUNTRY_MARKET","NO_ROUNDING_ON_LEGACY_MARKET","DUPLICATE_LANGUAGES","DUPLICATE_REGION_MARKET","DUPLICATE_UNIQUE_MARKET","REGION_SPECIFIC_LANGUAGE","CANNOT_HAVE_SUBFOLDER_AND_DOMAIN","CANNOT_ADD_WEB_PRESENCE_TO_PRIMARY_MARKET","MARKET_REACHED_WEB_PRESENCE_LIMIT","MARKET_NOT_COMPATIBLE_WITH_CONDITION_TYPES","MISSING_COUNTRY_CODE","MISSING_PROVINCE_CODE","MISSING_SUBDIVISION_CODE","CANNOT_HAVE_MULTIPLE_SUBFOLDERS_PER_MARKET","CANNOT_HAVE_BOTH_SUBFOLDER_AND_DOMAIN_WEB_PRESENCES","REQUIRES_DOMAIN_OR_SUBFOLDER","PRIMARY_MARKET_MUST_USE_PRIMARY_DOMAIN","CANNOT_DELETE_PRIMARY_MARKET_WEB_PRESENCE","SHOP_REACHED_MARKETS_LIMIT","CANNOT_DISABLE_PRIMARY_MARKET","UNPUBLISHED_LANGUAGE","DISABLED_LANGUAGE","CANNOT_SET_DEFAULT_LOCALE_TO_NULL","UNSUPPORTED_COUNTRY_REGION","CANNOT_ADD_CUSTOMER_DOMAIN","MARKET_MANAGER_NOT_COMPATIBLE_WITH_CONDITION_TYPES","GENERIC_ERROR","MARKET_UPDATE_CONCURRENT_MODIFICATION","INVALID_STATUS_AND_ENABLED_COMBINATION","INVALID_PROVINCE_FORMAT","INVALID_SUBDIVISION_FORMAT","CONDITIONS_NOT_FOUND","SPECIFIED_CONDITIONS_CANNOT_BE_EMPTY","CUSTOMIZATIONS_NOT_FOUND","DISCOUNT_NOT_MARKET_CONTEXTUAL","DISCOUNT_EXCEEDS_MARKET_LIMIT","DISCOUNT_NOT_COMPATIBLE_WITH_B2B_MARKET","WILDCARD_NOT_SUPPORTED","SPECIFIED_NOT_VALID_FOR_INPUT","WEB_PRESENCE_NOT_COMPATIBLE_WITH_CONDITION_TYPES","CATALOG_NOT_COMPATIBLE_WITH_CONDITION_TYPES","CATALOG_TYPE_NOT_SUPPORTED","INCLUSIVE_PRICING_NOT_COMPATIBLE_WITH_CONDITION_TYPES","INCOMPATIBLE_CONDITIONS","SHIPPING_NOT_COMPATIBLE_WITH_CONDITION_TYPES","MANAGED_MARKET","MULTIPLE_CURRENCIES_NOT_SUPPORTED","UNSUPPORTED_CURRENCY","ADAPTIVE_PRICING_REQUIRES_LOCAL_CURRENCIES","SHOP_MUST_HAVE_PRIMARY_DOMAIN_WEB_PRESENCE","MUST_HAVE_AT_LEAST_ONE_ACTIVE_REGION_MARKET","USER_LACKS_PERMISSION","CONTAINS_REGIONS_THAT_CANNOT_BE_MANAGED","UNIFIED_MARKETS_NOT_ENABLED","WEB_PRESENCE_REACHED_MARKETS_LIMIT","WEB_PRESENCE_RETAIL_LOCATION","CATALOG_CONDITION_TYPES_MUST_BE_THE_SAME","MARKET_CANT_HAVE_DIRECT_CONNECTION_CATALOG","NOT_ENTITLED_TO_ACTIVATE_MARKET","B2B_MARKET_MUST_BE_MERCHANT_MANAGED","POS_LOCATION_MARKET_MUST_BE_MERCHANT_MANAGED","MANAGED_MARKETS_CATALOG_NOT_ALLOWED","MANAGED_MARKETS_RESOURCE_NOT_ALLOWED","RETAIL_LOCATION_CURRENCY_MUST_BE_LOCAL","MANAGED_MARKET_CURRENCY_MUST_MATCH_COUNTRY","CATALOGS_WITH_VOLUME_PRICING_OR_QUANTITY_RULES_NOT_SUPPORTED","MIXED_COUNTRY_LOCATIONS_NOT_ALLOWED","MIXED_COUNTRY_SUBDIVISIONS_NOT_ALLOWED","SUBDIVISION_MARKET_REQUIRES_COUNTRY_COVERAGE","LOCATION_MATCH_ALL_REQUIRES_ONE_SPECIFIC_REGION","LOCATION_REGION_COUNTRY_MISMATCH","UNPERMITTED_ENTITLEMENTS_MARKET_CATALOGS","CANNOT_ACTIVATE_MARKET_B2B_CATALOG_LIMIT_REACHED","B2B_CATALOG_LIMIT_REACHED","INVALID_CHANNEL_IDS","INVALID_COUNTRY_AND_SUBDIVISION_CONDITIONS","SUBDIVISION_MUST_BELONG_TO_COUNTRY","CANNOT_ADD_ALL_SUBDIVISIONS_FOR_A_COUNTRY_TO_A_MARKET","INVALID_RESPONDER_FOR_PROVINCE_DRIVEN_MARKET","INVALID_CUSTOMIZATION_FOR_SUBDIVISION_CONDITION","INCOMPATIBLE_CONFIGURATION","CHANNEL_MARKET_MUST_HAVE_SINGLE_CHANNEL_DRIVER","CHANNEL_NOT_VALID_FOR_CHANNEL_MARKET","CHANNEL_DRIVER_MUST_HAVE_CHANNEL_SPECIFICATION","REGION_NOT_SUPPORTED_FOR_CHANNEL","ADAPTIVE_PRICING_REQUIRES_MANAGED_MARKETS","ADAPTIVE_PRICING_REQUIRED_SETUP_ERROR","GLOBAL_E_PRICING_STRATEGY_NOT_PERMITTED"],"d":{"CANNOT_ADD_REGIONS_TO_PRIMARY_MARKET":"This will no longer be used after legacy markets are removed in April 2026","CANNOT_ADD_WEB_PRESENCE_TO_PRIMARY_MARKET":"No longer used","CANNOT_DELETE_PRIMARY_MARKET_WEB_PRESENCE":"No longer used","INVALID_RESPONDER_FOR_PROVINCE_DRIVEN_MARKET":"No longer used","MARKET_NOT_COMPATIBLE_WITH_CONDITION_TYPES":"This will no longer be used after legacy markets are removed in April 2026","NO_LOCAL_CURRENCIES_ON_SINGLE_COUNTRY_MARKET":"This will no longer be used after legacy markets are removed in April 2026","NO_ROUNDING_ON_LEGACY_MARKET":"This will no longer be used after legacy markets are removed in April 2026","PRIMARY_MARKET_MUST_USE_PRIMARY_DOMAIN":"This will no longer be used after legacy markets are removed in April 2026","REQUIRES_EXACTLY_ONE_OPTION":"No longer used","SHOP_REACHED_MARKETS_LIMIT":"No longer used","SUBFOLDER_SUFFIX_MUST_CONTAIN_ONLY_LETTERS":"No longer used","UNIFIED_MARKETS_NOT_ENABLED":"This will no longer be used after legacy markets are removed in April 2026","WEB_PRESENCE_RETAIL_LOCATION":"No longer used"}}}, +"MarketWebPresence":{"o":{"f":{"alternateLocales":"[ShopLocale!]!","defaultLocale":"ShopLocale!","domain":"Domain","id":"ID!","market":"Market","markets":["MarketConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"rootUrls":"[MarketWebPresenceRootUrl!]!","subfolderSuffix":"String"},"t":["Node"],"d":{"market":"Use `markets` instead."}}}, +"MarketWebPresenceConnection":{"o":{"f":{"edges":"[MarketWebPresenceEdge!]!","nodes":"[MarketWebPresence!]!","pageInfo":"PageInfo!"}}}, +"MarketWebPresenceCreateInput":{"i":{"alternateLocales":"[String!]","defaultLocale":"String!","domainId":"ID","subfolderSuffix":"String"}}, +"MarketWebPresenceCreatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketWebPresenceDeletePayload":{"o":{"f":{"deletedId":"ID","market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketWebPresenceEdge":{"o":{"f":{"cursor":"String!","node":"MarketWebPresence!"}}}, +"MarketWebPresenceRootUrl":{"o":{"f":{"locale":"String!","url":"URL!"}}}, +"MarketWebPresenceUpdateInput":{"i":{"alternateLocales":"[String!]","defaultLocale":"String","domainId":"ID","subfolderSuffix":"String"}}, +"MarketWebPresenceUpdatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketingActivitiesDeleteAllExternalPayload":{"o":{"f":{"job":"Job","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingActivity":{"o":{"f":{"activityListUrl":"URL","adSpend":"MoneyV2","app":"App!","appErrors":"MarketingActivityExtensionAppErrors","budget":"MarketingBudget","createdAt":"DateTime!","formData":"String","hierarchyLevel":"MarketingActivityHierarchyLevel","id":"ID!","inMainWorkflowVersion":"Boolean!","isExternal":"Boolean!","marketingChannel":"MarketingChannel!","marketingChannelType":"MarketingChannel!","marketingEvent":"MarketingEvent","parentActivityId":"ID","parentRemoteId":"String","sourceAndMedium":"String!","status":"MarketingActivityStatus!","statusBadgeType":"MarketingActivityStatusBadgeType","statusBadgeTypeV2":"BadgeType","statusLabel":"String!","statusTransitionedAt":"DateTime","tactic":"MarketingTactic!","targetStatus":"MarketingActivityStatus","title":"String!","updatedAt":"DateTime!","urlParameterValue":"String","utmParameters":"UTMParameters"},"t":["Node"],"d":{"marketingChannel":"Use `marketingChannelType` instead.","statusBadgeType":"Use `statusBadgeTypeV2` instead."}}}, +"MarketingActivityBudgetInput":{"i":{"budgetType":"MarketingBudgetBudgetType","total":"MoneyInput"}}, +"MarketingActivityConnection":{"o":{"f":{"edges":"[MarketingActivityEdge!]!","nodes":"[MarketingActivity!]!","pageInfo":"PageInfo!"}}}, +"MarketingActivityCreateExternalInput":{"i":{"f":{"adSpend":"MoneyInput","budget":"MarketingActivityBudgetInput","channel":"MarketingChannel","channelHandle":"String","end":"DateTime","hierarchyLevel":"MarketingActivityHierarchyLevel","marketingChannelType":"MarketingChannel!","parentActivityId":"ID","parentRemoteId":"String","referringDomain":"String","remoteId":"String","remotePreviewImageUrl":"URL","remoteUrl":"URL!","scheduledEnd":"DateTime","scheduledStart":"DateTime","start":"DateTime","status":"MarketingActivityExternalStatus","tactic":"MarketingTactic!","title":"String!","urlParameterValue":"String","utm":"UTMInput"},"d":{"channel":"This field was renamed for clarity, please switch to using marketingChannelType when migrating to the latest API version."}}}, +"MarketingActivityCreateExternalPayload":{"o":{"f":{"marketingActivity":"MarketingActivity","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingActivityCreateInput":{"i":{"f":{"budget":"MarketingActivityBudgetInput","context":"String","formData":"String","marketingActivityExtensionId":"ID!","marketingActivityTitle":"String","status":"MarketingActivityStatus!","urlParameterValue":"String","utm":"UTMInput"},"d":{"budget":"Marketing activity app extensions are deprecated and will be removed in the near future.","context":"Marketing activity app extensions are deprecated and will be removed in the near future.","formData":"Marketing activity app extensions are deprecated and will be removed in the near future.","marketingActivityTitle":"Marketing activity app extensions are deprecated and will be removed in the near future.","urlParameterValue":"Marketing activity app extensions are deprecated and will be removed in the near future.","utm":"Marketing activity app extensions are deprecated and will be removed in the near future."}}}, +"MarketingActivityCreatePayload":{"o":{"f":{"marketingActivity":"MarketingActivity","redirectPath":"String","userErrors":"[UserError!]!"},"d":{"marketingActivity":"Marketing activity app extensions are deprecated and will be removed in the near future.","redirectPath":"Marketing activity app extensions are deprecated and will be removed in the near future."}}}, +"MarketingActivityDeleteExternalPayload":{"o":{"f":{"deletedMarketingActivityId":"ID","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingActivityEdge":{"o":{"f":{"cursor":"String!","node":"MarketingActivity!"}}}, +"MarketingActivityExtensionAppErrorCode":{"e":["NOT_ONBOARDED_ERROR","VALIDATION_ERROR","API_ERROR","PLATFORM_ERROR","INSTALL_REQUIRED_ERROR"]}, +"MarketingActivityExtensionAppErrors":{"o":{"f":{"code":"MarketingActivityExtensionAppErrorCode!","userErrors":"[UserError!]!"}}}, +"MarketingActivityExternalStatus":{"e":["ACTIVE","INACTIVE","PAUSED","SCHEDULED","DELETED_EXTERNALLY","UNDEFINED"]}, +"MarketingActivityHierarchyLevel":{"e":["AD","AD_GROUP","CAMPAIGN"]}, +"MarketingActivitySortKeys":{"e":["CREATED_AT","ID","TITLE"]}, +"MarketingActivityStatus":{"e":["ACTIVE","DELETED","DELETED_EXTERNALLY","DISCONNECTED","DRAFT","FAILED","INACTIVE","PAUSED","PENDING","SCHEDULED","UNDEFINED"]}, +"MarketingActivityStatusBadgeType":{"e":["DEFAULT","SUCCESS","ATTENTION","WARNING","INFO","CRITICAL"]}, +"MarketingActivityUpdateExternalInput":{"i":{"f":{"adSpend":"MoneyInput","budget":"MarketingActivityBudgetInput","channel":"MarketingChannel","end":"DateTime","marketingChannelType":"MarketingChannel","referringDomain":"String","remotePreviewImageUrl":"URL","remoteUrl":"URL","scheduledEnd":"DateTime","scheduledStart":"DateTime","start":"DateTime","status":"MarketingActivityExternalStatus","tactic":"MarketingTactic","title":"String"},"d":{"channel":"This field was renamed for clarity, please switch to using marketingChannelType when migrating to the latest API version."}}}, +"MarketingActivityUpdateExternalPayload":{"o":{"f":{"marketingActivity":"MarketingActivity","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingActivityUpdateInput":{"i":{"f":{"adSpend":"MoneyInput","budget":"MarketingActivityBudgetInput","context":"String","errors":"JSON","formData":"String","id":"ID!","marketedResources":"[ID!]","marketingRecommendationId":"ID","status":"MarketingActivityStatus","targetStatus":"MarketingActivityStatus","title":"String","urlParameterValue":"String","utm":"UTMInput"},"d":{"adSpend":"Use `MarketingEngagementCreate.MarketingEngagementInput.adSpend` GraphQL to send the ad spend.","budget":"Marketing activity app extensions are deprecated and will be removed in the near future.","context":"This context is no longer needed by Shopify in the callback.","errors":"Marketing activity app extensions are deprecated and will be removed in the near future.","formData":"Marketing activity app extensions are deprecated and will be removed in the near future.","marketedResources":"Marketing activity app extensions are deprecated and will be removed in the near future.","marketingRecommendationId":"Marketing activity app extensions are deprecated and will be removed in the near future.","status":"Marketing activity app extensions are deprecated and will be removed in the near future.","targetStatus":"Marketing activity app extensions are deprecated and will be removed in the near future.","title":"Marketing activity app extensions are deprecated and will be removed in the near future.","urlParameterValue":"Marketing activity app extensions are deprecated and will be removed in the near future.","utm":"Marketing activity app extensions are deprecated and will be removed in the near future."}}}, +"MarketingActivityUpdatePayload":{"o":{"f":{"marketingActivity":"MarketingActivity","redirectPath":"String","userErrors":"[UserError!]!"}}}, +"MarketingActivityUpsertExternalInput":{"i":{"adSpend":"MoneyInput","budget":"MarketingActivityBudgetInput","channelHandle":"String","end":"DateTime","hierarchyLevel":"MarketingActivityHierarchyLevel","marketingChannelType":"MarketingChannel!","parentRemoteId":"String","referringDomain":"String","remoteId":"String!","remotePreviewImageUrl":"URL","remoteUrl":"URL!","scheduledEnd":"DateTime","scheduledStart":"DateTime","start":"DateTime","status":"MarketingActivityExternalStatus!","tactic":"MarketingTactic!","title":"String!","urlParameterValue":"String","utm":"UTMInput"}}, +"MarketingActivityUpsertExternalPayload":{"o":{"f":{"marketingActivity":"MarketingActivity","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingActivityUserError":{"o":{"f":{"code":"MarketingActivityUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MarketingActivityUserErrorCode":{"e":["INVALID","TAKEN","MARKETING_ACTIVITY_DOES_NOT_EXIST","MARKETING_ACTIVITY_WITH_REMOTE_ID_ALREADY_EXISTS","MARKETING_ACTIVITY_WITH_UTM_CAMPAIGN_ALREADY_EXISTS","MARKETING_ACTIVITY_WITH_URL_PARAMETER_VALUE_ALREADY_EXISTS","MARKETING_EVENT_DOES_NOT_EXIST","CURRENCY_CODE_MISMATCH_INPUT","MARKETING_ACTIVITY_CURRENCY_CODE_MISMATCH","DELETE_JOB_FAILED_TO_ENQUEUE","NON_HIERARCHIAL_REQUIRES_UTM_URL_PARAMETER","DELETE_JOB_ENQUEUED","ACTIVITY_NOT_EXTERNAL","IMMUTABLE_CHANNEL_HANDLE","IMMUTABLE_URL_PARAMETER","IMMUTABLE_UTM_PARAMETERS","IMMUTABLE_PARENT_ID","IMMUTABLE_HIERARCHY_LEVEL","INVALID_REMOTE_ID","INVALID_CHANNEL_HANDLE","INVALID_DELETE_ACTIVITY_EXTERNAL_ARGUMENTS","INVALID_DELETE_ENGAGEMENTS_ARGUMENTS","INVALID_MARKETING_ACTIVITY_EXTERNAL_ARGUMENTS","INVALID_MARKETING_ENGAGEMENT_ARGUMENTS","INVALID_MARKETING_ENGAGEMENT_ARGUMENT_MISSING","CANNOT_DELETE_ACTIVITY_WITH_CHILD_EVENTS","CANNOT_UPDATE_TACTIC_TO_STOREFRONT_APP","CANNOT_UPDATE_TACTIC_IF_ORIGINALLY_STOREFRONT_APP"]}, +"MarketingBudget":{"o":{"f":{"budgetType":"MarketingBudgetBudgetType!","total":"MoneyV2!"}}}, +"MarketingBudgetBudgetType":{"e":["DAILY","LIFETIME"]}, +"MarketingChannel":{"e":["SEARCH","DISPLAY","SOCIAL","EMAIL","REFERRAL"]}, +"MarketingEngagement":{"o":{"f":{"adSpend":"MoneyV2","allConversions":"Decimal","channelHandle":"String","clicksCount":"Int","commentsCount":"Int","complaintsCount":"Int","failsCount":"Int","favoritesCount":"Int","firstTimeCustomers":"Decimal","impressionsCount":"Int","isCumulative":"Boolean!","marketingActivity":"MarketingActivity","occurredOn":"Date!","orders":"Decimal","primaryConversions":"Decimal","returningCustomers":"Decimal","sales":"MoneyV2","sendsCount":"Int","sessionsCount":"Int","sharesCount":"Int","uniqueClicksCount":"Int","uniqueViewsCount":"Int","unsubscribesCount":"Int","utcOffset":"UtcOffset!","viewsCount":"Int"},"d":{"channelHandle":"Channel-level engagements are deprecated. Provide engagement metrics on a marketing activity using `marketingActivityId` or `remoteId` instead.","isCumulative":"Cumulative metrics are being phased out. Send non-cumulative engagement metrics instead (values aggregated over the single day indicated in `occurredOn`, with `isCumulative: false`). Existing activities that have been sending cumulative metrics can migrate to non-cumulative at any time."}}}, +"MarketingEngagementCreatePayload":{"o":{"f":{"marketingEngagement":"MarketingEngagement","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingEngagementInput":{"i":{"f":{"adSpend":"MoneyInput","allConversions":"Decimal","clicksCount":"Int","commentsCount":"Int","complaintsCount":"Int","failsCount":"Int","favoritesCount":"Int","firstTimeCustomers":"Decimal","impressionsCount":"Int","isCumulative":"Boolean=","occurredOn":"Date!","orders":"Decimal","primaryConversions":"Decimal","returningCustomers":"Decimal","sales":"MoneyInput","sendsCount":"Int","sessionsCount":"Int","sharesCount":"Int","uniqueClicksCount":"Int","uniqueViewsCount":"Int","unsubscribesCount":"Int","utcOffset":"UtcOffset!","viewsCount":"Int"},"d":{"isCumulative":"Cumulative metrics are being phased out. Send non-cumulative engagement metrics instead (values aggregated over the single day indicated in `occurredOn`, with `isCumulative: false`). Existing activities that have been sending cumulative metrics can migrate to non-cumulative at any time."}}}, +"MarketingEngagementsDeletePayload":{"o":{"f":{"result":"String","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingEvent":{"o":{"f":{"app":"App!","channel":"MarketingChannel","channelHandle":"String","description":"String","endedAt":"DateTime","id":"ID!","legacyResourceId":"UnsignedInt64!","manageUrl":"URL","marketingChannelType":"MarketingChannel","previewUrl":"URL","remoteId":"String","scheduledToEndAt":"DateTime","sourceAndMedium":"String!","startedAt":"DateTime!","targetTypeDisplayText":"String!","type":"MarketingTactic!","utmCampaign":"String","utmMedium":"String","utmSource":"String"},"t":["LegacyInteroperability","Node"],"d":{"channel":"Use `marketingChannelType` instead.","targetTypeDisplayText":"Use `sourceAndMedium` instead."}}}, +"MarketingEventConnection":{"o":{"f":{"edges":"[MarketingEventEdge!]!","nodes":"[MarketingEvent!]!","pageInfo":"PageInfo!"}}}, +"MarketingEventEdge":{"o":{"f":{"cursor":"String!","node":"MarketingEvent!"}}}, +"MarketingEventSortKeys":{"e":["ID","STARTED_AT"]}, +"MarketingTactic":{"e":["ABANDONED_CART","AD","AFFILIATE","LINK","LOYALTY","MESSAGE","NEWSLETTER","NOTIFICATION","POST","RETARGETING","TRANSACTIONAL","STOREFRONT_APP","SEO"]}, +"MarketsB2BEntitlement":{"o":{"f":{"catalogs":"MarketsCatalogsEntitlement!","enabled":"Boolean!"}}}, +"MarketsCatalogsEntitlement":{"o":{"f":{"enabled":"Boolean!","limit":"Int!"}}}, +"MarketsRegionsEntitlement":{"o":{"f":{"catalogs":"MarketsCatalogsEntitlement!","enabled":"Boolean!"}}}, +"MarketsResolvedValues":{"o":{"f":{"catalogs":["MarketCatalogConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"currencyCode":"CurrencyCode!","priceInclusivity":"ResolvedPriceInclusivity!","webPresences":["MarketWebPresenceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"MarketsRetailEntitlement":{"o":{"f":{"catalogs":"MarketsCatalogsEntitlement!","enabled":"Boolean!"}}}, +"MarketsSortKeys":{"e":["CREATED_AT","ID","MARKET_CONDITION_TYPES","MARKET_TYPE","NAME","STATUS","UPDATED_AT"]}, +"MarketsThemesEntitlement":{"o":{"f":{"enabled":"Boolean!"}}}, +"MarketsType":{"o":{"f":{"b2b":"MarketsB2BEntitlement!","regions":"MarketsRegionsEntitlement!","retail":"MarketsRetailEntitlement!","themes":"MarketsThemesEntitlement!"}}}, +"Media":{"n":{"f":{"alt":"String","id":"ID!","mediaContentType":"MediaContentType!","mediaErrors":"[MediaError!]!","mediaWarnings":"[MediaWarning!]!","preview":"MediaPreviewImage","status":"MediaStatus!"},"t":["ExternalVideo","MediaImage","Model3d","Video"]}}, +"MediaConnection":{"o":{"f":{"edges":"[MediaEdge!]!","nodes":"[Media!]!","pageInfo":"PageInfo!"}}}, +"MediaContentType":{"e":["VIDEO","EXTERNAL_VIDEO","MODEL_3D","IMAGE"]}, +"MediaEdge":{"o":{"f":{"cursor":"String!","node":"Media!"}}}, +"MediaError":{"o":{"f":{"code":"MediaErrorCode!","details":"String","message":"String!"}}}, +"MediaErrorCode":{"e":["UNKNOWN","INVALID_SIGNED_URL","IMAGE_DOWNLOAD_FAILURE","IMAGE_PROCESSING_FAILURE","MEDIA_TIMEOUT_ERROR","EXTERNAL_VIDEO_NOT_FOUND","EXTERNAL_VIDEO_UNLISTED","EXTERNAL_VIDEO_INVALID_ASPECT_RATIO","EXTERNAL_VIDEO_EMBED_DISABLED","EXTERNAL_VIDEO_EMBED_NOT_FOUND_OR_TRANSCODING","GENERIC_FILE_DOWNLOAD_FAILURE","GENERIC_FILE_INVALID_SIZE","VIDEO_METADATA_READ_ERROR","VIDEO_INVALID_FILETYPE_ERROR","VIDEO_MIN_WIDTH_ERROR","VIDEO_MAX_WIDTH_ERROR","VIDEO_MIN_HEIGHT_ERROR","VIDEO_MAX_HEIGHT_ERROR","VIDEO_MIN_DURATION_ERROR","VIDEO_MAX_DURATION_ERROR","VIDEO_VALIDATION_ERROR","MODEL3D_VALIDATION_ERROR","MODEL3D_THUMBNAIL_GENERATION_ERROR","MODEL3D_THUMBNAIL_REGENERATION_ERROR","MODEL3D_GLB_TO_USDZ_CONVERSION_ERROR","MODEL3D_GLB_OUTPUT_CREATION_ERROR","MODEL3D_PROCESSING_FAILURE","UNSUPPORTED_IMAGE_FILE_TYPE","INVALID_IMAGE_FILE_SIZE","INVALID_IMAGE_ASPECT_RATIO","INVALID_IMAGE_RESOLUTION","FILE_STORAGE_LIMIT_EXCEEDED","DUPLICATE_FILENAME_ERROR"]}, +"MediaHost":{"e":["YOUTUBE","VIMEO"]}, +"MediaImage":{"o":{"f":{"alt":"String","createdAt":"DateTime!","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","id":"ID!","image":"Image","mediaContentType":"MediaContentType!","mediaErrors":"[MediaError!]!","mediaWarnings":"[MediaWarning!]!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"mimeType":"String","originalSource":"MediaImageOriginalSource","preview":"MediaPreviewImage","status":"MediaStatus!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"updatedAt":"DateTime!"},"t":["File","HasMetafields","HasPublishedTranslations","Media","Node"],"d":{"metafield":"No longer supported. Use metaobjects instead.","metafields":"No longer supported. Use metaobjects instead."}}}, +"MediaImageOriginalSource":{"o":{"f":{"fileSize":"Int","url":"URL"}}}, +"MediaPreviewImage":{"o":{"f":{"image":"Image","status":"MediaPreviewImageStatus!"}}}, +"MediaPreviewImageStatus":{"e":["UPLOADED","PROCESSING","READY","FAILED"]}, +"MediaStatus":{"e":["UPLOADED","PROCESSING","READY","FAILED"]}, +"MediaUserError":{"o":{"f":{"code":"MediaUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MediaUserErrorCode":{"e":["INVALID","BLANK","VIDEO_VALIDATION_ERROR","MODEL3D_VALIDATION_ERROR","VIDEO_THROTTLE_EXCEEDED","MODEL3D_THROTTLE_EXCEEDED","PRODUCT_MEDIA_LIMIT_EXCEEDED","SHOP_MEDIA_LIMIT_EXCEEDED","PRODUCT_DOES_NOT_EXIST","MEDIA_DOES_NOT_EXIST","MEDIA_DOES_NOT_EXIST_ON_PRODUCT","TOO_MANY_MEDIA_PER_INPUT_PAIR","MAXIMUM_VARIANT_MEDIA_PAIRS_EXCEEDED","INVALID_MEDIA_TYPE","PRODUCT_VARIANT_SPECIFIED_MULTIPLE_TIMES","PRODUCT_VARIANT_DOES_NOT_EXIST_ON_PRODUCT","NON_READY_MEDIA","PRODUCT_VARIANT_ALREADY_HAS_MEDIA","MEDIA_IS_NOT_ATTACHED_TO_VARIANT","MEDIA_CANNOT_BE_MODIFIED","PRODUCT_SUSPENDED","MISSING_ARGUMENTS"]}, +"MediaWarning":{"o":{"f":{"code":"MediaWarningCode!","message":"String"}}}, +"MediaWarningCode":{"e":["MODEL_SMALL_PHYSICAL_SIZE","MODEL_LARGE_PHYSICAL_SIZE","MODEL_PREVIEW_IMAGE_FAIL"]}, +"Menu":{"o":{"f":{"createdAt":"DateTime!","handle":"String!","id":"ID!","isDefault":"Boolean!","items":["[MenuItem!]!",{"limit":"Int"}],"title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["HasPublishedTranslations","Node"]}}, +"MenuConnection":{"o":{"f":{"edges":"[MenuEdge!]!","nodes":"[Menu!]!","pageInfo":"PageInfo!"}}}, +"MenuCreatePayload":{"o":{"f":{"menu":"Menu","userErrors":"[MenuCreateUserError!]!"}}}, +"MenuCreateUserError":{"o":{"f":{"code":"MenuCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MenuCreateUserErrorCode":{"e":["NOT_FOUND","NESTING_TOO_DEEP"]}, +"MenuDeletePayload":{"o":{"f":{"deletedMenuId":"ID","userErrors":"[MenuDeleteUserError!]!"}}}, +"MenuDeleteUserError":{"o":{"f":{"code":"MenuDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MenuDeleteUserErrorCode":{"e":["MENU_DOES_NOT_EXIST","UNABLE_TO_DELETE_DEFAULT_MENU"]}, +"MenuEdge":{"o":{"f":{"cursor":"String!","node":"Menu!"}}}, +"MenuItem":{"o":{"f":{"id":"ID!","items":"[MenuItem!]!","resourceId":"ID","tags":"[String!]!","title":"String!","type":"MenuItemType!","url":"String"}}}, +"MenuItemCreateInput":{"i":{"items":"[MenuItemCreateInput!]","resourceId":"ID","tags":"[String!]","title":"String!","type":"MenuItemType!","url":"String"}}, +"MenuItemType":{"e":["FRONTPAGE","COLLECTION","COLLECTIONS","PRODUCT","CATALOG","PAGE","BLOG","ARTICLE","SEARCH","SHOP_POLICY","HTTP","METAOBJECT","CUSTOMER_ACCOUNT_PAGE"]}, +"MenuItemUpdateInput":{"i":{"id":"ID","items":"[MenuItemUpdateInput!]","resourceId":"ID","tags":"[String!]","title":"String!","type":"MenuItemType!","url":"String"}}, +"MenuSortKeys":{"e":["ID","TITLE","UPDATED_AT"]}, +"MenuUpdatePayload":{"o":{"f":{"menu":"Menu","userErrors":"[MenuUpdateUserError!]!"}}}, +"MenuUpdateUserError":{"o":{"f":{"code":"MenuUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MenuUpdateUserErrorCode":{"e":["NOT_FOUND","NESTING_TOO_DEEP"]}, +"MerchandiseDiscountClass":{"e":["PRODUCT","ORDER"]}, +"MerchantApprovalSignals":{"o":{"f":{"identityVerified":"Boolean!","verifiedByShopify":"Boolean!","verifiedByShopifyTier":"String!"}}}, +"Metafield":{"o":{"f":{"compareDigest":"String!","createdAt":"DateTime!","definition":"MetafieldDefinition","description":"String","id":"ID!","jsonValue":"JSON!","key":"String!","legacyResourceId":"UnsignedInt64!","namespace":"String!","owner":"HasMetafields!","ownerType":"MetafieldOwnerType!","reference":"MetafieldReference","references":["MetafieldReferenceConnection",{"after":"String","before":"String","first":"Int","last":"Int"}],"sizeInBytes":"Int!","translatable":"Boolean!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"type":"String!","updatedAt":"DateTime!","value":"String!"},"t":["HasCompareDigest","HasPublishedTranslations","LegacyInteroperability","Node"],"d":{"description":"This field will be removed in a future release. Use the `description` on the metafield definition instead."}}}, +"MetafieldAccess":{"o":{"f":{"admin":"MetafieldAdminAccess","customerAccount":"MetafieldCustomerAccountAccess!","storefront":"MetafieldStorefrontAccess"}}}, +"MetafieldAccessInput":{"i":{"admin":"MetafieldAdminAccessInput","customerAccount":"MetafieldCustomerAccountAccessInput","storefront":"MetafieldStorefrontAccessInput"}}, +"MetafieldAccessUpdateInput":{"i":{"admin":"MetafieldAdminAccessInput","customerAccount":"MetafieldCustomerAccountAccessInput","storefront":"MetafieldStorefrontAccessInput"}}, +"MetafieldAdminAccess":{"e":["PRIVATE","PUBLIC_READ","PUBLIC_READ_WRITE","MERCHANT_READ","MERCHANT_READ_WRITE"]}, +"MetafieldAdminAccessInput":{"e":["MERCHANT_READ","MERCHANT_READ_WRITE"]}, +"MetafieldCapabilities":{"o":{"f":{"adminFilterable":"MetafieldCapabilityAdminFilterable!","analyticsQueryable":"MetafieldCapabilityAnalyticsQueryable!","cartToOrderCopyable":"MetafieldCapabilityCartToOrderCopyable!","smartCollectionCondition":"MetafieldCapabilitySmartCollectionCondition!","uniqueValues":"MetafieldCapabilityUniqueValues!"}}}, +"MetafieldCapabilityAdminFilterable":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!","status":"MetafieldDefinitionAdminFilterStatus!"}}}, +"MetafieldCapabilityAdminFilterableInput":{"i":{"enabled":"Boolean!"}}, +"MetafieldCapabilityAnalyticsQueryable":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!"}}}, +"MetafieldCapabilityAnalyticsQueryableInput":{"i":{"enabled":"Boolean!"}}, +"MetafieldCapabilityCartToOrderCopyable":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!"}}}, +"MetafieldCapabilityCartToOrderCopyableInput":{"i":{"enabled":"Boolean!"}}, +"MetafieldCapabilityCreateInput":{"i":{"adminFilterable":"MetafieldCapabilityAdminFilterableInput","analyticsQueryable":"MetafieldCapabilityAnalyticsQueryableInput","cartToOrderCopyable":"MetafieldCapabilityCartToOrderCopyableInput","smartCollectionCondition":"MetafieldCapabilitySmartCollectionConditionInput","uniqueValues":"MetafieldCapabilityUniqueValuesInput"}}, +"MetafieldCapabilitySmartCollectionCondition":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!"}}}, +"MetafieldCapabilitySmartCollectionConditionInput":{"i":{"enabled":"Boolean!"}}, +"MetafieldCapabilityUniqueValues":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!"}}}, +"MetafieldCapabilityUniqueValuesInput":{"i":{"enabled":"Boolean!"}}, +"MetafieldCapabilityUpdateInput":{"i":{"adminFilterable":"MetafieldCapabilityAdminFilterableInput","analyticsQueryable":"MetafieldCapabilityAnalyticsQueryableInput","cartToOrderCopyable":"MetafieldCapabilityCartToOrderCopyableInput","smartCollectionCondition":"MetafieldCapabilitySmartCollectionConditionInput","uniqueValues":"MetafieldCapabilityUniqueValuesInput"}}, +"MetafieldConnection":{"o":{"f":{"edges":"[MetafieldEdge!]!","nodes":"[Metafield!]!","pageInfo":"PageInfo!"}}}, +"MetafieldCustomerAccountAccess":{"e":["READ_WRITE","READ","NONE"]}, +"MetafieldCustomerAccountAccessInput":{"e":["READ_WRITE","READ","NONE"]}, +"MetafieldDefinition":{"o":{"f":{"access":"MetafieldAccess!","capabilities":"MetafieldCapabilities!","constraints":"MetafieldDefinitionConstraints","description":"String","id":"ID!","key":"String!","metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","validationStatus":"MetafieldValidationStatus="}],"metafieldsCount":["Int!",{"validationStatus":"MetafieldValidationStatus"}],"name":"String!","namespace":"String!","ownerType":"MetafieldOwnerType!","pinnedPosition":"Int","standardTemplate":"StandardMetafieldDefinitionTemplate","type":"MetafieldDefinitionType!","useAsCollectionCondition":"Boolean!","validationStatus":"MetafieldDefinitionValidationStatus!","validations":"[MetafieldDefinitionValidation!]!"},"t":["Node"]}}, +"MetafieldDefinitionAdminFilterStatus":{"e":["NOT_FILTERABLE","IN_PROGRESS","FILTERABLE","FAILED"]}, +"MetafieldDefinitionConnection":{"o":{"f":{"edges":"[MetafieldDefinitionEdge!]!","nodes":"[MetafieldDefinition!]!","pageInfo":"PageInfo!"}}}, +"MetafieldDefinitionConstraintStatus":{"e":["CONSTRAINED_AND_UNCONSTRAINED","CONSTRAINED_ONLY","UNCONSTRAINED_ONLY"]}, +"MetafieldDefinitionConstraintSubtypeIdentifier":{"i":{"key":"String!","value":"String!"}}, +"MetafieldDefinitionConstraintValue":{"o":{"f":{"value":"String!"}}}, +"MetafieldDefinitionConstraintValueConnection":{"o":{"f":{"edges":"[MetafieldDefinitionConstraintValueEdge!]!","nodes":"[MetafieldDefinitionConstraintValue!]!","pageInfo":"PageInfo!"}}}, +"MetafieldDefinitionConstraintValueEdge":{"o":{"f":{"cursor":"String!","node":"MetafieldDefinitionConstraintValue!"}}}, +"MetafieldDefinitionConstraintValueUpdateInput":{"i":{"create":"String","delete":"String"}}, +"MetafieldDefinitionConstraints":{"o":{"f":{"key":"String","values":["MetafieldDefinitionConstraintValueConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"MetafieldDefinitionConstraintsInput":{"i":{"key":"String!","values":"[String!]!"}}, +"MetafieldDefinitionConstraintsUpdatesInput":{"i":{"key":"String","values":"[MetafieldDefinitionConstraintValueUpdateInput!]"}}, +"MetafieldDefinitionCreatePayload":{"o":{"f":{"createdDefinition":"MetafieldDefinition","userErrors":"[MetafieldDefinitionCreateUserError!]!"}}}, +"MetafieldDefinitionCreateUserError":{"o":{"f":{"code":"MetafieldDefinitionCreateUserErrorCode","elementIndex":"Int","elementKey":"String","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldDefinitionCreateUserErrorCode":{"e":["INVALID","INCLUSION","PRESENT","TAKEN","TOO_LONG","TOO_SHORT","BLANK","CAPABILITY_REQUIRED_BUT_DISABLED","RESOURCE_TYPE_LIMIT_EXCEEDED","RESOURCE_TYPE_LIMIT_EXCEEDED_BY_APP","LIMIT_EXCEEDED","INVALID_OPTION","DUPLICATE_OPTION","RESERVED_NAMESPACE_KEY","PINNED_LIMIT_REACHED","UNSTRUCTURED_ALREADY_EXISTS","UNSUPPORTED_PINNING","INVALID_CHARACTER","TYPE_NOT_ALLOWED_FOR_CONDITIONS","OWNER_TYPE_LIMIT_EXCEEDED_FOR_AUTOMATED_COLLECTIONS","OWNER_TYPE_LIMIT_EXCEEDED_FOR_USE_AS_ADMIN_FILTERS","INVALID_CONSTRAINTS","INVALID_INPUT_COMBINATION","INVALID_CAPABILITY","ADMIN_ACCESS_INPUT_NOT_ALLOWED"]}, +"MetafieldDefinitionDeletePayload":{"o":{"f":{"deletedDefinition":"MetafieldDefinitionIdentifier","deletedDefinitionId":"ID","userErrors":"[MetafieldDefinitionDeleteUserError!]!"}}}, +"MetafieldDefinitionDeleteUserError":{"o":{"f":{"code":"MetafieldDefinitionDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldDefinitionDeleteUserErrorCode":{"e":["PRESENT","NOT_FOUND","INTERNAL_ERROR","ID_TYPE_DELETION_ERROR","REFERENCE_TYPE_DELETION_ERROR","RESERVED_NAMESPACE_ORPHANED_METAFIELDS","METAFIELD_DEFINITION_IN_USE","APP_CONFIG_MANAGED","STANDARD_METAFIELD_DEFINITION_DEPENDENT_ON_APP","DISALLOWED_OWNER_TYPE"]}, +"MetafieldDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"MetafieldDefinition!"}}}, +"MetafieldDefinitionIdentifier":{"o":{"f":{"key":"String!","namespace":"String!","ownerType":"MetafieldOwnerType!"}}}, +"MetafieldDefinitionIdentifierInput":{"i":{"key":"String!","namespace":"String","ownerType":"MetafieldOwnerType!"}}, +"MetafieldDefinitionInput":{"i":{"f":{"access":"MetafieldAccessInput","capabilities":"MetafieldCapabilityCreateInput","constraints":"MetafieldDefinitionConstraintsInput","description":"String","key":"String!","name":"String!","namespace":"String","ownerType":"MetafieldOwnerType!","pin":"Boolean=","type":"String!","useAsCollectionCondition":"Boolean=","validations":"[MetafieldDefinitionValidationInput!]"},"d":{"useAsCollectionCondition":"Use `smartCollectionCondition` instead."}}}, +"MetafieldDefinitionPinPayload":{"o":{"f":{"pinnedDefinition":"MetafieldDefinition","userErrors":"[MetafieldDefinitionPinUserError!]!"}}}, +"MetafieldDefinitionPinUserError":{"o":{"f":{"code":"MetafieldDefinitionPinUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldDefinitionPinUserErrorCode":{"e":["NOT_FOUND","PINNED_LIMIT_REACHED","ALREADY_PINNED","INTERNAL_ERROR","UNSUPPORTED_PINNING","DISALLOWED_OWNER_TYPE"]}, +"MetafieldDefinitionPinnedStatus":{"e":["ANY","PINNED","UNPINNED"]}, +"MetafieldDefinitionSortKeys":{"e":["ID","NAME","PINNED_POSITION","RELEVANCE"]}, +"MetafieldDefinitionSupportedValidation":{"o":{"f":{"name":"String!","type":"String!"}}}, +"MetafieldDefinitionType":{"o":{"f":{"category":"String!","name":"String!","supportedValidations":"[MetafieldDefinitionSupportedValidation!]!","supportsDefinitionMigrations":"Boolean!","valueType":"MetafieldValueType!"},"d":{"valueType":"`valueType` is deprecated and `name` should be used for type information."}}}, +"MetafieldDefinitionUnpinPayload":{"o":{"f":{"unpinnedDefinition":"MetafieldDefinition","userErrors":"[MetafieldDefinitionUnpinUserError!]!"}}}, +"MetafieldDefinitionUnpinUserError":{"o":{"f":{"code":"MetafieldDefinitionUnpinUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldDefinitionUnpinUserErrorCode":{"e":["NOT_FOUND","NOT_PINNED","INTERNAL_ERROR","APP_CONFIG_MANAGED","DISALLOWED_OWNER_TYPE"]}, +"MetafieldDefinitionUpdateInput":{"i":{"f":{"access":"MetafieldAccessUpdateInput","capabilities":"MetafieldCapabilityUpdateInput","constraintsUpdates":"MetafieldDefinitionConstraintsUpdatesInput","description":"String","key":"String!","name":"String","namespace":"String","ownerType":"MetafieldOwnerType!","pin":"Boolean","useAsCollectionCondition":"Boolean=","validations":"[MetafieldDefinitionValidationInput!]"},"d":{"useAsCollectionCondition":"Use `smartCollectionCondition` instead."}}}, +"MetafieldDefinitionUpdatePayload":{"o":{"f":{"updatedDefinition":"MetafieldDefinition","userErrors":"[MetafieldDefinitionUpdateUserError!]!","validationJob":"Job"}}}, +"MetafieldDefinitionUpdateUserError":{"o":{"f":{"code":"MetafieldDefinitionUpdateUserErrorCode","elementIndex":"Int","elementKey":"String","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldDefinitionUpdateUserErrorCode":{"e":["PRESENT","TOO_LONG","BLANK","INVALID","NOT_FOUND","INVALID_INPUT","CAPABILITY_REQUIRED_BUT_DISABLED","PINNED_LIMIT_REACHED","INTERNAL_ERROR","UNSUPPORTED_PINNING","INVALID_OPTION","DUPLICATE_OPTION","TYPE_NOT_ALLOWED_FOR_CONDITIONS","METAFIELD_DEFINITION_IN_USE","OWNER_TYPE_LIMIT_EXCEEDED_FOR_AUTOMATED_COLLECTIONS","OWNER_TYPE_LIMIT_EXCEEDED_FOR_USE_AS_ADMIN_FILTERS","METAOBJECT_DEFINITION_CHANGED","DISALLOWED_OWNER_TYPE","INVALID_INPUT_COMBINATION","INVALID_CONSTRAINTS","INVALID_CAPABILITY","CAPABILITY_CANNOT_BE_DISABLED","ADMIN_ACCESS_INPUT_NOT_ALLOWED","APP_CONFIG_MANAGED"]}, +"MetafieldDefinitionValidation":{"o":{"f":{"name":"String!","type":"String!","value":"String"}}}, +"MetafieldDefinitionValidationInput":{"i":{"name":"String!","value":"String!"}}, +"MetafieldDefinitionValidationStatus":{"e":["ALL_VALID","IN_PROGRESS","SOME_INVALID"]}, +"MetafieldEdge":{"o":{"f":{"cursor":"String!","node":"Metafield!"}}}, +"MetafieldIdentifier":{"o":{"f":{"key":"String!","namespace":"String!","ownerId":"ID!"}}}, +"MetafieldIdentifierInput":{"i":{"key":"String!","namespace":"String!","ownerId":"ID!"}}, +"MetafieldInput":{"i":{"id":"ID","key":"String","namespace":"String","type":"String","value":"String"}}, +"MetafieldOwnerType":{"e":{"v":["API_PERMISSION","COMPANY","COMPANY_LOCATION","PAYMENT_CUSTOMIZATION","VALIDATION","CUSTOMER","DELIVERY_CUSTOMIZATION","DRAFTORDER","GIFT_CARD_TRANSACTION","TRANSFER","MARKET","CARTTRANSFORM","COLLECTION","MEDIA_IMAGE","PRODUCT","PRODUCTVARIANT","SELLING_PLAN","ARTICLE","BLOG","PAGE","FULFILLMENT_CONSTRAINT_RULE","ORDER_ROUTING_LOCATION_RULE","DISCOUNT","ORDER","LOCATION","SHOP"],"d":{"MEDIA_IMAGE":"`MEDIA_IMAGE` is deprecated."}}}, +"MetafieldReference":{"u":["Article","Collection","Company","Customer","GenericFile","MediaImage","Metaobject","Model3d","Order","Page","Product","ProductVariant","TaxonomyValue","Video"]}, +"MetafieldReferenceConnection":{"o":{"f":{"edges":"[MetafieldReferenceEdge!]!","nodes":"[MetafieldReference]!","pageInfo":"PageInfo!"}}}, +"MetafieldReferenceEdge":{"o":{"f":{"cursor":"String!","node":"MetafieldReference"}}}, +"MetafieldReferencer":{"u":["AppInstallation","Article","Blog","Collection","Company","CompanyLocation","Customer","DeliveryCustomization","DiscountAutomaticNode","DiscountCodeNode","DiscountNode","DraftOrder","FulfillmentOrder","Location","Market","Metaobject","Order","Page","PaymentCustomization","Product","ProductVariant","Shop"]}, +"MetafieldRelation":{"o":{"f":{"key":"String!","name":"String!","namespace":"String!","referencer":"MetafieldReferencer!","target":"MetafieldReference!"},"d":{"target":"No longer supported. Access the object directly instead."}}}, +"MetafieldRelationConnection":{"o":{"f":{"edges":"[MetafieldRelationEdge!]!","nodes":"[MetafieldRelation!]!","pageInfo":"PageInfo!"}}}, +"MetafieldRelationEdge":{"o":{"f":{"cursor":"String!","node":"MetafieldRelation!"}}}, +"MetafieldStorefrontAccess":{"e":["PUBLIC_READ","NONE"]}, +"MetafieldStorefrontAccessInput":{"e":["PUBLIC_READ","NONE"]}, +"MetafieldValidationStatus":{"e":["ANY","VALID","INVALID"]}, +"MetafieldValueType":{"e":["STRING","INTEGER","JSON_STRING","BOOLEAN"]}, +"MetafieldsDeletePayload":{"o":{"f":{"deletedMetafields":"[MetafieldIdentifier]","userErrors":"[UserError!]!"}}}, +"MetafieldsSetInput":{"i":{"compareDigest":"String","key":"String!","namespace":"String","ownerId":"ID!","type":"String","value":"String!"}}, +"MetafieldsSetPayload":{"o":{"f":{"metafields":"[Metafield!]","userErrors":"[MetafieldsSetUserError!]!"}}}, +"MetafieldsSetUserError":{"o":{"f":{"code":"MetafieldsSetUserErrorCode","elementIndex":"Int","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldsSetUserErrorCode":{"e":["CAPABILITY_VIOLATION","STALE_OBJECT","INVALID_COMPARE_DIGEST","INVALID_TYPE","INVALID_VALUE","APP_NOT_AUTHORIZED","INCLUSION","TAKEN","PRESENT","BLANK","TOO_LONG","TOO_SHORT","LESS_THAN_OR_EQUAL_TO","INVALID","INTERNAL_ERROR"]}, +"Metaobject":{"o":{"f":{"capabilities":"MetaobjectCapabilityData!","createdAt":"DateTime!","createdBy":"App!","createdByApp":"App!","createdByStaff":"StaffMember","definition":"MetaobjectDefinition!","displayName":"String!","field":["MetaobjectField",{"key":"String!"}],"fields":"[MetaobjectField!]!","handle":"String!","id":"ID!","referencedBy":["MetafieldRelationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"staffMember":"StaffMember","thumbnailField":"MetaobjectField","type":"String!","updatedAt":"DateTime!","values":"JSON!"},"t":["Node"],"d":{"staffMember":"Use `createdByStaff` instead."}}}, +"MetaobjectAccess":{"o":{"f":{"admin":"MetaobjectAdminAccess!","customerAccount":"MetaobjectCustomerAccountAccess!","storefront":"MetaobjectStorefrontAccess!"}}}, +"MetaobjectAccessInput":{"i":{"admin":"MetaobjectAdminAccessInput","customerAccount":"MetaobjectCustomerAccountAccess","storefront":"MetaobjectStorefrontAccess"}}, +"MetaobjectAdminAccess":{"e":{"v":["PRIVATE","MERCHANT_READ","MERCHANT_READ_WRITE","PUBLIC_READ","PUBLIC_READ_WRITE"],"d":{"PRIVATE":"Use MERCHANT_READ instead. Removed in API version 2027-01.","PUBLIC_READ":"Use MERCHANT_READ instead. Removed in API version 2027-01."}}}, +"MetaobjectAdminAccessInput":{"e":["MERCHANT_READ","MERCHANT_READ_WRITE"]}, +"MetaobjectBulkDeletePayload":{"o":{"f":{"job":"Job","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectBulkDeleteWhereCondition":{"i":{"ids":"[ID!]","type":"String"}}, +"MetaobjectCapabilities":{"o":{"f":{"onlineStore":"MetaobjectCapabilitiesOnlineStore","publishable":"MetaobjectCapabilitiesPublishable!","renderable":"MetaobjectCapabilitiesRenderable","translatable":"MetaobjectCapabilitiesTranslatable!"}}}, +"MetaobjectCapabilitiesOnlineStore":{"o":{"f":{"data":"MetaobjectCapabilityDefinitionDataOnlineStore","enabled":"Boolean!"}}}, +"MetaobjectCapabilitiesPublishable":{"o":{"f":{"enabled":"Boolean!"}}}, +"MetaobjectCapabilitiesRenderable":{"o":{"f":{"data":"MetaobjectCapabilityDefinitionDataRenderable","enabled":"Boolean!"}}}, +"MetaobjectCapabilitiesTranslatable":{"o":{"f":{"enabled":"Boolean!"}}}, +"MetaobjectCapabilityCreateInput":{"i":{"onlineStore":"MetaobjectCapabilityOnlineStoreInput","publishable":"MetaobjectCapabilityPublishableInput","renderable":"MetaobjectCapabilityRenderableInput","translatable":"MetaobjectCapabilityTranslatableInput"}}, +"MetaobjectCapabilityData":{"o":{"f":{"onlineStore":"MetaobjectCapabilityDataOnlineStore","publishable":"MetaobjectCapabilityDataPublishable"}}}, +"MetaobjectCapabilityDataInput":{"i":{"onlineStore":"MetaobjectCapabilityDataOnlineStoreInput","publishable":"MetaobjectCapabilityDataPublishableInput"}}, +"MetaobjectCapabilityDataOnlineStore":{"o":{"f":{"templateSuffix":"String"}}}, +"MetaobjectCapabilityDataOnlineStoreInput":{"i":{"templateSuffix":"String"}}, +"MetaobjectCapabilityDataPublishable":{"o":{"f":{"status":"MetaobjectStatus!"}}}, +"MetaobjectCapabilityDataPublishableInput":{"i":{"status":"MetaobjectStatus!"}}, +"MetaobjectCapabilityDefinitionDataOnlineStore":{"o":{"f":{"canCreateRedirects":"Boolean!","urlHandle":"String!"}}}, +"MetaobjectCapabilityDefinitionDataOnlineStoreInput":{"i":{"createRedirects":"Boolean=","urlHandle":"String!"}}, +"MetaobjectCapabilityDefinitionDataRenderable":{"o":{"f":{"metaDescriptionKey":"String","metaTitleKey":"String"}}}, +"MetaobjectCapabilityDefinitionDataRenderableInput":{"i":{"metaDescriptionKey":"String","metaTitleKey":"String"}}, +"MetaobjectCapabilityOnlineStoreInput":{"i":{"data":"MetaobjectCapabilityDefinitionDataOnlineStoreInput","enabled":"Boolean!"}}, +"MetaobjectCapabilityPublishableInput":{"i":{"enabled":"Boolean!"}}, +"MetaobjectCapabilityRenderableInput":{"i":{"data":"MetaobjectCapabilityDefinitionDataRenderableInput","enabled":"Boolean!"}}, +"MetaobjectCapabilityTranslatableInput":{"i":{"enabled":"Boolean!"}}, +"MetaobjectCapabilityType":{"e":["PUBLISHABLE","TRANSLATABLE","RENDERABLE","ONLINE_STORE"]}, +"MetaobjectCapabilityUpdateInput":{"i":{"onlineStore":"MetaobjectCapabilityOnlineStoreInput","publishable":"MetaobjectCapabilityPublishableInput","renderable":"MetaobjectCapabilityRenderableInput","translatable":"MetaobjectCapabilityTranslatableInput"}}, +"MetaobjectConnection":{"o":{"f":{"edges":"[MetaobjectEdge!]!","nodes":"[Metaobject!]!","pageInfo":"PageInfo!"}}}, +"MetaobjectCreateInput":{"i":{"capabilities":"MetaobjectCapabilityDataInput","fields":"[MetaobjectFieldInput!]","handle":"String","type":"String!","values":"JSON"}}, +"MetaobjectCreatePayload":{"o":{"f":{"metaobject":"Metaobject","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectCustomerAccountAccess":{"e":["NONE","READ"]}, +"MetaobjectDefinition":{"o":{"f":{"access":"MetaobjectAccess!","capabilities":"MetaobjectCapabilities!","createdAt":"DateTime!","createdByApp":"App!","createdByStaff":"StaffMember","description":"String","displayNameKey":"String","fieldDefinitions":"[MetaobjectFieldDefinition!]!","hasThumbnailField":"Boolean!","id":"ID!","metaobjects":["MetaobjectConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"metaobjectsCount":"Int!","name":"String!","standardTemplate":"StandardMetaobjectDefinitionTemplate","type":"String!","updatedAt":"DateTime!"},"t":["Node"]}}, +"MetaobjectDefinitionConnection":{"o":{"f":{"edges":"[MetaobjectDefinitionEdge!]!","nodes":"[MetaobjectDefinition!]!","pageInfo":"PageInfo!"}}}, +"MetaobjectDefinitionCreateInput":{"i":{"access":"MetaobjectAccessInput","capabilities":"MetaobjectCapabilityCreateInput","description":"String","displayNameKey":"String","fieldDefinitions":"[MetaobjectFieldDefinitionCreateInput!]","name":"String","type":"String!"}}, +"MetaobjectDefinitionCreatePayload":{"o":{"f":{"metaobjectDefinition":"MetaobjectDefinition","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectDefinitionDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"MetaobjectDefinition!"}}}, +"MetaobjectDefinitionUpdateInput":{"i":{"access":"MetaobjectAccessInput","capabilities":"MetaobjectCapabilityUpdateInput","description":"String","displayNameKey":"String","fieldDefinitions":"[MetaobjectFieldDefinitionOperationInput!]","name":"String","resetFieldOrder":"Boolean="}}, +"MetaobjectDefinitionUpdatePayload":{"o":{"f":{"metaobjectDefinition":"MetaobjectDefinition","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectEdge":{"o":{"f":{"cursor":"String!","node":"Metaobject!"}}}, +"MetaobjectField":{"o":{"f":{"definition":"MetaobjectFieldDefinition!","jsonValue":"JSON","key":"String!","reference":"MetafieldReference","references":["MetafieldReferenceConnection",{"after":"String","before":"String","first":"Int","last":"Int"}],"thumbnail":"MetaobjectThumbnail","type":"String!","value":"String"}}}, +"MetaobjectFieldCapabilityAdminFilterable":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!"}}}, +"MetaobjectFieldCapabilityAdminFilterableInput":{"i":{"enabled":"Boolean!"}}, +"MetaobjectFieldDefinition":{"o":{"f":{"capabilities":"MetaobjectFieldDefinitionCapabilities!","description":"String","key":"String!","name":"String!","required":"Boolean!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!"}}}, +"MetaobjectFieldDefinitionCapabilities":{"o":{"f":{"adminFilterable":"MetaobjectFieldCapabilityAdminFilterable!"}}}, +"MetaobjectFieldDefinitionCapabilityCreateInput":{"i":{"adminFilterable":"MetaobjectFieldCapabilityAdminFilterableInput"}}, +"MetaobjectFieldDefinitionCreateInput":{"i":{"capabilities":"MetaobjectFieldDefinitionCapabilityCreateInput","description":"String","key":"String!","name":"String","required":"Boolean=","type":"String!","validations":"[MetafieldDefinitionValidationInput!]"}}, +"MetaobjectFieldDefinitionDeleteInput":{"i":{"key":"String!"}}, +"MetaobjectFieldDefinitionOperationInput":{"i":{"create":"MetaobjectFieldDefinitionCreateInput","delete":"MetaobjectFieldDefinitionDeleteInput","update":"MetaobjectFieldDefinitionUpdateInput"}}, +"MetaobjectFieldDefinitionUpdateInput":{"i":{"capabilities":"MetaobjectFieldDefinitionCapabilityCreateInput","description":"String","key":"String!","name":"String","required":"Boolean","validations":"[MetafieldDefinitionValidationInput!]"}}, +"MetaobjectFieldInput":{"i":{"key":"String!","value":"String!"}}, +"MetaobjectHandleInput":{"i":{"handle":"String!","type":"String!"}}, +"MetaobjectStatus":{"e":["DRAFT","ACTIVE"]}, +"MetaobjectStorefrontAccess":{"e":["NONE","PUBLIC_READ"]}, +"MetaobjectThumbnail":{"o":{"f":{"file":"File","hex":"String"}}}, +"MetaobjectUpdateInput":{"i":{"capabilities":"MetaobjectCapabilityDataInput","fields":"[MetaobjectFieldInput!]","handle":"String","redirectNewHandle":"Boolean=","values":"JSON"}}, +"MetaobjectUpdatePayload":{"o":{"f":{"metaobject":"Metaobject","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectUpsertInput":{"i":{"capabilities":"MetaobjectCapabilityDataInput","fields":"[MetaobjectFieldInput!]","handle":"String"}}, +"MetaobjectUpsertPayload":{"o":{"f":{"metaobject":"Metaobject","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectUserError":{"o":{"f":{"code":"MetaobjectUserErrorCode","elementIndex":"Int","elementKey":"String","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetaobjectUserErrorCode":{"e":["INVALID","INCLUSION","TAKEN","TOO_LONG","TOO_SHORT","PRESENT","BLANK","INVALID_TYPE","INVALID_VALUE","INVALID_OPTION","DUPLICATE_FIELD_INPUT","UNDEFINED_OBJECT_TYPE","UNDEFINED_OBJECT_FIELD","OBJECT_FIELD_TAKEN","OBJECT_FIELD_REQUIRED","RECORD_NOT_FOUND","INTERNAL_ERROR","MAX_DEFINITIONS_EXCEEDED","MAX_OBJECTS_EXCEEDED","INPUT_LIMIT_EXCEEDED","IMMUTABLE","NOT_AUTHORIZED","RESERVED_NAME","DISPLAY_NAME_CONFLICT","ADMIN_ACCESS_INPUT_NOT_ALLOWED","APP_CONFIG_MANAGED","STANDARD_METAOBJECT_DEFINITION_DEPENDENT_ON_APP","CAPABILITY_NOT_ENABLED","URL_HANDLE_TAKEN","URL_HANDLE_INVALID","URL_HANDLE_BLANK","FIELD_TYPE_INVALID","MISSING_REQUIRED_KEYS","REFERENCE_EXISTS_ERROR"]}, +"MethodDefinitionSortKeys":{"e":["ID","RATE_PROVIDER_TYPE"]}, +"MobilePlatformApplication":{"u":["AndroidApplication","AppleApplication"]}, +"MobilePlatformApplicationConnection":{"o":{"f":{"edges":"[MobilePlatformApplicationEdge!]!","nodes":"[MobilePlatformApplication!]!","pageInfo":"PageInfo!"}}}, +"MobilePlatformApplicationCreateAndroidInput":{"i":{"appLinksEnabled":"Boolean!","applicationId":"String","sha256CertFingerprints":"[String!]!"}}, +"MobilePlatformApplicationCreateAppleInput":{"i":{"appClipApplicationId":"String","appClipsEnabled":"Boolean","appId":"String","sharedWebCredentialsEnabled":"Boolean!","universalLinksEnabled":"Boolean!"}}, +"MobilePlatformApplicationCreateInput":{"i":{"android":"MobilePlatformApplicationCreateAndroidInput","apple":"MobilePlatformApplicationCreateAppleInput"}}, +"MobilePlatformApplicationCreatePayload":{"o":{"f":{"mobilePlatformApplication":"MobilePlatformApplication","userErrors":"[MobilePlatformApplicationUserError!]!"}}}, +"MobilePlatformApplicationDeletePayload":{"o":{"f":{"deletedMobilePlatformApplicationId":"ID","userErrors":"[MobilePlatformApplicationUserError!]!"}}}, +"MobilePlatformApplicationEdge":{"o":{"f":{"cursor":"String!","node":"MobilePlatformApplication!"}}}, +"MobilePlatformApplicationUpdateAndroidInput":{"i":{"appLinksEnabled":"Boolean","applicationId":"String","sha256CertFingerprints":"[String!]"}}, +"MobilePlatformApplicationUpdateAppleInput":{"i":{"appClipApplicationId":"String","appClipsEnabled":"Boolean","appId":"String","sharedWebCredentialsEnabled":"Boolean","universalLinksEnabled":"Boolean"}}, +"MobilePlatformApplicationUpdateInput":{"i":{"android":"MobilePlatformApplicationUpdateAndroidInput","apple":"MobilePlatformApplicationUpdateAppleInput"}}, +"MobilePlatformApplicationUpdatePayload":{"o":{"f":{"mobilePlatformApplication":"MobilePlatformApplication","userErrors":"[MobilePlatformApplicationUserError!]!"}}}, +"MobilePlatformApplicationUserError":{"o":{"f":{"code":"MobilePlatformApplicationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MobilePlatformApplicationUserErrorCode":{"e":["INVALID","NOT_FOUND","TOO_LONG"]}, +"Model3d":{"o":{"f":{"alt":"String","boundingBox":"Model3dBoundingBox","createdAt":"DateTime!","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","filename":"String!","id":"ID!","mediaContentType":"MediaContentType!","mediaErrors":"[MediaError!]!","mediaWarnings":"[MediaWarning!]!","originalSource":"Model3dSource","preview":"MediaPreviewImage","sources":"[Model3dSource!]!","status":"MediaStatus!","updatedAt":"DateTime!"},"t":["File","Media","Node"]}}, +"Model3dBoundingBox":{"o":{"f":{"size":"Vector3!"}}}, +"Model3dSource":{"o":{"f":{"filesize":"Int!","format":"String!","mimeType":"String!","url":"String!"}}}, +"Money":"s", +"MoneyBag":{"o":{"f":{"presentmentMoney":"MoneyV2!","shopMoney":"MoneyV2!"}}}, +"MoneyBagInput":{"i":{"presentmentMoney":"MoneyInput","shopMoney":"MoneyInput!"}}, +"MoneyInput":{"i":{"amount":"Decimal!","currencyCode":"CurrencyCode!"}}, +"MoneyV2":{"o":{"f":{"amount":"Decimal!","currencyCode":"CurrencyCode!"}}}, +"MoveInput":{"i":{"id":"ID!","newPosition":"UnsignedInt64!"}}, +"Mutation":{"o":{"f":{"abandonmentEmailStateUpdate":["AbandonmentEmailStateUpdatePayload",{"emailSentAt":"DateTime","emailState":"AbandonmentEmailState!","emailStateChangeReason":"String","id":"ID!"}],"abandonmentUpdateActivitiesDeliveryStatuses":["AbandonmentUpdateActivitiesDeliveryStatusesPayload",{"abandonmentId":"ID!","deliveredAt":"DateTime","deliveryStatus":"AbandonmentDeliveryState!","deliveryStatusChangeReason":"String","marketingActivityId":"ID!"}],"analyticsAnnotationCreate":["AnalyticsAnnotationCreatePayload",{"input":"AnalyticsAnnotationCreateInput!"}],"analyticsAnnotationDelete":["AnalyticsAnnotationDeletePayload",{"id":"ID!"}],"analyticsAnnotationUpdate":["AnalyticsAnnotationUpdatePayload",{"id":"ID!","input":"AnalyticsAnnotationUpdateInput!"}],"analyticsTargetCreate":["AnalyticsTargetCreatePayload",{"input":"AnalyticsTargetCreateInput!"}],"analyticsTargetUpdate":["AnalyticsTargetUpdatePayload",{"id":"ID!","input":"AnalyticsTargetUpdateInput!"}],"analyticsTargetsDelete":["AnalyticsTargetsDeletePayload",{"ids":"[ID!]!"}],"appPurchaseOneTimeCreate":["AppPurchaseOneTimeCreatePayload",{"name":"String!","price":"MoneyInput!","returnUrl":"URL!","test":"Boolean="}],"appRevokeAccessScopes":["AppRevokeAccessScopesPayload",{"scopes":"[String!]!"}],"appSubscriptionCancel":["AppSubscriptionCancelPayload",{"id":"ID!","prorate":"Boolean="}],"appSubscriptionCreate":["AppSubscriptionCreatePayload",{"lineItems":"[AppSubscriptionLineItemInput!]!","name":"String!","replacementBehavior":"AppSubscriptionReplacementBehavior=","returnUrl":"URL!","test":"Boolean=","trialDays":"Int"}],"appSubscriptionLineItemUpdate":["AppSubscriptionLineItemUpdatePayload",{"cappedAmount":"MoneyInput!","id":"ID!"}],"appSubscriptionTrialExtend":["AppSubscriptionTrialExtendPayload",{"days":"Int!","id":"ID!"}],"appUninstall":"AppUninstallPayload","appUsageRecordCreate":["AppUsageRecordCreatePayload",{"description":"String!","idempotencyKey":"String","price":"MoneyInput!","subscriptionLineItemId":"ID!"}],"articleCreate":["ArticleCreatePayload",{"article":"ArticleCreateInput!","blog":"ArticleBlogInput"}],"articleDelete":["ArticleDeletePayload",{"id":"ID!"}],"articleUpdate":["ArticleUpdatePayload",{"article":"ArticleUpdateInput!","blog":"ArticleBlogInput","id":"ID!"}],"backupRegionUpdate":["BackupRegionUpdatePayload",{"region":"BackupRegionUpdateInput"}],"blogCreate":["BlogCreatePayload",{"blog":"BlogCreateInput!"}],"blogDelete":["BlogDeletePayload",{"id":"ID!"}],"blogUpdate":["BlogUpdatePayload",{"blog":"BlogUpdateInput!","id":"ID!"}],"bulkOperationCancel":["BulkOperationCancelPayload",{"id":"ID!"}],"bulkOperationRunMutation":["BulkOperationRunMutationPayload",{"clientIdentifier":"String","groupObjects":"Boolean=","mutation":"String!","stagedUploadPath":"String!"}],"bulkOperationRunQuery":["BulkOperationRunQueryPayload",{"groupObjects":"Boolean!=","query":"String!"}],"bulkProductResourceFeedbackCreate":["BulkProductResourceFeedbackCreatePayload",{"feedbackInput":"[ProductResourceFeedbackInput!]!"}],"carrierServiceCreate":["CarrierServiceCreatePayload",{"input":"DeliveryCarrierServiceCreateInput!"}],"carrierServiceDelete":["CarrierServiceDeletePayload",{"id":"ID!"}],"carrierServiceUpdate":["CarrierServiceUpdatePayload",{"input":"DeliveryCarrierServiceUpdateInput!"}],"cartTransformCreate":["CartTransformCreatePayload",{"blockOnFailure":"Boolean=","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]="}],"cartTransformDelete":["CartTransformDeletePayload",{"id":"ID!"}],"cashDrawerCreate":["CashDrawerCreatePayload",{"locationId":"ID!","name":"String!"}],"cashDrawerFindOrCreate":["CashDrawerFindOrCreatePayload",{"locationId":"ID!","name":"String!","pointOfSaleDeviceId":"ID!"}],"cashDrawerUpdate":["CashDrawerUpdatePayload",{"id":"ID!","input":"CashDrawerUpdateInput!"}],"cashManagementReasonCodeCreate":["CashManagementReasonCodeCreatePayload",{"code":"String!"}],"cashManagementReasonCodeDelete":["CashManagementReasonCodeDeletePayload",{"id":"ID!"}],"catalogContextUpdate":["CatalogContextUpdatePayload",{"catalogId":"ID!","contextsToAdd":"CatalogContextInput","contextsToRemove":"CatalogContextInput"}],"catalogCreate":["CatalogCreatePayload",{"input":"CatalogCreateInput!"}],"catalogDelete":["CatalogDeletePayload",{"deleteDependentResources":"Boolean=","id":"ID!"}],"catalogUpdate":["CatalogUpdatePayload",{"id":"ID!","input":"CatalogUpdateInput!"}],"channelCreate":["ChannelCreatePayload",{"input":"ChannelCreateInput!"}],"channelDelete":["ChannelDeletePayload",{"id":"ID!"}],"channelFullSync":["ChannelFullSyncPayload",{"beforeUpdatedAt":"DateTime","channelId":"ID!","country":"CountryCode","language":"LanguageCode","updatedAtSince":"DateTime"}],"channelUpdate":["ChannelUpdatePayload",{"id":"ID!","input":"ChannelUpdateInput!"}],"checkoutAndAccountsConfigurationUpdate":["CheckoutAndAccountsConfigurationUpdatePayload",{"configuration":"CheckoutAndAccountsConfigurationInput!","id":"ID!"}],"checkoutBrandingUpsert":["CheckoutBrandingUpsertPayload",{"checkoutBrandingInput":"CheckoutBrandingInput","checkoutProfileId":"ID!"}],"collectionAddProducts":["CollectionAddProductsPayload",{"id":"ID!","productIds":"[ID!]!"}],"collectionAddProductsV2":["CollectionAddProductsV2Payload",{"id":"ID!","productIds":"[ID!]!"}],"collectionConditionsSourceCreate":["CollectionConditionsSourceCreatePayload",{"input":"CollectionCreateConditionsSourceInput!"}],"collectionConditionsSourceDelete":["CollectionConditionsSourceDeletePayload",{"id":"ID!"}],"collectionConditionsSourceUpdate":["CollectionConditionsSourceUpdatePayload",{"input":"CollectionUpdateConditionsSourceInput!"}],"collectionCreate":["CollectionCreatePayload",{"collection":"CollectionCreateInput","input":"CollectionInput"}],"collectionDelete":["CollectionDeletePayload",{"input":"CollectionDeleteInput!"}],"collectionDuplicate":["CollectionDuplicatePayload",{"input":"CollectionDuplicateInput!"}],"collectionPublish":["CollectionPublishPayload",{"input":"CollectionPublishInput!"}],"collectionRemoveProducts":["CollectionRemoveProductsPayload",{"id":"ID!","productIds":"[ID!]!"}],"collectionReorderProducts":["CollectionReorderProductsPayload",{"id":"ID!","moves":"[MoveInput!]!"}],"collectionUnpublish":["CollectionUnpublishPayload",{"input":"CollectionUnpublishInput!"}],"collectionUpdate":["CollectionUpdatePayload",{"collection":"CollectionUpdateInput","input":"CollectionInput"}],"combinedListingUpdate":["CombinedListingUpdatePayload",{"optionsAndValues":"[OptionAndValueInput!]","parentProductId":"ID!","productsAdded":"[ChildProductRelationInput!]","productsEdited":"[ChildProductRelationInput!]","productsRemovedIds":"[ID!]","title":"String"}],"commentApprove":["CommentApprovePayload",{"id":"ID!"}],"commentDelete":["CommentDeletePayload",{"id":"ID!"}],"commentNotSpam":["CommentNotSpamPayload",{"id":"ID!"}],"commentSpam":["CommentSpamPayload",{"id":"ID!"}],"companiesDelete":["CompaniesDeletePayload",{"companyIds":"[ID!]!"}],"companyAddressDelete":["CompanyAddressDeletePayload",{"addressId":"ID!"}],"companyAssignCustomerAsContact":["CompanyAssignCustomerAsContactPayload",{"companyId":"ID!","customerId":"ID!"}],"companyAssignMainContact":["CompanyAssignMainContactPayload",{"companyContactId":"ID!","companyId":"ID!"}],"companyContactAssignRole":["CompanyContactAssignRolePayload",{"companyContactId":"ID!","companyContactRoleId":"ID!","companyLocationId":"ID!"}],"companyContactAssignRoles":["CompanyContactAssignRolesPayload",{"companyContactId":"ID!","rolesToAssign":"[CompanyContactRoleAssign!]!"}],"companyContactCreate":["CompanyContactCreatePayload",{"companyId":"ID!","input":"CompanyContactInput!"}],"companyContactDelete":["CompanyContactDeletePayload",{"companyContactId":"ID!"}],"companyContactRemoveFromCompany":["CompanyContactRemoveFromCompanyPayload",{"companyContactId":"ID!"}],"companyContactRevokeRole":["CompanyContactRevokeRolePayload",{"companyContactId":"ID!","companyContactRoleAssignmentId":"ID!"}],"companyContactRevokeRoles":["CompanyContactRevokeRolesPayload",{"companyContactId":"ID!","revokeAll":"Boolean=","roleAssignmentIds":"[ID!]"}],"companyContactSendWelcomeEmail":["CompanyContactSendWelcomeEmailPayload",{"companyContactId":"ID!","email":"EmailInput"}],"companyContactUpdate":["CompanyContactUpdatePayload",{"companyContactId":"ID!","input":"CompanyContactInput!"}],"companyContactsDelete":["CompanyContactsDeletePayload",{"companyContactIds":"[ID!]!"}],"companyCreate":["CompanyCreatePayload",{"input":"CompanyCreateInput!"}],"companyDelete":["CompanyDeletePayload",{"id":"ID!"}],"companyLocationAssignAddress":["CompanyLocationAssignAddressPayload",{"address":"CompanyAddressInput!","addressTypes":"[CompanyAddressType!]!","locationId":"ID!"}],"companyLocationAssignRoles":["CompanyLocationAssignRolesPayload",{"companyLocationId":"ID!","rolesToAssign":"[CompanyLocationRoleAssign!]!"}],"companyLocationAssignStaffMembers":["CompanyLocationAssignStaffMembersPayload",{"companyLocationId":"ID!","staffMemberIds":"[ID!]!"}],"companyLocationAssignTaxExemptions":["CompanyLocationAssignTaxExemptionsPayload",{"companyLocationId":"ID!","taxExemptions":"[TaxExemption!]!"}],"companyLocationCreate":["CompanyLocationCreatePayload",{"companyId":"ID!","input":"CompanyLocationInput!"}],"companyLocationCreateTaxRegistration":["CompanyLocationCreateTaxRegistrationPayload",{"locationId":"ID!","taxId":"String!"}],"companyLocationDelete":["CompanyLocationDeletePayload",{"companyLocationId":"ID!"}],"companyLocationRemoveStaffMembers":["CompanyLocationRemoveStaffMembersPayload",{"companyLocationStaffMemberAssignmentIds":"[ID!]!"}],"companyLocationRevokeRoles":["CompanyLocationRevokeRolesPayload",{"companyLocationId":"ID!","rolesToRevoke":"[ID!]!"}],"companyLocationRevokeTaxExemptions":["CompanyLocationRevokeTaxExemptionsPayload",{"companyLocationId":"ID!","taxExemptions":"[TaxExemption!]!"}],"companyLocationRevokeTaxRegistration":["CompanyLocationRevokeTaxRegistrationPayload",{"companyLocationId":"ID!"}],"companyLocationTaxSettingsUpdate":["CompanyLocationTaxSettingsUpdatePayload",{"companyLocationId":"ID!","exemptionsToAssign":"[TaxExemption!]","exemptionsToRemove":"[TaxExemption!]","taxExempt":"Boolean","taxRegistrationId":"String"}],"companyLocationUpdate":["CompanyLocationUpdatePayload",{"companyLocationId":"ID!","input":"CompanyLocationUpdateInput!"}],"companyLocationsDelete":["CompanyLocationsDeletePayload",{"companyLocationIds":"[ID!]!"}],"companyRevokeMainContact":["CompanyRevokeMainContactPayload",{"companyId":"ID!"}],"companyUpdate":["CompanyUpdatePayload",{"companyId":"ID!","input":"CompanyInput!"}],"consentPolicyUpdate":["ConsentPolicyUpdatePayload",{"consentPolicies":"[ConsentPolicyInput!]!"}],"customerAddTaxExemptions":["CustomerAddTaxExemptionsPayload",{"customerId":"ID!","taxExemptions":"[TaxExemption!]!"}],"customerAddressCreate":["CustomerAddressCreatePayload",{"address":"MailingAddressInput!","customerId":"ID!","setAsDefault":"Boolean"}],"customerAddressDelete":["CustomerAddressDeletePayload",{"addressId":"ID!","customerId":"ID!"}],"customerAddressUpdate":["CustomerAddressUpdatePayload",{"address":"MailingAddressInput!","addressId":"ID!","customerId":"ID!","setAsDefault":"Boolean"}],"customerCancelDataErasure":["CustomerCancelDataErasurePayload",{"customerId":"ID!"}],"customerCreate":["CustomerCreatePayload",{"input":"CustomerInput!"}],"customerDelete":["CustomerDeletePayload",{"input":"CustomerDeleteInput!"}],"customerEmailMarketingConsentUpdate":["CustomerEmailMarketingConsentUpdatePayload",{"input":"CustomerEmailMarketingConsentUpdateInput!"}],"customerGenerateAccountActivationUrl":["CustomerGenerateAccountActivationUrlPayload",{"customerId":"ID!"}],"customerMerge":["CustomerMergePayload",{"customerOneId":"ID!","customerTwoId":"ID!","overrideFields":"CustomerMergeOverrideFields"}],"customerPaymentMethodCreateFromDuplicationData":["CustomerPaymentMethodCreateFromDuplicationDataPayload",{"billingAddress":"MailingAddressInput!","customerId":"ID!","encryptedDuplicationData":"String!"}],"customerPaymentMethodCreditCardCreate":["CustomerPaymentMethodCreditCardCreatePayload",{"billingAddress":"MailingAddressInput!","customerId":"ID!","sessionId":"String!"}],"customerPaymentMethodCreditCardUpdate":["CustomerPaymentMethodCreditCardUpdatePayload",{"billingAddress":"MailingAddressInput!","id":"ID!","sessionId":"String!"}],"customerPaymentMethodGetDuplicationData":["CustomerPaymentMethodGetDuplicationDataPayload",{"customerPaymentMethodId":"ID!","targetCustomerId":"ID!","targetShopId":"ID!"}],"customerPaymentMethodGetUpdateUrl":["CustomerPaymentMethodGetUpdateUrlPayload",{"customerPaymentMethodId":"ID!"}],"customerPaymentMethodPaypalBillingAgreementCreate":["CustomerPaymentMethodPaypalBillingAgreementCreatePayload",{"billingAddress":"MailingAddressInput","billingAgreementId":"String!","customerId":"ID!","inactive":"Boolean="}],"customerPaymentMethodPaypalBillingAgreementUpdate":["CustomerPaymentMethodPaypalBillingAgreementUpdatePayload",{"billingAddress":"MailingAddressInput!","id":"ID!"}],"customerPaymentMethodRemoteCreate":["CustomerPaymentMethodRemoteCreatePayload",{"customerId":"ID!","remoteReference":"CustomerPaymentMethodRemoteInput!"}],"customerPaymentMethodRevoke":["CustomerPaymentMethodRevokePayload",{"customerPaymentMethodId":"ID!"}],"customerPaymentMethodSendUpdateEmail":["CustomerPaymentMethodSendUpdateEmailPayload",{"customerPaymentMethodId":"ID!","email":"EmailInput"}],"customerRemoveTaxExemptions":["CustomerRemoveTaxExemptionsPayload",{"customerId":"ID!","taxExemptions":"[TaxExemption!]!"}],"customerReplaceTaxExemptions":["CustomerReplaceTaxExemptionsPayload",{"customerId":"ID!","taxExemptions":"[TaxExemption!]!"}],"customerRequestDataErasure":["CustomerRequestDataErasurePayload",{"customerId":"ID!"}],"customerSegmentMembersQueryCreate":["CustomerSegmentMembersQueryCreatePayload",{"input":"CustomerSegmentMembersQueryInput!"}],"customerSendAccountInviteEmail":["CustomerSendAccountInviteEmailPayload",{"customerId":"ID!","email":"EmailInput"}],"customerSet":["CustomerSetPayload",{"identifier":"CustomerSetIdentifiers","input":"CustomerSetInput!"}],"customerSmsMarketingConsentUpdate":["CustomerSmsMarketingConsentUpdatePayload",{"input":"CustomerSmsMarketingConsentUpdateInput!"}],"customerUpdate":["CustomerUpdatePayload",{"input":"CustomerInput!"}],"customerUpdateDefaultAddress":["CustomerUpdateDefaultAddressPayload",{"addressId":"ID!","customerId":"ID!"}],"customerWhatsAppMarketingConsentUpdate":["CustomerWhatsAppMarketingConsentUpdatePayload",{"input":"CustomerWhatsAppMarketingConsentUpdateInput!"}],"dataSaleOptOut":["DataSaleOptOutPayload",{"email":"String!"}],"delegateAccessTokenCreate":["DelegateAccessTokenCreatePayload",{"input":"DelegateAccessTokenInput!"}],"delegateAccessTokenDestroy":["DelegateAccessTokenDestroyPayload",{"accessToken":"String!"}],"deliveryCustomizationActivation":["DeliveryCustomizationActivationPayload",{"enabled":"Boolean!","ids":"[ID!]!"}],"deliveryCustomizationCreate":["DeliveryCustomizationCreatePayload",{"deliveryCustomization":"DeliveryCustomizationInput!"}],"deliveryCustomizationDelete":["DeliveryCustomizationDeletePayload",{"id":"ID!"}],"deliveryCustomizationUpdate":["DeliveryCustomizationUpdatePayload",{"deliveryCustomization":"DeliveryCustomizationInput!","id":"ID!"}],"deliveryProfileCreate":["DeliveryProfileCreatePayload",{"profile":"DeliveryProfileInput!"}],"deliveryProfileRemove":["DeliveryProfileRemovePayload",{"id":"ID!"}],"deliveryProfileUpdate":["DeliveryProfileUpdatePayload",{"id":"ID!","profile":"DeliveryProfileInput!"}],"deliveryPromiseParticipantsUpdate":["DeliveryPromiseParticipantsUpdatePayload",{"brandedPromiseHandle":"String!","ownersToAdd":"[ID!]=","ownersToRemove":"[ID!]="}],"deliveryPromiseProviderUpsert":["DeliveryPromiseProviderUpsertPayload",{"active":"Boolean","fulfillmentDelay":"Int","locationId":"ID!","timeZone":"String"}],"deliverySettingUpdate":"DeliverySettingUpdatePayload","deliveryShippingOriginAssign":["DeliveryShippingOriginAssignPayload",{"locationId":"ID!"}],"discountAutomaticActivate":["DiscountAutomaticActivatePayload",{"id":"ID!"}],"discountAutomaticAppCreate":["DiscountAutomaticAppCreatePayload",{"automaticAppDiscount":"DiscountAutomaticAppInput!"}],"discountAutomaticAppUpdate":["DiscountAutomaticAppUpdatePayload",{"automaticAppDiscount":"DiscountAutomaticAppInput!","id":"ID!"}],"discountAutomaticBasicCreate":["DiscountAutomaticBasicCreatePayload",{"automaticBasicDiscount":"DiscountAutomaticBasicInput!"}],"discountAutomaticBasicUpdate":["DiscountAutomaticBasicUpdatePayload",{"automaticBasicDiscount":"DiscountAutomaticBasicInput!","id":"ID!"}],"discountAutomaticBulkDelete":["DiscountAutomaticBulkDeletePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String"}],"discountAutomaticBxgyCreate":["DiscountAutomaticBxgyCreatePayload",{"automaticBxgyDiscount":"DiscountAutomaticBxgyInput!"}],"discountAutomaticBxgyUpdate":["DiscountAutomaticBxgyUpdatePayload",{"automaticBxgyDiscount":"DiscountAutomaticBxgyInput!","id":"ID!"}],"discountAutomaticDeactivate":["DiscountAutomaticDeactivatePayload",{"id":"ID!"}],"discountAutomaticDelete":["DiscountAutomaticDeletePayload",{"id":"ID!"}],"discountAutomaticFreeShippingCreate":["DiscountAutomaticFreeShippingCreatePayload",{"freeShippingAutomaticDiscount":"DiscountAutomaticFreeShippingInput!"}],"discountAutomaticFreeShippingUpdate":["DiscountAutomaticFreeShippingUpdatePayload",{"freeShippingAutomaticDiscount":"DiscountAutomaticFreeShippingInput!","id":"ID!"}],"discountBulkTagsAdd":["DiscountBulkTagsAddPayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String","tags":"[String!]!"}],"discountBulkTagsRemove":["DiscountBulkTagsRemovePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String","tags":"[String!]!"}],"discountCodeActivate":["DiscountCodeActivatePayload",{"id":"ID!"}],"discountCodeAppCreate":["DiscountCodeAppCreatePayload",{"codeAppDiscount":"DiscountCodeAppInput!"}],"discountCodeAppUpdate":["DiscountCodeAppUpdatePayload",{"codeAppDiscount":"DiscountCodeAppInput!","id":"ID!"}],"discountCodeBasicCreate":["DiscountCodeBasicCreatePayload",{"basicCodeDiscount":"DiscountCodeBasicInput!"}],"discountCodeBasicUpdate":["DiscountCodeBasicUpdatePayload",{"basicCodeDiscount":"DiscountCodeBasicInput!","id":"ID!"}],"discountCodeBulkActivate":["DiscountCodeBulkActivatePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String"}],"discountCodeBulkDeactivate":["DiscountCodeBulkDeactivatePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String"}],"discountCodeBulkDelete":["DiscountCodeBulkDeletePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String"}],"discountCodeBxgyCreate":["DiscountCodeBxgyCreatePayload",{"bxgyCodeDiscount":"DiscountCodeBxgyInput!"}],"discountCodeBxgyUpdate":["DiscountCodeBxgyUpdatePayload",{"bxgyCodeDiscount":"DiscountCodeBxgyInput!","id":"ID!"}],"discountCodeDeactivate":["DiscountCodeDeactivatePayload",{"id":"ID!"}],"discountCodeDelete":["DiscountCodeDeletePayload",{"id":"ID!"}],"discountCodeFreeShippingCreate":["DiscountCodeFreeShippingCreatePayload",{"freeShippingCodeDiscount":"DiscountCodeFreeShippingInput!"}],"discountCodeFreeShippingUpdate":["DiscountCodeFreeShippingUpdatePayload",{"freeShippingCodeDiscount":"DiscountCodeFreeShippingInput!","id":"ID!"}],"discountCodeRedeemCodeBulkDelete":["DiscountCodeRedeemCodeBulkDeletePayload",{"discountId":"ID!","ids":"[ID!]","savedSearchId":"ID","search":"String"}],"discountRedeemCodeBulkAdd":["DiscountRedeemCodeBulkAddPayload",{"codes":"[DiscountRedeemCodeInput!]!","discountId":"ID!"}],"disputeEvidenceUpdate":["DisputeEvidenceUpdatePayload",{"id":"ID!","input":"ShopifyPaymentsDisputeEvidenceUpdateInput!"}],"draftOrderBulkAddTags":["DraftOrderBulkAddTagsPayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String","tags":"[String!]!"}],"draftOrderBulkDelete":["DraftOrderBulkDeletePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String"}],"draftOrderBulkRemoveTags":["DraftOrderBulkRemoveTagsPayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String","tags":"[String!]!"}],"draftOrderCalculate":["DraftOrderCalculatePayload",{"input":"DraftOrderInput!"}],"draftOrderComplete":["DraftOrderCompletePayload",{"id":"ID!","paymentGatewayId":"ID","paymentPending":"Boolean=","sourceName":"String"}],"draftOrderCreate":["DraftOrderCreatePayload",{"input":"DraftOrderInput!"}],"draftOrderCreateFromOrder":["DraftOrderCreateFromOrderPayload",{"orderId":"ID!"}],"draftOrderDelete":["DraftOrderDeletePayload",{"input":"DraftOrderDeleteInput!"}],"draftOrderDuplicate":["DraftOrderDuplicatePayload",{"draftOrderId":"ID","id":"ID"}],"draftOrderInvoicePreview":["DraftOrderInvoicePreviewPayload",{"email":"EmailInput","id":"ID!"}],"draftOrderInvoiceSend":["DraftOrderInvoiceSendPayload",{"email":"EmailInput","id":"ID!"}],"draftOrderUpdate":["DraftOrderUpdatePayload",{"id":"ID!","input":"DraftOrderInput!"}],"eventBridgeServerPixelUpdate":["EventBridgeServerPixelUpdatePayload",{"arn":"ARN!"}],"eventBridgeWebhookSubscriptionCreate":["EventBridgeWebhookSubscriptionCreatePayload",{"topic":"WebhookSubscriptionTopic!","webhookSubscription":"EventBridgeWebhookSubscriptionInput!"}],"eventBridgeWebhookSubscriptionUpdate":["EventBridgeWebhookSubscriptionUpdatePayload",{"id":"ID!","webhookSubscription":"EventBridgeWebhookSubscriptionInput!"}],"fileAcknowledgeUpdateFailed":["FileAcknowledgeUpdateFailedPayload",{"fileIds":"[ID!]!"}],"fileCreate":["FileCreatePayload",{"files":"[FileCreateInput!]!"}],"fileDelete":["FileDeletePayload",{"fileIds":"[ID!]!"}],"fileUpdate":["FileUpdatePayload",{"files":"[FileUpdateInput!]!"}],"flowGenerateSignature":["FlowGenerateSignaturePayload",{"id":"ID!","payload":"String!"}],"flowTriggerReceive":["FlowTriggerReceivePayload",{"body":"String","handle":"String","payload":"JSON"}],"fulfillmentCancel":["FulfillmentCancelPayload",{"id":"ID!"}],"fulfillmentConstraintRuleCreate":["FulfillmentConstraintRuleCreatePayload",{"deliveryMethodTypes":"[DeliveryMethodType!]!","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]="}],"fulfillmentConstraintRuleDelete":["FulfillmentConstraintRuleDeletePayload",{"id":"ID!"}],"fulfillmentConstraintRuleUpdate":["FulfillmentConstraintRuleUpdatePayload",{"deliveryMethodTypes":"[DeliveryMethodType!]!","id":"ID!"}],"fulfillmentCreate":["FulfillmentCreatePayload",{"fulfillment":"FulfillmentInput!","message":"String"}],"fulfillmentCreateV2":["FulfillmentCreateV2Payload",{"fulfillment":"FulfillmentV2Input!","message":"String"}],"fulfillmentEventCreate":["FulfillmentEventCreatePayload",{"fulfillmentEvent":"FulfillmentEventInput!"}],"fulfillmentOrderAcceptCancellationRequest":["FulfillmentOrderAcceptCancellationRequestPayload",{"id":"ID!","message":"String"}],"fulfillmentOrderAcceptFulfillmentRequest":["FulfillmentOrderAcceptFulfillmentRequestPayload",{"estimatedShippedAt":"DateTime","id":"ID!","message":"String"}],"fulfillmentOrderCancel":["FulfillmentOrderCancelPayload",{"id":"ID!"}],"fulfillmentOrderClose":["FulfillmentOrderClosePayload",{"id":"ID!","message":"String"}],"fulfillmentOrderHold":["FulfillmentOrderHoldPayload",{"fulfillmentHold":"FulfillmentOrderHoldInput!","id":"ID!"}],"fulfillmentOrderLineItemsPreparedForPickup":["FulfillmentOrderLineItemsPreparedForPickupPayload",{"input":"FulfillmentOrderLineItemsPreparedForPickupInput!"}],"fulfillmentOrderMerge":["FulfillmentOrderMergePayload",{"fulfillmentOrderMergeInputs":"[FulfillmentOrderMergeInput!]!"}],"fulfillmentOrderMove":["FulfillmentOrderMovePayload",{"fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]","id":"ID!","newLocationId":"ID!"}],"fulfillmentOrderOpen":["FulfillmentOrderOpenPayload",{"id":"ID!"}],"fulfillmentOrderRejectCancellationRequest":["FulfillmentOrderRejectCancellationRequestPayload",{"id":"ID!","message":"String"}],"fulfillmentOrderRejectFulfillmentRequest":["FulfillmentOrderRejectFulfillmentRequestPayload",{"id":"ID!","lineItems":"[IncomingRequestLineItemInput!]","message":"String","reason":"FulfillmentOrderRejectionReason"}],"fulfillmentOrderReleaseHold":["FulfillmentOrderReleaseHoldPayload",{"externalId":"String","holdIds":"[ID!]","id":"ID!"}],"fulfillmentOrderReportProgress":["FulfillmentOrderReportProgressPayload",{"id":"ID!","progressReport":"FulfillmentOrderReportProgressInput"}],"fulfillmentOrderReschedule":["FulfillmentOrderReschedulePayload",{"fulfillAt":"DateTime!","id":"ID!"}],"fulfillmentOrderSplit":["FulfillmentOrderSplitPayload",{"fulfillmentOrderSplits":"[FulfillmentOrderSplitInput!]!"}],"fulfillmentOrderSubmitCancellationRequest":["FulfillmentOrderSubmitCancellationRequestPayload",{"id":"ID!","message":"String"}],"fulfillmentOrderSubmitFulfillmentRequest":["FulfillmentOrderSubmitFulfillmentRequestPayload",{"fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]","id":"ID!","message":"String","notifyCustomer":"Boolean"}],"fulfillmentOrdersReroute":["FulfillmentOrdersReroutePayload",{"excludedLocationIds":"[ID!]","fulfillmentOrderIds":"[ID!]!","includedLocationIds":"[ID!]"}],"fulfillmentOrdersSetFulfillmentDeadline":["FulfillmentOrdersSetFulfillmentDeadlinePayload",{"fulfillmentDeadline":"DateTime!","fulfillmentOrderIds":"[ID!]!"}],"fulfillmentServiceCreate":["FulfillmentServiceCreatePayload",{"callbackUrl":"URL","fulfillmentOrdersOptIn":"Boolean=","inventoryManagement":"Boolean=","name":"String!","requiresShippingMethod":"Boolean=","trackingSupport":"Boolean="}],"fulfillmentServiceDelete":["FulfillmentServiceDeletePayload",{"destinationLocationId":"ID","id":"ID!","inventoryAction":"FulfillmentServiceDeleteInventoryAction="}],"fulfillmentServiceUpdate":["FulfillmentServiceUpdatePayload",{"callbackUrl":"URL","fulfillmentOrdersOptIn":"Boolean","id":"ID!","inventoryManagement":"Boolean","name":"String","requiresShippingMethod":"Boolean=","trackingSupport":"Boolean"}],"fulfillmentTrackingInfoUpdate":["FulfillmentTrackingInfoUpdatePayload",{"fulfillmentId":"ID!","notifyCustomer":"Boolean","trackingInfoInput":"FulfillmentTrackingInput!"}],"fulfillmentTrackingInfoUpdateV2":["FulfillmentTrackingInfoUpdateV2Payload",{"fulfillmentId":"ID!","notifyCustomer":"Boolean","trackingInfoInput":"FulfillmentTrackingInput!"}],"giftCardCreate":["GiftCardCreatePayload",{"input":"GiftCardCreateInput!"}],"giftCardCredit":["GiftCardCreditPayload",{"creditInput":"GiftCardCreditInput!","id":"ID!"}],"giftCardDeactivate":["GiftCardDeactivatePayload",{"id":"ID!"}],"giftCardDebit":["GiftCardDebitPayload",{"debitInput":"GiftCardDebitInput!","id":"ID!"}],"giftCardProductSet":["GiftCardProductSetPayload",{"identifier":"ProductSetIdentifiers","input":"GiftCardProductSetInput!","synchronous":"Boolean="}],"giftCardSendNotificationToCustomer":["GiftCardSendNotificationToCustomerPayload",{"id":"ID!"}],"giftCardSendNotificationToRecipient":["GiftCardSendNotificationToRecipientPayload",{"id":"ID!"}],"giftCardUpdate":["GiftCardUpdatePayload",{"id":"ID!","input":"GiftCardUpdateInput!"}],"inventoryActivate":["InventoryActivatePayload",{"available":"Int","inventoryItemId":"ID!","locationId":"ID!","onHand":"Int","stockAtLegacyLocation":"Boolean="}],"inventoryAdjustQuantities":["InventoryAdjustQuantitiesPayload",{"input":"InventoryAdjustQuantitiesInput!"}],"inventoryBulkToggleActivation":["InventoryBulkToggleActivationPayload",{"inventoryItemId":"ID!","inventoryItemUpdates":"[InventoryBulkToggleActivationInput!]!"}],"inventoryDeactivate":["InventoryDeactivatePayload",{"inventoryLevelId":"ID!"}],"inventoryItemUpdate":["InventoryItemUpdatePayload",{"id":"ID!","input":"InventoryItemInput!"}],"inventoryMoveQuantities":["InventoryMoveQuantitiesPayload",{"input":"InventoryMoveQuantitiesInput!"}],"inventorySetOnHandQuantities":["InventorySetOnHandQuantitiesPayload",{"input":"InventorySetOnHandQuantitiesInput!"}],"inventorySetQuantities":["InventorySetQuantitiesPayload",{"input":"InventorySetQuantitiesInput!"}],"inventoryShipmentAddItems":["InventoryShipmentAddItemsPayload",{"id":"ID!","lineItems":"[InventoryShipmentLineItemInput!]!"}],"inventoryShipmentCreate":["InventoryShipmentCreatePayload",{"input":"InventoryShipmentCreateInput!"}],"inventoryShipmentCreateInTransit":["InventoryShipmentCreateInTransitPayload",{"input":"InventoryShipmentCreateInput!"}],"inventoryShipmentDelete":["InventoryShipmentDeletePayload",{"id":"ID!"}],"inventoryShipmentMarkInTransit":["InventoryShipmentMarkInTransitPayload",{"dateShipped":"DateTime","id":"ID!"}],"inventoryShipmentReceive":["InventoryShipmentReceivePayload",{"bulkReceiveAction":"InventoryShipmentReceiveLineItemReason","dateReceived":"DateTime","id":"ID!","lineItems":"[InventoryShipmentReceiveItemInput!]"}],"inventoryShipmentRemoveItems":["InventoryShipmentRemoveItemsPayload",{"id":"ID!","lineItems":"[ID!]!"}],"inventoryShipmentSetBarcode":["InventoryShipmentSetBarcodePayload",{"barcode":"String!","id":"ID!"}],"inventoryShipmentSetTracking":["InventoryShipmentSetTrackingPayload",{"id":"ID!","tracking":"InventoryShipmentTrackingInput!"}],"inventoryShipmentUpdateItemQuantities":["InventoryShipmentUpdateItemQuantitiesPayload",{"id":"ID!","items":"[InventoryShipmentUpdateItemQuantitiesInput!]="}],"inventoryTransferCancel":["InventoryTransferCancelPayload",{"id":"ID!"}],"inventoryTransferCreate":["InventoryTransferCreatePayload",{"input":"InventoryTransferCreateInput!"}],"inventoryTransferCreateAsReadyToShip":["InventoryTransferCreateAsReadyToShipPayload",{"input":"InventoryTransferCreateAsReadyToShipInput!"}],"inventoryTransferDelete":["InventoryTransferDeletePayload",{"id":"ID!"}],"inventoryTransferDuplicate":["InventoryTransferDuplicatePayload",{"id":"ID!"}],"inventoryTransferEdit":["InventoryTransferEditPayload",{"id":"ID!","input":"InventoryTransferEditInput!"}],"inventoryTransferMarkAsReadyToShip":["InventoryTransferMarkAsReadyToShipPayload",{"id":"ID!"}],"inventoryTransferRemoveItems":["InventoryTransferRemoveItemsPayload",{"input":"InventoryTransferRemoveItemsInput!"}],"inventoryTransferSetItems":["InventoryTransferSetItemsPayload",{"input":"InventoryTransferSetItemsInput!"}],"locationActivate":["LocationActivatePayload",{"locationId":"ID!"}],"locationAdd":["LocationAddPayload",{"input":"LocationAddInput!"}],"locationDeactivate":["LocationDeactivatePayload",{"destinationLocationId":"ID","locationId":"ID!"}],"locationDelete":["LocationDeletePayload",{"locationId":"ID!"}],"locationEdit":["LocationEditPayload",{"id":"ID!","input":"LocationEditInput!"}],"locationLocalPickupDisable":["LocationLocalPickupDisablePayload",{"locationId":"ID!"}],"locationLocalPickupEnable":["LocationLocalPickupEnablePayload",{"localPickupSettings":"DeliveryLocationLocalPickupEnableInput!"}],"marketCreate":["MarketCreatePayload",{"input":"MarketCreateInput!"}],"marketCurrencySettingsUpdate":["MarketCurrencySettingsUpdatePayload",{"input":"MarketCurrencySettingsUpdateInput!","marketId":"ID!"}],"marketDelete":["MarketDeletePayload",{"id":"ID!"}],"marketLocalizationsRegister":["MarketLocalizationsRegisterPayload",{"marketLocalizations":"[MarketLocalizationRegisterInput!]!","resourceId":"ID!"}],"marketLocalizationsRemove":["MarketLocalizationsRemovePayload",{"marketIds":"[ID!]!","marketLocalizationKeys":"[String!]!","resourceId":"ID!"}],"marketRegionDelete":["MarketRegionDeletePayload",{"id":"ID!"}],"marketRegionsCreate":["MarketRegionsCreatePayload",{"marketId":"ID!","regions":"[MarketRegionCreateInput!]!"}],"marketRegionsDelete":["MarketRegionsDeletePayload",{"ids":"[ID!]!"}],"marketUpdate":["MarketUpdatePayload",{"id":"ID!","input":"MarketUpdateInput!"}],"marketWebPresenceCreate":["MarketWebPresenceCreatePayload",{"marketId":"ID!","webPresence":"MarketWebPresenceCreateInput!"}],"marketWebPresenceDelete":["MarketWebPresenceDeletePayload",{"webPresenceId":"ID!"}],"marketWebPresenceUpdate":["MarketWebPresenceUpdatePayload",{"webPresence":"MarketWebPresenceUpdateInput!","webPresenceId":"ID!"}],"marketingActivitiesDeleteAllExternal":"MarketingActivitiesDeleteAllExternalPayload","marketingActivityCreate":["MarketingActivityCreatePayload",{"input":"MarketingActivityCreateInput!"}],"marketingActivityCreateExternal":["MarketingActivityCreateExternalPayload",{"input":"MarketingActivityCreateExternalInput!"}],"marketingActivityDeleteExternal":["MarketingActivityDeleteExternalPayload",{"marketingActivityId":"ID","remoteId":"String"}],"marketingActivityUpdate":["MarketingActivityUpdatePayload",{"input":"MarketingActivityUpdateInput!"}],"marketingActivityUpdateExternal":["MarketingActivityUpdateExternalPayload",{"input":"MarketingActivityUpdateExternalInput!","marketingActivityId":"ID","remoteId":"String","utm":"UTMInput"}],"marketingActivityUpsertExternal":["MarketingActivityUpsertExternalPayload",{"input":"MarketingActivityUpsertExternalInput!"}],"marketingEngagementCreate":["MarketingEngagementCreatePayload",{"channelHandle":"String","marketingActivityId":"ID","marketingEngagement":"MarketingEngagementInput!","remoteId":"String"}],"marketingEngagementsDelete":["MarketingEngagementsDeletePayload",{"channelHandle":"String","deleteEngagementsForAllChannels":"Boolean="}],"menuCreate":["MenuCreatePayload",{"handle":"String!","items":"[MenuItemCreateInput!]!","title":"String!"}],"menuDelete":["MenuDeletePayload",{"id":"ID!"}],"menuUpdate":["MenuUpdatePayload",{"handle":"String","id":"ID!","items":"[MenuItemUpdateInput!]!","title":"String!"}],"metafieldDefinitionCreate":["MetafieldDefinitionCreatePayload",{"definition":"MetafieldDefinitionInput!"}],"metafieldDefinitionDelete":["MetafieldDefinitionDeletePayload",{"deleteAllAssociatedMetafields":"Boolean=","id":"ID","identifier":"MetafieldDefinitionIdentifierInput"}],"metafieldDefinitionPin":["MetafieldDefinitionPinPayload",{"definitionId":"ID","identifier":"MetafieldDefinitionIdentifierInput"}],"metafieldDefinitionUnpin":["MetafieldDefinitionUnpinPayload",{"definitionId":"ID","identifier":"MetafieldDefinitionIdentifierInput"}],"metafieldDefinitionUpdate":["MetafieldDefinitionUpdatePayload",{"definition":"MetafieldDefinitionUpdateInput!"}],"metafieldsDelete":["MetafieldsDeletePayload",{"metafields":"[MetafieldIdentifierInput!]!"}],"metafieldsSet":["MetafieldsSetPayload",{"metafields":"[MetafieldsSetInput!]!"}],"metaobjectBulkDelete":["MetaobjectBulkDeletePayload",{"where":"MetaobjectBulkDeleteWhereCondition!"}],"metaobjectCreate":["MetaobjectCreatePayload",{"metaobject":"MetaobjectCreateInput!"}],"metaobjectDefinitionCreate":["MetaobjectDefinitionCreatePayload",{"definition":"MetaobjectDefinitionCreateInput!"}],"metaobjectDefinitionDelete":["MetaobjectDefinitionDeletePayload",{"id":"ID!"}],"metaobjectDefinitionUpdate":["MetaobjectDefinitionUpdatePayload",{"definition":"MetaobjectDefinitionUpdateInput!","id":"ID!"}],"metaobjectDelete":["MetaobjectDeletePayload",{"id":"ID!"}],"metaobjectUpdate":["MetaobjectUpdatePayload",{"id":"ID!","metaobject":"MetaobjectUpdateInput!"}],"metaobjectUpsert":["MetaobjectUpsertPayload",{"handle":"MetaobjectHandleInput!","metaobject":"MetaobjectUpsertInput","values":"JSON"}],"mobilePlatformApplicationCreate":["MobilePlatformApplicationCreatePayload",{"input":"MobilePlatformApplicationCreateInput!"}],"mobilePlatformApplicationDelete":["MobilePlatformApplicationDeletePayload",{"id":"ID!"}],"mobilePlatformApplicationUpdate":["MobilePlatformApplicationUpdatePayload",{"id":"ID!","input":"MobilePlatformApplicationUpdateInput!"}],"orderAttributionDefinitionDelete":["OrderAttributionDefinitionDeletePayload",{"id":"ID!"}],"orderAttributionDefinitionUpsert":["OrderAttributionDefinitionUpsertPayload",{"input":"OrderAttributionDefinitionUpsertInput!"}],"orderCancel":["OrderCancelPayload",{"notifyCustomer":"Boolean=","orderId":"ID!","reason":"OrderCancelReason!","refund":"Boolean","refundMethod":"OrderCancelRefundMethodInput","restock":"Boolean!","staffNote":"String="}],"orderCapture":["OrderCapturePayload",{"input":"OrderCaptureInput!"}],"orderClose":["OrderClosePayload",{"input":"OrderCloseInput!"}],"orderCreate":["OrderCreatePayload",{"options":"OrderCreateOptionsInput","order":"OrderCreateOrderInput!"}],"orderCreateMandatePayment":["OrderCreateMandatePaymentPayload",{"amount":"MoneyInput","autoCapture":"Boolean=","id":"ID!","idempotencyKey":"String!","mandateId":"ID!","paymentScheduleId":"ID"}],"orderCreateManualPayment":["OrderCreateManualPaymentPayload",{"amount":"MoneyInput","id":"ID!","paymentMethodName":"String","processedAt":"DateTime"}],"orderCustomerRemove":["OrderCustomerRemovePayload",{"orderId":"ID!"}],"orderCustomerSet":["OrderCustomerSetPayload",{"customerId":"ID!","orderId":"ID!"}],"orderDelete":["OrderDeletePayload",{"orderId":"ID!"}],"orderEditAddCustomItem":["OrderEditAddCustomItemPayload",{"id":"ID!","locationId":"ID","price":"MoneyInput!","quantity":"Int!","requiresShipping":"Boolean","taxable":"Boolean","title":"String!"}],"orderEditAddLineItemDiscount":["OrderEditAddLineItemDiscountPayload",{"discount":"OrderEditAppliedDiscountInput!","id":"ID!","lineItemId":"ID!"}],"orderEditAddShippingLine":["OrderEditAddShippingLinePayload",{"id":"ID!","shippingLine":"OrderEditAddShippingLineInput!"}],"orderEditAddVariant":["OrderEditAddVariantPayload",{"allowDuplicates":"Boolean=","id":"ID!","locationId":"ID","quantity":"Int!","variantId":"ID!"}],"orderEditBegin":["OrderEditBeginPayload",{"id":"ID!"}],"orderEditCommit":["OrderEditCommitPayload",{"id":"ID!","notifyCustomer":"Boolean","staffNote":"String"}],"orderEditRemoveDiscount":["OrderEditRemoveDiscountPayload",{"discountApplicationId":"ID!","id":"ID!"}],"orderEditRemoveLineItemDiscount":["OrderEditRemoveLineItemDiscountPayload",{"discountApplicationId":"ID!","id":"ID!"}],"orderEditRemoveShippingLine":["OrderEditRemoveShippingLinePayload",{"id":"ID!","shippingLineId":"ID!"}],"orderEditSetQuantity":["OrderEditSetQuantityPayload",{"id":"ID!","lineItemId":"ID!","locationId":"ID","quantity":"Int!","restock":"Boolean"}],"orderEditUpdateDiscount":["OrderEditUpdateDiscountPayload",{"discount":"OrderEditAppliedDiscountInput!","discountApplicationId":"ID!","id":"ID!"}],"orderEditUpdateShippingLine":["OrderEditUpdateShippingLinePayload",{"id":"ID!","shippingLine":"OrderEditUpdateShippingLineInput!","shippingLineId":"ID!"}],"orderInvoiceSend":["OrderInvoiceSendPayload",{"email":"EmailInput","id":"ID!"}],"orderMarkAsPaid":["OrderMarkAsPaidPayload",{"input":"OrderMarkAsPaidInput!"}],"orderOpen":["OrderOpenPayload",{"input":"OrderOpenInput!"}],"orderRiskAssessmentCreate":["OrderRiskAssessmentCreatePayload",{"orderRiskAssessmentInput":"OrderRiskAssessmentCreateInput!"}],"orderUpdate":["OrderUpdatePayload",{"input":"OrderInput!"}],"pageCreate":["PageCreatePayload",{"page":"PageCreateInput!"}],"pageDelete":["PageDeletePayload",{"id":"ID!"}],"pageUpdate":["PageUpdatePayload",{"id":"ID!","page":"PageUpdateInput!"}],"paymentCustomizationActivation":["PaymentCustomizationActivationPayload",{"enabled":"Boolean!","ids":"[ID!]!"}],"paymentCustomizationCreate":["PaymentCustomizationCreatePayload",{"paymentCustomization":"PaymentCustomizationInput!"}],"paymentCustomizationDelete":["PaymentCustomizationDeletePayload",{"id":"ID!"}],"paymentCustomizationUpdate":["PaymentCustomizationUpdatePayload",{"id":"ID!","paymentCustomization":"PaymentCustomizationInput!"}],"paymentInstrumentSendAddEmail":["PaymentInstrumentSendAddEmailPayload",{"email":"EmailInput","mandate":"PaymentInstrumentMandateInput!"}],"paymentReminderSend":["PaymentReminderSendPayload",{"paymentScheduleId":"ID!"}],"paymentScheduleCapture":["PaymentScheduleCapturePayload",{"paymentScheduleId":"ID!"}],"paymentTermsCreate":["PaymentTermsCreatePayload",{"paymentTermsAttributes":"PaymentTermsCreateInput!","referenceId":"ID!"}],"paymentTermsDelete":["PaymentTermsDeletePayload",{"input":"PaymentTermsDeleteInput!"}],"paymentTermsUpdate":["PaymentTermsUpdatePayload",{"input":"PaymentTermsUpdateInput!"}],"pointOfSaleDeviceAssignToCashDrawer":["PointOfSaleDeviceAssignToCashDrawerPayload",{"cashDrawerId":"ID!","pointOfSaleDeviceId":"ID!"}],"pointOfSaleDevicePaymentSessionAdjust":["PointOfSaleDevicePaymentSessionAdjustPayload",{"cash":"MoneyInput!","note":"String","pointOfSaleDevicePaymentSessionId":"ID!","reasonCodeId":"ID","staffMemberId":"ID!","time":"DateTime"}],"pointOfSaleDevicePaymentSessionClose":["PointOfSaleDevicePaymentSessionClosePayload",{"balance":"MoneyInput!","note":"String","pointOfSaleDevicePaymentSessionId":"ID!","reasonCodeId":"ID","staffMemberId":"ID!","time":"DateTime"}],"pointOfSaleDevicePaymentSessionCount":["PointOfSaleDevicePaymentSessionCountPayload",{"balance":"MoneyInput!","note":"String","pointOfSaleDevicePaymentSessionId":"ID!","reasonCodeId":"ID","staffMemberId":"ID!","time":"DateTime"}],"pointOfSaleDevicePaymentSessionOpen":["PointOfSaleDevicePaymentSessionOpenPayload",{"balance":"MoneyInput","note":"String","pointOfSaleDeviceId":"ID!","reasonCodeId":"ID","staffMemberId":"ID!","time":"DateTime"}],"previewInstall":["PreviewInstallPayload",{"storefrontGenerationPreviewUuid":"String!"}],"priceListCreate":["PriceListCreatePayload",{"input":"PriceListCreateInput!"}],"priceListDelete":["PriceListDeletePayload",{"id":"ID!"}],"priceListFixedPricesAdd":["PriceListFixedPricesAddPayload",{"priceListId":"ID!","prices":"[PriceListPriceInput!]!"}],"priceListFixedPricesByProductUpdate":["PriceListFixedPricesByProductUpdatePayload",{"priceListId":"ID!","pricesToAdd":"[PriceListProductPriceInput!]","pricesToDeleteByProductIds":"[ID!]"}],"priceListFixedPricesDelete":["PriceListFixedPricesDeletePayload",{"priceListId":"ID!","variantIds":"[ID!]!"}],"priceListFixedPricesUpdate":["PriceListFixedPricesUpdatePayload",{"priceListId":"ID!","pricesToAdd":"[PriceListPriceInput!]!","variantIdsToDelete":"[ID!]!"}],"priceListUpdate":["PriceListUpdatePayload",{"id":"ID!","input":"PriceListUpdateInput!"}],"privacyFeaturesDisable":["PrivacyFeaturesDisablePayload",{"featuresToDisable":"[PrivacyFeaturesEnum!]!"}],"productBundleCreate":["ProductBundleCreatePayload",{"input":"ProductBundleCreateInput!"}],"productBundleUpdate":["ProductBundleUpdatePayload",{"input":"ProductBundleUpdateInput!"}],"productChangeStatus":["ProductChangeStatusPayload",{"productId":"ID!","status":"ProductStatus!"}],"productCreate":["ProductCreatePayload",{"input":"ProductInput","media":"[CreateMediaInput!]","product":"ProductCreateInput"}],"productCreateMedia":["ProductCreateMediaPayload",{"media":"[CreateMediaInput!]!","productId":"ID!"}],"productDelete":["ProductDeletePayload",{"input":"ProductDeleteInput!","synchronous":"Boolean="}],"productDeleteMedia":["ProductDeleteMediaPayload",{"mediaIds":"[ID!]!","productId":"ID!"}],"productDuplicate":["ProductDuplicatePayload",{"includeImages":"Boolean=","includeTranslations":"Boolean=","newStatus":"ProductStatus","newTitle":"String!","productId":"ID!","synchronous":"Boolean="}],"productFeedCreate":["ProductFeedCreatePayload",{"input":"ProductFeedInput"}],"productFeedDelete":["ProductFeedDeletePayload",{"id":"ID!"}],"productFullSync":["ProductFullSyncPayload",{"beforeUpdatedAt":"DateTime","id":"ID!","updatedAtSince":"DateTime"}],"productJoinSellingPlanGroups":["ProductJoinSellingPlanGroupsPayload",{"id":"ID!","sellingPlanGroupIds":"[ID!]!"}],"productLeaveSellingPlanGroups":["ProductLeaveSellingPlanGroupsPayload",{"id":"ID!","sellingPlanGroupIds":"[ID!]!"}],"productOptionUpdate":["ProductOptionUpdatePayload",{"option":"OptionUpdateInput!","optionValuesToAdd":"[OptionValueCreateInput!]","optionValuesToDelete":"[ID!]","optionValuesToUpdate":"[OptionValueUpdateInput!]","productId":"ID!","variantStrategy":"ProductOptionUpdateVariantStrategy"}],"productOptionsCreate":["ProductOptionsCreatePayload",{"options":"[OptionCreateInput!]!","productId":"ID!","variantStrategy":"ProductOptionCreateVariantStrategy="}],"productOptionsDelete":["ProductOptionsDeletePayload",{"options":"[ID!]!","productId":"ID!","strategy":"ProductOptionDeleteStrategy="}],"productOptionsReorder":["ProductOptionsReorderPayload",{"options":"[OptionReorderInput!]!","productId":"ID!"}],"productPublish":["ProductPublishPayload",{"input":"ProductPublishInput!"}],"productReorderMedia":["ProductReorderMediaPayload",{"id":"ID!","moves":"[MoveInput!]!"}],"productSet":["ProductSetPayload",{"identifier":"ProductSetIdentifiers","input":"ProductSetInput!","synchronous":"Boolean="}],"productUnpublish":["ProductUnpublishPayload",{"input":"ProductUnpublishInput!"}],"productUpdate":["ProductUpdatePayload",{"identifier":"ProductUpdateIdentifiers","input":"ProductInput","media":"[CreateMediaInput!]","product":"ProductUpdateInput"}],"productUpdateMedia":["ProductUpdateMediaPayload",{"media":"[UpdateMediaInput!]!","productId":"ID!"}],"productVariantAppendMedia":["ProductVariantAppendMediaPayload",{"productId":"ID!","variantMedia":"[ProductVariantAppendMediaInput!]!"}],"productVariantDetachMedia":["ProductVariantDetachMediaPayload",{"productId":"ID!","variantMedia":"[ProductVariantDetachMediaInput!]!"}],"productVariantJoinSellingPlanGroups":["ProductVariantJoinSellingPlanGroupsPayload",{"id":"ID!","sellingPlanGroupIds":"[ID!]!"}],"productVariantLeaveSellingPlanGroups":["ProductVariantLeaveSellingPlanGroupsPayload",{"id":"ID!","sellingPlanGroupIds":"[ID!]!"}],"productVariantRelationshipBulkUpdate":["ProductVariantRelationshipBulkUpdatePayload",{"input":"[ProductVariantRelationshipUpdateInput!]!"}],"productVariantsBulkCreate":["ProductVariantsBulkCreatePayload",{"media":"[CreateMediaInput!]","productId":"ID!","strategy":"ProductVariantsBulkCreateStrategy=","variants":"[ProductVariantsBulkInput!]!"}],"productVariantsBulkDelete":["ProductVariantsBulkDeletePayload",{"productId":"ID!","variantsIds":"[ID!]!"}],"productVariantsBulkReorder":["ProductVariantsBulkReorderPayload",{"positions":"[ProductVariantPositionInput!]!","productId":"ID!"}],"productVariantsBulkUpdate":["ProductVariantsBulkUpdatePayload",{"allowPartialUpdates":"Boolean=","media":"[CreateMediaInput!]","productId":"ID!","variants":"[ProductVariantsBulkInput!]!"}],"pubSubServerPixelUpdate":["PubSubServerPixelUpdatePayload",{"pubSubProject":"String!","pubSubTopic":"String!"}],"pubSubWebhookSubscriptionCreate":["PubSubWebhookSubscriptionCreatePayload",{"topic":"WebhookSubscriptionTopic!","webhookSubscription":"PubSubWebhookSubscriptionInput!"}],"pubSubWebhookSubscriptionUpdate":["PubSubWebhookSubscriptionUpdatePayload",{"id":"ID!","webhookSubscription":"PubSubWebhookSubscriptionInput!"}],"publicationCreate":["PublicationCreatePayload",{"input":"PublicationCreateInput!"}],"publicationDelete":["PublicationDeletePayload",{"id":"ID!"}],"publicationUpdate":["PublicationUpdatePayload",{"id":"ID!","input":"PublicationUpdateInput!"}],"publishablePublish":["PublishablePublishPayload",{"id":"ID!","input":"[PublicationInput!]!"}],"publishablePublishToCurrentChannel":["PublishablePublishToCurrentChannelPayload",{"id":"ID!"}],"publishableUnpublish":["PublishableUnpublishPayload",{"id":"ID!","input":"[PublicationInput!]!"}],"publishableUnpublishToCurrentChannel":["PublishableUnpublishToCurrentChannelPayload",{"id":"ID!"}],"quantityPricingByVariantUpdate":["QuantityPricingByVariantUpdatePayload",{"input":"QuantityPricingByVariantUpdateInput!","priceListId":"ID!"}],"quantityRulesAdd":["QuantityRulesAddPayload",{"priceListId":"ID!","quantityRules":"[QuantityRuleInput!]!"}],"quantityRulesDelete":["QuantityRulesDeletePayload",{"priceListId":"ID!","variantIds":"[ID!]!"}],"refundCreate":["RefundCreatePayload",{"input":"RefundInput!"}],"removeFromReturn":["RemoveFromReturnPayload",{"exchangeLineItems":"[ExchangeLineItemRemoveFromReturnInput!]","returnId":"ID!","returnLineItems":"[ReturnLineItemRemoveFromReturnInput!]"}],"requestedOrderEditCreate":["RequestedOrderEditCreatePayload",{"input":"RequestedOrderEditCreateInput!"}],"requestedOrderEditDecline":["RequestedOrderEditDeclinePayload",{"input":"RequestedOrderEditDeclineInput!"}],"requestedOrderEditResolve":["RequestedOrderEditResolvePayload",{"input":"RequestedOrderEditResolveInput!"}],"returnApproveRequest":["ReturnApproveRequestPayload",{"input":"ReturnApproveRequestInput!"}],"returnCancel":["ReturnCancelPayload",{"id":"ID!","notifyCustomer":"Boolean="}],"returnClose":["ReturnClosePayload",{"id":"ID!"}],"returnCreate":["ReturnCreatePayload",{"returnInput":"ReturnInput!"}],"returnDeclineRequest":["ReturnDeclineRequestPayload",{"input":"ReturnDeclineRequestInput!"}],"returnLineItemRemoveFromReturn":["ReturnLineItemRemoveFromReturnPayload",{"returnId":"ID!","returnLineItems":"[ReturnLineItemRemoveFromReturnInput!]!"}],"returnProcess":["ReturnProcessPayload",{"input":"ReturnProcessInput!"}],"returnRefund":["ReturnRefundPayload",{"returnRefundInput":"ReturnRefundInput!"}],"returnReopen":["ReturnReopenPayload",{"id":"ID!"}],"returnRequest":["ReturnRequestPayload",{"input":"ReturnRequestInput!"}],"reverseDeliveryCreateWithShipping":["ReverseDeliveryCreateWithShippingPayload",{"labelInput":"ReverseDeliveryLabelInput=","notifyCustomer":"Boolean=","reverseDeliveryLineItems":"[ReverseDeliveryLineItemInput!]!","reverseFulfillmentOrderId":"ID!","trackingInput":"ReverseDeliveryTrackingInput="}],"reverseDeliveryShippingUpdate":["ReverseDeliveryShippingUpdatePayload",{"labelInput":"ReverseDeliveryLabelInput=","notifyCustomer":"Boolean=","reverseDeliveryId":"ID!","trackingInput":"ReverseDeliveryTrackingInput="}],"reverseFulfillmentOrderDispose":["ReverseFulfillmentOrderDisposePayload",{"dispositionInputs":"[ReverseFulfillmentOrderDisposeInput!]!"}],"savedSearchCreate":["SavedSearchCreatePayload",{"input":"SavedSearchCreateInput!"}],"savedSearchDelete":["SavedSearchDeletePayload",{"input":"SavedSearchDeleteInput!"}],"savedSearchUpdate":["SavedSearchUpdatePayload",{"input":"SavedSearchUpdateInput!"}],"scriptTagCreate":["ScriptTagCreatePayload",{"input":"ScriptTagInput!"}],"scriptTagDelete":["ScriptTagDeletePayload",{"id":"ID!"}],"scriptTagUpdate":["ScriptTagUpdatePayload",{"id":"ID!","input":"ScriptTagInput!"}],"segmentCreate":["SegmentCreatePayload",{"name":"String!","query":"String!"}],"segmentDelete":["SegmentDeletePayload",{"id":"ID!"}],"segmentUpdate":["SegmentUpdatePayload",{"id":"ID!","name":"String","query":"String"}],"sellingPlanGroupAddProductVariants":["SellingPlanGroupAddProductVariantsPayload",{"id":"ID!","productVariantIds":"[ID!]!"}],"sellingPlanGroupAddProducts":["SellingPlanGroupAddProductsPayload",{"id":"ID!","productIds":"[ID!]!"}],"sellingPlanGroupCreate":["SellingPlanGroupCreatePayload",{"input":"SellingPlanGroupInput!","resources":"SellingPlanGroupResourceInput"}],"sellingPlanGroupDelete":["SellingPlanGroupDeletePayload",{"id":"ID!"}],"sellingPlanGroupRemoveProductVariants":["SellingPlanGroupRemoveProductVariantsPayload",{"id":"ID!","productVariantIds":"[ID!]!"}],"sellingPlanGroupRemoveProducts":["SellingPlanGroupRemoveProductsPayload",{"id":"ID!","productIds":"[ID!]!"}],"sellingPlanGroupUpdate":["SellingPlanGroupUpdatePayload",{"id":"ID!","input":"SellingPlanGroupInput!"}],"serverPixelCreate":"ServerPixelCreatePayload","serverPixelDelete":"ServerPixelDeletePayload","shippingLabelPurchase":["ShippingLabelPurchasePayload",{"shippingLabelPurchase":"ShippingLabelPurchaseInput!"}],"shippingPackageDelete":["ShippingPackageDeletePayload",{"id":"ID!"}],"shippingPackageMakeDefault":["ShippingPackageMakeDefaultPayload",{"id":"ID!"}],"shippingPackageUpdate":["ShippingPackageUpdatePayload",{"id":"ID!","shippingPackage":"CustomShippingPackageInput!"}],"shopLocaleDisable":["ShopLocaleDisablePayload",{"locale":"String!"}],"shopLocaleEnable":["ShopLocaleEnablePayload",{"locale":"String!","marketWebPresenceIds":"[ID!]"}],"shopLocaleUpdate":["ShopLocaleUpdatePayload",{"locale":"String!","shopLocale":"ShopLocaleInput!"}],"shopPolicyUpdate":["ShopPolicyUpdatePayload",{"shopPolicy":"ShopPolicyInput!"}],"shopResourceFeedbackCreate":["ShopResourceFeedbackCreatePayload",{"input":"ResourceFeedbackCreateInput!"}],"shopifyPaymentsPayoutAlternateCurrencyCreate":["ShopifyPaymentsPayoutAlternateCurrencyCreatePayload",{"accountId":"ID","currency":"CurrencyCode!"}],"stagedUploadTargetGenerate":["StagedUploadTargetGeneratePayload",{"input":"StagedUploadTargetGenerateInput!"}],"stagedUploadTargetsGenerate":["StagedUploadTargetsGeneratePayload",{"input":"[StageImageInput!]!"}],"stagedUploadsCreate":["StagedUploadsCreatePayload",{"input":"[StagedUploadInput!]!"}],"standardMetafieldDefinitionEnable":["StandardMetafieldDefinitionEnablePayload",{"access":"StandardMetafieldDefinitionAccessInput","capabilities":"MetafieldCapabilityCreateInput","id":"ID","key":"String","namespace":"String","ownerType":"MetafieldOwnerType!","pin":"Boolean=","useAsCollectionCondition":"Boolean=","visibleToStorefrontApi":"Boolean="}],"standardMetaobjectDefinitionEnable":["StandardMetaobjectDefinitionEnablePayload",{"type":"String!"}],"storeCreditAccountCredit":["StoreCreditAccountCreditPayload",{"creditInput":"StoreCreditAccountCreditInput!","id":"ID!"}],"storeCreditAccountDebit":["StoreCreditAccountDebitPayload",{"debitInput":"StoreCreditAccountDebitInput!","id":"ID!"}],"storefrontAccessTokenCreate":["StorefrontAccessTokenCreatePayload",{"input":"StorefrontAccessTokenInput!"}],"storefrontAccessTokenDelete":["StorefrontAccessTokenDeletePayload",{"input":"StorefrontAccessTokenDeleteInput!"}],"subscriptionBillingAttemptCreate":["SubscriptionBillingAttemptCreatePayload",{"subscriptionBillingAttemptInput":"SubscriptionBillingAttemptInput!","subscriptionContractId":"ID!"}],"subscriptionBillingCycleBulkCharge":["SubscriptionBillingCycleBulkChargePayload",{"actor":"SubscriptionActor","billingAttemptExpectedDateRange":"SubscriptionBillingCyclesDateRangeSelector!","filters":"SubscriptionBillingCycleBulkFilters","inventoryPolicy":"SubscriptionBillingAttemptInventoryPolicy=","paymentProcessingPolicy":"SubscriptionBillingAttemptPaymentProcessingPolicy="}],"subscriptionBillingCycleBulkSearch":["SubscriptionBillingCycleBulkSearchPayload",{"billingAttemptExpectedDateRange":"SubscriptionBillingCyclesDateRangeSelector!","filters":"SubscriptionBillingCycleBulkFilters"}],"subscriptionBillingCycleCharge":["SubscriptionBillingCycleChargePayload",{"actor":"SubscriptionActor","billingCycleSelector":"SubscriptionBillingCycleSelector!","inventoryPolicy":"SubscriptionBillingAttemptInventoryPolicy=","paymentProcessingPolicy":"SubscriptionBillingAttemptPaymentProcessingPolicy","subscriptionContractId":"ID!"}],"subscriptionBillingCycleContractDraftCommit":["SubscriptionBillingCycleContractDraftCommitPayload",{"draftId":"ID!"}],"subscriptionBillingCycleContractDraftConcatenate":["SubscriptionBillingCycleContractDraftConcatenatePayload",{"concatenatedBillingCycleContracts":"[SubscriptionBillingCycleInput!]!","draftId":"ID!"}],"subscriptionBillingCycleContractEdit":["SubscriptionBillingCycleContractEditPayload",{"actor":"SubscriptionActor","billingCycleInput":"SubscriptionBillingCycleInput!"}],"subscriptionBillingCycleContractEditCalculate":["SubscriptionBillingCycleContractEditCalculatePayload",{"actor":"SubscriptionActor","billingCycleEditInput":"SubscriptionContractCalculationBillingCycleEditInput!","billingCycleSelector":"SubscriptionBillingCycleSelector!","contractId":"ID!"}],"subscriptionBillingCycleEditDelete":["SubscriptionBillingCycleEditDeletePayload",{"billingCycleInput":"SubscriptionBillingCycleInput!"}],"subscriptionBillingCycleEditsDelete":["SubscriptionBillingCycleEditsDeletePayload",{"contractId":"ID!","targetSelection":"SubscriptionBillingCyclesTargetSelection!"}],"subscriptionBillingCycleScheduleEdit":["SubscriptionBillingCycleScheduleEditPayload",{"billingCycleInput":"SubscriptionBillingCycleInput!","input":"SubscriptionBillingCycleScheduleEditInput!"}],"subscriptionBillingCycleSkip":["SubscriptionBillingCycleSkipPayload",{"billingCycleInput":"SubscriptionBillingCycleInput!"}],"subscriptionBillingCycleUnskip":["SubscriptionBillingCycleUnskipPayload",{"billingCycleInput":"SubscriptionBillingCycleInput!"}],"subscriptionContractActivate":["SubscriptionContractActivatePayload",{"actor":"SubscriptionActor","subscriptionContractId":"ID!"}],"subscriptionContractAtomicCreate":["SubscriptionContractAtomicCreatePayload",{"input":"SubscriptionContractAtomicCreateInput!"}],"subscriptionContractCalculationCommit":["SubscriptionContractCalculationCommitPayload",{"id":"ID!"}],"subscriptionContractCancel":["SubscriptionContractCancelPayload",{"actor":"SubscriptionActor","subscriptionContractId":"ID!"}],"subscriptionContractCreate":["SubscriptionContractCreatePayload",{"input":"SubscriptionContractCreateInput!"}],"subscriptionContractCreateCalculate":["SubscriptionContractCreateCalculatePayload",{"contractCreateInput":"SubscriptionContractCalculationContractCreateInput!"}],"subscriptionContractExpire":["SubscriptionContractExpirePayload",{"actor":"SubscriptionActor","subscriptionContractId":"ID!"}],"subscriptionContractFail":["SubscriptionContractFailPayload",{"actor":"SubscriptionActor","subscriptionContractId":"ID!"}],"subscriptionContractPause":["SubscriptionContractPausePayload",{"actor":"SubscriptionActor","subscriptionContractId":"ID!"}],"subscriptionContractProductChange":["SubscriptionContractProductChangePayload",{"actor":"SubscriptionActor","input":"SubscriptionContractProductChangeInput!","lineId":"ID!","subscriptionContractId":"ID!"}],"subscriptionContractSetNextBillingDate":["SubscriptionContractSetNextBillingDatePayload",{"contractId":"ID!","date":"DateTime!"}],"subscriptionContractUpdate":["SubscriptionContractUpdatePayload",{"actor":"SubscriptionActor","contractId":"ID!"}],"subscriptionContractUpdateCalculate":["SubscriptionContractUpdateCalculatePayload",{"actor":"SubscriptionActor","contractId":"ID!","contractUpdateInput":"SubscriptionContractCalculationContractUpdateInput!"}],"subscriptionDraftCommit":["SubscriptionDraftCommitPayload",{"draftId":"ID!"}],"subscriptionDraftDiscountAdd":["SubscriptionDraftDiscountAddPayload",{"draftId":"ID!","input":"SubscriptionManualDiscountInput!"}],"subscriptionDraftDiscountCodeApply":["SubscriptionDraftDiscountCodeApplyPayload",{"draftId":"ID!","redeemCode":"String!"}],"subscriptionDraftDiscountRemove":["SubscriptionDraftDiscountRemovePayload",{"discountId":"ID!","draftId":"ID!"}],"subscriptionDraftDiscountUpdate":["SubscriptionDraftDiscountUpdatePayload",{"discountId":"ID!","draftId":"ID!","input":"SubscriptionManualDiscountInput!"}],"subscriptionDraftFreeShippingDiscountAdd":["SubscriptionDraftFreeShippingDiscountAddPayload",{"draftId":"ID!","input":"SubscriptionFreeShippingDiscountInput!"}],"subscriptionDraftFreeShippingDiscountUpdate":["SubscriptionDraftFreeShippingDiscountUpdatePayload",{"discountId":"ID!","draftId":"ID!","input":"SubscriptionFreeShippingDiscountInput!"}],"subscriptionDraftLineAdd":["SubscriptionDraftLineAddPayload",{"draftId":"ID!","input":"SubscriptionLineInput!"}],"subscriptionDraftLineRemove":["SubscriptionDraftLineRemovePayload",{"draftId":"ID!","lineId":"ID!"}],"subscriptionDraftLineUpdate":["SubscriptionDraftLineUpdatePayload",{"draftId":"ID!","input":"SubscriptionLineUpdateInput!","lineId":"ID!"}],"subscriptionDraftUpdate":["SubscriptionDraftUpdatePayload",{"draftId":"ID!","input":"SubscriptionDraftInput!"}],"tagsAdd":["TagsAddPayload",{"id":"ID!","tags":"[String!]!"}],"tagsRemove":["TagsRemovePayload",{"id":"ID!","tags":"[String!]!"}],"taxAppConfigure":["TaxAppConfigurePayload",{"ready":"Boolean!"}],"taxSummaryCreate":["TaxSummaryCreatePayload",{"endTime":"DateTime","orderId":"ID","startTime":"DateTime"}],"themeCreate":["ThemeCreatePayload",{"name":"String","role":"ThemeRole=","source":"URL!"}],"themeDelete":["ThemeDeletePayload",{"id":"ID!"}],"themeDuplicate":["ThemeDuplicatePayload",{"id":"ID!","name":"String"}],"themeFilesCopy":["ThemeFilesCopyPayload",{"files":"[ThemeFilesCopyFileInput!]!","themeId":"ID!"}],"themeFilesDelete":["ThemeFilesDeletePayload",{"files":"[String!]!","themeId":"ID!"}],"themeFilesUpsert":["ThemeFilesUpsertPayload",{"files":"[OnlineStoreThemeFilesUpsertFileInput!]!","themeId":"ID!"}],"themePublish":["ThemePublishPayload",{"id":"ID!"}],"themeUpdate":["ThemeUpdatePayload",{"id":"ID!","input":"OnlineStoreThemeInput!"}],"transactionVoid":["TransactionVoidPayload",{"parentTransactionId":"ID!"}],"translationsRegister":["TranslationsRegisterPayload",{"resourceId":"ID!","translations":"[TranslationInput!]!"}],"translationsRemove":["TranslationsRemovePayload",{"locales":"[String!]!","marketIds":"[ID!]","resourceId":"ID!","translationKeys":"[String!]!"}],"urlRedirectBulkDeleteAll":"UrlRedirectBulkDeleteAllPayload","urlRedirectBulkDeleteByIds":["UrlRedirectBulkDeleteByIdsPayload",{"ids":"[ID!]!"}],"urlRedirectBulkDeleteBySavedSearch":["UrlRedirectBulkDeleteBySavedSearchPayload",{"savedSearchId":"ID!"}],"urlRedirectBulkDeleteBySearch":["UrlRedirectBulkDeleteBySearchPayload",{"search":"String!"}],"urlRedirectCreate":["UrlRedirectCreatePayload",{"urlRedirect":"UrlRedirectInput!"}],"urlRedirectDelete":["UrlRedirectDeletePayload",{"id":"ID!"}],"urlRedirectImportCreate":["UrlRedirectImportCreatePayload",{"url":"URL!"}],"urlRedirectImportSubmit":["UrlRedirectImportSubmitPayload",{"id":"ID!"}],"urlRedirectUpdate":["UrlRedirectUpdatePayload",{"id":"ID!","urlRedirect":"UrlRedirectInput!"}],"validationCreate":["ValidationCreatePayload",{"validation":"ValidationCreateInput!"}],"validationDelete":["ValidationDeletePayload",{"id":"ID!"}],"validationUpdate":["ValidationUpdatePayload",{"id":"ID!","validation":"ValidationUpdateInput!"}],"webPixelCreate":["WebPixelCreatePayload",{"webPixel":"WebPixelInput!"}],"webPixelDelete":["WebPixelDeletePayload",{"id":"ID!"}],"webPixelUpdate":["WebPixelUpdatePayload",{"id":"ID!","webPixel":"WebPixelInput!"}],"webPresenceCreate":["WebPresenceCreatePayload",{"input":"WebPresenceCreateInput!"}],"webPresenceDelete":["WebPresenceDeletePayload",{"id":"ID!"}],"webPresenceUpdate":["WebPresenceUpdatePayload",{"id":"ID!","input":"WebPresenceUpdateInput!"}],"webhookSubscriptionCreate":["WebhookSubscriptionCreatePayload",{"topic":"WebhookSubscriptionTopic!","webhookSubscription":"WebhookSubscriptionInput!"}],"webhookSubscriptionDelete":["WebhookSubscriptionDeletePayload",{"id":"ID!"}],"webhookSubscriptionUpdate":["WebhookSubscriptionUpdatePayload",{"id":"ID!","webhookSubscription":"WebhookSubscriptionInput!"}]},"d":{"abandonmentEmailStateUpdate":"Use `abandonmentUpdateActivitiesDeliveryStatuses` instead.","bulkOperationRunMutation(groupObjects)":"This argument has no effect on output order.","cartTransformCreate(functionId)":"Use `functionHandle` instead.","checkoutBrandingUpsert":"Use `checkoutAndAccountsConfigurationUpdate` instead.","collectionAddProducts":"Use `collectionUpdate` with inclusion.selectionsToAdd instead.","collectionAddProductsV2":"Use `collectionUpdate` with inclusion.selectionsToAdd instead.","collectionCreate(input)":"Use `collection` instead.","collectionPublish":"Use `publishablePublish` instead.","collectionRemoveProducts":"Use `collectionUpdate` with inclusions.selectionsToRemove instead.","collectionUnpublish":"Use `publishableUnpublish` instead.","collectionUpdate(input)":"This argument does not support new collection model features, such as multiple sources. Use `collection` to ensure compatibility with all collections.","companyLocationAssignTaxExemptions":"Use `companyLocationTaxSettingsUpdate` instead.","companyLocationCreateTaxRegistration":"Use `companyLocationTaxSettingsUpdate` instead.","companyLocationRevokeTaxExemptions":"Use `companyLocationTaxSettingsUpdate` instead.","companyLocationRevokeTaxRegistration":"Use `companyLocationTaxSettingsUpdate` instead.","deliveryShippingOriginAssign":"Single origin shipping mode is no longer supported.","draftOrderComplete(paymentPending)":"Create a draft with payment terms rather than marking the draft as pending.","draftOrderDuplicate(draftOrderId)":"Use `id` instead.","eventBridgeWebhookSubscriptionCreate":"Use `webhookSubscriptionCreate` instead.","eventBridgeWebhookSubscriptionUpdate":"Use `webhookSubscriptionUpdate` instead.","flowTriggerReceive(body)":"Use `payload` and `handle` to execute your Flow trigger.","fulfillmentConstraintRuleCreate(functionId)":"Use `functionHandle` instead.","fulfillmentCreateV2":"Use `fulfillmentCreate` instead.","fulfillmentServiceCreate(fulfillmentOrdersOptIn)":"Migration period ended. Defaults to `true`.","fulfillmentServiceUpdate(fulfillmentOrdersOptIn)":"Migration period has ended.","fulfillmentTrackingInfoUpdateV2":"Use `fulfillmentTrackingInfoUpdate` instead.","inventoryActivate(stockAtLegacyLocation)":"All fulfillment services now permit SKU sharing, so activation no longer depends on this argument. It's ignored and has no effect; stop passing it.","inventorySetOnHandQuantities":"Use `inventorySetQuantities` to set on_hand or available quantites instead.","marketCurrencySettingsUpdate":"Use `marketCreate` and `marketUpdate` for creating and updating\nmarket currency settings, respectively. Removed in API version 2027-01.","marketRegionDelete":"Use `marketUpdate` instead.","marketRegionsCreate":"This mutation is deprecated and will be removed in the future. Use `marketCreate` or `marketUpdate` instead.","marketRegionsDelete":"Use `marketUpdate` instead.","marketWebPresenceCreate":"Use `webPresenceCreate` instead.","marketWebPresenceDelete":"Use `webPresenceDelete` instead.","marketWebPresenceUpdate":"Use `webPresenceUpdate` instead.","marketingActivityCreateExternal":"Use `marketingActivityUpsertExternal` instead.","marketingEngagementCreate(channelHandle)":"Channel-level engagements are deprecated. Provide engagement metrics on a marketing activity using `marketingActivityId` or `remoteId` instead.","marketingEngagementsDelete":"Channel-level engagements are deprecated. Activity-level engagement data cannot be deleted directly; delete the MarketingActivity instead.","marketingEngagementsDelete(channelHandle)":"Channel-level engagements are deprecated. Activity-level engagement data cannot be deleted directly; delete the MarketingActivity instead.","marketingEngagementsDelete(deleteEngagementsForAllChannels)":"Channel-level engagements are deprecated. Activity-level engagement data cannot be deleted directly; delete the MarketingActivity instead.","orderCancel(refund)":"Use `refundMethod` instead.","orderEditRemoveLineItemDiscount":"Use `orderEditRemoveDiscount` instead.","orderEditSetQuantity(locationId)":"No longer supported.","productChangeStatus":"Use `productUpdate` instead.","productCreate(input)":"Use `product` instead.","productCreateMedia":"Use `productUpdate` or `productSet` instead.","productDeleteMedia":"Use `fileUpdate` instead.","productPublish":"Use `publishablePublish` instead.","productUnpublish":"Use `publishableUnpublish` instead.","productUpdate(input)":"Use `product` instead.","productUpdateMedia":"Use `fileUpdate` instead.","pubSubWebhookSubscriptionCreate":"Use `webhookSubscriptionCreate` instead.","pubSubWebhookSubscriptionUpdate":"Use `webhookSubscriptionUpdate` instead.","publishablePublishToCurrentChannel":"Use `publishablePublish` instead.","publishableUnpublishToCurrentChannel":"Use `publishableUnpublish` instead.","returnCancel(notifyCustomer)":"Not supported. This argument will be removed in a future version.","returnLineItemRemoveFromReturn":"Use `removeFromReturn` instead.","returnRefund":"Use `returnProcess` instead.","stagedUploadTargetGenerate":"Use `stagedUploadsCreate` instead.","stagedUploadTargetsGenerate":"Use `stagedUploadsCreate` instead.","standardMetafieldDefinitionEnable(useAsCollectionCondition)":"Use `capabilities.smartCollectionCondition` instead.","standardMetafieldDefinitionEnable(visibleToStorefrontApi)":"Use `access.storefront` instead.","subscriptionContractCreate":"Use [`subscriptionContractCreateCalculate`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/subscriptionContractCreateCalculate) instead.","subscriptionContractUpdate":"Use [`subscriptionContractUpdateCalculate`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/subscriptionContractUpdateCalculate) instead.","subscriptionDraftCommit":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftDiscountAdd":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftDiscountCodeApply":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftDiscountRemove":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftDiscountUpdate":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftFreeShippingDiscountAdd":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftFreeShippingDiscountUpdate":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftLineAdd":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftLineRemove":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftLineUpdate":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftUpdate":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead."}}}, +"MutationsStagedUploadTargetGenerateUploadParameter":{"o":{"f":{"name":"String!","value":"String!"}}}, +"Navigable":{"n":{"f":{"defaultCursor":"String!"},"t":["AbandonedCheckout","Article","Company","CompanyLocation","CustomerAccountAppExtensionPage","CustomerAccountNativePage","DraftOrder","Page","Product","ProductVariant"]}}, +"NavigationItem":{"o":{"f":{"id":"String!","title":"String!","url":"URL!"}}}, +"Node":{"n":{"f":{"id":"ID!"},"t":["AbandonedCheckout","AbandonedCheckoutLineItem","Abandonment","AddAllProductsOperation","AdditionalFee","AnalyticsAnnotation","AnalyticsTarget","App","AppCatalog","AppCredit","AppInstallation","AppPurchaseOneTime","AppRevenueAttributionRecord","AppSubscription","AppUsageRecord","Article","BasicEvent","Blog","BulkOperation","BusinessEntity","CalculatedOrder","CartTransform","CashDrawer","CashManagementCustomReasonCode","CashManagementDefaultReasonCode","CashManagementSystemReasonCode","CashTrackingAdjustment","CashTrackingSession","CatalogCsvOperation","Channel","ChannelDefinition","ChannelInformation","CheckoutAndAccountsConfiguration","CheckoutAndAccountsConfigurationOverride","CheckoutProfile","Collection","CollectionConditionsSource","CollectionSubCollectionsSource","Comment","CommentEvent","Company","CompanyAddress","CompanyContact","CompanyContactRole","CompanyContactRoleAssignment","CompanyLocation","CompanyLocationCatalog","CompanyLocationStaffMemberAssignment","ConsentPolicy","CurrencyExchangeAdjustment","Customer","CustomerAccountAppExtensionPage","CustomerAccountNativePage","CustomerPaymentMethod","CustomerSegmentMembersQuery","CustomerVisit","DeliveryCarrierService","DeliveryCondition","DeliveryCountry","DeliveryCustomization","DeliveryLocationGroup","DeliveryMethod","DeliveryMethodDefinition","DeliveryParticipant","DeliveryProfile","DeliveryProfileItem","DeliveryPromiseParticipant","DeliveryPromiseProvider","DeliveryProvince","DeliveryRateDefinition","DeliveryZone","DiscountAutomaticBxgy","DiscountAutomaticNode","DiscountCodeNode","DiscountNode","DiscountRedeemCodeBulkCreation","Domain","DraftOrder","DraftOrderLineItem","DraftOrderTag","Duty","ExchangeLineItem","ExchangeV2","ExternalVideo","Fulfillment","FulfillmentConstraintRule","FulfillmentEvent","FulfillmentHold","FulfillmentLineItem","FulfillmentOrder","FulfillmentOrderDestination","FulfillmentOrderLineItem","FulfillmentOrderMerchantRequest","GenericFile","GiftCard","GiftCardCashOutTransaction","GiftCardCreditTransaction","GiftCardDebitTransaction","IdentityProviderSubject","InventoryAdjustmentGroup","InventoryItem","InventoryItemMeasurement","InventoryLevel","InventoryPurchaseOrder","InventoryPurchaseOrderLineItem","InventoryQuantity","InventoryShipment","InventoryShipmentLineItem","InventoryTransfer","InventoryTransferLineItem","LineItem","LineItemGroup","Location","MailingAddress","Market","MarketCatalog","MarketRegionCountry","MarketRegionSubdivision","MarketRelationship","MarketWebPresence","MarketingActivity","MarketingEvent","MediaImage","Menu","Metafield","MetafieldDefinition","Metaobject","MetaobjectDefinition","Model3d","OnlineStoreTheme","Order","OrderAdjustment","OrderAttributionDefinition","OrderCancelJobResult","OrderCreateMandatePaymentJobResult","OrderDisputeSummary","OrderEditSession","OrderTransaction","Page","PaymentCustomization","PaymentMandate","PaymentSchedule","PaymentTerms","PaymentTermsTemplate","PointOfSaleDevice","PointOfSaleDevicePaymentSession","PriceList","Product","ProductBundleOperation","ProductDeleteOperation","ProductDuplicateOperation","ProductFeed","ProductOption","ProductOptionValue","ProductSetOperation","ProductTaxonomyNode","ProductVariant","ProductVariantComponent","Publication","PublicationResourceOperation","QuantityPriceBreak","Refund","RefundShippingLine","RequestedOrderEdit","RequestedOrderEditLineItem","Return","ReturnLineItem","ReturnPolicyProfile","ReturnReasonDefinition","ReturnableFulfillment","ReverseDelivery","ReverseDeliveryLineItem","ReverseFulfillmentOrder","ReverseFulfillmentOrderDisposition","ReverseFulfillmentOrderLineItem","Rollout","RolloutTreatment","SaleAdditionalFee","SavedSearch","ScriptTag","Segment","SellingPlan","SellingPlanGroup","ServerPixel","ShippingLabel","ShippingLabelPurchaseResult","Shop","ShopAddress","ShopPolicy","ShopifyPaymentsAccount","ShopifyPaymentsBalanceTransaction","ShopifyPaymentsBankAccount","ShopifyPaymentsDispute","ShopifyPaymentsDisputeEvidence","ShopifyPaymentsDisputeFileUpload","ShopifyPaymentsDisputeFulfillment","ShopifyPaymentsPayout","StaffMember","StandardMetafieldDefinitionTemplate","StoreCreditAccount","StoreCreditAccountCreditTransaction","StoreCreditAccountDebitRevertTransaction","StoreCreditAccountDebitTransaction","StorefrontAccessToken","SubscriptionBillingAttempt","SubscriptionContract","SubscriptionDraft","TaxonomyAttribute","TaxonomyCategory","TaxonomyChoiceListAttribute","TaxonomyMeasurementAttribute","TaxonomyValue","TenderTransaction","TransactionFee","UnverifiedReturnLineItem","UrlRedirect","UrlRedirectImport","Validation","Video","WebPixel","WebhookSubscription"]}}, +"NotificationUsage":{"e":["WEB","SMS"]}, +"ObjectDimensionsInput":{"i":{"height":"Float!","length":"Float!","unit":"LengthUnit!","width":"Float!"}}, +"OnlineStore":{"o":{"f":{"passwordProtection":"OnlineStorePasswordProtection!"}}}, +"OnlineStorePasswordProtection":{"o":{"f":{"enabled":"Boolean!"}}}, +"OnlineStorePreviewable":{"n":{"f":{"onlineStorePreviewUrl":"URL"},"t":["Product"]}}, +"OnlineStoreTheme":{"o":{"f":{"createdAt":"DateTime!","files":["OnlineStoreThemeFileConnection",{"after":"String","filenames":"[String!]","first":"Int="}],"id":"ID!","name":"String!","prefix":"String!","processing":"Boolean!","processingFailed":"Boolean!","role":"ThemeRole!","themeStoreId":"Int","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"updatedAt":"DateTime!"},"t":["HasPublishedTranslations","Node"]}}, +"OnlineStoreThemeConnection":{"o":{"f":{"edges":"[OnlineStoreThemeEdge!]!","nodes":"[OnlineStoreTheme!]!","pageInfo":"PageInfo!"}}}, +"OnlineStoreThemeEdge":{"o":{"f":{"cursor":"String!","node":"OnlineStoreTheme!"}}}, +"OnlineStoreThemeFile":{"o":{"f":{"body":"OnlineStoreThemeFileBody!","checksumMd5":"String","contentType":"String!","createdAt":"DateTime!","filename":"String!","size":"UnsignedInt64!","updatedAt":"DateTime!"}}}, +"OnlineStoreThemeFileBody":{"u":["OnlineStoreThemeFileBodyBase64","OnlineStoreThemeFileBodyText","OnlineStoreThemeFileBodyUrl"]}, +"OnlineStoreThemeFileBodyBase64":{"o":{"f":{"contentBase64":"String!"}}}, +"OnlineStoreThemeFileBodyInput":{"i":{"type":"OnlineStoreThemeFileBodyInputType!","value":"String!"}}, +"OnlineStoreThemeFileBodyInputType":{"e":["TEXT","BASE64","URL"]}, +"OnlineStoreThemeFileBodyText":{"o":{"f":{"content":"String!"}}}, +"OnlineStoreThemeFileBodyUrl":{"o":{"f":{"url":"URL!"}}}, +"OnlineStoreThemeFileConnection":{"o":{"f":{"edges":"[OnlineStoreThemeFileEdge!]!","nodes":"[OnlineStoreThemeFile!]!","pageInfo":"PageInfo!","userErrors":"[OnlineStoreThemeFileReadResult!]!"}}}, +"OnlineStoreThemeFileEdge":{"o":{"f":{"cursor":"String!","node":"OnlineStoreThemeFile!"}}}, +"OnlineStoreThemeFileOperationResult":{"o":{"f":{"checksumMd5":"String","createdAt":"DateTime!","filename":"String!","size":"UnsignedInt64!","updatedAt":"DateTime!"}}}, +"OnlineStoreThemeFileReadResult":{"o":{"f":{"code":"OnlineStoreThemeFileResultType!","filename":"String!"}}}, +"OnlineStoreThemeFileResultType":{"e":["SUCCESS","ERROR","CONFLICT","UNPROCESSABLE_ENTITY","BAD_REQUEST","TIMEOUT","NOT_FOUND"]}, +"OnlineStoreThemeFilesUpsertFileInput":{"i":{"body":"OnlineStoreThemeFileBodyInput!","filename":"String!"}}, +"OnlineStoreThemeFilesUserErrors":{"o":{"f":{"code":"OnlineStoreThemeFilesUserErrorsCode","field":"[String!]","filename":"String","message":"String!"},"t":["DisplayableError"]}}, +"OnlineStoreThemeFilesUserErrorsCode":{"e":["NOT_FOUND","LESS_THAN_OR_EQUAL_TO","THEME_FILES_CONFLICT","DUPLICATE_FILE_INPUT","ACCESS_DENIED","THEME_LIMITED_PLAN","THEME_CONTEXTUALIZATION_NOT_COMPATIBLE_WITH_CONDITION_TYPES","FILE_VALIDATION_ERROR","ERROR","THROTTLED"]}, +"OnlineStoreThemeInput":{"i":{"name":"String"}}, +"OptionAndValueInput":{"i":{"linkedMetafield":"LinkedMetafieldInput","name":"String!","optionId":"ID","values":"[String!]!"}}, +"OptionCreateInput":{"i":{"linkedMetafield":"LinkedMetafieldCreateInput","name":"String","position":"Int","values":"[OptionValueCreateInput!]"}}, +"OptionReorderInput":{"i":{"id":"ID","name":"String","values":"[OptionValueReorderInput!]"}}, +"OptionSetInput":{"i":{"id":"ID","linkedMetafield":"LinkedMetafieldCreateInput","name":"String","position":"Int","values":"[OptionValueSetInput!]"}}, +"OptionUpdateInput":{"i":{"id":"ID!","linkedMetafield":"LinkedMetafieldUpdateInput","name":"String","position":"Int"}}, +"OptionValueCreateInput":{"i":{"linkedMetafieldValue":"String","name":"String"}}, +"OptionValueReorderInput":{"i":{"id":"ID","name":"String"}}, +"OptionValueSetInput":{"i":{"id":"ID","name":"String"}}, +"OptionValueUpdateInput":{"i":{"id":"ID!","linkedMetafieldValue":"String","name":"String"}}, +"Order":{"o":{"f":{"additionalFees":"[AdditionalFee!]!","agreements":["SalesAgreementConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"alerts":"[ResourceAlert!]!","app":"OrderApp","attribution":"OrderAttribution","billingAddress":"MailingAddress","billingAddressMatchesShippingAddress":"Boolean!","canMarkAsPaid":"Boolean!","canNotifyCustomer":"Boolean!","cancelReason":"OrderCancelReason","cancellation":"OrderCancellation","cancelledAt":"DateTime","capturable":"Boolean!","cartDiscountAmount":"Money","cartDiscountAmountSet":"MoneyBag","cartToken":"String","channel":"Channel","channelInformation":"ChannelInformation","checkoutToken":"String","clientIp":"String","closed":"Boolean!","closedAt":"DateTime","confirmationNumber":"String","confirmed":"Boolean!","createdAt":"DateTime!","currencyCode":"CurrencyCode!","currentCartDiscountAmountSet":"MoneyBag!","currentShippingPriceSet":"MoneyBag!","currentSubtotalLineItemsQuantity":"Int!","currentSubtotalPriceSet":"MoneyBag!","currentTaxLines":"[TaxLine!]!","currentTotalAdditionalFeesSet":"MoneyBag","currentTotalDiscountsSet":"MoneyBag!","currentTotalDutiesSet":"MoneyBag","currentTotalPriceSet":"MoneyBag!","currentTotalTaxSet":"MoneyBag!","currentTotalWeight":"UnsignedInt64!","customAttributes":"[Attribute!]!","customer":"Customer","customerAcceptsMarketing":"Boolean!","customerJourney":"CustomerJourney","customerJourneySummary":"CustomerJourneySummary","customerLocale":"String","discountApplications":["DiscountApplicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountCode":"String","discountCodes":"[String!]!","displayAddress":"MailingAddress","displayFinancialStatus":"OrderDisplayFinancialStatus","displayFulfillmentStatus":"OrderDisplayFulfillmentStatus!","displayRequestedEditStatus":"OrderDisplayRequestedEditStatus!","disputes":"[OrderDisputeSummary!]!","dutiesIncluded":"Boolean!","edited":"Boolean!","email":"String","estimatedTaxes":"Boolean!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"exchangeV2s":["ExchangeV2Connection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"fulfillable":"Boolean!","fulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","before":"String","displayable":"Boolean=","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"fulfillments":["[Fulfillment!]!",{"first":"Int","query":"String"}],"fulfillmentsCount":"Count","fullyPaid":"Boolean!","hasTimelineComment":"Boolean!","id":"ID!","landingPageDisplayText":"String","landingPageUrl":"URL","legacyResourceId":"UnsignedInt64!","lineItems":["LineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"localizationExtensions":["LocalizationExtensionConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizationExtensionPurpose!]","reverse":"Boolean="}],"localizedFields":["LocalizedFieldConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizedFieldPurpose!]","reverse":"Boolean="}],"merchantBusinessEntity":"BusinessEntity!","merchantEditable":"Boolean!","merchantEditableErrors":"[String!]!","merchantOfRecordApp":"OrderApp","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","netPayment":"Money!","netPaymentSet":"MoneyBag!","nonFulfillableLineItems":["LineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"note":"String","number":"Int!","originalTotalAdditionalFeesSet":"MoneyBag","originalTotalDutiesSet":"MoneyBag","originalTotalPriceSet":"MoneyBag!","paymentCollectionDetails":"OrderPaymentCollectionDetails!","paymentGatewayNames":"[String!]!","paymentTerms":"PaymentTerms","phone":"String","physicalLocation":"Location","poNumber":"String","presentmentCurrencyCode":"CurrencyCode!","processedAt":"DateTime!","productNetwork":"Boolean!","publication":"Publication","purchasingEntity":"PurchasingEntity","referralCode":"String","referrerDisplayText":"String","referrerUrl":"URL","refundDiscrepancySet":"MoneyBag!","refundable":"Boolean!","refunds":["[Refund!]!",{"first":"Int"}],"registeredSourceUrl":"URL","requestedOrderEdits":["RequestedOrderEditConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}],"requiresShipping":"Boolean!","restockable":"Boolean!","retailLocation":"Location","returnStatus":"OrderReturnStatus!","returns":["ReturnConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"risk":"OrderRiskSummary!","riskLevel":"OrderRiskLevel!","risks":["[OrderRisk!]!",{"first":"Int"}],"shippingAddress":"MailingAddress","shippingLine":"ShippingLine","shippingLines":["ShippingLineConnection!",{"after":"String","before":"String","first":"Int","includeRemovals":"Boolean=","last":"Int","reverse":"Boolean="}],"shopifyProtect":"ShopifyProtectOrderSummary","sourceIdentifier":"String","sourceName":"String","staffMember":"StaffMember","statusPageUrl":["URL!",{"audience":"Audience","notificationUsage":"NotificationUsage"}],"subtotalLineItemsQuantity":"Int!","subtotalPrice":"Money","subtotalPriceSet":"MoneyBag","suggestedRefund":["SuggestedRefund",{"refundDuties":"[RefundDutyInput!]","refundLineItems":"[RefundLineItemInput!]","refundMethodAllocation":"RefundMethodAllocation=","refundShipping":"Boolean","shippingAmount":"Money","suggestFullRefund":"Boolean="}],"tags":"[String!]!","taxExempt":"Boolean!","taxLines":"[TaxLine!]!","taxesIncluded":"Boolean!","test":"Boolean!","totalCapturable":"Money!","totalCapturableSet":"MoneyBag!","totalCashRoundingAdjustment":"CashRoundingAdjustment!","totalDiscounts":"Money","totalDiscountsSet":"MoneyBag","totalOutstandingSet":"MoneyBag!","totalPrice":"Money!","totalPriceSet":"MoneyBag!","totalReceived":"Money!","totalReceivedSet":"MoneyBag!","totalRefunded":"Money!","totalRefundedSet":"MoneyBag!","totalRefundedShippingSet":"MoneyBag!","totalShippingPrice":"Money!","totalShippingPriceSet":"MoneyBag!","totalTax":"Money","totalTaxSet":"MoneyBag","totalTipReceived":"MoneyV2!","totalTipReceivedSet":"MoneyBag!","totalWeight":"UnsignedInt64","transactions":["[OrderTransaction!]!",{"capturable":"Boolean","first":"Int","manuallyResolvable":"Boolean"}],"transactionsCount":"Count","unpaid":"Boolean!","updatedAt":"DateTime!"},"t":["CommentEventSubject","HasEvents","HasLocalizationExtensions","HasLocalizedFields","HasMetafieldDefinitions","HasMetafields","LegacyInteroperability","Node"],"d":{"cartDiscountAmount":"Use `cartDiscountAmountSet` instead.","channel":"Use `publication` instead.","channelInformation":"Use `attribution` instead.","customerJourney":"Use `customerJourneySummary` instead.","exchangeV2s":"Use `returns` instead.","landingPageDisplayText":"Use `customerJourneySummary.lastVisit.landingPageHtml` instead","landingPageUrl":"Use `customerJourneySummary.lastVisit.landingPage` instead","localizationExtensions":"This connection will be removed in a future version. Use `localizedFields` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","netPayment":"Use `netPaymentSet` instead.","physicalLocation":"Use `fulfillmentOrders` to get the fulfillment location for the order","referralCode":"Use `customerJourneySummary.lastVisit.referralCode` instead","referrerDisplayText":"Use `customerJourneySummary.lastVisit.referralInfoHtml` instead","referrerUrl":"Use `customerJourneySummary.lastVisit.referrerUrl` instead","riskLevel":"This field is deprecated in favor of OrderRiskAssessment.riskLevel which allows for more granular risk levels, including PENDING and NONE.","risks":"This field is deprecated in favor of OrderRiskAssessment, which provides enhanced capabilities such as distinguishing risks from their provider.","subtotalPrice":"Use `subtotalPriceSet` instead.","totalCapturable":"Use `totalCapturableSet` instead.","totalDiscounts":"Use `totalDiscountsSet` instead.","totalPrice":"Use `totalPriceSet` instead.","totalReceived":"Use `totalReceivedSet` instead.","totalRefunded":"Use `totalRefundedSet` instead.","totalShippingPrice":"Use `totalShippingPriceSet` instead.","totalTax":"Use `totalTaxSet` instead.","totalTipReceived":"Use `totalTipReceivedSet` instead."}}}, +"OrderActionType":{"e":["ORDER","ORDER_EDIT","REFUND","RETURN","UNKNOWN"]}, +"OrderAdjustment":{"o":{"f":{"amountSet":"MoneyBag!","id":"ID!","reason":"OrderAdjustmentDiscrepancyReason","taxAmountSet":"MoneyBag!"},"t":["Node"]}}, +"OrderAdjustmentConnection":{"o":{"f":{"edges":"[OrderAdjustmentEdge!]!","nodes":"[OrderAdjustment!]!","pageInfo":"PageInfo!"}}}, +"OrderAdjustmentDiscrepancyReason":{"e":["RESTOCK","DAMAGE","CUSTOMER","REFUND_DISCREPANCY","FULL_RETURN_BALANCING_ADJUSTMENT","PENDING_REFUND_DISCREPANCY"]}, +"OrderAdjustmentEdge":{"o":{"f":{"cursor":"String!","node":"OrderAdjustment!"}}}, +"OrderAdjustmentInputDiscrepancyReason":{"e":["RESTOCK","DAMAGE","CUSTOMER","OTHER"]}, +"OrderAgreement":{"o":{"f":{"app":"App","happenedAt":"DateTime!","id":"ID!","order":"Order!","reason":"OrderActionType!","sales":["SaleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"user":"StaffMember"},"t":["SalesAgreement"]}}, +"OrderApp":{"o":{"f":{"icon":"Image!","id":"ID!","name":"String!"}}}, +"OrderAttribution":{"o":{"f":{"displayName":"String!","handle":"String!","icon":"String"}}}, +"OrderAttributionDefinition":{"o":{"f":{"displayName":"String!","handle":"String!","icon":"String","id":"ID!"},"t":["Node"]}}, +"OrderAttributionDefinitionConnection":{"o":{"f":{"edges":"[OrderAttributionDefinitionEdge!]!","nodes":"[OrderAttributionDefinition!]!","pageInfo":"PageInfo!"}}}, +"OrderAttributionDefinitionDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[OrderAttributionDefinitionDeleteUserError!]!"}}}, +"OrderAttributionDefinitionDeleteUserError":{"o":{"f":{"code":"OrderAttributionDefinitionDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderAttributionDefinitionDeleteUserErrorCode":{"e":["INVALID","NOT_FOUND"]}, +"OrderAttributionDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"OrderAttributionDefinition!"}}}, +"OrderAttributionDefinitionUpsertInput":{"i":{"displayName":"String!","handle":"String!","icon":"String"}}, +"OrderAttributionDefinitionUpsertPayload":{"o":{"f":{"orderAttributionDefinition":"OrderAttributionDefinition","userErrors":"[OrderAttributionDefinitionUpsertUserError!]!"}}}, +"OrderAttributionDefinitionUpsertUserError":{"o":{"f":{"code":"OrderAttributionDefinitionUpsertUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderAttributionDefinitionUpsertUserErrorCode":{"e":["INVALID"]}, +"OrderCancelJobResult":{"o":{"f":{"done":"Boolean!","errors":"[OrderCancelUserError!]!","id":"ID!","order":"Order","status":"OrderCancelStatus!"},"t":["JobResult","Node"]}}, +"OrderCancelPayload":{"o":{"f":{"job":"Job","jobResult":"OrderCancelJobResult","orderCancelUserErrors":"[OrderCancelUserError!]!","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `orderCancelUserErrors` instead."}}}, +"OrderCancelReason":{"e":["CUSTOMER","DECLINED","FRAUD","INVENTORY","STAFF","OTHER"]}, +"OrderCancelRefundMethodInput":{"i":{"originalPaymentMethodsRefund":"Boolean","storeCreditRefund":"OrderCancelStoreCreditRefundInput"}}, +"OrderCancelStatus":{"e":["STARTED","SUCCEEDED","FAILED"]}, +"OrderCancelStoreCreditRefundInput":{"i":{"expiresAt":"DateTime"}}, +"OrderCancelUserError":{"o":{"f":{"code":"OrderCancelUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCancelUserErrorCode":{"e":["NO_REFUND_PERMISSION","NO_REFUND_TO_STORE_CREDIT_PERMISSION","STORE_CREDIT_REFUND_EXPIRATION_IN_PAST","STORE_CREDIT_REFUND_MISSING_CUSTOMER","STORE_CREDIT_REFUND_B2B_NOT_SUPPORTED","NOT_FOUND","INVALID","INTERNAL_ERROR"]}, +"OrderCancellation":{"o":{"f":{"staffNote":"String"}}}, +"OrderCaptureInput":{"i":{"amount":"Money!","currency":"CurrencyCode","finalCapture":"Boolean","id":"ID!","parentTransactionId":"ID!"}}, +"OrderCapturePayload":{"o":{"f":{"transaction":"OrderTransaction","userErrors":"[UserError!]!"}}}, +"OrderCloseInput":{"i":{"id":"ID!"}}, +"OrderClosePayload":{"o":{"f":{"order":"Order","userErrors":"[UserError!]!"}}}, +"OrderConnection":{"o":{"f":{"edges":"[OrderEdge!]!","nodes":"[Order!]!","pageInfo":"PageInfo!"}}}, +"OrderCreateAssociateCustomerAttributesInput":{"i":{"email":"String","id":"ID"}}, +"OrderCreateCustomAttributeInput":{"i":{"key":"String!","value":"String!"}}, +"OrderCreateCustomerAddressInput":{"i":{"address1":"String","address2":"String","city":"String","company":"String","country":"String","firstName":"String","lastName":"String","phone":"String","province":"String","zip":"String"}}, +"OrderCreateCustomerInput":{"i":{"toAssociate":"OrderCreateAssociateCustomerAttributesInput","toUpsert":"OrderCreateUpsertCustomerAttributesInput"}}, +"OrderCreateDiscountCodeInput":{"i":{"freeShippingDiscountCode":"OrderCreateFreeShippingDiscountCodeAttributesInput","itemFixedDiscountCode":"OrderCreateFixedDiscountCodeAttributesInput","itemPercentageDiscountCode":"OrderCreatePercentageDiscountCodeAttributesInput"}}, +"OrderCreateFinancialStatus":{"e":["PENDING","AUTHORIZED","PARTIALLY_PAID","PAID","PARTIALLY_REFUNDED","REFUNDED","VOIDED","EXPIRED"]}, +"OrderCreateFixedDiscountCodeAttributesInput":{"i":{"amountSet":"MoneyBagInput","code":"String!"}}, +"OrderCreateFreeShippingDiscountCodeAttributesInput":{"i":{"code":"String!"}}, +"OrderCreateFulfillmentInput":{"i":{"locationId":"ID!","notifyCustomer":"Boolean=","originAddress":"FulfillmentOriginAddressInput","shipmentStatus":"FulfillmentEventStatus","trackingCompany":"String","trackingNumber":"String","trackingNumbers":"[String!]"}}, +"OrderCreateFulfillmentStatus":{"e":["FULFILLED","PARTIAL","RESTOCKED"]}, +"OrderCreateInputsInventoryBehavior":{"e":["BYPASS","DECREMENT_IGNORING_POLICY","DECREMENT_OBEYING_POLICY"]}, +"OrderCreateLineItemInput":{"i":{"fulfillmentService":"String","giftCard":"Boolean=","priceSet":"MoneyBagInput","productId":"ID","properties":"[OrderCreateLineItemPropertyInput!]","quantity":"Int!","requiresShipping":"Boolean=","sku":"String","taxLines":"[OrderCreateTaxLineInput!]","taxable":"Boolean=","title":"String","variantId":"ID","variantTitle":"String","vendor":"String","weight":"WeightInput"}}, +"OrderCreateLineItemPropertyInput":{"i":{"name":"String!","value":"String!"}}, +"OrderCreateMandatePaymentJobResult":{"o":{"f":{"done":"Boolean!","errors":"[UserError!]!","id":"ID!","order":"Order","status":"OrderCreateMandatePaymentStatus!"},"t":["JobResult","Node"]}}, +"OrderCreateMandatePaymentPayload":{"o":{"f":{"job":"Job","jobResult":"OrderCreateMandatePaymentJobResult","paymentReferenceId":"String","userErrors":"[OrderCreateMandatePaymentUserError!]!"}}}, +"OrderCreateMandatePaymentStatus":{"e":["STARTED","SUCCEEDED","FAILED"]}, +"OrderCreateMandatePaymentUserError":{"o":{"f":{"code":"OrderCreateMandatePaymentUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCreateMandatePaymentUserErrorCode":{"e":["ORDER_MANDATE_PAYMENT_ERROR_CODE"]}, +"OrderCreateManualPaymentOrderCreateManualPaymentError":{"o":{"f":{"code":"OrderCreateManualPaymentOrderCreateManualPaymentErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCreateManualPaymentOrderCreateManualPaymentErrorCode":{"e":["ORDER_NOT_FOUND","AMOUNT_NOT_POSITIVE","GATEWAY_NOT_FOUND","AMOUNT_EXCEEDS_BALANCE","ORDER_IS_TEMPORARILY_UNAVAILABLE","PROCESSED_AT_INVALID","CURRENCY_MISMATCH"]}, +"OrderCreateManualPaymentPayload":{"o":{"f":{"order":"Order","userErrors":"[OrderCreateManualPaymentOrderCreateManualPaymentError!]!"}}}, +"OrderCreateOptionsInput":{"i":{"inventoryBehaviour":"OrderCreateInputsInventoryBehavior=","sendFulfillmentReceipt":"Boolean=","sendReceipt":"Boolean="}}, +"OrderCreateOrderInput":{"i":{"f":{"billingAddress":"MailingAddressInput","buyerAcceptsMarketing":"Boolean=","closedAt":"DateTime","companyLocationId":"ID","currency":"CurrencyCode","customAttributes":"[OrderCreateCustomAttributeInput!]","customer":"OrderCreateCustomerInput","customerId":"ID","discountCode":"OrderCreateDiscountCodeInput","email":"String","financialStatus":"OrderCreateFinancialStatus","fulfillment":"OrderCreateFulfillmentInput","fulfillmentStatus":"OrderCreateFulfillmentStatus","lineItems":"[OrderCreateLineItemInput!]","metafields":"[MetafieldInput!]","name":"String","note":"String","phone":"String","poNumber":"String","presentmentCurrency":"CurrencyCode","processedAt":"DateTime","referringSite":"URL","shippingAddress":"MailingAddressInput","shippingLines":"[OrderCreateShippingLineInput!]","sourceIdentifier":"String","sourceName":"String","sourceUrl":"URL","tags":"[String!]","taxLines":"[OrderCreateTaxLineInput!]","taxesIncluded":"Boolean=","test":"Boolean=","transactions":"[OrderCreateOrderTransactionInput!]","userId":"ID"},"d":{"customerId":"This is replaced by the `customer` field in a future version."}}}, +"OrderCreateOrderTransactionInput":{"i":{"amountSet":"MoneyBagInput!","authorizationCode":"String","deviceId":"ID","gateway":"String","giftCardId":"ID","kind":"OrderTransactionKind=","locationId":"ID","processedAt":"DateTime","receiptJson":"JSON","status":"OrderTransactionStatus=","test":"Boolean=","userId":"ID"}}, +"OrderCreatePayload":{"o":{"f":{"order":"Order","userErrors":"[OrderCreateUserError!]!"}}}, +"OrderCreatePercentageDiscountCodeAttributesInput":{"i":{"code":"String!","percentage":"Float"}}, +"OrderCreateShippingLineInput":{"i":{"code":"String","priceSet":"MoneyBagInput!","source":"String","taxLines":"[OrderCreateTaxLineInput!]","title":"String!"}}, +"OrderCreateTaxLineInput":{"i":{"channelLiable":"Boolean=","priceSet":"MoneyBagInput","rate":"Decimal!","title":"String!"}}, +"OrderCreateUpsertCustomerAttributesInput":{"i":{"addresses":"[OrderCreateCustomerAddressInput!]","email":"String","firstName":"String","id":"ID","lastName":"String","multipassIdentifier":"String","note":"String","phone":"String","tags":"[String!]","taxExempt":"Boolean"}}, +"OrderCreateUserError":{"o":{"f":{"code":"OrderCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCreateUserErrorCode":{"e":["INVALID","FULFILLMENT_SERVICE_INVALID","INVENTORY_CLAIM_FAILED","PROCESSED_AT_INVALID","TAX_LINE_RATE_MISSING","REDUNDANT_CUSTOMER_FIELDS","SHOP_DORMANT"]}, +"OrderCustomerRemovePayload":{"o":{"f":{"order":"Order","userErrors":"[OrderCustomerRemoveUserError!]!"}}}, +"OrderCustomerRemoveUserError":{"o":{"f":{"code":"OrderCustomerRemoveUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCustomerRemoveUserErrorCode":{"e":["NOT_FOUND","INVALID","NOT_SAVED"]}, +"OrderCustomerSetPayload":{"o":{"f":{"order":"Order","userErrors":"[OrderCustomerSetUserError!]!"}}}, +"OrderCustomerSetUserError":{"o":{"f":{"code":"OrderCustomerSetUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCustomerSetUserErrorCode":{"e":["NOT_FOUND","INVALID","NOT_SAVED","NOT_PERMITTED"]}, +"OrderDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[OrderDeleteUserError!]!"}}}, +"OrderDeleteUserError":{"o":{"f":{"code":"OrderDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderDeleteUserErrorCode":{"e":["NOT_FOUND","INVALID"]}, +"OrderDisplayFinancialStatus":{"e":["PENDING","AUTHORIZED","PARTIALLY_PAID","PARTIALLY_REFUNDED","VOIDED","PAID","REFUNDED","EXPIRED"]}, +"OrderDisplayFulfillmentStatus":{"e":["UNFULFILLED","PARTIALLY_FULFILLED","FULFILLED","RESTOCKED","PENDING_FULFILLMENT","OPEN","IN_PROGRESS","ON_HOLD","SCHEDULED","REQUEST_DECLINED","FULFILLMENT_NOT_REQUIRED"]}, +"OrderDisplayRequestedEditStatus":{"e":["NONE","REQUESTED","RESOLVED","DECLINED"]}, +"OrderDisputeSummary":{"o":{"f":{"id":"ID!","initiatedAs":"DisputeType!","status":"DisputeStatus!"},"t":["Node"]}}, +"OrderEdge":{"o":{"f":{"cursor":"String!","node":"Order!"}}}, +"OrderEditAddCustomItemPayload":{"o":{"f":{"calculatedLineItem":"CalculatedLineItem","calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditAddLineItemDiscountPayload":{"o":{"f":{"addedDiscountStagedChange":"OrderStagedChangeAddLineItemDiscount","calculatedLineItem":"CalculatedLineItem","calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditAddShippingLineInput":{"i":{"price":"MoneyInput!","title":"String!"}}, +"OrderEditAddShippingLinePayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","calculatedShippingLine":"CalculatedShippingLine","orderEditSession":"OrderEditSession","userErrors":"[OrderEditAddShippingLineUserError!]!"}}}, +"OrderEditAddShippingLineUserError":{"o":{"f":{"code":"OrderEditAddShippingLineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderEditAddShippingLineUserErrorCode":{"e":["INVALID"]}, +"OrderEditAddVariantPayload":{"o":{"f":{"calculatedLineItem":"CalculatedLineItem","calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditAgreement":{"o":{"f":{"app":"App","happenedAt":"DateTime!","id":"ID!","reason":"OrderActionType!","sales":["SaleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"user":"StaffMember"},"t":["SalesAgreement"]}}, +"OrderEditAppliedDiscountInput":{"i":{"description":"String","fixedValue":"MoneyInput","percentValue":"Float"}}, +"OrderEditBeginPayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditCommitPayload":{"o":{"f":{"order":"Order","successMessages":"[String!]","userErrors":"[UserError!]!"}}}, +"OrderEditRemoveDiscountPayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[OrderEditRemoveDiscountUserError!]!"}}}, +"OrderEditRemoveDiscountUserError":{"o":{"f":{"code":"OrderEditRemoveDiscountUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderEditRemoveDiscountUserErrorCode":{"e":["INVALID"]}, +"OrderEditRemoveLineItemDiscountPayload":{"o":{"f":{"calculatedLineItem":"CalculatedLineItem","calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditRemoveShippingLinePayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[OrderEditRemoveShippingLineUserError!]!"}}}, +"OrderEditRemoveShippingLineUserError":{"o":{"f":{"code":"OrderEditRemoveShippingLineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderEditRemoveShippingLineUserErrorCode":{"e":["INVALID"]}, +"OrderEditSession":{"o":{"f":{"id":"ID!"},"t":["Node"]}}, +"OrderEditSetQuantityPayload":{"o":{"f":{"calculatedLineItem":"CalculatedLineItem","calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditUpdateDiscountPayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[OrderEditUpdateDiscountUserError!]!"}}}, +"OrderEditUpdateDiscountUserError":{"o":{"f":{"code":"OrderEditUpdateDiscountUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderEditUpdateDiscountUserErrorCode":{"e":["INVALID"]}, +"OrderEditUpdateShippingLineInput":{"i":{"price":"MoneyInput","title":"String"}}, +"OrderEditUpdateShippingLinePayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[OrderEditUpdateShippingLineUserError!]!"}}}, +"OrderEditUpdateShippingLineUserError":{"o":{"f":{"code":"OrderEditUpdateShippingLineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderEditUpdateShippingLineUserErrorCode":{"e":["INVALID"]}, +"OrderIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","id":"ID"}}, +"OrderInput":{"i":{"f":{"customAttributes":"[AttributeInput!]","email":"String","id":"ID!","localizationExtensions":"[LocalizationExtensionInput!]","localizedFields":"[LocalizedFieldInput!]","metafields":"[MetafieldInput!]","note":"String","phone":"String","poNumber":"String","shippingAddress":"MailingAddressInput","tags":"[String!]"},"d":{"localizationExtensions":"This field will be removed in a future version. Use `localizedFields` instead."}}}, +"OrderInvoiceSendPayload":{"o":{"f":{"order":"Order","userErrors":"[OrderInvoiceSendUserError!]!"}}}, +"OrderInvoiceSendUserError":{"o":{"f":{"code":"OrderInvoiceSendUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderInvoiceSendUserErrorCode":{"e":["ORDER_INVOICE_SEND_UNSUCCESSFUL"]}, +"OrderMarkAsPaidInput":{"i":{"id":"ID!"}}, +"OrderMarkAsPaidPayload":{"o":{"f":{"order":"Order","userErrors":"[UserError!]!"}}}, +"OrderOpenInput":{"i":{"id":"ID!"}}, +"OrderOpenPayload":{"o":{"f":{"order":"Order","userErrors":"[UserError!]!"}}}, +"OrderPaymentCollectionDetails":{"o":{"f":{"additionalPaymentCollectionUrl":"URL","vaultedPaymentMethods":"[PaymentMandate!]"}}}, +"OrderPaymentStatus":{"o":{"f":{"errorMessage":"String","paymentReferenceId":"String!","status":"OrderPaymentStatusResult!","transactions":"[OrderTransaction!]!","translatedErrorMessage":"String"}}}, +"OrderPaymentStatusResult":{"e":["SUCCESS","AUTHORIZED","VOIDED","REFUNDED","CAPTURED","PURCHASED","ERROR","PROCESSING","REDIRECT_REQUIRED","RETRYABLE","UNKNOWN","INITIATED","PENDING","PARTIAL_SUCCESS"]}, +"OrderReturnStatus":{"e":["IN_PROGRESS","INSPECTION_COMPLETE","NO_RETURN","RETURNED","RETURN_FAILED","RETURN_REQUESTED"]}, +"OrderRisk":{"o":{"f":{"display":"Boolean!","level":"OrderRiskLevel","message":"String"},"d":{"display":"This field is deprecated in favor of OrderRiskAssessment.facts.","level":"This field is deprecated in favor of OrderRiskAssessment.riskLevel which allows for more granular risk levels, including PENDING and NONE.","message":"This field is deprecated in favor of OrderRiskAssessment.facts."}}}, +"OrderRiskAssessment":{"o":{"f":{"facts":"[RiskFact!]!","provider":"App","riskLevel":"RiskAssessmentResult!"}}}, +"OrderRiskAssessmentCreateInput":{"i":{"facts":"[OrderRiskAssessmentFactInput!]!","orderId":"ID!","riskLevel":"RiskAssessmentResult!"}}, +"OrderRiskAssessmentCreatePayload":{"o":{"f":{"orderRiskAssessment":"OrderRiskAssessment","userErrors":"[OrderRiskAssessmentCreateUserError!]!"}}}, +"OrderRiskAssessmentCreateUserError":{"o":{"f":{"code":"OrderRiskAssessmentCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderRiskAssessmentCreateUserErrorCode":{"e":["TOO_MANY_FACTS","ORDER_ALREADY_FULFILLED","INVALID","NOT_FOUND"]}, +"OrderRiskAssessmentFactInput":{"i":{"description":"String!","sentiment":"RiskFactSentiment!"}}, +"OrderRiskLevel":{"e":["LOW","MEDIUM","HIGH"]}, +"OrderRiskRecommendationResult":{"e":["CANCEL","INVESTIGATE","ACCEPT","NONE"]}, +"OrderRiskSummary":{"o":{"f":{"assessments":"[OrderRiskAssessment!]!","recommendation":"OrderRiskRecommendationResult!"}}}, +"OrderSortKeys":{"e":["CREATED_AT","CURRENT_TOTAL_PRICE","CUSTOMER_NAME","DESTINATION","FINANCIAL_STATUS","FULFILLMENT_STATUS","ID","ORDER_NUMBER","PO_NUMBER","PROCESSED_AT","RELEVANCE","TOTAL_ITEMS_QUANTITY","TOTAL_PRICE","UPDATED_AT"]}, +"OrderStagedChange":{"u":["OrderStagedChangeAddCustomItem","OrderStagedChangeAddLineItemDiscount","OrderStagedChangeAddShippingLine","OrderStagedChangeAddVariant","OrderStagedChangeDecrementItem","OrderStagedChangeIncrementItem","OrderStagedChangeRemoveDiscount","OrderStagedChangeRemoveShippingLine"]}, +"OrderStagedChangeAddCustomItem":{"o":{"f":{"originalUnitPrice":"MoneyV2!","quantity":"Int!","title":"String!"}}}, +"OrderStagedChangeAddLineItemDiscount":{"o":{"f":{"description":"String!","id":"ID!","value":"PricingValue!"}}}, +"OrderStagedChangeAddShippingLine":{"o":{"f":{"phone":"String","presentmentTitle":"String","price":"MoneyV2!","title":"String"}}}, +"OrderStagedChangeAddVariant":{"o":{"f":{"quantity":"Int!","variant":"ProductVariant!"}}}, +"OrderStagedChangeConnection":{"o":{"f":{"edges":"[OrderStagedChangeEdge!]!","nodes":"[OrderStagedChange!]!","pageInfo":"PageInfo!"}}}, +"OrderStagedChangeDecrementItem":{"o":{"f":{"delta":"Int!","lineItem":"LineItem!","restock":"Boolean!"}}}, +"OrderStagedChangeEdge":{"o":{"f":{"cursor":"String!","node":"OrderStagedChange!"}}}, +"OrderStagedChangeIncrementItem":{"o":{"f":{"delta":"Int!","lineItem":"LineItem!"}}}, +"OrderStagedChangeRemoveDiscount":{"o":{"f":{"discountApplication":"DiscountApplication!"}}}, +"OrderStagedChangeRemoveShippingLine":{"o":{"f":{"shippingLine":"ShippingLine!"}}}, +"OrderTransaction":{"o":{"f":{"accountNumber":"String","amount":"Money!","amountRoundingSet":"MoneyBag","amountSet":"MoneyBag!","amountV2":"MoneyV2!","authorizationCode":"String","authorizationExpiresAt":"DateTime","createdAt":"DateTime!","currencyExchangeAdjustment":"CurrencyExchangeAdjustment","device":"PointOfSaleDevice","errorCode":"OrderTransactionErrorCode","fees":"[TransactionFee!]!","formattedGateway":"String","gateway":"String","id":"ID!","kind":"OrderTransactionKind!","location":"Location","manualPaymentGateway":"Boolean!","manuallyCapturable":"Boolean!","maximumRefundable":"Money","maximumRefundableV2":"MoneyV2","multiCapturable":"Boolean!","order":"Order","parentTransaction":"OrderTransaction","paymentDetails":"PaymentDetails","paymentIcon":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"paymentId":"String","paymentMethod":"PaymentMethods","processedAt":"DateTime","receiptJson":"JSON","settlementCurrency":"CurrencyCode","settlementCurrencyRate":"Decimal","shopifyPaymentsSet":"ShopifyPaymentsTransactionSet","status":"OrderTransactionStatus!","test":"Boolean!","totalUnsettled":"Money","totalUnsettledSet":"MoneyBag","totalUnsettledV2":"MoneyV2","user":"StaffMember"},"t":["Node"],"d":{"amount":"Use `amountSet` instead.","amountV2":"Use `amountSet` instead.","authorizationCode":"Use `paymentId` instead.","maximumRefundable":"Use `maximumRefundableV2` instead.","paymentIcon(crop)":"Use `Image.url(transform: { crop:})` instead.","paymentIcon(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","paymentIcon(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","paymentIcon(scale)":"Use `Image.url(transform: { scale:})` instead.","paymentMethod":"Use `paymentIcon` instead.","totalUnsettled":"Use `totalUnsettledSet` instead.","totalUnsettledV2":"Use `totalUnsettledSet` instead."}}}, +"OrderTransactionConnection":{"o":{"f":{"edges":"[OrderTransactionEdge!]!","nodes":"[OrderTransaction!]!","pageInfo":"PageInfo!"}}}, +"OrderTransactionEdge":{"o":{"f":{"cursor":"String!","node":"OrderTransaction!"}}}, +"OrderTransactionErrorCode":{"e":["INCORRECT_NUMBER","INVALID_NUMBER","INVALID_EXPIRY_DATE","INVALID_CVC","EXPIRED_CARD","INCORRECT_CVC","INCORRECT_ZIP","INCORRECT_ADDRESS","INCORRECT_PIN","CARD_DECLINED","PROCESSING_ERROR","CALL_ISSUER","PICK_UP_CARD","CONFIG_ERROR","TEST_MODE_LIVE_CARD","UNSUPPORTED_FEATURE","GENERIC_ERROR","INVALID_COUNTRY","INVALID_AMOUNT","PAYMENT_METHOD_UNAVAILABLE","AMAZON_PAYMENTS_INVALID_PAYMENT_METHOD","AMAZON_PAYMENTS_MAX_AMOUNT_CHARGED","AMAZON_PAYMENTS_MAX_AMOUNT_REFUNDED","AMAZON_PAYMENTS_MAX_AUTHORIZATIONS_CAPTURED","AMAZON_PAYMENTS_MAX_REFUNDS_PROCESSED","AMAZON_PAYMENTS_ORDER_REFERENCE_CANCELED","AMAZON_PAYMENTS_STALE","AMOUNT_TOO_LARGE","AMOUNT_TOO_SMALL","AUTHENTICATION_FAILED","AUTHENTICATION_REQUIRED","CANCELLED_PAYMENT","CARD_TESTING","DO_NOT_HONOR","FRAUD_SUSPECTED","INSUFFICIENT_FUNDS","INVALID_CURRENCY","INVALID_PAYMENT_METHOD","INVALID_PURCHASE_TYPE","MERCHANT_ACCOUNT_ERROR","MERCHANT_RULE","INSTRUMENT_DECLINED","PAYMENT_METHOD_UNSUPPORTED","PAYMENT_PROVIDER_ERROR","RETRY_DECLINED","TRANSACTION_LIMIT_EXCEEDED","AUTHORIZATION_EXPIRED"]}, +"OrderTransactionInput":{"i":{"amount":"Money!","gateway":"String!","kind":"OrderTransactionKind!","orderId":"ID!","parentId":"ID"}}, +"OrderTransactionKind":{"e":["SALE","CAPTURE","AUTHORIZATION","VOID","REFUND","CHANGE","EMV_AUTHORIZATION","SUGGESTED_REFUND"]}, +"OrderTransactionStatus":{"e":["SUCCESS","FAILURE","PENDING","ERROR","AWAITING_RESPONSE","UNKNOWN"]}, +"OrderUpdatePayload":{"o":{"f":{"order":"Order","userErrors":"[UserError!]!"}}}, +"PackageInfoInput":{"i":{"carrierPackage":"ShippingCarrierPackageInput","customPackage":"ShippingLabelPurchaseCustomPackageInput"}}, +"Page":{"o":{"f":{"body":"HTML!","bodySummary":"String!","createdAt":"DateTime!","defaultCursor":"String!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"handle":"String!","id":"ID!","isPublished":"Boolean!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"publishedAt":"DateTime","templateSuffix":"String","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"updatedAt":"DateTime!"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Navigable","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"PageConnection":{"o":{"f":{"edges":"[PageEdge!]!","nodes":"[Page!]!","pageInfo":"PageInfo!"}}}, +"PageCreateInput":{"i":{"body":"String","handle":"String","isPublished":"Boolean","metafields":"[MetafieldInput!]","publishDate":"DateTime","templateSuffix":"String","title":"String!"}}, +"PageCreatePayload":{"o":{"f":{"page":"Page","userErrors":"[PageCreateUserError!]!"}}}, +"PageCreateUserError":{"o":{"f":{"code":"PageCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PageCreateUserErrorCode":{"e":["INVALID_PUBLISH_DATE","BLANK","TOO_LONG","TOO_SHORT","TOO_BIG","TAKEN","INVALID","INVALID_VALUE","INVALID_TYPE"]}, +"PageDeletePayload":{"o":{"f":{"deletedPageId":"ID","userErrors":"[PageDeleteUserError!]!"}}}, +"PageDeleteUserError":{"o":{"f":{"code":"PageDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PageDeleteUserErrorCode":{"e":["NOT_FOUND"]}, +"PageEdge":{"o":{"f":{"cursor":"String!","node":"Page!"}}}, +"PageInfo":{"o":{"f":{"endCursor":"String","hasNextPage":"Boolean!","hasPreviousPage":"Boolean!","startCursor":"String"}}}, +"PageSortKeys":{"e":["ID","PUBLISHED_AT","TITLE","UPDATED_AT"]}, +"PageUpdateInput":{"i":{"body":"String","handle":"String","isPublished":"Boolean","metafields":"[MetafieldInput!]","publishDate":"DateTime","redirectNewHandle":"Boolean=","templateSuffix":"String","title":"String"}}, +"PageUpdatePayload":{"o":{"f":{"page":"Page","userErrors":"[PageUpdateUserError!]!"}}}, +"PageUpdateUserError":{"o":{"f":{"code":"PageUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PageUpdateUserErrorCode":{"e":["INVALID_PUBLISH_DATE","NOT_FOUND","BLANK","TOO_LONG","TOO_BIG","TAKEN","INVALID","INVALID_VALUE","INVALID_TYPE"]}, +"PaymentCustomization":{"o":{"f":{"enabled":"Boolean!","errorHistory":"FunctionsErrorHistory","functionId":"String!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"shopifyFunction":"ShopifyFunction!","title":"String!"},"t":["HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"PaymentCustomizationActivationPayload":{"o":{"f":{"ids":"[String!]","userErrors":"[PaymentCustomizationError!]!"}}}, +"PaymentCustomizationConnection":{"o":{"f":{"edges":"[PaymentCustomizationEdge!]!","nodes":"[PaymentCustomization!]!","pageInfo":"PageInfo!"}}}, +"PaymentCustomizationCreatePayload":{"o":{"f":{"paymentCustomization":"PaymentCustomization","userErrors":"[PaymentCustomizationError!]!"}}}, +"PaymentCustomizationDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[PaymentCustomizationError!]!"}}}, +"PaymentCustomizationEdge":{"o":{"f":{"cursor":"String!","node":"PaymentCustomization!"}}}, +"PaymentCustomizationError":{"o":{"f":{"code":"PaymentCustomizationErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentCustomizationErrorCode":{"e":["CUSTOM_APP_FUNCTION_NOT_ELIGIBLE","FUNCTION_DOES_NOT_IMPLEMENT","FUNCTION_NOT_FOUND","FUNCTION_PENDING_DELETION","INVALID","PAYMENT_CUSTOMIZATION_NOT_FOUND","PAYMENT_CUSTOMIZATION_FUNCTION_NOT_ELIGIBLE","MAXIMUM_ACTIVE_PAYMENT_CUSTOMIZATIONS","REQUIRED_INPUT_FIELD","INVALID_METAFIELDS","MAXIMUM_PAYMENT_CUSTOMIZATIONS","FUNCTION_ID_CANNOT_BE_CHANGED","MISSING_FUNCTION_IDENTIFIER","MULTIPLE_FUNCTION_IDENTIFIERS"]}, +"PaymentCustomizationInput":{"i":{"f":{"enabled":"Boolean","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]=","title":"String"},"d":{"functionId":"Use `functionHandle` instead."}}}, +"PaymentCustomizationUpdatePayload":{"o":{"f":{"paymentCustomization":"PaymentCustomization","userErrors":"[PaymentCustomizationError!]!"}}}, +"PaymentDetails":{"u":["CardPaymentDetails","LocalPaymentMethodsPaymentDetails","PaypalWalletPaymentDetails","ShopPayInstallmentsPaymentDetails"]}, +"PaymentInstrument":{"u":["BankAccount","VaultCreditCard","VaultPaypalBillingAgreement"]}, +"PaymentInstrumentMandateInput":{"i":{"resourceId":"String!","resourceType":"PaymentInstrumentMandateResourceType!"}}, +"PaymentInstrumentMandateResourceType":{"e":["SUBSCRIPTIONS","ORDERS","DRAFT_ORDERS"]}, +"PaymentInstrumentSendAddEmailPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"PaymentMandate":{"o":{"f":{"id":"ID!","paymentInstrument":"PaymentInstrument!"},"t":["Node"]}}, +"PaymentMandateResource":{"o":{"f":{"id":"ID!","resourceId":"ID","resourceType":"MandateResourceType"}}}, +"PaymentMandateResourceConnection":{"o":{"f":{"edges":"[PaymentMandateResourceEdge!]!","nodes":"[PaymentMandateResource!]!","pageInfo":"PageInfo!"}}}, +"PaymentMandateResourceEdge":{"o":{"f":{"cursor":"String!","node":"PaymentMandateResource!"}}}, +"PaymentMethods":{"e":["VISA","MASTERCARD","DISCOVER","AMERICAN_EXPRESS","DINERS_CLUB","JCB","UNIONPAY","ELO","DANKORT","MAESTRO","FORBRUGSFORENINGEN","PAYPAL","BOGUS","BITCOIN","LITECOIN","DOGECOIN","INTERAC","EFTPOS","CARTES_BANCAIRES","BANCONTACT"]}, +"PaymentReminderSendPayload":{"o":{"f":{"success":"Boolean","userErrors":"[PaymentReminderSendUserError!]!"}}}, +"PaymentReminderSendUserError":{"o":{"f":{"code":"PaymentReminderSendUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentReminderSendUserErrorCode":{"e":["PAYMENT_REMINDER_SEND_UNSUCCESSFUL"]}, +"PaymentSchedule":{"o":{"f":{"amount":"MoneyV2!","balanceDue":"MoneyV2!","completedAt":"DateTime","due":"Boolean!","dueAt":"DateTime","id":"ID!","issuedAt":"DateTime","paymentTerms":"PaymentTerms!","totalBalance":"MoneyV2!"},"t":["Node"],"d":{"amount":"Use `balanceDue`, `totalBalance`, or `Order.totalOutstandingSet` instead."}}}, +"PaymentScheduleCapturePayload":{"o":{"f":{"job":"Job","jobResult":"OrderCreateMandatePaymentJobResult","paymentReferenceId":"String","userErrors":"[PaymentScheduleCaptureUserError!]!"}}}, +"PaymentScheduleCaptureUserError":{"o":{"f":{"code":"PaymentScheduleCaptureUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentScheduleCaptureUserErrorCode":{"e":["PAYMENT_SCHEDULE_CAPTURE_ERROR_CODE"]}, +"PaymentScheduleConnection":{"o":{"f":{"edges":"[PaymentScheduleEdge!]!","nodes":"[PaymentSchedule!]!","pageInfo":"PageInfo!"}}}, +"PaymentScheduleEdge":{"o":{"f":{"cursor":"String!","node":"PaymentSchedule!"}}}, +"PaymentScheduleInput":{"i":{"dueAt":"DateTime","issuedAt":"DateTime"}}, +"PaymentSettings":{"o":{"f":{"supportedDigitalWallets":"[DigitalWallet!]!"}}}, +"PaymentTerms":{"o":{"f":{"draftOrder":"DraftOrder","due":"Boolean!","dueInDays":"Int","id":"ID!","order":"Order","overdue":"Boolean!","paymentSchedules":["PaymentScheduleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"paymentTermsName":"String!","paymentTermsType":"PaymentTermsType!","translatedName":"String!"},"t":["Node"]}}, +"PaymentTermsCreateInput":{"i":{"paymentSchedules":"[PaymentScheduleInput!]","paymentTermsTemplateId":"ID!"}}, +"PaymentTermsCreatePayload":{"o":{"f":{"paymentTerms":"PaymentTerms","userErrors":"[PaymentTermsCreateUserError!]!"}}}, +"PaymentTermsCreateUserError":{"o":{"f":{"code":"PaymentTermsCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentTermsCreateUserErrorCode":{"e":["PAYMENT_TERMS_CREATION_UNSUCCESSFUL"]}, +"PaymentTermsDeleteInput":{"i":{"paymentTermsId":"ID!"}}, +"PaymentTermsDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[PaymentTermsDeleteUserError!]!"}}}, +"PaymentTermsDeleteUserError":{"o":{"f":{"code":"PaymentTermsDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentTermsDeleteUserErrorCode":{"e":["PAYMENT_TERMS_DELETE_UNSUCCESSFUL"]}, +"PaymentTermsInput":{"i":{"paymentSchedules":"[PaymentScheduleInput!]","paymentTermsTemplateId":"ID"}}, +"PaymentTermsTemplate":{"o":{"f":{"description":"String!","dueInDays":"Int","id":"ID!","name":"String!","paymentTermsType":"PaymentTermsType!","translatedName":"String!"},"t":["Node"]}}, +"PaymentTermsType":{"e":["RECEIPT","NET","FIXED","FULFILLMENT","UNKNOWN"]}, +"PaymentTermsUpdateInput":{"i":{"paymentTermsAttributes":"PaymentTermsInput!","paymentTermsId":"ID!"}}, +"PaymentTermsUpdatePayload":{"o":{"f":{"paymentTerms":"PaymentTerms","userErrors":"[PaymentTermsUpdateUserError!]!"}}}, +"PaymentTermsUpdateUserError":{"o":{"f":{"code":"PaymentTermsUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentTermsUpdateUserErrorCode":{"e":["PAYMENT_TERMS_UPDATE_UNSUCCESSFUL"]}, +"PayoutSortKeys":{"e":["ADJUSTMENT_GROSS","ADVANCE_GROSS","AMOUNT","CHARGE_GROSS","DUTIES_GROSS","FEE_AMOUNT","ID","ISSUED_AT","REFUND_GROSS","SHIPPING_LABEL_GROSS","STATUS"]}, +"PaypalExpressSubscriptionsGatewayStatus":{"e":["ENABLED","DISABLED","PENDING"]}, +"PaypalWalletPaymentDetails":{"o":{"f":{"paymentMethodName":"String"},"t":["BasePaymentDetails"]}}, +"PickupInStoreLocation":{"o":{"f":{"code":"String!","distanceFromBuyer":"Distance","handle":"String!","instructions":"String!","locationId":"ID!","source":"String!","title":"String!"}}}, +"PointOfSaleDevice":{"o":{"f":{"activePaymentSession":"PointOfSaleDevicePaymentSession","cashDrawer":"CashDrawer","fiscalDeviceIdentifier":"String","id":"ID!"},"t":["Node"]}}, +"PointOfSaleDeviceAssignToCashDrawerPayload":{"o":{"f":{"pointOfSaleDevice":"PointOfSaleDevice","userErrors":"[PointOfSaleDeviceAssignToCashDrawerUserError!]!"}}}, +"PointOfSaleDeviceAssignToCashDrawerUserError":{"o":{"f":{"code":"PointOfSaleDeviceAssignToCashDrawerUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PointOfSaleDeviceAssignToCashDrawerUserErrorCode":{"e":["INTERNAL_ERROR","LOCATION_MISMATCH","CASH_DRAWER_NOT_FOUND","POINT_OF_SALE_DEVICE_NOT_FOUND"]}, +"PointOfSaleDeviceConnection":{"o":{"f":{"edges":"[PointOfSaleDeviceEdge!]!","nodes":"[PointOfSaleDevice!]!","pageInfo":"PageInfo!"}}}, +"PointOfSaleDeviceEdge":{"o":{"f":{"cursor":"String!","node":"PointOfSaleDevice!"}}}, +"PointOfSaleDevicePaymentSession":{"o":{"f":{"cashActivities":["CashActivityConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","staffMemberId":"ID"}],"cashCountedAtClose":"MoneyV2","cashCountedAtOpen":"MoneyV2!","cashDrawer":"CashDrawer!","closingAdjustment":"MoneyV2","closingBalance":"MoneyV2","closingNote":"String","closingStaffMember":"StaffMember","closingTime":"DateTime","currency":"String!","expectedCashAtClose":"MoneyV2","expectedCashAtOpen":"MoneyV2!","id":"ID!","location":"Location!","netCashSales":"MoneyV2!","netSales":"MoneyV2!","openingNote":"String","openingStaffMember":"StaffMember!","openingTime":"DateTime!","pointOfSaleDevice":"PointOfSaleDevice!","status":"PointOfSaleDevicePaymentSessionStatus!","totalAdjustments":"MoneyV2!","totalCashRefunds":"MoneyV2!","totalCashSales":"MoneyV2!","totalDiscrepancy":"MoneyV2!","totalRefunds":"MoneyV2!","totalSales":"MoneyV2!","totalsReady":"Boolean!"},"t":["Node"]}}, +"PointOfSaleDevicePaymentSessionAdjustPayload":{"o":{"f":{"pointOfSaleDevicePaymentSession":"PointOfSaleDevicePaymentSession","userErrors":"[UserError!]!"}}}, +"PointOfSaleDevicePaymentSessionClosePayload":{"o":{"f":{"pointOfSaleDevicePaymentSession":"PointOfSaleDevicePaymentSession","userErrors":"[PointOfSaleDevicePaymentSessionCloseUserError!]!"}}}, +"PointOfSaleDevicePaymentSessionCloseUserError":{"o":{"f":{"code":"PointOfSaleDevicePaymentSessionCloseUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PointOfSaleDevicePaymentSessionCloseUserErrorCode":{"e":["STAFF_MEMBER_NOT_FOUND","PAYMENT_SESSION_NOT_FOUND","SESSION_ALREADY_CLOSED","TIME_BEFORE_SESSION_OPEN","REASON_CODE_NOT_FOUND","CURRENCY_MISMATCH","NO_CASH_DRAWER_ASSOCIATED","FAILED_TO_CLOSE_SESSION"]}, +"PointOfSaleDevicePaymentSessionConnection":{"o":{"f":{"edges":"[PointOfSaleDevicePaymentSessionEdge!]!","nodes":"[PointOfSaleDevicePaymentSession!]!","pageInfo":"PageInfo!"}}}, +"PointOfSaleDevicePaymentSessionCountPayload":{"o":{"f":{"pointOfSaleDevicePaymentSession":"PointOfSaleDevicePaymentSession","userErrors":"[PointOfSaleDevicePaymentSessionCountUserError!]!"}}}, +"PointOfSaleDevicePaymentSessionCountUserError":{"o":{"f":{"code":"PointOfSaleDevicePaymentSessionCountUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PointOfSaleDevicePaymentSessionCountUserErrorCode":{"e":["STAFF_MEMBER_NOT_FOUND","PAYMENT_SESSION_NOT_FOUND","SESSION_ALREADY_CLOSED","TIME_BEFORE_SESSION_OPEN","REASON_CODE_NOT_FOUND","CURRENCY_MISMATCH","NO_CASH_DRAWER_ASSOCIATED","FAILED_TO_RECORD_COUNT"]}, +"PointOfSaleDevicePaymentSessionEdge":{"o":{"f":{"cursor":"String!","node":"PointOfSaleDevicePaymentSession!"}}}, +"PointOfSaleDevicePaymentSessionOpenPayload":{"o":{"f":{"pointOfSaleDevicePaymentSession":"PointOfSaleDevicePaymentSession","userErrors":"[PointOfSaleDevicePaymentSessionOpenUserError!]!"}}}, +"PointOfSaleDevicePaymentSessionOpenUserError":{"o":{"f":{"code":"PointOfSaleDevicePaymentSessionOpenUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PointOfSaleDevicePaymentSessionOpenUserErrorCode":{"e":["POINT_OF_SALE_DEVICE_NOT_FOUND","NO_CASH_DRAWER_ASSOCIATED","NOT_SAVED","ALREADY_OPEN","STAFF_MEMBER_NOT_FOUND","CURRENCY_MISMATCH","REASON_CODE_NOT_FOUND"]}, +"PointOfSaleDevicePaymentSessionSortKeys":{"e":["CLOSING_TIME","ID","OPENING_TIME"]}, +"PointOfSaleDevicePaymentSessionStatus":{"e":["OPEN","CLOSED"]}, +"PreferredRateSelectionInput":{"i":{"carrierCode":"String!","serviceCode":"String!"}}, +"PreparedFulfillmentOrderLineItemsInput":{"i":{"fulfillmentOrderId":"ID!"}}, +"PreviewInstallPayload":{"o":{"f":{"newTheme":"OnlineStoreTheme","userErrors":"[PreviewInstallUserError!]!"}}}, +"PreviewInstallUserError":{"o":{"f":{"code":"PreviewInstallUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PreviewInstallUserErrorCode":{"e":["INTERNAL_ERROR"]}, +"PriceCalculationType":{"e":["COMPONENTS_SUM","FIXED","NONE"]}, +"PriceInput":{"i":{"calculation":"PriceCalculationType","price":"Money"}}, +"PriceList":{"o":{"f":{"catalog":"Catalog","createdAt":"DateTime!","currency":"CurrencyCode!","fixedPricesCount":"Int!","id":"ID!","name":"String!","parent":"PriceListParent","prices":["PriceListPriceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","originType":"PriceListPriceOriginType","query":"String","reverse":"Boolean="}],"quantityRules":["QuantityRuleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","originType":"QuantityRuleOriginType","reverse":"Boolean="}]},"t":["Node"]}}, +"PriceListAdjustment":{"o":{"f":{"type":"PriceListAdjustmentType!","value":"Float!"}}}, +"PriceListAdjustmentInput":{"i":{"type":"PriceListAdjustmentType!","value":"Float!"}}, +"PriceListAdjustmentSettings":{"o":{"f":{"compareAtMode":"PriceListCompareAtMode!"}}}, +"PriceListAdjustmentSettingsInput":{"i":{"compareAtMode":"PriceListCompareAtMode!="}}, +"PriceListAdjustmentType":{"e":["PERCENTAGE_DECREASE","PERCENTAGE_INCREASE"]}, +"PriceListCompareAtMode":{"e":["ADJUSTED","NULLIFY"]}, +"PriceListConnection":{"o":{"f":{"edges":"[PriceListEdge!]!","nodes":"[PriceList!]!","pageInfo":"PageInfo!"}}}, +"PriceListCreateInput":{"i":{"catalogId":"ID","currency":"CurrencyCode!","name":"String!","parent":"PriceListParentCreateInput!"}}, +"PriceListCreatePayload":{"o":{"f":{"priceList":"PriceList","userErrors":"[PriceListUserError!]!"}}}, +"PriceListDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[PriceListUserError!]!"}}}, +"PriceListEdge":{"o":{"f":{"cursor":"String!","node":"PriceList!"}}}, +"PriceListFixedPricesAddPayload":{"o":{"f":{"prices":"[PriceListPrice!]","userErrors":"[PriceListPriceUserError!]!"}}}, +"PriceListFixedPricesByProductBulkUpdateUserError":{"o":{"f":{"code":"PriceListFixedPricesByProductBulkUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PriceListFixedPricesByProductBulkUpdateUserErrorCode":{"e":["NO_UPDATE_OPERATIONS_SPECIFIED","PRICES_TO_ADD_CURRENCY_MISMATCH","PRICE_LIST_DOES_NOT_EXIST","DUPLICATE_ID_IN_INPUT","ID_MUST_BE_MUTUALLY_EXCLUSIVE","PRODUCT_DOES_NOT_EXIST","PRICE_LIMIT_EXCEEDED","LOCAL_CURRENCY_GIFT_CARD_ISSUANCE_CURRENCY_MISMATCH","LOCAL_CURRENCY_GIFT_CARD_LIMIT_EXCEEDED"]}, +"PriceListFixedPricesByProductUpdatePayload":{"o":{"f":{"priceList":"PriceList","pricesToAddProducts":"[Product!]","pricesToDeleteProducts":"[Product!]","userErrors":"[PriceListFixedPricesByProductBulkUpdateUserError!]!"}}}, +"PriceListFixedPricesDeletePayload":{"o":{"f":{"deletedFixedPriceVariantIds":"[ID!]","userErrors":"[PriceListPriceUserError!]!"}}}, +"PriceListFixedPricesUpdatePayload":{"o":{"f":{"deletedFixedPriceVariantIds":"[ID!]","priceList":"PriceList","pricesAdded":"[PriceListPrice!]","userErrors":"[PriceListPriceUserError!]!"}}}, +"PriceListParent":{"o":{"f":{"adjustment":"PriceListAdjustment!","settings":"PriceListAdjustmentSettings!"}}}, +"PriceListParentCreateInput":{"i":{"adjustment":"PriceListAdjustmentInput!","settings":"PriceListAdjustmentSettingsInput"}}, +"PriceListParentUpdateInput":{"i":{"adjustment":"PriceListAdjustmentInput!","settings":"PriceListAdjustmentSettingsInput"}}, +"PriceListPrice":{"o":{"f":{"compareAtPrice":"MoneyV2","originType":"PriceListPriceOriginType!","price":"MoneyV2!","quantityPriceBreaks":["QuantityPriceBreakConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"QuantityPriceBreakSortKeys="}],"variant":"ProductVariant!"}}}, +"PriceListPriceConnection":{"o":{"f":{"edges":"[PriceListPriceEdge!]!","nodes":"[PriceListPrice!]!","pageInfo":"PageInfo!"}}}, +"PriceListPriceEdge":{"o":{"f":{"cursor":"String!","node":"PriceListPrice!"}}}, +"PriceListPriceInput":{"i":{"compareAtPrice":"MoneyInput","price":"MoneyInput!","variantId":"ID!"}}, +"PriceListPriceOriginType":{"e":["FIXED","RELATIVE"]}, +"PriceListPriceUserError":{"o":{"f":{"code":"PriceListPriceUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PriceListPriceUserErrorCode":{"e":["BLANK","PRICE_LIST_NOT_FOUND","PRICE_LIST_CURRENCY_MISMATCH","LOCAL_CURRENCY_GIFT_CARD_ISSUANCE_CURRENCY_MISMATCH","LOCAL_CURRENCY_GIFT_CARD_LIMIT_EXCEEDED","VARIANT_NOT_FOUND","PRICE_NOT_FIXED"]}, +"PriceListProductPriceInput":{"i":{"compareAtPrice":"MoneyInput","price":"MoneyInput!","productId":"ID!"}}, +"PriceListSortKeys":{"e":["ID","NAME"]}, +"PriceListUpdateInput":{"i":{"catalogId":"ID","currency":"CurrencyCode","name":"String","parent":"PriceListParentUpdateInput"}}, +"PriceListUpdatePayload":{"o":{"f":{"priceList":"PriceList","userErrors":"[PriceListUserError!]!"}}}, +"PriceListUserError":{"o":{"f":{"code":"PriceListUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PriceListUserErrorCode":{"e":["TAKEN","BLANK","INCLUSION","TOO_LONG","PRICE_LIST_NOT_FOUND","PRICE_LIST_LOCKED","CURRENCY_MARKET_MISMATCH","INVALID_ADJUSTMENT_VALUE","INVALID_ADJUSTMENT_MIN_VALUE","INVALID_ADJUSTMENT_MAX_VALUE","CATALOG_CONTEXT_DOES_NOT_SUPPORT_QUANTITY_RULES","CATALOG_CONTEXT_DOES_NOT_SUPPORT_QUANTITY_PRICE_BREAKS","CONTEXT_RULE_LIMIT_ONE_OPTION","CURRENCY_NOT_SUPPORTED","PRICE_LIST_NOT_ALLOWED_FOR_PRIMARY_MARKET","CATALOG_DOES_NOT_EXIST","CATALOG_MARKET_AND_PRICE_LIST_CURRENCY_MISMATCH","CATALOG_TAKEN","COUNTRY_PRICE_LIST_ASSIGNMENT","GENERIC_ERROR"]}, +"PricingAuditTrail":{"o":{"f":{"priceAdjustments":"[AuditTrailAdjustment!]!"}}}, +"PricingPercentageValue":{"o":{"f":{"percentage":"Float!"}}}, +"PricingValue":{"u":["MoneyV2","PricingPercentageValue"]}, +"PrivacyCountryCode":{"e":["AN","AC","AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NS","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TA","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW","XX"]}, +"PrivacyFeaturesDisablePayload":{"o":{"f":{"featuresDisabled":"[PrivacyFeaturesEnum!]","userErrors":"[PrivacyFeaturesDisableUserError!]!"}}}, +"PrivacyFeaturesDisableUserError":{"o":{"f":{"code":"PrivacyFeaturesDisableUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PrivacyFeaturesDisableUserErrorCode":{"e":["FAILED"]}, +"PrivacyFeaturesEnum":{"e":["COOKIE_BANNER","DATA_SALE_OPT_OUT_PAGE","PRIVACY_POLICY"]}, +"PrivacyPolicy":{"o":{"f":{"autoManaged":"Boolean!","supportedLocales":"[String!]!"}}}, +"PrivacySettings":{"o":{"f":{"banner":"CookieBanner","dataSaleOptOutPage":"DataSaleOptOutPage","privacyPolicy":"PrivacyPolicy"}}}, +"Product":{"o":{"f":{"availablePublicationsCount":"Count","bodyHtml":"String","bundleComponents":["ProductBundleComponentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"bundleConsolidatedOptions":"[ComponentizedProductsBundleConsolidatedOption!]","category":"TaxonomyCategory","collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CollectionSortKeys="}],"combinedListing":"CombinedListing","combinedListingRole":"CombinedListingsRole","compareAtPriceRange":"ProductCompareAtPriceRange","contextualPricing":["ProductContextualPricing!",{"context":"ContextualPricingContext!"}],"createdAt":"DateTime!","customProductType":"String","defaultCursor":"String!","description":["String!",{"truncateAt":"Int"}],"descriptionHtml":"HTML!","descriptionPlainSummary":"String!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"featuredImage":"Image","featuredMedia":"Media","feedback":"ResourceFeedback","giftCardSettings":"GiftCardProductSettings","giftCardTemplateSuffix":"String","handle":"String!","hasOnlyDefaultVariant":"Boolean!","hasOutOfStockVariants":"Boolean!","hasVariantsThatRequiresComponents":"Boolean!","id":"ID!","images":["ImageConnection!",{"after":"String","before":"String","crop":"CropRegion","first":"Int","last":"Int","maxHeight":"Int","maxWidth":"Int","reverse":"Boolean=","scale":"Int=","sortKey":"ProductImageSortKeys="}],"inCollection":["Boolean!",{"id":"ID!"}],"isGiftCard":"Boolean!","legacyResourceId":"UnsignedInt64!","media":["MediaConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ProductMediaSortKeys="}],"mediaCount":"Count","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"onlineStorePreviewUrl":"URL","onlineStoreUrl":"URL","options":["[ProductOption!]!",{"first":"Int"}],"priceRange":"ProductPriceRange!","priceRangeV2":"ProductPriceRangeV2!","productCategory":"ProductCategory","productComponents":["ProductComponentTypeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productComponentsCount":"Count","productParents":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"productPublications":["ProductPublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productType":"String!","publicationCount":["Int!",{"onlyPublished":"Boolean="}],"publications":["ProductPublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"publishedAt":"DateTime","publishedInContext":["Boolean!",{"context":"ContextualPublicationContext!"}],"publishedOnChannel":["Boolean!",{"channelId":"ID!"}],"publishedOnCurrentChannel":"Boolean!","publishedOnCurrentPublication":"Boolean!","publishedOnPublication":["Boolean!",{"publicationId":"ID!"}],"requiresSellingPlan":"Boolean!","resourcePublicationOnCurrentPublication":"ResourcePublicationV2","resourcePublications":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"resourcePublicationsCount":["Count",{"onlyPublished":"Boolean="}],"resourcePublicationsV2":["ResourcePublicationV2Connection!",{"after":"String","before":"String","catalogType":"CatalogType","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"restrictedForResource":["RestrictedForResource",{"calculatedOrderId":"ID!"}],"sellingPlanGroupCount":"Int!","sellingPlanGroups":["SellingPlanGroupConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"sellingPlanGroupsCount":"Count","seo":"SEO!","standardizedProductType":"StandardizedProductType","status":"ProductStatus!","storefrontId":"StorefrontID!","tags":"[String!]!","templateSuffix":"String","title":"String!","totalInventory":"Int!","totalVariants":"Int!","tracksInventory":"Boolean!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"unpublishedChannels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unpublishedPublications":["PublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!","variants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"ProductVariantSortKeys="}],"variantsCount":"Count","variantsInCollection":["ProductVariantConnection",{"after":"String","before":"String","collectionId":"ID!","first":"Int","last":"Int"}],"variantsInCollectionCount":["Count",{"collectionId":"ID!"}],"vendor":"String!"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","LegacyInteroperability","Navigable","Node","OnlineStorePreviewable","Publishable"],"d":{"bodyHtml":"Use `descriptionHtml` instead.","customProductType":"Use `productType` instead.","descriptionPlainSummary":"Use `description` instead.","featuredImage":"Use `featuredMedia` instead.","images":"Use `media` instead.","images(crop)":"Use `Image.url(transform: { crop:})` instead.","images(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","images(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","images(scale)":"Use `Image.url(transform: { scale:})` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","priceRange":"Use `priceRangeV2` instead.","productCategory":"Use `category` instead.","productPublications":"Use `resourcePublications` instead.","publicationCount":"Use `resourcePublicationsCount` instead.","publications":"Use `resourcePublications` instead.","publishedOnChannel":"Use `publishedOnPublication` instead.","publishedOnCurrentChannel":"Use `publishedOnCurrentPublication` instead.","publishedOnCurrentPublication":"Use `publishedOnPublication` instead.","resourcePublicationOnCurrentPublication":"Use `resourcePublications` instead.","sellingPlanGroupCount":"Use `sellingPlanGroupsCount` instead.","standardizedProductType":"Use `productCategory` instead.","storefrontId":"Use `id` instead.","totalVariants":"Use `variantsCount` instead.","unpublishedChannels":"Use `unpublishedPublications` instead."}}}, +"ProductBundleComponent":{"o":{"f":{"componentProduct":"Product!","componentVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"componentVariantsCount":"Count","optionSelections":"[ProductBundleComponentOptionSelection!]!","quantity":"Int","quantityOption":"ProductBundleComponentQuantityOption"}}}, +"ProductBundleComponentConnection":{"o":{"f":{"edges":"[ProductBundleComponentEdge!]!","nodes":"[ProductBundleComponent!]!","pageInfo":"PageInfo!"}}}, +"ProductBundleComponentEdge":{"o":{"f":{"cursor":"String!","node":"ProductBundleComponent!"}}}, +"ProductBundleComponentInput":{"i":{"optionSelections":"[ProductBundleComponentOptionSelectionInput!]!","productId":"ID!","quantity":"Int","quantityOption":"ProductBundleComponentQuantityOptionInput"}}, +"ProductBundleComponentOptionSelection":{"o":{"f":{"componentOption":"ProductOption!","parentOption":"ProductOption","values":"[ProductBundleComponentOptionSelectionValue!]!"}}}, +"ProductBundleComponentOptionSelectionInput":{"i":{"componentOptionId":"ID!","name":"String!","values":"[String!]!"}}, +"ProductBundleComponentOptionSelectionStatus":{"e":["SELECTED","DESELECTED","NEW","UNAVAILABLE"]}, +"ProductBundleComponentOptionSelectionValue":{"o":{"f":{"selectionStatus":"ProductBundleComponentOptionSelectionStatus!","value":"String!"}}}, +"ProductBundleComponentQuantityOption":{"o":{"f":{"name":"String!","parentOption":"ProductOption","values":"[ProductBundleComponentQuantityOptionValue!]!"}}}, +"ProductBundleComponentQuantityOptionInput":{"i":{"name":"String!","values":"[ProductBundleComponentQuantityOptionValueInput!]!"}}, +"ProductBundleComponentQuantityOptionValue":{"o":{"f":{"name":"String!","quantity":"Int!"}}}, +"ProductBundleComponentQuantityOptionValueInput":{"i":{"name":"String!","quantity":"Int!"}}, +"ProductBundleConsolidatedOptionComponentInput":{"i":{"componentOptionId":"ID","componentOptionValue":"String!"}}, +"ProductBundleConsolidatedOptionInput":{"i":{"optionName":"String!","optionSelections":"[ProductBundleConsolidatedOptionSelectionInput!]!"}}, +"ProductBundleConsolidatedOptionSelectionInput":{"i":{"components":"[ProductBundleConsolidatedOptionComponentInput!]!","optionValue":"String!"}}, +"ProductBundleCreateInput":{"i":{"components":"[ProductBundleComponentInput!]!","consolidatedOptions":"[ProductBundleConsolidatedOptionInput!]","title":"String!"}}, +"ProductBundleCreatePayload":{"o":{"f":{"productBundleOperation":"ProductBundleOperation","userErrors":"[UserError!]!"}}}, +"ProductBundleMutationUserError":{"o":{"f":{"code":"ProductBundleMutationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductBundleMutationUserErrorCode":{"e":["GENERIC_ERROR","PRODUCT_DOES_NOT_EXIST","INVALID_INPUT","JOB_ERROR"]}, +"ProductBundleOperation":{"o":{"f":{"id":"ID!","product":"Product","status":"ProductOperationStatus!","userErrors":"[ProductBundleMutationUserError!]!"},"t":["Node","ProductOperation"]}}, +"ProductBundleUpdateInput":{"i":{"components":"[ProductBundleComponentInput!]","consolidatedOptions":"[ProductBundleConsolidatedOptionInput!]","productId":"ID!","title":"String"}}, +"ProductBundleUpdatePayload":{"o":{"f":{"productBundleOperation":"ProductBundleOperation","userErrors":"[UserError!]!"}}}, +"ProductCategory":{"o":{"f":{"productTaxonomyNode":"ProductTaxonomyNode"}}}, +"ProductChangeStatusPayload":{"o":{"f":{"product":"Product","userErrors":"[ProductChangeStatusUserError!]!"}}}, +"ProductChangeStatusUserError":{"o":{"f":{"code":"ProductChangeStatusUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductChangeStatusUserErrorCode":{"e":["PRODUCT_NOT_FOUND","COMBINED_LISTINGS_NOT_COMPATIBLE_WITH_SHOP"]}, +"ProductClaimOwnershipInput":{"i":{"bundles":"Boolean"}}, +"ProductCollectionSortKeys":{"e":["BEST_SELLING","COLLECTION_DEFAULT","CREATED","ID","MANUAL","PRICE","RELEVANCE","TITLE"]}, +"ProductCompareAtPriceRange":{"o":{"f":{"maxVariantCompareAtPrice":"MoneyV2!","minVariantCompareAtPrice":"MoneyV2!"}}}, +"ProductComponentType":{"o":{"f":{"componentVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"componentVariantsCount":"Count","nonComponentVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"nonComponentVariantsCount":"Count","product":"Product!"}}}, +"ProductComponentTypeConnection":{"o":{"f":{"edges":"[ProductComponentTypeEdge!]!","nodes":"[ProductComponentType!]!","pageInfo":"PageInfo!"}}}, +"ProductComponentTypeEdge":{"o":{"f":{"cursor":"String!","node":"ProductComponentType!"}}}, +"ProductConnection":{"o":{"f":{"edges":"[ProductEdge!]!","nodes":"[Product!]!","pageInfo":"PageInfo!"}}}, +"ProductContextualPricing":{"o":{"f":{"fixedQuantityRulesCount":"Int!","maxVariantPricing":"ProductVariantContextualPricing","minVariantPricing":"ProductVariantContextualPricing","priceRange":"ProductPriceRangeV2!"}}}, +"ProductCreateInput":{"i":{"category":"ID","claimOwnership":"ProductClaimOwnershipInput","collectionsToJoin":"[ID!]","combinedListingRole":"CombinedListingsRole","descriptionHtml":"String","giftCard":"Boolean","giftCardTemplateSuffix":"String","handle":"String","metafields":"[MetafieldInput!]","productOptions":"[OptionCreateInput!]","productType":"String","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","vendor":"String"}}, +"ProductCreateMediaPayload":{"o":{"f":{"media":"[Media!]","mediaUserErrors":"[MediaUserError!]!","product":"Product","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `mediaUserErrors` instead."}}}, +"ProductCreatePayload":{"o":{"f":{"product":"Product","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"ProductDeleteInput":{"i":{"id":"ID!"}}, +"ProductDeleteMediaPayload":{"o":{"f":{"deletedMediaIds":"[ID!]","deletedProductImageIds":"[ID!]","mediaUserErrors":"[MediaUserError!]!","product":"Product","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `mediaUserErrors` instead."}}}, +"ProductDeleteOperation":{"o":{"f":{"deletedProductId":"ID","id":"ID!","product":"Product","status":"ProductOperationStatus!","userErrors":"[UserError!]!"},"t":["Node","ProductOperation"]}}, +"ProductDeletePayload":{"o":{"f":{"deletedProductId":"ID","productDeleteOperation":"ProductDeleteOperation","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"ProductDiscountsWithTagsOnSameCartLineInput":{"i":{"add":"[String!]","remove":"[String!]"}}, +"ProductDuplicateJob":{"o":{"f":{"done":"Boolean!","id":"ID!"}}}, +"ProductDuplicateOperation":{"o":{"f":{"id":"ID!","newProduct":"Product","product":"Product","status":"ProductOperationStatus!","userErrors":"[UserError!]!"},"t":["Node","ProductOperation"]}}, +"ProductDuplicatePayload":{"o":{"f":{"imageJob":"Job","newProduct":"Product","productDuplicateOperation":"ProductDuplicateOperation","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"ProductEdge":{"o":{"f":{"cursor":"String!","node":"Product!"}}}, +"ProductFeed":{"o":{"f":{"channelId":"ID!","country":"CountryCode","id":"ID!","language":"LanguageCode","status":"ProductFeedStatus!"},"t":["Node"]}}, +"ProductFeedConnection":{"o":{"f":{"edges":"[ProductFeedEdge!]!","nodes":"[ProductFeed!]!","pageInfo":"PageInfo!"}}}, +"ProductFeedCreatePayload":{"o":{"f":{"productFeed":"ProductFeed","userErrors":"[ProductFeedCreateUserError!]!"}}}, +"ProductFeedCreateUserError":{"o":{"f":{"code":"ProductFeedCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductFeedCreateUserErrorCode":{"e":["INVALID","TAKEN"]}, +"ProductFeedDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[ProductFeedDeleteUserError!]!"}}}, +"ProductFeedDeleteUserError":{"o":{"f":{"code":"ProductFeedDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductFeedDeleteUserErrorCode":{"e":["INVALID"]}, +"ProductFeedEdge":{"o":{"f":{"cursor":"String!","node":"ProductFeed!"}}}, +"ProductFeedInput":{"i":{"channelId":"ID","country":"CountryCode!","language":"LanguageCode!"}}, +"ProductFeedStatus":{"e":["ACTIVE","INACTIVE"]}, +"ProductFullSyncPayload":{"o":{"f":{"id":"ID","userErrors":"[ProductFullSyncUserError!]!"}}}, +"ProductFullSyncUserError":{"o":{"f":{"code":"ProductFullSyncUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductFullSyncUserErrorCode":{"e":["INVALID"]}, +"ProductIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"}}, +"ProductImageSortKeys":{"e":["CREATED_AT","ID","POSITION"]}, +"ProductInput":{"i":{"f":{"category":"ID","claimOwnership":"ProductClaimOwnershipInput","collectionsToJoin":"[ID!]","collectionsToLeave":"[ID!]","combinedListingRole":"CombinedListingsRole","descriptionHtml":"String","giftCard":"Boolean","giftCardTemplateSuffix":"String","handle":"String","id":"ID","metafields":"[MetafieldInput!]","productOptions":"[OptionCreateInput!]","productPublications":"[ProductPublicationInput!]","productType":"String","publications":"[ProductPublicationInput!]","publishDate":"DateTime","publishOn":"DateTime","published":"Boolean","publishedAt":"DateTime","redirectNewHandle":"Boolean","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","vendor":"String"},"d":{"productPublications":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publications":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publishDate":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publishOn":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","published":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publishedAt":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead."}}}, +"ProductJoinSellingPlanGroupsPayload":{"o":{"f":{"product":"Product","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"ProductLeaveSellingPlanGroupsPayload":{"o":{"f":{"product":"Product","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"ProductMediaSortKeys":{"e":["ID","POSITION"]}, +"ProductOperation":{"n":{"f":{"product":"Product","status":"ProductOperationStatus!"},"t":["ProductBundleOperation","ProductDeleteOperation","ProductDuplicateOperation","ProductSetOperation"]}}, +"ProductOperationStatus":{"e":["CREATED","ACTIVE","COMPLETE"]}, +"ProductOption":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","linkedMetafield":"LinkedMetafield","name":"String!","optionValues":"[ProductOptionValue!]!","position":"Int!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"values":"[String!]!"},"t":["HasPublishedTranslations","Node"]}}, +"ProductOptionCreateVariantStrategy":{"e":["LEAVE_AS_IS","CREATE"]}, +"ProductOptionDeleteStrategy":{"e":["DEFAULT","POSITION","NON_DESTRUCTIVE"]}, +"ProductOptionUpdatePayload":{"o":{"f":{"product":"Product","userErrors":"[ProductOptionUpdateUserError!]!"}}}, +"ProductOptionUpdateUserError":{"o":{"f":{"code":"ProductOptionUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductOptionUpdateUserErrorCode":{"e":["PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","OPTION_DOES_NOT_EXIST","OPTION_ALREADY_EXISTS","INVALID_POSITION","INVALID_NAME","OPTION_VALUES_OVER_LIMIT","OPTION_VALUE_DOES_NOT_EXIST","OPTION_VALUE_ALREADY_EXISTS","OPTION_VALUE_HAS_VARIANTS","CANNOT_DELETE_ALL_OPTION_VALUES_IN_OPTION","CANNOT_LEAVE_OPTIONS_WITHOUT_VARIANTS","NO_KEY_ON_CREATE","KEY_MISSING_IN_INPUT","DUPLICATED_OPTION_VALUE","OPTION_NAME_TOO_LONG","OPTION_VALUE_NAME_TOO_LONG","OPTION_VALUE_CONFLICTING_OPERATION","CANNOT_CREATE_VARIANTS_ABOVE_LIMIT","CANNOT_COMBINE_LINKED_AND_NONLINKED_OPTION_VALUES","INVALID_METAFIELD_VALUE_FOR_LINKED_OPTION","DUPLICATE_LINKED_OPTION","OPTION_LINKED_METAFIELD_ALREADY_TAKEN","LINKED_OPTION_UPDATE_MISSING_VALUES","LINKED_OPTIONS_NOT_SUPPORTED_FOR_SHOP","LINKED_METAFIELD_DEFINITION_NOT_FOUND","CANNOT_MAKE_CHANGES_IF_VARIANT_IS_MISSING_REQUIRED_SKU","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION","CANNOT_DELETE_VARIANT_WITHOUT_PERMISSION","TOO_MANY_VARIANTS_CREATED"]}, +"ProductOptionUpdateVariantStrategy":{"e":["LEAVE_AS_IS","MANAGE"]}, +"ProductOptionValue":{"o":{"f":{"hasVariants":"Boolean!","id":"ID!","linkedMetafieldValue":"String","name":"String!","swatch":"ProductOptionValueSwatch","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["HasPublishedTranslations","Node"]}}, +"ProductOptionValueSwatch":{"o":{"f":{"color":"Color","image":"MediaImage"}}}, +"ProductOptionsCreatePayload":{"o":{"f":{"product":"Product","userErrors":"[ProductOptionsCreateUserError!]!"}}}, +"ProductOptionsCreateUserError":{"o":{"f":{"code":"ProductOptionsCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductOptionsCreateUserErrorCode":{"e":["OPTION_ALREADY_EXISTS","OPTIONS_OVER_LIMIT","OPTION_VALUES_OVER_LIMIT","INVALID_NAME","PRODUCT_SUSPENDED","NEW_OPTION_WITHOUT_VALUE_FOR_EXISTING_VARIANTS","DUPLICATED_OPTION_NAME","DUPLICATED_OPTION_VALUE","OPTION_NAME_MISSING","OPTION_VALUES_MISSING","OPTION_VALUE_NAME_TOO_LONG","OPTION_NAME_TOO_LONG","POSITION_OUT_OF_BOUNDS","OPTION_POSITION_MISSING","PRODUCT_DOES_NOT_EXIST","LINKED_METAFIELD_DEFINITION_NOT_FOUND","INVALID_METAFIELD_VALUE_FOR_LINKED_OPTION","MISSING_METAFIELD_VALUES_FOR_LINKED_OPTION","CANNOT_COMBINE_LINKED_METAFIELD_AND_OPTION_VALUES","DUPLICATE_LINKED_OPTION","OPTION_LINKED_METAFIELD_ALREADY_TAKEN","LINKED_OPTIONS_NOT_SUPPORTED_FOR_SHOP","CANNOT_MAKE_CHANGES_IF_VARIANT_IS_MISSING_REQUIRED_SKU","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION","LINKED_METAFIELD_VALUE_WITHOUT_LINKED_OPTION","TOO_MANY_VARIANTS_CREATED"]}, +"ProductOptionsDeletePayload":{"o":{"f":{"deletedOptionsIds":"[ID!]","product":"Product","userErrors":"[ProductOptionsDeleteUserError!]!"}}}, +"ProductOptionsDeleteUserError":{"o":{"f":{"code":"ProductOptionsDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductOptionsDeleteUserErrorCode":{"e":["PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","OPTION_DOES_NOT_EXIST","OPTIONS_DO_NOT_BELONG_TO_THE_SAME_PRODUCT","CANNOT_DELETE_OPTION_WITH_MULTIPLE_VALUES","CANNOT_USE_NON_DESTRUCTIVE_STRATEGY","CANNOT_MAKE_CHANGES_IF_VARIANT_IS_MISSING_REQUIRED_SKU","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION","CANNOT_DELETE_VARIANT_WITHOUT_PERMISSION"]}, +"ProductOptionsReorderPayload":{"o":{"f":{"product":"Product","userErrors":"[ProductOptionsReorderUserError!]!"}}}, +"ProductOptionsReorderUserError":{"o":{"f":{"code":"ProductOptionsReorderUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductOptionsReorderUserErrorCode":{"e":["OPTION_NAME_DOES_NOT_EXIST","OPTION_VALUE_DOES_NOT_EXIST","OPTION_ID_DOES_NOT_EXIST","OPTION_VALUE_ID_DOES_NOT_EXIST","DUPLICATED_OPTION_NAME","DUPLICATED_OPTION_VALUE","MISSING_OPTION_NAME","MISSING_OPTION_VALUE","PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","NO_KEY_ON_REORDER","MIXING_ID_AND_NAME_KEYS_IS_NOT_ALLOWED","CANNOT_MAKE_CHANGES_IF_VARIANT_IS_MISSING_REQUIRED_SKU"]}, +"ProductPriceRange":{"o":{"f":{"maxVariantPrice":"MoneyV2!","minVariantPrice":"MoneyV2!"}}}, +"ProductPriceRangeV2":{"o":{"f":{"maxVariantPrice":"MoneyV2!","minVariantPrice":"MoneyV2!"}}}, +"ProductPublication":{"o":{"f":{"channel":"Channel!","isPublished":"Boolean!","product":"Product!","publishDate":"DateTime"}}}, +"ProductPublicationConnection":{"o":{"f":{"edges":"[ProductPublicationEdge!]!","nodes":"[ProductPublication!]!","pageInfo":"PageInfo!"}}}, +"ProductPublicationEdge":{"o":{"f":{"cursor":"String!","node":"ProductPublication!"}}}, +"ProductPublicationInput":{"i":{"f":{"channelHandle":"String","channelId":"ID","publicationId":"ID","publishDate":"DateTime"},"d":{"channelHandle":"Use publicationId instead.","channelId":"Use publicationId instead."}}}, +"ProductPublishInput":{"i":{"id":"ID!","productPublications":"[ProductPublicationInput!]!"}}, +"ProductPublishPayload":{"o":{"f":{"product":"Product","productPublications":"[ProductPublication!]","shop":"Shop!","userErrors":"[UserError!]!"},"d":{"productPublications":"Use Product.publications instead."}}}, +"ProductReorderMediaPayload":{"o":{"f":{"job":"Job","mediaUserErrors":"[MediaUserError!]!","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `mediaUserErrors` instead."}}}, +"ProductResourceFeedback":{"o":{"f":{"channel":"Channel","feedbackGeneratedAt":"DateTime!","messages":"[String!]!","productId":"ID!","productUpdatedAt":"DateTime!","state":"ResourceFeedbackState!"}}}, +"ProductResourceFeedbackInput":{"i":{"channelId":"ID","feedbackGeneratedAt":"DateTime!","messages":"[String!]","productId":"ID!","productUpdatedAt":"DateTime!","state":"ResourceFeedbackState!"}}, +"ProductSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineItem":"LineItem!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"ProductSetIdentifiers":{"i":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"}}, +"ProductSetInput":{"i":{"f":{"category":"ID","claimOwnership":"ProductClaimOwnershipInput","collections":"[ID!]","combinedListingRole":"CombinedListingsRole","descriptionHtml":"String","files":"[FileSetInput!]","giftCard":"Boolean","giftCardTemplateSuffix":"String","handle":"String","id":"ID","metafields":"[MetafieldInput!]","productOptions":"[OptionSetInput!]","productType":"String","redirectNewHandle":"Boolean","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","variants":"[ProductVariantSetInput!]","vendor":"String"},"d":{"id":"Use `identifier` instead to get the product's ID"}}}, +"ProductSetInventoryInput":{"i":{"locationId":"ID!","name":"String!","quantity":"Int!"}}, +"ProductSetOperation":{"o":{"f":{"id":"ID!","product":"Product","status":"ProductOperationStatus!","userErrors":"[ProductSetUserError!]!"},"t":["Node","ProductOperation"]}}, +"ProductSetPayload":{"o":{"f":{"product":"Product","productSetOperation":"ProductSetOperation","userErrors":"[ProductSetUserError!]!"}}}, +"ProductSetUserError":{"o":{"f":{"code":"ProductSetUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductSetUserErrorCode":{"e":["ID_NOT_ALLOWED","MISSING_FIELD_REQUIRED","INPUT_MISMATCH","NOT_FOUND","METAFIELD_MISMATCH","GENERIC_ERROR","INVALID_METAFIELD","INVALID_VARIANT","PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","PRODUCT_VARIANT_DOES_NOT_EXIST","OPTION_DOES_NOT_EXIST","OPTION_VALUE_DOES_NOT_EXIST","OPTIONS_OVER_LIMIT","OPTION_VALUES_OVER_LIMIT","OPTION_VALUES_MISSING","DUPLICATED_OPTION_NAME","DUPLICATED_OPTION_VALUE","VARIANTS_OVER_LIMIT","PRODUCT_OPTIONS_INPUT_MISSING","VARIANTS_INPUT_MISSING","GIFT_CARDS_NOT_ACTIVATED","GIFT_CARD_ATTRIBUTE_CANNOT_BE_CHANGED","INVALID_PRODUCT","INVALID_INPUT","JOB_ERROR","CAPABILITY_VIOLATION","CANNOT_COMBINE_LINKED_AND_NONLINKED_OPTION_VALUES","INVALID_METAFIELD_VALUE_FOR_LINKED_OPTION","DUPLICATE_LINKED_OPTION","DUPLICATED_METAFIELD_VALUE","LINKED_OPTIONS_NOT_SUPPORTED_FOR_SHOP","LINKED_METAFIELD_DEFINITION_NOT_FOUND","DUPLICATED_VALUE","HANDLE_NOT_UNIQUE","INCOMPATIBLE_BARCODE_FIELDS","BLANK_BARCODE_VALUE","TOO_MANY_BARCODES","BARCODE_VALUE_TOO_LONG","DUPLICATE_BARCODE_VALUE","INVALID_BARCODE_TYPE","INVALID_BARCODE_SEPARATORS","INVALID_BARCODE_LENGTH","INVALID_BARCODE_PREFIX","INVALID_BARCODE_CHARACTERS","BARCODE_CHECKSUM_VALIDATION_FAILED","INVENTORY_QUANTITIES_LIMIT_EXCEEDED"]}, +"ProductSortKeys":{"e":["CREATED_AT","ID","INVENTORY_TOTAL","PRODUCT_TYPE","PUBLISHED_AT","RELEVANCE","TITLE","UPDATED_AT","VENDOR"]}, +"ProductStatus":{"e":["ACTIVE","ARCHIVED","DRAFT","UNLISTED"]}, +"ProductTaxonomyNode":{"o":{"f":{"fullName":"String!","id":"ID!","isLeaf":"Boolean!","isRoot":"Boolean!","name":"String!"},"t":["Node"]}}, +"ProductUnpublishInput":{"i":{"id":"ID!","productPublications":"[ProductPublicationInput!]!"}}, +"ProductUnpublishPayload":{"o":{"f":{"product":"Product","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"ProductUpdateIdentifiers":{"i":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"}}, +"ProductUpdateInput":{"i":{"category":"ID","collectionsToJoin":"[ID!]","collectionsToLeave":"[ID!]","deleteConflictingConstrainedMetafields":"Boolean=","descriptionHtml":"String","giftCardTemplateSuffix":"String","handle":"String","id":"ID","metafields":"[MetafieldInput!]","productType":"String","redirectNewHandle":"Boolean","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","vendor":"String"}}, +"ProductUpdateMediaPayload":{"o":{"f":{"media":"[Media!]","mediaUserErrors":"[MediaUserError!]!","product":"Product","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `mediaUserErrors` instead."}}}, +"ProductUpdatePayload":{"o":{"f":{"product":"Product","userErrors":"[UserError!]!"}}}, +"ProductVariant":{"o":{"f":{"availableForSale":"Boolean!","availablePublicationsCount":"Count","barcode":"String","barcodes":["ProductVariantBarcodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}],"compareAtPrice":"Money","contextualPricing":["ProductVariantContextualPricing!",{"context":"ContextualPricingContext!"}],"createdAt":"DateTime!","defaultCursor":"String!","deliveryProfile":"DeliveryProfile","displayName":"String!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","image":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"inventoryItem":"InventoryItem!","inventoryPolicy":"ProductVariantInventoryPolicy!","inventoryQuantity":"Int","legacyResourceId":"UnsignedInt64!","media":["MediaConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"position":"Int!","presentmentPrices":["ProductVariantPricePairConnection!",{"after":"String","before":"String","first":"Int","last":"Int","presentmentCurrencies":"[CurrencyCode!]","reverse":"Boolean="}],"price":"Money!","product":"Product!","productParents":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"productVariantComponents":["ProductVariantComponentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"publicationCount":["Int!",{"onlyPublished":"Boolean="}],"publishedOnChannel":["Boolean!",{"channelId":"ID!"}],"publishedOnCurrentChannel":"Boolean!","publishedOnCurrentPublication":"Boolean!","publishedOnPublication":["Boolean!",{"publicationId":"ID!"}],"requiresComponents":"Boolean!","resourcePublications":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"resourcePublicationsCount":["Count",{"onlyPublished":"Boolean="}],"resourcePublicationsV2":["ResourcePublicationV2Connection!",{"after":"String","before":"String","catalogType":"CatalogType","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"selectedOptions":"[SelectedOption!]!","sellableOnlineQuantity":"Int!","sellingPlanGroupCount":"Int!","sellingPlanGroups":["SellingPlanGroupConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"sellingPlanGroupsCount":"Count","showUnitPrice":"Boolean!","sku":"String","storefrontId":"StorefrontID!","taxCode":"String","taxable":"Boolean!","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"unitPrice":"MoneyV2","unitPriceMeasurement":"UnitPriceMeasurement","unpublishedChannels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unpublishedPublications":["PublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","LegacyInteroperability","Navigable","Node","Publishable"],"d":{"barcode":"Use `barcodes` instead.","image":"Use `media` instead.","image(crop)":"Use `Image.url(transform: { crop:})` instead.","image(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","image(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","image(scale)":"Use `Image.url(transform: { scale:})` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","presentmentPrices":"Use `contextualPricing` instead.","publicationCount":"Use `resourcePublicationsCount` instead.","publishedOnChannel":"Use `publishedOnPublication` instead.","publishedOnCurrentChannel":"Use `publishedOnCurrentPublication` instead.","publishedOnCurrentPublication":"Use `publishedOnPublication` instead.","sellingPlanGroupCount":"Use `sellingPlanGroupsCount` instead.","storefrontId":"Use `id` instead.","taxCode":"This field should no longer be used in new integrations. This field will not be available in future API versions.","unpublishedChannels":"Use `unpublishedPublications` instead."}}}, +"ProductVariantAppendMediaInput":{"i":{"mediaIds":"[ID!]!","variantId":"ID!"}}, +"ProductVariantAppendMediaPayload":{"o":{"f":{"product":"Product","productVariants":"[ProductVariant!]","userErrors":"[MediaUserError!]!"}}}, +"ProductVariantBarcode":{"o":{"f":{"type":"BarcodeType","value":"String!"}}}, +"ProductVariantBarcodeConnection":{"o":{"f":{"edges":"[ProductVariantBarcodeEdge!]!","nodes":"[ProductVariantBarcode!]!","pageInfo":"PageInfo!"}}}, +"ProductVariantBarcodeEdge":{"o":{"f":{"cursor":"String!","node":"ProductVariantBarcode!"}}}, +"ProductVariantComponent":{"o":{"f":{"id":"ID!","productVariant":"ProductVariant!","quantity":"Int!"},"t":["Node"]}}, +"ProductVariantComponentConnection":{"o":{"f":{"edges":"[ProductVariantComponentEdge!]!","nodes":"[ProductVariantComponent!]!","pageInfo":"PageInfo!"}}}, +"ProductVariantComponentEdge":{"o":{"f":{"cursor":"String!","node":"ProductVariantComponent!"}}}, +"ProductVariantConnection":{"o":{"f":{"edges":"[ProductVariantEdge!]!","nodes":"[ProductVariant!]!","pageInfo":"PageInfo!"}}}, +"ProductVariantContextualPricing":{"o":{"f":{"auditTrail":"PricingAuditTrail!","compareAtPrice":"MoneyV2","price":"MoneyV2!","quantityPriceBreaks":["QuantityPriceBreakConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"QuantityPriceBreakSortKeys="}],"quantityRule":"QuantityRule!","unitPrice":"MoneyV2"}}}, +"ProductVariantDetachMediaInput":{"i":{"mediaIds":"[ID!]!","variantId":"ID!"}}, +"ProductVariantDetachMediaPayload":{"o":{"f":{"product":"Product","productVariants":"[ProductVariant!]","userErrors":"[MediaUserError!]!"}}}, +"ProductVariantEdge":{"o":{"f":{"cursor":"String!","node":"ProductVariant!"}}}, +"ProductVariantGroupRelationshipInput":{"i":{"id":"ID!","quantity":"Int!"}}, +"ProductVariantIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","id":"ID"}}, +"ProductVariantInventoryPolicy":{"e":["DENY","CONTINUE"]}, +"ProductVariantJoinSellingPlanGroupsPayload":{"o":{"f":{"productVariant":"ProductVariant","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"ProductVariantLeaveSellingPlanGroupsPayload":{"o":{"f":{"productVariant":"ProductVariant","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"ProductVariantPositionInput":{"i":{"id":"ID!","position":"Int!"}}, +"ProductVariantPricePair":{"o":{"f":{"compareAtPrice":"MoneyV2","price":"MoneyV2!"}}}, +"ProductVariantPricePairConnection":{"o":{"f":{"edges":"[ProductVariantPricePairEdge!]!","nodes":"[ProductVariantPricePair!]!","pageInfo":"PageInfo!"}}}, +"ProductVariantPricePairEdge":{"o":{"f":{"cursor":"String!","node":"ProductVariantPricePair!"}}}, +"ProductVariantRelationshipBulkUpdatePayload":{"o":{"f":{"parentProductVariants":"[ProductVariant!]","userErrors":"[ProductVariantRelationshipBulkUpdateUserError!]!"}}}, +"ProductVariantRelationshipBulkUpdateUserError":{"o":{"f":{"code":"ProductVariantRelationshipBulkUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductVariantRelationshipBulkUpdateUserErrorCode":{"e":["PARENT_REQUIRED","FAILED_TO_CREATE","PRODUCT_VARIANTS_NOT_FOUND","CIRCULAR_REFERENCE","NESTED_PARENT_PRODUCT_VARIANT","INVALID_QUANTITY","DUPLICATE_PRODUCT_VARIANT_RELATIONSHIP","EXCEEDED_PRODUCT_VARIANT_RELATIONSHIP_LIMIT","PRODUCT_VARIANT_RELATIONSHIP_TYPE_CONFLICT","UNEXPECTED_ERROR","FAILED_TO_REMOVE","MUST_SPECIFY_COMPONENTS","FAILED_TO_UPDATE","FAILED_TO_UPDATE_PARENT_PRODUCT_VARIANT_PRICE","UPDATE_PARENT_VARIANT_PRICE_REQUIRED","PRODUCT_VARIANTS_NOT_COMPONENTS","PRODUCT_EXPANDER_APP_OWNERSHIP_ALREADY_EXISTS","UNSUPPORTED_MULTIPACK_RELATIONSHIP","PARENT_PRODUCT_VARIANT_CANNOT_BE_GIFT_CARD","PARENT_PRODUCT_VARIANT_CANNOT_REQUIRE_SELLING_PLAN","PARENT_PRODUCT_VARIANT_CANNOT_BE_COMBINED_LISTING","CHILD_PRODUCT_VARIANT_CANNOT_BE_COMBINED_LISTING"]}, +"ProductVariantRelationshipUpdateInput":{"i":{"parentProductId":"ID","parentProductVariantId":"ID","priceInput":"PriceInput=","productVariantRelationshipsToCreate":"[ProductVariantGroupRelationshipInput!]=","productVariantRelationshipsToRemove":"[ID!]=","productVariantRelationshipsToUpdate":"[ProductVariantGroupRelationshipInput!]=","removeAllProductVariantRelationships":"Boolean="}}, +"ProductVariantSetInput":{"i":{"f":{"barcode":"String","barcodes":"[BarcodeInput!]","compareAtPrice":"Money","file":"FileSetInput","id":"ID","inventoryItem":"InventoryItemInput","inventoryPolicy":"ProductVariantInventoryPolicy","inventoryQuantities":"[ProductSetInventoryInput!]","metafields":"[MetafieldInput!]","optionValues":"[VariantOptionValueInput!]!","position":"Int","price":"Money","published":"Boolean","requiresComponents":"Boolean","showUnitPrice":"Boolean","sku":"String","taxCode":"String","taxable":"Boolean","unitPriceMeasurement":"UnitPriceMeasurementInput"},"d":{"barcode":"Use `barcodes` instead."}}}, +"ProductVariantSortKeys":{"e":["FULL_TITLE","ID","INVENTORY_LEVELS_AVAILABLE","INVENTORY_MANAGEMENT","INVENTORY_POLICY","INVENTORY_QUANTITY","NAME","POPULAR","POSITION","RELEVANCE","SKU","TITLE"]}, +"ProductVariantsBulkCreatePayload":{"o":{"f":{"product":"Product","productVariants":"[ProductVariant!]","userErrors":"[ProductVariantsBulkCreateUserError!]!"}}}, +"ProductVariantsBulkCreateStrategy":{"e":["DEFAULT","REMOVE_STANDALONE_VARIANT","PRESERVE_STANDALONE_VARIANT"]}, +"ProductVariantsBulkCreateUserError":{"o":{"f":{"code":"ProductVariantsBulkCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductVariantsBulkCreateUserErrorCode":{"e":["INVALID_INPUT","PRODUCT_DOES_NOT_EXIST","NO_KEY_ON_CREATE","VARIANT_ALREADY_EXISTS","PRODUCT_SUSPENDED","GREATER_THAN_OR_EQUAL_TO","LOCAL_CURRENCY_GIFT_CARD_PRICE_MUST_BE_ZERO","NEED_TO_ADD_OPTION_VALUES","OPTION_VALUES_FOR_NUMBER_OF_UNKNOWN_OPTIONS","TOO_MANY_INVENTORY_LOCATIONS","SUBSCRIPTION_VIOLATION","VARIANT_ALREADY_EXISTS_CHANGE_OPTION_VALUE","TRACKED_VARIANT_LOCATION_NOT_FOUND","MUST_BE_FOR_THIS_PRODUCT","NOT_DEFINED_FOR_SHOP","INVALID","NEGATIVE_PRICE_VALUE","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION","CANNOT_SET_NAME_FOR_LINKED_OPTION_VALUE","INVENTORY_QUANTITIES_LIMIT_EXCEEDED","INCOMPATIBLE_BARCODE_FIELDS","BLANK_BARCODE_VALUE","TOO_MANY_BARCODES","BARCODE_VALUE_TOO_LONG","DUPLICATE_BARCODE_VALUE","INVALID_BARCODE_TYPE","INVALID_BARCODE_SEPARATORS","INVALID_BARCODE_LENGTH","INVALID_BARCODE_PREFIX","INVALID_BARCODE_CHARACTERS","BARCODE_CHECKSUM_VALIDATION_FAILED"]}, +"ProductVariantsBulkDeletePayload":{"o":{"f":{"product":"Product","userErrors":"[ProductVariantsBulkDeleteUserError!]!"}}}, +"ProductVariantsBulkDeleteUserError":{"o":{"f":{"code":"ProductVariantsBulkDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductVariantsBulkDeleteUserErrorCode":{"e":["PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","CANNOT_DELETE_LAST_VARIANT","AT_LEAST_ONE_VARIANT_DOES_NOT_BELONG_TO_THE_PRODUCT","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION"]}, +"ProductVariantsBulkInput":{"i":{"f":{"barcode":"String","barcodes":"[BarcodeInput!]","compareAtPrice":"Money","id":"ID","inventoryItem":"InventoryItemInput","inventoryPolicy":"ProductVariantInventoryPolicy","inventoryQuantities":"[InventoryLevelInput!]","mediaId":"ID","mediaSrc":"[String!]","metafields":"[MetafieldInput!]","optionValues":"[VariantOptionValueInput!]","price":"Money","published":"Boolean","quantityAdjustments":"[InventoryAdjustmentInput!]","requiresComponents":"Boolean","showUnitPrice":"Boolean","taxCode":"String","taxable":"Boolean","unitPriceMeasurement":"UnitPriceMeasurementInput"},"d":{"barcode":"Use `barcodes` instead."}}}, +"ProductVariantsBulkReorderPayload":{"o":{"f":{"product":"Product","userErrors":"[ProductVariantsBulkReorderUserError!]!"}}}, +"ProductVariantsBulkReorderUserError":{"o":{"f":{"code":"ProductVariantsBulkReorderUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductVariantsBulkReorderUserErrorCode":{"e":["PRODUCT_DOES_NOT_EXIST","MISSING_VARIANT","INVALID_POSITION","DUPLICATED_VARIANT_ID","GENERIC_ERROR"]}, +"ProductVariantsBulkUpdatePayload":{"o":{"f":{"product":"Product","productVariants":"[ProductVariant!]","userErrors":"[ProductVariantsBulkUpdateUserError!]!"}}}, +"ProductVariantsBulkUpdateUserError":{"o":{"f":{"code":"ProductVariantsBulkUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductVariantsBulkUpdateUserErrorCode":{"e":["INVALID_INPUT","CANNOT_SPECIFY_BOTH","MUST_SPECIFY_ONE_OF_PAIR","OPTION_VALUE_NAME_TOO_LONG","PRODUCT_DOES_NOT_EXIST","PRODUCT_VARIANT_ID_MISSING","PRODUCT_VARIANT_DOES_NOT_EXIST","OPTION_DOES_NOT_EXIST","OPTION_VALUE_DOES_NOT_EXIST","MUST_BE_FOR_THIS_PRODUCT","NOT_DEFINED_FOR_SHOP","PRODUCT_SUSPENDED","NO_INVENTORY_QUANTITIES_ON_VARIANTS_UPDATE","VARIANT_ALREADY_EXISTS","GREATER_THAN_OR_EQUAL_TO","NEED_TO_ADD_OPTION_VALUES","OPTION_VALUES_FOR_NUMBER_OF_UNKNOWN_OPTIONS","SUBSCRIPTION_VIOLATION","NO_INVENTORY_QUANTITES_DURING_UPDATE","NEGATIVE_PRICE_VALUE","LOCAL_CURRENCY_GIFT_CARD_PRICE_MUST_BE_ZERO","BLANK","TOO_SHORT","TOO_LONG","INVALID_VALUE","CANNOT_SET_NAME_FOR_LINKED_OPTION_VALUE","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION","INVENTORY_QUANTITIES_LIMIT_EXCEEDED","INCOMPATIBLE_BARCODE_FIELDS","BLANK_BARCODE_VALUE","TOO_MANY_BARCODES","BARCODE_VALUE_TOO_LONG","DUPLICATE_BARCODE_VALUE","INVALID_BARCODE_TYPE","INVALID_BARCODE_SEPARATORS","INVALID_BARCODE_LENGTH","INVALID_BARCODE_PREFIX","INVALID_BARCODE_CHARACTERS","BARCODE_CHECKSUM_VALIDATION_FAILED"]}, +"ProfileItemSortKeys":{"e":["CREATED_AT","ID","INVENTORY_TOTAL","PRODUCT_TYPE","PUBLISHED_AT","RELEVANCE","TITLE","UPDATED_AT","VENDOR"]}, +"PubSubServerPixelUpdatePayload":{"o":{"f":{"serverPixel":"ServerPixel","userErrors":"[ErrorsServerPixelUserError!]!"}}}, +"PubSubWebhookSubscriptionCreatePayload":{"o":{"f":{"userErrors":"[PubSubWebhookSubscriptionCreateUserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"PubSubWebhookSubscriptionCreateUserError":{"o":{"f":{"code":"PubSubWebhookSubscriptionCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PubSubWebhookSubscriptionCreateUserErrorCode":{"e":["INVALID_PARAMETERS","TAKEN"]}, +"PubSubWebhookSubscriptionInput":{"i":{"filter":"String","format":"WebhookSubscriptionFormat","includeFields":"[String!]","metafieldNamespaces":"[String!]","metafields":"[HasMetafieldsMetafieldIdentifierInput!]","name":"String","pubSubProject":"String!","pubSubTopic":"String!"}}, +"PubSubWebhookSubscriptionUpdatePayload":{"o":{"f":{"userErrors":"[PubSubWebhookSubscriptionUpdateUserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"PubSubWebhookSubscriptionUpdateUserError":{"o":{"f":{"code":"PubSubWebhookSubscriptionUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PubSubWebhookSubscriptionUpdateUserErrorCode":{"e":["INVALID_PARAMETERS","TAKEN"]}, +"Publication":{"o":{"f":{"app":"App!","autoPublish":"Boolean!","catalog":"Catalog","channels":["ChannelConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collectionPublicationsV3":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"hasCollection":["Boolean!",{"id":"ID!"}],"id":"ID!","includedProducts":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"ProductSortKeys="}],"includedProductsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"name":"String!","operation":"PublicationOperation","productPublicationsV3":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"ProductSortKeys="}],"supportsFuturePublishing":"Boolean!"},"t":["Node"],"d":{"app":"Use [AppCatalog.apps](https://shopify.dev/api/admin-graphql/unstable/objects/AppCatalog#connection-appcatalog-apps) instead.","name":"Use [Catalog.title](https://shopify.dev/api/admin-graphql/unstable/interfaces/Catalog#field-catalog-title) instead."}}}, +"PublicationConnection":{"o":{"f":{"edges":"[PublicationEdge!]!","nodes":"[Publication!]!","pageInfo":"PageInfo!"}}}, +"PublicationCreateInput":{"i":{"autoPublish":"Boolean=","catalogId":"ID","defaultState":"PublicationCreateInputPublicationDefaultState="}}, +"PublicationCreateInputPublicationDefaultState":{"e":["EMPTY","ALL_PRODUCTS"]}, +"PublicationCreatePayload":{"o":{"f":{"publication":"Publication","userErrors":"[PublicationUserError!]!"}}}, +"PublicationDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[PublicationUserError!]!"}}}, +"PublicationEdge":{"o":{"f":{"cursor":"String!","node":"Publication!"}}}, +"PublicationInput":{"i":{"f":{"channelId":"ID","publicationId":"ID","publishDate":"DateTime"},"d":{"channelId":"Use publicationId instead."}}}, +"PublicationOperation":{"u":["AddAllProductsOperation","CatalogCsvOperation","PublicationResourceOperation"]}, +"PublicationResourceOperation":{"o":{"f":{"id":"ID!","processedRowCount":"Int","rowCount":"RowCount","status":"ResourceOperationStatus!"},"t":["Node","ResourceOperation"]}}, +"PublicationUpdateInput":{"i":{"autoPublish":"Boolean","publishablesToAdd":"[ID!]=","publishablesToRemove":"[ID!]="}}, +"PublicationUpdatePayload":{"o":{"f":{"publication":"Publication","userErrors":"[PublicationUserError!]!"}}}, +"PublicationUserError":{"o":{"f":{"code":"PublicationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PublicationUserErrorCode":{"e":["UNSUPPORTED_PUBLICATION_ACTION","PUBLICATION_NOT_FOUND","PUBLICATION_LOCKED","UNSUPPORTED_PUBLISHABLE_TYPE","INVALID_PUBLISHABLE_ID","MARKET_NOT_FOUND","CATALOG_NOT_FOUND","CANNOT_MODIFY_APP_CATALOG_PUBLICATION","CANNOT_MODIFY_MARKET_CATALOG_PUBLICATION","CANNOT_MODIFY_APP_CATALOG","CANNOT_MODIFY_MARKET_CATALOG","INVALID","TAKEN","TOO_LONG","TOO_SHORT","BLANK","PRODUCT_TYPE_INCOMPATIBLE_WITH_CATALOG_TYPE","PUBLICATION_UPDATE_LIMIT_EXCEEDED","CANNOT_COMBINE_PRODUCTS_AND_VARIANTS","VARIANTS_BELONG_TO_MULTIPLE_PRODUCTS","PRODUCT_LOCK_ERROR","VARIANT_PUBLISHING_UNSUPPORTED_PRODUCT_TYPE"]}, +"Publishable":{"n":{"f":{"availablePublicationsCount":"Count","publicationCount":["Int!",{"onlyPublished":"Boolean="}],"publishedOnChannel":["Boolean!",{"channelId":"ID!"}],"publishedOnCurrentChannel":"Boolean!","publishedOnCurrentPublication":"Boolean!","publishedOnPublication":["Boolean!",{"publicationId":"ID!"}],"resourcePublications":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"resourcePublicationsCount":["Count",{"onlyPublished":"Boolean="}],"resourcePublicationsV2":["ResourcePublicationV2Connection!",{"after":"String","before":"String","catalogType":"CatalogType","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"unpublishedChannels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unpublishedPublications":["PublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Collection","Product","ProductVariant"],"d":{"publicationCount":"Use `resourcePublicationsCount` instead.","publishedOnChannel":"Use `publishedOnPublication` instead.","publishedOnCurrentChannel":"Use `publishedOnCurrentPublication` instead.","publishedOnCurrentPublication":"Use `publishedOnPublication` instead.","unpublishedChannels":"Use `unpublishedPublications` instead."}}}, +"PublishablePublishPayload":{"o":{"f":{"publishable":"Publishable","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"PublishablePublishToCurrentChannelPayload":{"o":{"f":{"publishable":"Publishable","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"PublishableUnpublishPayload":{"o":{"f":{"publishable":"Publishable","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"PublishableUnpublishToCurrentChannelPayload":{"o":{"f":{"publishable":"Publishable","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"PurchaseOrderLineItemSortKeys":{"e":["ID"]}, +"PurchasingCompany":{"o":{"f":{"company":"Company!","contact":"CompanyContact","location":"CompanyLocation!"}}}, +"PurchasingCompanyInput":{"i":{"companyContactId":"ID!","companyId":"ID!","companyLocationId":"ID!"}}, +"PurchasingEntity":{"u":["Customer","PurchasingCompany"]}, +"PurchasingEntityInput":{"i":{"customerId":"ID","purchasingCompany":"PurchasingCompanyInput"}}, +"QuantityPriceBreak":{"o":{"f":{"id":"ID!","minimumQuantity":"Int!","price":"MoneyV2!","priceList":"PriceList!","variant":"ProductVariant!"},"t":["Node"]}}, +"QuantityPriceBreakConnection":{"o":{"f":{"edges":"[QuantityPriceBreakEdge!]!","nodes":"[QuantityPriceBreak!]!","pageInfo":"PageInfo!"}}}, +"QuantityPriceBreakEdge":{"o":{"f":{"cursor":"String!","node":"QuantityPriceBreak!"}}}, +"QuantityPriceBreakInput":{"i":{"minimumQuantity":"Int!","price":"MoneyInput!","variantId":"ID!"}}, +"QuantityPriceBreakSortKeys":{"e":["ID","MINIMUM_QUANTITY"]}, +"QuantityPricingByVariantUpdateInput":{"i":{"pricesToAdd":"[PriceListPriceInput!]!","pricesToDeleteByVariantId":"[ID!]!","quantityPriceBreaksToAdd":"[QuantityPriceBreakInput!]!","quantityPriceBreaksToDelete":"[ID!]!","quantityPriceBreaksToDeleteByVariantId":"[ID!]","quantityRulesToAdd":"[QuantityRuleInput!]!","quantityRulesToDeleteByVariantId":"[ID!]!"}}, +"QuantityPricingByVariantUpdatePayload":{"o":{"f":{"productVariants":"[ProductVariant!]","userErrors":"[QuantityPricingByVariantUserError!]!"}}}, +"QuantityPricingByVariantUserError":{"o":{"f":{"code":"QuantityPricingByVariantUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"QuantityPricingByVariantUserErrorCode":{"e":["BLANK","PRICE_LIST_NOT_FOUND","GENERIC_ERROR","QUANTITY_PRICE_BREAK_ADD_INVALID","QUANTITY_PRICE_BREAK_ADD_PRICE_LIST_PRICE_NOT_FOUND","QUANTITY_PRICE_BREAK_ADD_LIMIT_EXCEEDED","QUANTITY_PRICE_BREAK_ADD_CURRENCY_MISMATCH","QUANTITY_PRICE_BREAK_ADD_FAILED_TO_SAVE","QUANTITY_PRICE_BREAK_ADD_MIN_LOWER_THAN_QUANTITY_RULES_MIN","QUANTITY_PRICE_BREAK_ADD_MIN_HIGHER_THAN_QUANTITY_RULES_MAX","QUANTITY_PRICE_BREAK_ADD_MIN_NOT_A_MULTIPLE_OF_QUANTITY_RULES_INCREMENT","QUANTITY_PRICE_BREAK_ADD_VARIANT_NOT_FOUND","QUANTITY_PRICE_BREAK_ADD_DUPLICATE_INPUT_FOR_VARIANT_AND_MIN","QUANTITY_PRICE_BREAK_DELETE_NOT_FOUND","QUANTITY_PRICE_BREAK_DELETE_FAILED","QUANTITY_RULE_ADD_VARIANT_NOT_FOUND","QUANTITY_RULE_ADD_MIN_HIGHER_THAN_QUANTITY_PRICE_BREAK_MIN","QUANTITY_RULE_ADD_MAX_LOWER_THAN_QUANTITY_PRICE_BREAK_MIN","QUANTITY_RULE_ADD_INCREMENT_NOT_A_MULTIPLE_OF_QUANTITY_PRICE_BREAK_MIN","QUANTITY_RULE_ADD_CATALOG_CONTEXT_NOT_SUPPORTED","QUANTITY_RULE_ADD_INCREMENT_IS_GREATER_THAN_MINIMUM","QUANTITY_RULE_ADD_MINIMUM_NOT_A_MULTIPLE_OF_INCREMENT","QUANTITY_RULE_ADD_MAXIMUM_NOT_A_MULTIPLE_OF_INCREMENT","QUANTITY_RULE_ADD_MINIMUM_GREATER_THAN_MAXIMUM","QUANTITY_RULE_ADD_INCREMENT_IS_LESS_THAN_ONE","QUANTITY_RULE_ADD_MINIMUM_IS_LESS_THAN_ONE","QUANTITY_RULE_ADD_MAXIMUM_IS_LESS_THAN_ONE","QUANTITY_RULE_ADD_DUPLICATE_INPUT_FOR_VARIANT","QUANTITY_RULE_DELETE_RULE_NOT_FOUND","QUANTITY_RULE_DELETE_VARIANT_NOT_FOUND","PRICE_ADD_CURRENCY_MISMATCH","PRICE_ADD_VARIANT_NOT_FOUND","PRICE_ADD_DUPLICATE_INPUT_FOR_VARIANT","PRICE_ADD_LOCAL_CURRENCY_GIFT_CARD_ISSUANCE_CURRENCY_MISMATCH","PRICE_ADD_LOCAL_CURRENCY_GIFT_CARD_LIMIT_EXCEEDED","PRICE_DELETE_PRICE_NOT_FIXED","PRICE_DELETE_VARIANT_NOT_FOUND","QUANTITY_PRICE_BREAK_DELETE_BY_VARIANT_ID_VARIANT_NOT_FOUND"]}, +"QuantityRule":{"o":{"f":{"increment":"Int!","isDefault":"Boolean!","maximum":"Int","minimum":"Int!","originType":"QuantityRuleOriginType!","productVariant":"ProductVariant!"}}}, +"QuantityRuleConnection":{"o":{"f":{"edges":"[QuantityRuleEdge!]!","nodes":"[QuantityRule!]!","pageInfo":"PageInfo!"}}}, +"QuantityRuleEdge":{"o":{"f":{"cursor":"String!","node":"QuantityRule!"}}}, +"QuantityRuleInput":{"i":{"increment":"Int!","maximum":"Int=","minimum":"Int!","variantId":"ID!"}}, +"QuantityRuleOriginType":{"e":["FIXED","RELATIVE"]}, +"QuantityRuleUserError":{"o":{"f":{"code":"QuantityRuleUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"QuantityRuleUserErrorCode":{"e":["BLANK","PRODUCT_VARIANT_DOES_NOT_EXIST","PRICE_LIST_DOES_NOT_EXIST","VARIANT_QUANTITY_RULE_DOES_NOT_EXIST","MINIMUM_IS_GREATER_THAN_MAXIMUM","MINIMUM_IS_HIGHER_THAN_QUANTITY_PRICE_BREAK_MINIMUM","MAXIMUM_IS_LOWER_THAN_QUANTITY_PRICE_BREAK_MINIMUM","INCREMENT_NOT_A_MULTIPLE_OF_QUANTITY_PRICE_BREAK_MINIMUM","INCREMENT_IS_GREATER_THAN_MINIMUM","GREATER_THAN_OR_EQUAL_TO","MAXIMUM_NOT_MULTIPLE_OF_INCREMENT","MINIMUM_NOT_MULTIPLE_OF_INCREMENT","CATALOG_CONTEXT_DOES_NOT_SUPPORT_QUANTITY_RULES","DUPLICATE_INPUT_FOR_VARIANT","GENERIC_ERROR"]}, +"QuantityRulesAddPayload":{"o":{"f":{"quantityRules":"[QuantityRule!]","userErrors":"[QuantityRuleUserError!]!"}}}, +"QuantityRulesDeletePayload":{"o":{"f":{"deletedQuantityRulesVariantIds":"[ID!]","userErrors":"[QuantityRuleUserError!]!"}}}, +"QueryRoot":{"o":{"f":{"abandonedCheckouts":["AbandonedCheckoutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"AbandonedCheckoutSortKeys="}],"abandonedCheckoutsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"abandonment":["Abandonment",{"id":"ID!"}],"abandonmentByAbandonedCheckoutId":["Abandonment",{"abandonedCheckoutId":"ID!"}],"analyticsTargets":["AnalyticsTargetConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"AnalyticsTargetSortKeys="}],"app":["App",{"id":"ID"}],"appByHandle":["App",{"handle":"String!"}],"appByKey":["App",{"apiKey":"String!"}],"appDiscountType":["AppDiscountType",{"functionId":"String!"}],"appDiscountTypes":"[AppDiscountType!]!","appDiscountTypesNodes":["AppDiscountTypeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"appInstallation":["AppInstallation",{"id":"ID"}],"appInstallations":["AppInstallationConnection!",{"after":"String","before":"String","category":"AppInstallationCategory","first":"Int","last":"Int","privacy":"AppInstallationPrivacy=","reverse":"Boolean=","sortKey":"AppInstallationSortKeys="}],"article":["Article",{"id":"ID!"}],"articleAuthors":["ArticleAuthorConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"articleTags":["[String!]!",{"limit":"Int!","sort":"ArticleTagSort="}],"articles":["ArticleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ArticleSortKeys="}],"assignedFulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","assignmentStatus":"FulfillmentOrderAssignmentStatus","before":"String","first":"Int","last":"Int","locationIds":"[ID!]","reverse":"Boolean=","sortKey":"FulfillmentOrderSortKeys="}],"automaticDiscount":["DiscountAutomatic",{"id":"ID!"}],"automaticDiscountNode":["DiscountAutomaticNode",{"id":"ID!"}],"automaticDiscountNodes":["DiscountAutomaticNodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"AutomaticDiscountSortKeys="}],"automaticDiscountSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"automaticDiscounts":["DiscountAutomaticConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"AutomaticDiscountSortKeys="}],"availableBackupRegions":"[MarketRegion!]!","availableCarrierServices":"[DeliveryCarrierServiceAndLocations!]!","availableLocales":"[Locale!]!","backupRegion":"MarketRegion!","blog":["Blog",{"id":"ID!"}],"blogs":["BlogConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"BlogSortKeys="}],"blogsCount":["Count",{"limit":"Int=","query":"String"}],"bulkOperation":["BulkOperation",{"id":"ID!"}],"bulkOperations":["BulkOperationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"BulkOperationsSortKeys="}],"businessEntities":"[BusinessEntity!]!","businessEntity":["BusinessEntity",{"id":"ID"}],"carrierService":["DeliveryCarrierService",{"id":"ID!"}],"carrierServices":["DeliveryCarrierServiceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CarrierServiceSortKeys="}],"cartTransforms":["CartTransformConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"cashDrawer":["CashDrawer",{"id":"ID!"}],"cashDrawers":["CashDrawerConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String"}],"cashManagementLocationSummary":["CashManagementSummary!",{"endDate":"Date!","locationId":"ID!","startDate":"Date!"}],"cashManagementReasonCodes":["CashManagementReasonCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"cashManagementShopSummary":["CashManagementSummary!",{"currencyCode":"CurrencyCode!","endDate":"Date!","startDate":"Date!"}],"cashTrackingSession":["CashTrackingSession",{"id":"ID!"}],"cashTrackingSessions":["CashTrackingSessionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CashTrackingSessionsSortKeys="}],"catalog":["Catalog",{"id":"ID!"}],"catalogOperations":"[ResourceOperation!]!","catalogs":["CatalogConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CatalogSortKeys=","type":"CatalogType="}],"catalogsCount":["Count",{"limit":"Int=","query":"String","type":"CatalogType="}],"channel":["Channel",{"id":"ID!"}],"channelByHandle":["Channel",{"handle":"String!"}],"channels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"checkoutAndAccountsConfiguration":["CheckoutAndAccountsConfiguration",{"id":"ID!"}],"checkoutAndAccountsConfigurations":["CheckoutAndAccountsConfigurationConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CheckoutAndAccountsConfigurationsGraphQLSortKeys="}],"checkoutBranding":["CheckoutBranding",{"checkoutProfileId":"ID!"}],"checkoutProfile":["CheckoutProfile",{"id":"ID!"}],"checkoutProfiles":["CheckoutProfileConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CheckoutProfileSortKeys="}],"codeDiscountNode":["DiscountCodeNode",{"id":"ID!"}],"codeDiscountNodeByCode":["DiscountCodeNode",{"code":"String!"}],"codeDiscountNodes":["DiscountCodeNodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"CodeDiscountSortKeys="}],"codeDiscountSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collection":["Collection",{"id":"ID!"}],"collectionByHandle":["Collection",{"handle":"String!"}],"collectionByIdentifier":["Collection",{"identifier":"CollectionIdentifierInput!"}],"collectionConditionMetafieldDefinitions":"[CollectionConditionMetafieldDefinitionInterface!]!","collectionConditionsSources":["CollectionConditionsSourceConnection!",{"after":"String","appId":"ID!","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collectionConditionsSourcesByApp":["CollectionConditionsSourcesByAppConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collectionRulesConditions":"[CollectionRuleConditions!]!","collectionSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"CollectionSortKeys="}],"collectionsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"comment":["Comment",{"id":"ID!"}],"comments":["CommentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CommentSortKeys="}],"companies":["CompanyConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanySortKeys="}],"companiesCount":["Count",{"limit":"Int="}],"company":["Company",{"id":"ID!"}],"companyContact":["CompanyContact",{"id":"ID!"}],"companyContactRole":["CompanyContactRole",{"id":"ID!"}],"companyLocation":["CompanyLocation",{"id":"ID!"}],"companyLocations":["CompanyLocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyLocationSortKeys="}],"consentPolicy":["[ConsentPolicy!]!",{"consentRequired":"Boolean","countryCode":"PrivacyCountryCode","dataSaleOptOutRequired":"Boolean","id":"ID","regionCode":"String"}],"consentPolicyRegions":"[ConsentPolicyRegion!]!","currentAppInstallation":"AppInstallation!","currentBulkOperation":["BulkOperation",{"type":"BulkOperationType="}],"currentStaffMember":"StaffMember","customer":["Customer",{"id":"ID!"}],"customerAccountPage":["CustomerAccountPage",{"id":"ID!"}],"customerAccountPages":["CustomerAccountPageConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"customerByIdentifier":["Customer",{"identifier":"CustomerIdentifierInput!"}],"customerMergeJobStatus":["CustomerMergeRequest",{"jobId":"ID!"}],"customerMergePreview":["CustomerMergePreview!",{"customerOneId":"ID!","customerTwoId":"ID!","overrideFields":"CustomerMergeOverrideFields"}],"customerPaymentMethod":["CustomerPaymentMethod",{"id":"ID!","showRevoked":"Boolean="}],"customerSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CustomerSavedSearchSortKeys="}],"customerSegmentMembers":["CustomerSegmentMemberConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","queryId":"ID","reverse":"Boolean=","segmentId":"ID","sortKey":"String","timezone":"String"}],"customerSegmentMembersQuery":["CustomerSegmentMembersQuery",{"id":"ID!"}],"customerSegmentMembership":["SegmentMembershipResponse!",{"customerId":"ID!","segmentIds":"[ID!]!"}],"customers":["CustomerConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CustomerSortKeys="}],"customersCount":["Count",{"limit":"Int=","query":"String"}],"deletionEvents":["DeletionEventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DeletionEventSortKeys=","subjectTypes":"[DeletionEventSubjectType!]"}],"deliveryCustomization":["DeliveryCustomization",{"id":"ID!"}],"deliveryCustomizations":["DeliveryCustomizationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"deliveryProfile":["DeliveryProfile",{"id":"ID!"}],"deliveryProfiles":["DeliveryProfileConnection!",{"after":"String","before":"String","first":"Int","last":"Int","merchantOwnedOnly":"Boolean","reverse":"Boolean="}],"deliveryPromiseParticipants":["DeliveryPromiseParticipantConnection",{"after":"String","before":"String","brandedPromiseHandle":"String!","first":"Int","last":"Int","ownerIds":"[ID!]","reverse":"Boolean="}],"deliveryPromiseProvider":["DeliveryPromiseProvider",{"locationId":"ID!"}],"deliveryPromiseSettings":"DeliveryPromiseSetting!","discountCodesCount":["Count",{"limit":"Int=","query":"String"}],"discountNode":["DiscountNode",{"id":"ID!"}],"discountNodes":["DiscountNodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DiscountSortKeys="}],"discountNodesCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"discountRedeemCodeBulkCreation":["DiscountRedeemCodeBulkCreation",{"id":"ID!"}],"discountRedeemCodeSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DiscountCodeSortKeys="}],"discountTags":["StringConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DiscountTagSortKeys="}],"dispute":["ShopifyPaymentsDispute",{"id":"ID!"}],"disputeEvidence":["ShopifyPaymentsDisputeEvidence",{"id":"ID!"}],"disputes":["ShopifyPaymentsDisputeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"domain":["Domain",{"id":"ID!"}],"draftOrder":["DraftOrder",{"id":"ID!"}],"draftOrderAvailableDeliveryOptions":["DraftOrderAvailableDeliveryOptions!",{"input":"DraftOrderAvailableDeliveryOptionsInput!","localPickupCount":"Int","localPickupFrom":"Int","search":"String","sessionToken":"String"}],"draftOrderSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"draftOrderTag":["DraftOrderTag",{"id":"ID!"}],"draftOrders":["DraftOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DraftOrderSortKeys="}],"draftOrdersCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"event":["Event",{"id":"ID!"}],"events":["EventConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"eventsCount":["Count",{"query":"String"}],"fileSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"files":["FileConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"FileSortKeys="}],"financeAppAccessPolicy":"FinanceAppAccessPolicy!","financeKycInformation":"FinanceKycInformation","fulfillment":["Fulfillment",{"id":"ID!"}],"fulfillmentConstraintRules":"[FulfillmentConstraintRule!]!","fulfillmentOrder":["FulfillmentOrder",{"id":"ID!"}],"fulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","includeClosed":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","sortKey":"FulfillmentOrderSortKeys="}],"fulfillmentService":["FulfillmentService",{"id":"ID!"}],"giftCard":["GiftCard",{"id":"ID!"}],"giftCardConfiguration":"GiftCardConfiguration!","giftCards":["GiftCardConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"GiftCardSortKeys="}],"giftCardsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"inventoryItem":["InventoryItem",{"id":"ID!"}],"inventoryItems":["InventoryItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"inventoryLevel":["InventoryLevel",{"id":"ID!"}],"inventoryProperties":"InventoryProperties!","inventoryPurchaseOrder":["InventoryPurchaseOrder",{"id":"ID!"}],"inventoryPurchaseOrders":["InventoryPurchaseOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String"}],"inventoryShipment":["InventoryShipment",{"id":"ID!"}],"inventoryShipments":["InventoryShipmentConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","sortKey":"InventoryShipmentSortKeys="}],"inventoryTransfer":["InventoryTransfer",{"id":"ID!"}],"inventoryTransfers":["InventoryTransferConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"TransferSortKeys="}],"job":["Job",{"id":"ID!"}],"location":["Location",{"id":"ID"}],"locationByIdentifier":["Location",{"identifier":"LocationIdentifierInput!"}],"locations":["LocationConnection!",{"after":"String","before":"String","first":"Int","includeInactive":"Boolean=","includeLegacy":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","sortKey":"LocationSortKeys="}],"locationsAvailableForDeliveryProfiles":"[Location!]","locationsAvailableForDeliveryProfilesConnection":["LocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"locationsCount":["Count",{"limit":"Int=","query":"String"}],"manualHoldsFulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"market":["Market",{"id":"ID!"}],"marketByGeography":["Market",{"countryCode":"CountryCode!"}],"marketLocalizableResource":["MarketLocalizableResource",{"resourceId":"ID!"}],"marketLocalizableResources":["MarketLocalizableResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","resourceType":"MarketLocalizableResourceType!","reverse":"Boolean="}],"marketLocalizableResourcesByIds":["MarketLocalizableResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","resourceIds":"[ID!]!","reverse":"Boolean="}],"marketRelationships":["MarketRelationshipConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"marketRelationshipsStatus":"MarketRelationshipsStatus!","marketingActivities":["MarketingActivityConnection!",{"after":"String","before":"String","first":"Int","last":"Int","marketingActivityIds":"[ID!]=","query":"String","remoteIds":"[String!]=","reverse":"Boolean=","savedSearchId":"ID","sortKey":"MarketingActivitySortKeys=","utm":"UTMInput"}],"marketingActivity":["MarketingActivity",{"id":"ID!"}],"marketingEvent":["MarketingEvent",{"id":"ID!"}],"marketingEvents":["MarketingEventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"MarketingEventSortKeys="}],"markets":["MarketConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"MarketsSortKeys=","type":"MarketType="}],"marketsResolvedValues":["MarketsResolvedValues!",{"buyerSignal":"BuyerSignalInput!"}],"menu":["Menu",{"id":"ID!"}],"menus":["MenuConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"MenuSortKeys="}],"metafieldDefinition":["MetafieldDefinition",{"id":"ID","identifier":"MetafieldDefinitionIdentifierInput"}],"metafieldDefinitionTypes":"[MetafieldDefinitionType!]!","metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","constraintStatus":"MetafieldDefinitionConstraintStatus","constraintSubtype":"MetafieldDefinitionConstraintSubtypeIdentifier","first":"Int","key":"String","last":"Int","namespace":"String","ownerType":"MetafieldOwnerType!","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metaobject":["Metaobject",{"id":"ID!"}],"metaobjectByHandle":["Metaobject",{"handle":"MetaobjectHandleInput!"}],"metaobjectDefinition":["MetaobjectDefinition",{"id":"ID!"}],"metaobjectDefinitionByType":["MetaobjectDefinition",{"type":"String!"}],"metaobjectDefinitions":["MetaobjectDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"metaobjects":["MetaobjectConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"String","type":"String!"}],"mobilePlatformApplication":["MobilePlatformApplication",{"id":"ID!"}],"mobilePlatformApplications":["MobilePlatformApplicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"node":["Node",{"id":"ID!"}],"nodes":["[Node]!",{"ids":"[ID!]!"}],"onlineStore":"OnlineStore!","order":["Order",{"id":"ID!"}],"orderAttributionDefinitions":["OrderAttributionDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"orderByIdentifier":["Order",{"identifier":"OrderIdentifierInput!"}],"orderEditSession":["OrderEditSession",{"id":"ID!"}],"orderPaymentStatus":["OrderPaymentStatus",{"orderId":"ID!","paymentReferenceId":"String!"}],"orderSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"OrderSortKeys="}],"ordersCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"page":["Page",{"id":"ID!"}],"pages":["PageConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"PageSortKeys="}],"pagesCount":["Count",{"limit":"Int="}],"paymentCustomization":["PaymentCustomization",{"id":"ID!"}],"paymentCustomizations":["PaymentCustomizationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"paymentTermsTemplates":["[PaymentTermsTemplate!]!",{"paymentTermsType":"PaymentTermsType"}],"pendingOrdersCount":"Count","pointOfSaleDevice":["PointOfSaleDevice",{"id":"ID!"}],"pointOfSaleDevicePaymentSession":["PointOfSaleDevicePaymentSession",{"id":"ID!"}],"pointOfSaleDevicePaymentSessions":["PointOfSaleDevicePaymentSessionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"PointOfSaleDevicePaymentSessionSortKeys="}],"priceList":["PriceList",{"id":"ID!"}],"priceLists":["PriceListConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"PriceListSortKeys="}],"primaryMarket":"Market!","privacySettings":"PrivacySettings!","product":["Product",{"id":"ID!"}],"productByHandle":["Product",{"handle":"String!"}],"productByIdentifier":["Product",{"identifier":"ProductIdentifierInput!"}],"productDuplicateJob":["ProductDuplicateJob!",{"id":"ID!"}],"productFeed":["ProductFeed",{"id":"ID!"}],"productFeeds":["ProductFeedConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productOperation":["ProductOperation",{"id":"ID!"}],"productResourceFeedback":["ProductResourceFeedback",{"channelId":"ID","id":"ID!"}],"productSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productTags":["StringConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productTypes":["StringConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productVariant":["ProductVariant",{"id":"ID!"}],"productVariantByIdentifier":["ProductVariant",{"identifier":"ProductVariantIdentifierInput!"}],"productVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"ProductVariantSortKeys="}],"productVariantsCount":["Count",{"limit":"Int=","query":"String"}],"productVendors":["StringConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"ProductSortKeys="}],"productsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"publicApiVersions":"[ApiVersion!]!","publication":["Publication",{"id":"ID!"}],"publications":["PublicationConnection!",{"after":"String","before":"String","catalogType":"CatalogType","first":"Int","last":"Int","reverse":"Boolean="}],"publicationsCount":["Count",{"catalogType":"CatalogType","limit":"Int="}],"publishedProductsCount":["Count",{"limit":"Int=","publicationId":"ID!"}],"refund":["Refund",{"id":"ID!"}],"requestedOrderEditCalculate":["CalculatedRequestedOrderEdit",{"input":"CalculateRequestedOrderEditInput!"}],"return":["Return",{"id":"ID!"}],"returnCalculate":["CalculatedReturn",{"input":"CalculateReturnInput!"}],"returnPolicyProfile":["ReturnPolicyProfile",{"id":"ID!"}],"returnPolicyProfiles":["ReturnPolicyProfileConnection!",{"after":"String","before":"String","default":"Boolean","first":"Int","last":"Int","reverse":"Boolean="}],"returnReasonDefinitions":["ReturnReasonDefinitionConnection!",{"after":"String","before":"String","first":"Int","handles":"[String!]","ids":"[ID!]","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ReturnReasonDefinitionSortKeys="}],"returnableFulfillment":["ReturnableFulfillment",{"id":"ID!"}],"returnableFulfillments":["ReturnableFulfillmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","orderId":"ID!","reverse":"Boolean="}],"reverseDelivery":["ReverseDelivery",{"id":"ID!"}],"reverseFulfillmentOrder":["ReverseFulfillmentOrder",{"id":"ID!"}],"rollout":["Rollout",{"id":"ID!"}],"rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"RolloutSortKeys="}],"scriptTag":["ScriptTag",{"id":"ID!"}],"scriptTags":["ScriptTagConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","src":"URL"}],"segment":["Segment",{"id":"ID!"}],"segmentFilterSuggestions":["SegmentFilterConnection!",{"after":"String","first":"Int!","search":"String!"}],"segmentFilters":["SegmentFilterConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}],"segmentMigrations":["SegmentMigrationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","savedSearchId":"ID"}],"segmentValueSuggestions":["SegmentValueConnection!",{"after":"String","before":"String","filterQueryName":"String","first":"Int","functionParameterQueryName":"String","last":"Int","search":"String!"}],"segments":["SegmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"SegmentSortKeys="}],"segmentsCount":["Count",{"limit":"Int="}],"sellingPlanGroup":["SellingPlanGroup",{"id":"ID!"}],"sellingPlanGroups":["SellingPlanGroupConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"SellingPlanGroupSortKeys="}],"serverPixel":"ServerPixel","shippingLabel":["ShippingLabel",{"id":"ID!"}],"shop":"Shop!","shopBillingPreferences":"ShopBillingPreferences!","shopLocales":["[ShopLocale!]!",{"published":"Boolean="}],"shopPayPaymentRequestReceipt":["ShopPayPaymentRequestReceipt",{"token":"String!"}],"shopPayPaymentRequestReceipts":["ShopPayPaymentRequestReceiptConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ShopPayPaymentRequestReceiptsSortKeys="}],"shopifyFunction":["ShopifyFunction",{"id":"String!"}],"shopifyFunctions":["ShopifyFunctionConnection!",{"after":"String","apiType":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","useCreationUi":"Boolean"}],"shopifyPaymentsAccount":"ShopifyPaymentsAccount","shopifyqlQuery":["ShopifyqlQueryResponse",{"query":"String!"}],"staffMember":["StaffMember",{"id":"ID"}],"staffMembers":["StaffMemberConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"StaffMembersSortKeys="}],"standardMetafieldDefinitionTemplates":["StandardMetafieldDefinitionTemplateConnection!",{"after":"String","before":"String","constraintStatus":"MetafieldDefinitionConstraintStatus","constraintSubtype":"MetafieldDefinitionConstraintSubtypeIdentifier","excludeActivated":"Boolean=","first":"Int","last":"Int","reverse":"Boolean="}],"storeCreditAccount":["StoreCreditAccount",{"id":"ID!"}],"storeCreditConfiguration":"StoreCreditConfiguration!","subscriptionBillingAttempt":["SubscriptionBillingAttempt",{"id":"ID!"}],"subscriptionBillingAttempts":["SubscriptionBillingAttemptConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"SubscriptionBillingAttemptsSortKeys="}],"subscriptionBillingCycle":["SubscriptionBillingCycle",{"billingCycleInput":"SubscriptionBillingCycleInput!"}],"subscriptionBillingCycleBulkResults":["SubscriptionBillingCycleConnection!",{"after":"String","before":"String","first":"Int","jobId":"ID!","last":"Int","reverse":"Boolean="}],"subscriptionBillingCycles":["SubscriptionBillingCycleConnection!",{"after":"String","before":"String","billingCyclesDateRangeSelector":"SubscriptionBillingCyclesDateRangeSelector","billingCyclesIndexRangeSelector":"SubscriptionBillingCyclesIndexRangeSelector","contractId":"ID!","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"SubscriptionBillingCyclesSortKeys="}],"subscriptionContract":["SubscriptionContract",{"id":"ID!"}],"subscriptionContractCalculation":["SubscriptionContractCalculation",{"id":"ID!"}],"subscriptionContracts":["SubscriptionContractConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"SubscriptionContractsSortKeys="}],"subscriptionDraft":["SubscriptionDraft",{"id":"ID!"}],"taxonomy":"Taxonomy","tenderTransactions":["TenderTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"theme":["OnlineStoreTheme",{"id":"ID!"}],"themes":["OnlineStoreThemeConnection",{"after":"String","before":"String","first":"Int","last":"Int","names":"[String!]","reverse":"Boolean=","roles":"[ThemeRole!]"}],"translatableResource":["TranslatableResource",{"resourceId":"ID!"}],"translatableResources":["TranslatableResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","resourceType":"TranslatableResourceType!","reverse":"Boolean="}],"translatableResourcesByIds":["TranslatableResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","resourceIds":"[ID!]!","reverse":"Boolean="}],"urlRedirect":["UrlRedirect",{"id":"ID!"}],"urlRedirectImport":["UrlRedirectImport",{"id":"ID!"}],"urlRedirectSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"urlRedirects":["UrlRedirectConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"UrlRedirectSortKeys="}],"urlRedirectsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"validation":["Validation",{"id":"ID!"}],"validations":["ValidationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"ValidationSortKeys="}],"webPixel":["WebPixel",{"id":"ID"}],"webPresences":["MarketWebPresenceConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"webhookSubscription":["WebhookSubscription",{"id":"ID!"}],"webhookSubscriptions":["WebhookSubscriptionConnection!",{"after":"String","before":"String","callbackUrl":"URL","first":"Int","format":"WebhookSubscriptionFormat","last":"Int","query":"String","reverse":"Boolean=","sortKey":"WebhookSubscriptionSortKeys=","topics":"[WebhookSubscriptionTopic!]","uri":"String"}],"webhookSubscriptionsCount":["Count",{"limit":"Int=","query":"String"}]},"d":{"automaticDiscount":"Use `automaticDiscountNode` instead.","automaticDiscountNode":"Use `discountNode` instead.","automaticDiscountNodes":"Use `discountNodes` instead.","automaticDiscounts":"Use `automaticDiscountNodes` instead. This will be removed in 2027-01.","checkoutBranding":"Use `checkoutAndAccountsConfiguration` instead.","checkoutProfile":"Use `checkoutAndAccountsConfiguration` instead.","checkoutProfiles":"Use `checkoutAndAccountsConfigurations` instead.","codeDiscountNode":"Use `discountNode` instead.","codeDiscountNodes":"Use `discountNodes` instead.","collectionByHandle":"Use `collectionByIdentifier` instead.","collectionRulesConditions":"Use `CollectionSourceInclusionCondition*` and `CollectionSourceExclusionCondition*` types instead.","currentBulkOperation":"Use `bulkOperations` with status filter instead.","customerSavedSearches":"Use `segments` instead.","deletionEvents":"Use `events` instead.","locationsAvailableForDeliveryProfiles":"Use `locationsAvailableForDeliveryProfilesConnection` instead.","marketByGeography":"This `market_by_geography` field will be removed in a future version of the API.","metafieldDefinition(id)":"This field will be removed in a future version. Use the identifier input instead.","primaryMarket":"Use `backupRegion` instead.","productByHandle":"Use `productByIdentifier` instead.","segmentMigrations":"Use the migrated segment ID and query `segment` directly.","subscriptionDraft":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","webhookSubscriptions(callbackUrl)":"Use `uri` instead."}}}, +"Refund":{"o":{"f":{"createdAt":"DateTime","duties":"[RefundDuty!]","id":"ID!","legacyResourceId":"UnsignedInt64!","note":"String","order":"Order!","orderAdjustments":["OrderAdjustmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"processedAt":"DateTime!","refundLineItems":["RefundLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"refundShippingLines":["RefundShippingLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"return":"Return","staffMember":"StaffMember","totalRefunded":"MoneyV2!","totalRefundedSet":"MoneyBag!","transactions":["OrderTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["LegacyInteroperability","Node"],"d":{"totalRefunded":"Use `totalRefundedSet` instead."}}}, +"RefundAgreement":{"o":{"f":{"app":"App","happenedAt":"DateTime!","id":"ID!","reason":"OrderActionType!","refund":"Refund!","sales":["SaleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"user":"StaffMember"},"t":["SalesAgreement"]}}, +"RefundConnection":{"o":{"f":{"edges":"[RefundEdge!]!","nodes":"[Refund!]!","pageInfo":"PageInfo!"}}}, +"RefundCreatePayload":{"o":{"f":{"order":"Order","refund":"Refund","userErrors":"[UserError!]!"}}}, +"RefundDuty":{"o":{"f":{"amountSet":"MoneyBag!","originalDuty":"Duty"}}}, +"RefundDutyInput":{"i":{"dutyId":"ID!","refundType":"RefundDutyRefundType"}}, +"RefundDutyRefundType":{"e":["PROPORTIONAL","FULL"]}, +"RefundEdge":{"o":{"f":{"cursor":"String!","node":"Refund!"}}}, +"RefundInput":{"i":{"allowOverRefunding":"Boolean=","currency":"CurrencyCode","discrepancyReason":"OrderAdjustmentInputDiscrepancyReason","note":"String","notify":"Boolean","orderId":"ID!","processedAt":"DateTime","refundDuties":"[RefundDutyInput!]","refundLineItems":"[RefundLineItemInput!]","refundMethods":"[RefundMethodInput!]=","shipping":"ShippingRefundInput","transactions":"[OrderTransactionInput!]"}}, +"RefundLineItem":{"o":{"f":{"id":"ID","lineItem":"LineItem!","location":"Location","price":"Money!","priceSet":"MoneyBag!","quantity":"Int!","restockType":"RefundLineItemRestockType!","restocked":"Boolean!","subtotal":"Money!","subtotalSet":"MoneyBag!","totalTax":"Money!","totalTaxSet":"MoneyBag!"},"d":{"price":"Use `priceSet` instead.","subtotal":"Use `subtotalSet` instead.","totalTax":"Use `totalTaxSet` instead."}}}, +"RefundLineItemConnection":{"o":{"f":{"edges":"[RefundLineItemEdge!]!","nodes":"[RefundLineItem!]!","pageInfo":"PageInfo!"}}}, +"RefundLineItemEdge":{"o":{"f":{"cursor":"String!","node":"RefundLineItem!"}}}, +"RefundLineItemInput":{"i":{"lineItemId":"ID!","locationId":"ID","quantity":"Int!","restockType":"RefundLineItemRestockType"}}, +"RefundLineItemRestockType":{"e":["RETURN","CANCEL","LEGACY_RESTOCK","NO_RESTOCK"]}, +"RefundMethodAllocation":{"e":["ORIGINAL_PAYMENT_METHODS","STORE_CREDIT"]}, +"RefundMethodInput":{"i":{"storeCreditRefund":"StoreCreditRefundInput"}}, +"RefundReturnOutcome":{"o":{"f":{"amount":"MoneyBag!","suggestedRefundMethods":"[SuggestedRefundMethod!]!","suggestedTransactions":"[SuggestedOrderTransaction!]!"}}}, +"RefundShippingInput":{"i":{"fullRefund":"Boolean=","shippingRefundAmount":"MoneyInput"}}, +"RefundShippingLine":{"o":{"f":{"id":"ID!","shippingLine":"ShippingLine!","subtotalAmountSet":"MoneyBag!","taxAmountSet":"MoneyBag!"},"t":["Node"]}}, +"RefundShippingLineConnection":{"o":{"f":{"edges":"[RefundShippingLineEdge!]!","nodes":"[RefundShippingLine!]!","pageInfo":"PageInfo!"}}}, +"RefundShippingLineEdge":{"o":{"f":{"cursor":"String!","node":"RefundShippingLine!"}}}, +"RegionsCondition":{"o":{"f":{"applicationLevel":"MarketConditionApplicationType","regions":["MarketRegionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"RemoteAuthorizeNetCustomerPaymentProfileInput":{"i":{"customerPaymentProfileId":"String!","customerProfileId":"String!"}}, +"RemoteBraintreePaymentMethodInput":{"i":{"customerId":"String!","paymentMethodToken":"String!"}}, +"RemoteStripePaymentMethodInput":{"i":{"customerId":"String!","paymentMethodId":"String!"}}, +"RemoveFromReturnPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"RequestedOrderEdit":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","lineItems":"RequestedOrderEditLineItems!","order":"Order!","requestDeclinedAt":"DateTime","requestResolvedAt":"DateTime","requestedAt":"DateTime!","status":"RequestedOrderEditStatus!","updatedAt":"DateTime!"},"t":["Node"]}}, +"RequestedOrderEditConnection":{"o":{"f":{"edges":"[RequestedOrderEditEdge!]!","nodes":"[RequestedOrderEdit!]!","pageInfo":"PageInfo!"}}}, +"RequestedOrderEditCreateInput":{"i":{"lineItems":"RequestedOrderEditLineItemsInput!","orderId":"ID!"}}, +"RequestedOrderEditCreatePayload":{"o":{"f":{"requestedOrderEdit":"RequestedOrderEdit","userErrors":"[RequestedOrderEditCreateUserError!]!"}}}, +"RequestedOrderEditCreateUserError":{"o":{"f":{"code":"RequestedOrderEditCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"RequestedOrderEditCreateUserErrorCode":{"e":["NOT_FOUND","INVALID","INTERNAL_ERROR","BLANK"]}, +"RequestedOrderEditDeclineInput":{"i":{"declineNote":"String","id":"ID!"}}, +"RequestedOrderEditDeclinePayload":{"o":{"f":{"requestedOrderEdit":"RequestedOrderEdit","userErrors":"[RequestedOrderEditDeclineUserError!]!"}}}, +"RequestedOrderEditDeclineUserError":{"o":{"f":{"code":"RequestedOrderEditDeclineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"RequestedOrderEditDeclineUserErrorCode":{"e":["NOT_FOUND","INVALID"]}, +"RequestedOrderEditEdge":{"o":{"f":{"cursor":"String!","node":"RequestedOrderEdit!"}}}, +"RequestedOrderEditFinancialSummary":{"o":{"f":{"editOrderLevelDiscountSubtotalSet":"MoneyBag!","editSubtotalBeforeTargetAllDiscountsSet":"MoneyBag!","editSubtotalSet":"MoneyBag!","editSubtotalWithCartDiscountSet":"MoneyBag!","editTotalSet":"MoneyBag!","editTotalTaxSet":"MoneyBag!"}}}, +"RequestedOrderEditLineItem":{"o":{"f":{"id":"ID!","lineItem":"LineItem!","quantity":"Int!","resolvedQuantity":"Int!"},"t":["Node"]}}, +"RequestedOrderEditLineItemConnection":{"o":{"f":{"edges":"[RequestedOrderEditLineItemEdge!]!","nodes":"[RequestedOrderEditLineItem!]!","pageInfo":"PageInfo!"}}}, +"RequestedOrderEditLineItemEdge":{"o":{"f":{"cursor":"String!","node":"RequestedOrderEditLineItem!"}}}, +"RequestedOrderEditLineItemRemovalInput":{"i":{"lineItemId":"ID!","quantity":"Int!"}}, +"RequestedOrderEditLineItems":{"o":{"f":{"removals":["RequestedOrderEditLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}]}}}, +"RequestedOrderEditLineItemsInput":{"i":{"removals":"[RequestedOrderEditLineItemRemovalInput!]!"}}, +"RequestedOrderEditResolveInput":{"i":{"id":"ID!"}}, +"RequestedOrderEditResolvePayload":{"o":{"f":{"requestedOrderEdit":"RequestedOrderEdit","userErrors":"[RequestedOrderEditResolveUserError!]!"}}}, +"RequestedOrderEditResolveUserError":{"o":{"f":{"code":"RequestedOrderEditResolveUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"RequestedOrderEditResolveUserErrorCode":{"e":["NOT_FOUND","INVALID"]}, +"RequestedOrderEditStatus":{"e":["REQUESTED","RESOLVED","DECLINED"]}, +"ResolvedPriceInclusivity":{"o":{"f":{"dutiesIncluded":"Boolean!","taxesIncluded":"Boolean!"}}}, +"ResourceAlert":{"o":{"f":{"actions":"[ResourceAlertAction!]!","content":"HTML!","dismissibleHandle":"String","icon":"ResourceAlertIcon","severity":"ResourceAlertSeverity!","title":"String!"}}}, +"ResourceAlertAction":{"o":{"f":{"primary":"Boolean!","show":"String","title":"String!","url":"URL!"}}}, +"ResourceAlertIcon":{"e":["CHECKMARK_CIRCLE","INFORMATION_CIRCLE"]}, +"ResourceAlertSeverity":{"e":{"v":["DEFAULT","INFO","WARNING","SUCCESS","CRITICAL","ERROR"],"d":{"ERROR":"`ERROR` severity is being deprecated in favour of `WARNING` or `CRITICAL` instead."}}}, +"ResourceFeedback":{"o":{"f":{"appFeedback":"[AppFeedback!]!","details":"[AppFeedback!]!","summary":"String!"},"d":{"appFeedback":"Use `details` instead."}}}, +"ResourceFeedbackCreateInput":{"i":{"channelId":"ID","feedbackGeneratedAt":"DateTime!","messages":"[String!]","state":"ResourceFeedbackState!"}}, +"ResourceFeedbackState":{"e":["ACCEPTED","REQUIRES_ACTION"]}, +"ResourceOperation":{"n":{"f":{"id":"ID!","processedRowCount":"Int","rowCount":"RowCount","status":"ResourceOperationStatus!"},"t":["AddAllProductsOperation","CatalogCsvOperation","PublicationResourceOperation"]}}, +"ResourceOperationStatus":{"e":["CREATED","ACTIVE","COMPLETE"]}, +"ResourcePublication":{"o":{"f":{"channel":"Channel!","isPublished":"Boolean!","publication":"Publication!","publishDate":"DateTime!","publishable":"Publishable!"},"d":{"channel":"Use `publication` instead."}}}, +"ResourcePublicationConnection":{"o":{"f":{"edges":"[ResourcePublicationEdge!]!","nodes":"[ResourcePublication!]!","pageInfo":"PageInfo!"}}}, +"ResourcePublicationEdge":{"o":{"f":{"cursor":"String!","node":"ResourcePublication!"}}}, +"ResourcePublicationV2":{"o":{"f":{"isPublished":"Boolean!","publication":"Publication!","publishDate":"DateTime","publishable":"Publishable!"}}}, +"ResourcePublicationV2Connection":{"o":{"f":{"edges":"[ResourcePublicationV2Edge!]!","nodes":"[ResourcePublicationV2!]!","pageInfo":"PageInfo!"}}}, +"ResourcePublicationV2Edge":{"o":{"f":{"cursor":"String!","node":"ResourcePublicationV2!"}}}, +"RestockingFee":{"o":{"f":{"amountSet":"MoneyBag!","id":"ID!","percentage":"Float!"},"t":["Fee"]}}, +"RestockingFeeInput":{"i":{"percentage":"Float!"}}, +"RestrictedForResource":{"o":{"f":{"restricted":"Boolean!","restrictedReason":"String!"}}}, +"Return":{"o":{"f":{"closedAt":"DateTime","createdAt":"DateTime!","decline":"ReturnDecline","exchangeLineItems":["ExchangeLineItemConnection!",{"after":"String","before":"String","first":"Int","includeRemovedItems":"Boolean=","last":"Int","processingStatus":"ReturnProcessingStatusFilterInput","reverse":"Boolean="}],"id":"ID!","name":"String!","order":"Order!","refunds":["RefundConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"requestApprovedAt":"DateTime","returnLineItems":["ReturnLineItemTypeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","processingStatus":"ReturnProcessingStatusFilterInput","reverse":"Boolean="}],"returnShippingFees":"[ReturnShippingFee!]!","reverseFulfillmentOrders":["ReverseFulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"staffMember":"StaffMember","status":"ReturnStatus!","suggestedFinancialOutcome":["SuggestedReturnFinancialOutcome",{"exchangeLineItems":"[SuggestedOutcomeExchangeLineItemInput!]!","refundDuties":"[RefundDutyInput!]","refundMethodAllocation":"RefundMethodAllocation=","refundShipping":"RefundShippingInput","returnLineItems":"[SuggestedOutcomeReturnLineItemInput!]!","tipLineId":"ID"}],"suggestedRefund":["SuggestedReturnRefund",{"refundDuties":"[RefundDutyInput!]","refundShipping":"RefundShippingInput","returnRefundLineItems":"[ReturnRefundLineItemInput!]!"}],"totalQuantity":"Int!","transactions":["OrderTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Node"],"d":{"suggestedRefund":"Use `suggestedFinancialOutcome` instead."}}}, +"ReturnAgreement":{"o":{"f":{"app":"App","happenedAt":"DateTime!","id":"ID!","reason":"OrderActionType!","return":"Return!","sales":["SaleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"user":"StaffMember"},"t":["SalesAgreement"]}}, +"ReturnApproveRequestInput":{"i":{"f":{"id":"ID!","notifyCustomer":"Boolean=","unprocessed":"Boolean="},"d":{"unprocessed":"This field is temporary to support the transition to Returns Processing APIs."}}}, +"ReturnApproveRequestPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnCancelPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnClosePayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnConnection":{"o":{"f":{"edges":"[ReturnEdge!]!","nodes":"[Return!]!","pageInfo":"PageInfo!"}}}, +"ReturnCreatePayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnDecline":{"o":{"f":{"note":"String","reason":"ReturnDeclineReason!"}}}, +"ReturnDeclineReason":{"e":["RETURN_PERIOD_ENDED","FINAL_SALE","OTHER"]}, +"ReturnDeclineRequestInput":{"i":{"declineNote":"String","declineReason":"ReturnDeclineReason!","id":"ID!","notifyCustomer":"Boolean="}}, +"ReturnDeclineRequestPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnEdge":{"o":{"f":{"cursor":"String!","node":"Return!"}}}, +"ReturnErrorCode":{"e":["INTERNAL_ERROR","TOO_MANY_ARGUMENTS","BLANK","EQUAL_TO","GREATER_THAN","GREATER_THAN_OR_EQUAL_TO","INCLUSION","INVALID","LESS_THAN","LESS_THAN_OR_EQUAL_TO","NOT_A_NUMBER","PRESENT","TAKEN","TOO_BIG","TOO_LONG","TOO_SHORT","WRONG_LENGTH","ALREADY_EXISTS","CREATION_FAILED","FEATURE_NOT_ENABLED","INCOMPATIBLE_WITH_STANDARD_POLICY","INVALID_STATE","MISSING_PERMISSION","NOTIFICATION_FAILED","NOT_EDITABLE","NOT_FOUND"]}, +"ReturnInput":{"i":{"f":{"exchangeLineItems":"[ExchangeLineItemInput!]","notifyCustomer":"Boolean=","orderId":"ID!","requestedAt":"DateTime","returnLineItems":"[ReturnLineItemInput!]!","returnShippingFee":"ReturnShippingFeeInput","unprocessed":"Boolean="},"d":{"notifyCustomer":"This field is no longer supported and any value provided to it is currently ignored.","unprocessed":"This field is temporary to support the transition to Returns Processing APIs."}}}, +"ReturnLineItem":{"o":{"f":{"customerNote":"String","fulfillmentLineItem":"FulfillmentLineItem!","id":"ID!","processableQuantity":"Int!","processedQuantity":"Int!","quantity":"Int!","refundableQuantity":"Int!","refundedQuantity":"Int!","restockingFee":"RestockingFee","returnReason":"ReturnReason!","returnReasonDefinition":"ReturnReasonDefinition","returnReasonNote":"String!","totalWeight":"Weight","unprocessedQuantity":"Int!","withCodeDiscountedTotalPriceSet":"MoneyBag!"},"t":["Node","ReturnLineItemType"],"d":{"returnReason":"Use `returnReasonDefinition` instead. This field will be removed in the future."}}}, +"ReturnLineItemInput":{"i":{"f":{"fulfillmentLineItemId":"ID!","quantity":"Int!","restockingFee":"RestockingFeeInput","returnReason":"ReturnReason","returnReasonDefinitionId":"ID","returnReasonNote":"String="},"d":{"returnReason":"Use `returnReasonDefinitionId` instead. This field will be removed in the future."}}}, +"ReturnLineItemRemoveFromReturnInput":{"i":{"quantity":"Int!","returnLineItemId":"ID!"}}, +"ReturnLineItemRemoveFromReturnPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnLineItemType":{"n":{"f":{"customerNote":"String","id":"ID!","processableQuantity":"Int!","processedQuantity":"Int!","quantity":"Int!","refundableQuantity":"Int!","refundedQuantity":"Int!","returnReason":"ReturnReason!","returnReasonDefinition":"ReturnReasonDefinition","returnReasonNote":"String!","unprocessedQuantity":"Int!"},"t":["ReturnLineItem","UnverifiedReturnLineItem"],"d":{"returnReason":"Use `returnReasonDefinition` instead. This field will be removed in the future."}}}, +"ReturnLineItemTypeConnection":{"o":{"f":{"edges":"[ReturnLineItemTypeEdge!]!","nodes":"[ReturnLineItemType!]!","pageInfo":"PageInfo!"}}}, +"ReturnLineItemTypeEdge":{"o":{"f":{"cursor":"String!","node":"ReturnLineItemType!"}}}, +"ReturnOutcomeFinancialTransfer":{"u":["InvoiceReturnOutcome","RefundReturnOutcome"]}, +"ReturnPoliciesEditRules":{"o":{"f":{"canAcceptEdits":"Boolean!","editWindowMinutes":"Int"}}}, +"ReturnPoliciesReturnRules":{"o":{"f":{"canAcceptReturns":"Boolean!","extendWindowToBusinessDay":"Boolean","returnWindowDays":"Int","returnWindowStartingFrom":"ReturnPoliciesReturnWindowStartingFrom"}}}, +"ReturnPoliciesReturnWindowStartingFrom":{"e":["ITEM_DELIVERY_DATE","LAST_ITEM_DELIVERY_DATE"]}, +"ReturnPolicyProfile":{"o":{"f":{"default":"Boolean!","editRules":"ReturnPoliciesEditRules","id":"ID!","markets":"[Market!]!","name":"String","returnRules":"ReturnPoliciesReturnRules","updatedAt":"DateTime"},"t":["Node"]}}, +"ReturnPolicyProfileConnection":{"o":{"f":{"edges":"[ReturnPolicyProfileEdge!]!","nodes":"[ReturnPolicyProfile!]!","pageInfo":"PageInfo!"}}}, +"ReturnPolicyProfileEdge":{"o":{"f":{"cursor":"String!","node":"ReturnPolicyProfile!"}}}, +"ReturnProcessExchangeLineItemInput":{"i":{"id":"ID!","quantity":"Int!"}}, +"ReturnProcessFinancialTransferInput":{"i":{"issueRefund":"ReturnProcessRefundInput"}}, +"ReturnProcessInput":{"i":{"exchangeLineItems":"[ReturnProcessExchangeLineItemInput!]=","financialTransfer":"ReturnProcessFinancialTransferInput","note":"String","notifyCustomer":"Boolean=","refundDuties":"[RefundDutyInput!]=","refundShipping":"RefundShippingInput","returnId":"ID!","returnLineItems":"[ReturnProcessReturnLineItemInput!]=","tipLineId":"ID"}}, +"ReturnProcessPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnProcessRefundInput":{"i":{"allowOverRefunding":"Boolean=","orderTransactions":"[ReturnRefundOrderTransactionInput!]!","refundMethods":"[RefundMethodInput!]="}}, +"ReturnProcessReturnLineItemInput":{"i":{"dispositions":"[ReverseFulfillmentOrderDisposeInput!]","id":"ID!","quantity":"Int!"}}, +"ReturnProcessingStatusFilterInput":{"e":["PROCESSED","PROCESSABLE"]}, +"ReturnReason":{"e":["SIZE_TOO_SMALL","SIZE_TOO_LARGE","UNWANTED","NOT_AS_DESCRIBED","WRONG_ITEM","DEFECTIVE","STYLE","COLOR","OTHER","UNKNOWN"]}, +"ReturnReasonDefinition":{"o":{"f":{"deleted":"Boolean!","handle":"String!","id":"ID!","name":"String!"},"t":["Node"]}}, +"ReturnReasonDefinitionConnection":{"o":{"f":{"edges":"[ReturnReasonDefinitionEdge!]!","nodes":"[ReturnReasonDefinition!]!","pageInfo":"PageInfo!"}}}, +"ReturnReasonDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"ReturnReasonDefinition!"}}}, +"ReturnReasonDefinitionSortKeys":{"e":["HANDLE","ID","NAME"]}, +"ReturnRefundInput":{"i":{"notifyCustomer":"Boolean=","orderTransactions":"[ReturnRefundOrderTransactionInput!]=","refundDuties":"[RefundDutyInput!]","refundShipping":"RefundShippingInput","returnId":"ID!","returnRefundLineItems":"[ReturnRefundLineItemInput!]!"}}, +"ReturnRefundLineItemInput":{"i":{"quantity":"Int!","returnLineItemId":"ID!"}}, +"ReturnRefundOrderTransactionInput":{"i":{"parentId":"ID!","transactionAmount":"MoneyInput!"}}, +"ReturnRefundPayload":{"o":{"f":{"refund":"Refund","userErrors":"[ReturnUserError!]!"}}}, +"ReturnReopenPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnRequestInput":{"i":{"orderId":"ID!","returnLineItems":"[ReturnRequestLineItemInput!]!","returnShippingFee":"ReturnShippingFeeInput"}}, +"ReturnRequestLineItemInput":{"i":{"f":{"customerNote":"String","fulfillmentLineItemId":"ID!","quantity":"Int!","restockingFee":"RestockingFeeInput","returnReason":"ReturnReason","returnReasonDefinitionId":"ID"},"d":{"returnReason":"Use `returnReasonDefinitionId` instead. This field will be removed in the future."}}}, +"ReturnRequestPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnShippingFee":{"o":{"f":{"amountSet":"MoneyBag!","finalizedTaxAmountSet":"MoneyBag","id":"ID!"},"t":["Fee"]}}, +"ReturnShippingFeeInput":{"i":{"amount":"MoneyInput!"}}, +"ReturnStatus":{"e":["CANCELED","CLOSED","OPEN","REQUESTED","DECLINED"]}, +"ReturnUserError":{"o":{"f":{"code":"ReturnErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ReturnableFulfillment":{"o":{"f":{"fulfillment":"Fulfillment!","id":"ID!","returnableFulfillmentLineItems":["ReturnableFulfillmentLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Node"]}}, +"ReturnableFulfillmentConnection":{"o":{"f":{"edges":"[ReturnableFulfillmentEdge!]!","nodes":"[ReturnableFulfillment!]!","pageInfo":"PageInfo!"}}}, +"ReturnableFulfillmentEdge":{"o":{"f":{"cursor":"String!","node":"ReturnableFulfillment!"}}}, +"ReturnableFulfillmentLineItem":{"o":{"f":{"fulfillmentLineItem":"FulfillmentLineItem!","quantity":"Int!"}}}, +"ReturnableFulfillmentLineItemConnection":{"o":{"f":{"edges":"[ReturnableFulfillmentLineItemEdge!]!","nodes":"[ReturnableFulfillmentLineItem!]!","pageInfo":"PageInfo!"}}}, +"ReturnableFulfillmentLineItemEdge":{"o":{"f":{"cursor":"String!","node":"ReturnableFulfillmentLineItem!"}}}, +"ReverseDelivery":{"o":{"f":{"deliverable":"ReverseDeliveryDeliverable","id":"ID!","reverseDeliveryLineItems":["ReverseDeliveryLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"reverseFulfillmentOrder":"ReverseFulfillmentOrder!"},"t":["Node"]}}, +"ReverseDeliveryConnection":{"o":{"f":{"edges":"[ReverseDeliveryEdge!]!","nodes":"[ReverseDelivery!]!","pageInfo":"PageInfo!"}}}, +"ReverseDeliveryCreateWithShippingPayload":{"o":{"f":{"reverseDelivery":"ReverseDelivery","userErrors":"[ReturnUserError!]!"}}}, +"ReverseDeliveryDeliverable":{"u":["ReverseDeliveryShippingDeliverable"]}, +"ReverseDeliveryEdge":{"o":{"f":{"cursor":"String!","node":"ReverseDelivery!"}}}, +"ReverseDeliveryLabelInput":{"i":{"fileUrl":"URL!"}}, +"ReverseDeliveryLabelV2":{"o":{"f":{"createdAt":"DateTime!","publicFileUrl":"URL","updatedAt":"DateTime!"}}}, +"ReverseDeliveryLineItem":{"o":{"f":{"dispositions":"[ReverseFulfillmentOrderDisposition!]!","id":"ID!","quantity":"Int!","reverseFulfillmentOrderLineItem":"ReverseFulfillmentOrderLineItem!"},"t":["Node"]}}, +"ReverseDeliveryLineItemConnection":{"o":{"f":{"edges":"[ReverseDeliveryLineItemEdge!]!","nodes":"[ReverseDeliveryLineItem!]!","pageInfo":"PageInfo!"}}}, +"ReverseDeliveryLineItemEdge":{"o":{"f":{"cursor":"String!","node":"ReverseDeliveryLineItem!"}}}, +"ReverseDeliveryLineItemInput":{"i":{"quantity":"Int!","reverseFulfillmentOrderLineItemId":"ID!"}}, +"ReverseDeliveryShippingDeliverable":{"o":{"f":{"label":"ReverseDeliveryLabelV2","tracking":"ReverseDeliveryTrackingV2"}}}, +"ReverseDeliveryShippingUpdatePayload":{"o":{"f":{"reverseDelivery":"ReverseDelivery","userErrors":"[ReturnUserError!]!"}}}, +"ReverseDeliveryTrackingInput":{"i":{"number":"String","url":"URL"}}, +"ReverseDeliveryTrackingV2":{"o":{"f":{"carrierName":"String","number":"String","url":"URL"}}}, +"ReverseFulfillmentOrder":{"o":{"f":{"id":"ID!","lineItems":["ReverseFulfillmentOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"order":"Order","reverseDeliveries":["ReverseDeliveryConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"status":"ReverseFulfillmentOrderStatus!","thirdPartyConfirmation":"ReverseFulfillmentOrderThirdPartyConfirmation"},"t":["Node"]}}, +"ReverseFulfillmentOrderConnection":{"o":{"f":{"edges":"[ReverseFulfillmentOrderEdge!]!","nodes":"[ReverseFulfillmentOrder!]!","pageInfo":"PageInfo!"}}}, +"ReverseFulfillmentOrderDisposeInput":{"i":{"dispositionType":"ReverseFulfillmentOrderDispositionType!","locationId":"ID","quantity":"Int!","reverseFulfillmentOrderLineItemId":"ID!"}}, +"ReverseFulfillmentOrderDisposePayload":{"o":{"f":{"reverseFulfillmentOrderLineItems":"[ReverseFulfillmentOrderLineItem!]","userErrors":"[ReturnUserError!]!"}}}, +"ReverseFulfillmentOrderDisposition":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","location":"Location","quantity":"Int!","type":"ReverseFulfillmentOrderDispositionType!"},"t":["Node"]}}, +"ReverseFulfillmentOrderDispositionType":{"e":["RESTOCKED","PROCESSING_REQUIRED","NOT_RESTOCKED","MISSING"]}, +"ReverseFulfillmentOrderEdge":{"o":{"f":{"cursor":"String!","node":"ReverseFulfillmentOrder!"}}}, +"ReverseFulfillmentOrderLineItem":{"o":{"f":{"dispositions":"[ReverseFulfillmentOrderDisposition!]!","fulfillmentLineItem":"FulfillmentLineItem","id":"ID!","totalQuantity":"Int!"},"t":["Node"]}}, +"ReverseFulfillmentOrderLineItemConnection":{"o":{"f":{"edges":"[ReverseFulfillmentOrderLineItemEdge!]!","nodes":"[ReverseFulfillmentOrderLineItem!]!","pageInfo":"PageInfo!"}}}, +"ReverseFulfillmentOrderLineItemEdge":{"o":{"f":{"cursor":"String!","node":"ReverseFulfillmentOrderLineItem!"}}}, +"ReverseFulfillmentOrderStatus":{"e":["CANCELED","CLOSED","OPEN"]}, +"ReverseFulfillmentOrderThirdPartyConfirmation":{"o":{"f":{"status":"ReverseFulfillmentOrderThirdPartyConfirmationStatus!"}}}, +"ReverseFulfillmentOrderThirdPartyConfirmationStatus":{"e":["ACCEPTED","CANCEL_ACCEPTED","CANCEL_REJECTED","PENDING_ACCEPTANCE","PENDING_CANCELATION","REJECTED"]}, +"RiskAssessmentResult":{"e":["HIGH","MEDIUM","LOW","NONE","PENDING"]}, +"RiskFact":{"o":{"f":{"description":"String!","sentiment":"RiskFactSentiment!"}}}, +"RiskFactSentiment":{"e":["POSITIVE","NEUTRAL","NEGATIVE"]}, +"Rollout":{"o":{"f":{"archivedAt":"DateTime","concludedAt":"DateTime","createdAt":"DateTime!","effectiveTrafficAllocation":"Float!","id":"ID!","name":"String!","schedule":"RolloutSchedule","startedAt":"DateTime","status":"RolloutStatus!","trafficAllocation":"Int!","treatments":"[RolloutTreatment!]!","updatedAt":"DateTime!"},"t":["Node"]}}, +"RolloutCatalogActivateChange":{"o":{"f":{"catalog":"Catalog","id":"ID!"},"t":["RolloutCatalogChange","RolloutChange"]}}, +"RolloutCatalogChange":{"n":{"f":{"catalog":"Catalog","id":"ID!"},"t":["RolloutCatalogActivateChange","RolloutCatalogDraftChange"]}}, +"RolloutCatalogDraftChange":{"o":{"f":{"catalog":"Catalog","id":"ID!"},"t":["RolloutCatalogChange","RolloutChange"]}}, +"RolloutChange":{"n":{"f":{"id":"ID!"},"t":["RolloutCatalogActivateChange","RolloutCatalogDraftChange","RolloutCheckoutAndAccountsConfigurationPublishChange","RolloutDiscountActivateChange","RolloutDiscountExpireChange","RolloutThemePublishChange"]}}, +"RolloutChangeConnection":{"o":{"f":{"edges":"[RolloutChangeEdge!]!","nodes":"[RolloutChange!]!","pageInfo":"PageInfo!"}}}, +"RolloutChangeEdge":{"o":{"f":{"cursor":"String!","node":"RolloutChange!"}}}, +"RolloutCheckoutAndAccountsConfigurationChange":{"n":{"f":{"checkoutAndAccountsConfiguration":"CheckoutAndAccountsConfiguration","id":"ID!"},"t":["RolloutCheckoutAndAccountsConfigurationPublishChange"]}}, +"RolloutCheckoutAndAccountsConfigurationPublishChange":{"o":{"f":{"checkoutAndAccountsConfiguration":"CheckoutAndAccountsConfiguration","id":"ID!"},"t":["RolloutChange","RolloutCheckoutAndAccountsConfigurationChange"]}}, +"RolloutConnection":{"o":{"f":{"edges":"[RolloutEdge!]!","nodes":"[Rollout!]!","pageInfo":"PageInfo!"}}}, +"RolloutDiscountActivateChange":{"o":{"f":{"discount":"DiscountNode","id":"ID!"},"t":["RolloutChange","RolloutDiscountChange"]}}, +"RolloutDiscountChange":{"n":{"f":{"discount":"DiscountNode","id":"ID!"},"t":["RolloutDiscountActivateChange","RolloutDiscountExpireChange"]}}, +"RolloutDiscountExpireChange":{"o":{"f":{"discount":"DiscountNode","id":"ID!"},"t":["RolloutChange","RolloutDiscountChange"]}}, +"RolloutEdge":{"o":{"f":{"cursor":"String!","node":"Rollout!"}}}, +"RolloutSchedule":{"o":{"f":{"activateAt":"DateTime!","concludeAt":"DateTime"}}}, +"RolloutSortKeys":{"e":["ID","NAME","CREATED_AT","UPDATED_AT"]}, +"RolloutStatus":{"e":["DRAFT","SCHEDULED","PAUSED","ACTIVE","CONCLUDED","ARCHIVED"]}, +"RolloutThemeChange":{"n":{"f":{"id":"ID!","theme":"OnlineStoreTheme"},"t":["RolloutThemePublishChange"]}}, +"RolloutThemePublishChange":{"o":{"f":{"id":"ID!","theme":"OnlineStoreTheme"},"t":["RolloutChange","RolloutThemeChange"]}}, +"RolloutTreatment":{"o":{"f":{"changes":["RolloutChangeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"id":"ID!","rollout":"Rollout","split":"Int!"},"t":["Node"]}}, +"RowCount":{"o":{"f":{"count":"Int!","exceedsMax":"Boolean!"}}}, +"SEO":{"o":{"f":{"description":"String","title":"String"}}}, +"SEOInput":{"i":{"description":"String","title":"String"}}, +"Sale":{"n":{"f":{"actionType":"SaleActionType!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["AdditionalFeeSale","AdjustmentSale","DutySale","FeeSale","GiftCardSale","ProductSale","ShippingLineSale","TipSale","UnknownSale"]}}, +"SaleActionType":{"e":["ORDER","RETURN","UPDATE","UNKNOWN"]}, +"SaleAdditionalFee":{"o":{"f":{"id":"ID!","name":"String!","price":"MoneyBag!","taxLines":"[TaxLine!]!"},"t":["Node"]}}, +"SaleConnection":{"o":{"f":{"edges":"[SaleEdge!]!","nodes":"[Sale!]!","pageInfo":"PageInfo!"}}}, +"SaleEdge":{"o":{"f":{"cursor":"String!","node":"Sale!"}}}, +"SaleLineType":{"e":["PRODUCT","TIP","GIFT_CARD","SHIPPING","DUTY","ADDITIONAL_FEE","FEE","UNKNOWN","ADJUSTMENT"]}, +"SaleTax":{"o":{"f":{"amount":"MoneyBag!","id":"ID!","taxLine":"TaxLine!"}}}, +"SalesAgreement":{"n":{"f":{"app":"App","happenedAt":"DateTime!","id":"ID!","reason":"OrderActionType!","sales":["SaleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"user":"StaffMember"},"t":["OrderAgreement","OrderEditAgreement","RefundAgreement","ReturnAgreement"]}}, +"SalesAgreementConnection":{"o":{"f":{"edges":"[SalesAgreementEdge!]!","nodes":"[SalesAgreement!]!","pageInfo":"PageInfo!"}}}, +"SalesAgreementEdge":{"o":{"f":{"cursor":"String!","node":"SalesAgreement!"}}}, +"SavedSearch":{"o":{"f":{"filters":"[SearchFilter!]!","id":"ID!","legacyResourceId":"UnsignedInt64!","name":"String!","query":"String!","resourceType":"SearchResultType!","searchTerms":"String!"},"t":["LegacyInteroperability","Node"]}}, +"SavedSearchConnection":{"o":{"f":{"edges":"[SavedSearchEdge!]!","nodes":"[SavedSearch!]!","pageInfo":"PageInfo!"}}}, +"SavedSearchCreateInput":{"i":{"name":"String!","query":"String!","resourceType":"SearchResultType!"}}, +"SavedSearchCreatePayload":{"o":{"f":{"savedSearch":"SavedSearch","userErrors":"[UserError!]!"}}}, +"SavedSearchDeleteInput":{"i":{"id":"ID!"}}, +"SavedSearchDeletePayload":{"o":{"f":{"deletedSavedSearchId":"ID","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"SavedSearchEdge":{"o":{"f":{"cursor":"String!","node":"SavedSearch!"}}}, +"SavedSearchUpdateInput":{"i":{"id":"ID!","name":"String","query":"String"}}, +"SavedSearchUpdatePayload":{"o":{"f":{"savedSearch":"SavedSearch","userErrors":"[UserError!]!"}}}, +"ScheduledChangeSortKeys":{"e":["EXPECTED_AT","ID"]}, +"ScriptDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","description":"String!","index":"Int!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","title":"String!","value":"PricingValue!"},"t":["DiscountApplication"],"d":{"description":"Use `title` instead."}}}, +"ScriptTag":{"o":{"f":{"cache":"Boolean!","createdAt":"DateTime!","displayScope":"ScriptTagDisplayScope!","id":"ID!","legacyResourceId":"UnsignedInt64!","src":"URL!","updatedAt":"DateTime!"},"t":["LegacyInteroperability","Node"]}}, +"ScriptTagConnection":{"o":{"f":{"edges":"[ScriptTagEdge!]!","nodes":"[ScriptTag!]!","pageInfo":"PageInfo!"}}}, +"ScriptTagCreatePayload":{"o":{"f":{"scriptTag":"ScriptTag","userErrors":"[UserError!]!"}}}, +"ScriptTagDeletePayload":{"o":{"f":{"deletedScriptTagId":"ID","userErrors":"[UserError!]!"}}}, +"ScriptTagDisplayScope":{"e":{"v":["ALL","ORDER_STATUS","ONLINE_STORE"],"d":{"ALL":"`ALL` is deprecated. Use `ONLINE_STORE` instead.","ORDER_STATUS":"`ORDER_STATUS` is deprecated and unavailable as a mutation input."}}}, +"ScriptTagEdge":{"o":{"f":{"cursor":"String!","node":"ScriptTag!"}}}, +"ScriptTagInput":{"i":{"cache":"Boolean=","displayScope":"ScriptTagDisplayScope","src":"URL"}}, +"ScriptTagUpdatePayload":{"o":{"f":{"scriptTag":"ScriptTag","userErrors":"[UserError!]!"}}}, +"SearchFilter":{"o":{"f":{"key":"String!","value":"String!"}}}, +"SearchFilterOptions":{"o":{"f":{"productAvailability":"[FilterOption!]!"}}}, +"SearchResult":{"o":{"f":{"description":"String","image":"Image","reference":"Node!","title":"String!","url":"URL!"}}}, +"SearchResultConnection":{"o":{"f":{"edges":"[SearchResultEdge!]!","pageInfo":"PageInfo!","resultsAfterCount":"Int!"},"d":{"resultsAfterCount":"The provided information is not accurate."}}}, +"SearchResultEdge":{"o":{"f":{"cursor":"String!","node":"SearchResult!"}}}, +"SearchResultType":{"e":["CUSTOMER","DRAFT_ORDER","INVENTORY_TRANSFER","PRODUCT","COLLECTION","FILE","PAGE","BLOG","ARTICLE","URL_REDIRECT","PRICE_RULE","DISCOUNT_REDEEM_CODE","ORDER","BALANCE_TRANSACTION"]}, +"Segment":{"o":{"f":{"creationDate":"DateTime!","id":"ID!","lastEditDate":"DateTime!","name":"String!","query":"String!"},"t":["Node"]}}, +"SegmentAssociationFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentAttributeStatistics":{"o":{"f":{"average":"Float!","sum":"Float!"}}}, +"SegmentBooleanFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentConnection":{"o":{"f":{"edges":"[SegmentEdge!]!","nodes":"[Segment!]!","pageInfo":"PageInfo!"}}}, +"SegmentCreatePayload":{"o":{"f":{"segment":"Segment","userErrors":"[UserError!]!"}}}, +"SegmentDateFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentDeletePayload":{"o":{"f":{"deletedSegmentId":"ID","userErrors":"[UserError!]!"}}}, +"SegmentEdge":{"o":{"f":{"cursor":"String!","node":"Segment!"}}}, +"SegmentEnumFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentEventFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","parameters":"[SegmentEventFilterParameter!]!","queryName":"String!","returnValueType":"String!"},"t":["SegmentFilter"]}}, +"SegmentEventFilterParameter":{"o":{"f":{"acceptsMultipleValues":"Boolean!","localizedDescription":"String!","localizedName":"String!","maxRange":"Float","minRange":"Float","optional":"Boolean!","parameterType":"String!","queryName":"String!"}}}, +"SegmentFilter":{"n":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentAssociationFilter","SegmentBooleanFilter","SegmentDateFilter","SegmentEnumFilter","SegmentEventFilter","SegmentFloatFilter","SegmentIntegerFilter","SegmentStringFilter"]}}, +"SegmentFilterConnection":{"o":{"f":{"edges":"[SegmentFilterEdge!]!","nodes":"[SegmentFilter!]!","pageInfo":"PageInfo!"}}}, +"SegmentFilterEdge":{"o":{"f":{"cursor":"String!","node":"SegmentFilter!"}}}, +"SegmentFloatFilter":{"o":{"f":{"localizedName":"String!","maxRange":"Float","minRange":"Float","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentIntegerFilter":{"o":{"f":{"localizedName":"String!","maxRange":"Float","minRange":"Float","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentMembership":{"o":{"f":{"isMember":"Boolean!","segmentId":"ID!"}}}, +"SegmentMembershipResponse":{"o":{"f":{"memberships":"[SegmentMembership!]!"}}}, +"SegmentMigration":{"o":{"f":{"id":"ID!","savedSearchId":"ID!","segmentId":"ID"}}}, +"SegmentMigrationConnection":{"o":{"f":{"edges":"[SegmentMigrationEdge!]!","nodes":"[SegmentMigration!]!","pageInfo":"PageInfo!"}}}, +"SegmentMigrationEdge":{"o":{"f":{"cursor":"String!","node":"SegmentMigration!"}}}, +"SegmentSortKeys":{"e":["CREATION_DATE","ID","LAST_EDIT_DATE","RELEVANCE"]}, +"SegmentStatistics":{"o":{"f":{"attributeStatistics":["SegmentAttributeStatistics!",{"attributeName":"String!"}]}}}, +"SegmentStringFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentUpdatePayload":{"o":{"f":{"segment":"Segment","userErrors":"[UserError!]!"}}}, +"SegmentValue":{"o":{"f":{"localizedValue":"String!","queryName":"String!"}}}, +"SegmentValueConnection":{"o":{"f":{"edges":"[SegmentValueEdge!]!","nodes":"[SegmentValue!]!","pageInfo":"PageInfo!"}}}, +"SegmentValueEdge":{"o":{"f":{"cursor":"String!","node":"SegmentValue!"}}}, +"SelectedOption":{"o":{"f":{"name":"String!","optionValue":"ProductOptionValue!","value":"String!"}}}, +"SelectedVariantOptionInput":{"i":{"linkedMetafieldValue":"String","name":"String!","value":"String!"}}, +"SellingPlan":{"o":{"f":{"billingPolicy":"SellingPlanBillingPolicy!","category":"SellingPlanCategory","createdAt":"DateTime!","deliveryPolicy":"SellingPlanDeliveryPolicy!","description":"String","id":"ID!","inventoryPolicy":"SellingPlanInventoryPolicy","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","options":"[String!]!","position":"Int","pricingPolicies":"[SellingPlanPricingPolicy!]!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"SellingPlanAnchor":{"o":{"f":{"cutoffDay":"Int","day":"Int!","month":"Int","type":"SellingPlanAnchorType!"}}}, +"SellingPlanAnchorInput":{"i":{"cutoffDay":"Int","day":"Int","month":"Int","type":"SellingPlanAnchorType"}}, +"SellingPlanAnchorType":{"e":["WEEKDAY","MONTHDAY","YEARDAY"]}, +"SellingPlanBillingPolicy":{"u":["SellingPlanFixedBillingPolicy","SellingPlanRecurringBillingPolicy"]}, +"SellingPlanBillingPolicyInput":{"i":{"fixed":"SellingPlanFixedBillingPolicyInput","recurring":"SellingPlanRecurringBillingPolicyInput"}}, +"SellingPlanCategory":{"e":["OTHER","PRE_ORDER","SUBSCRIPTION","TRY_BEFORE_YOU_BUY"]}, +"SellingPlanCheckoutCharge":{"o":{"f":{"type":"SellingPlanCheckoutChargeType!","value":"SellingPlanCheckoutChargeValue!"}}}, +"SellingPlanCheckoutChargeInput":{"i":{"type":"SellingPlanCheckoutChargeType","value":"SellingPlanCheckoutChargeValueInput"}}, +"SellingPlanCheckoutChargePercentageValue":{"o":{"f":{"percentage":"Float!"}}}, +"SellingPlanCheckoutChargeType":{"e":["PERCENTAGE","PRICE"]}, +"SellingPlanCheckoutChargeValue":{"u":["MoneyV2","SellingPlanCheckoutChargePercentageValue"]}, +"SellingPlanCheckoutChargeValueInput":{"i":{"fixedValue":"Decimal","percentage":"Float"}}, +"SellingPlanConnection":{"o":{"f":{"edges":"[SellingPlanEdge!]!","nodes":"[SellingPlan!]!","pageInfo":"PageInfo!"}}}, +"SellingPlanDeliveryPolicy":{"u":["SellingPlanFixedDeliveryPolicy","SellingPlanRecurringDeliveryPolicy"]}, +"SellingPlanDeliveryPolicyInput":{"i":{"fixed":"SellingPlanFixedDeliveryPolicyInput","recurring":"SellingPlanRecurringDeliveryPolicyInput"}}, +"SellingPlanEdge":{"o":{"f":{"cursor":"String!","node":"SellingPlan!"}}}, +"SellingPlanFixedBillingPolicy":{"o":{"f":{"checkoutCharge":"SellingPlanCheckoutCharge!","remainingBalanceChargeExactTime":"DateTime","remainingBalanceChargeTimeAfterCheckout":"String","remainingBalanceChargeTrigger":"SellingPlanRemainingBalanceChargeTrigger!"}}}, +"SellingPlanFixedBillingPolicyInput":{"i":{"checkoutCharge":"SellingPlanCheckoutChargeInput","remainingBalanceChargeExactTime":"DateTime","remainingBalanceChargeTimeAfterCheckout":"String","remainingBalanceChargeTrigger":"SellingPlanRemainingBalanceChargeTrigger"}}, +"SellingPlanFixedDeliveryPolicy":{"o":{"f":{"anchors":"[SellingPlanAnchor!]!","cutoff":"Int","fulfillmentExactTime":"DateTime","fulfillmentTrigger":"SellingPlanFulfillmentTrigger!","intent":"SellingPlanFixedDeliveryPolicyIntent!","preAnchorBehavior":"SellingPlanFixedDeliveryPolicyPreAnchorBehavior!"}}}, +"SellingPlanFixedDeliveryPolicyInput":{"i":{"anchors":"[SellingPlanAnchorInput!]","cutoff":"Int","fulfillmentExactTime":"DateTime","fulfillmentTrigger":"SellingPlanFulfillmentTrigger","intent":"SellingPlanFixedDeliveryPolicyIntent","preAnchorBehavior":"SellingPlanFixedDeliveryPolicyPreAnchorBehavior"}}, +"SellingPlanFixedDeliveryPolicyIntent":{"e":["FULFILLMENT_BEGIN"]}, +"SellingPlanFixedDeliveryPolicyPreAnchorBehavior":{"e":["ASAP","NEXT"]}, +"SellingPlanFixedPricingPolicy":{"o":{"f":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyAdjustmentValue!","createdAt":"DateTime!"},"t":["SellingPlanPricingPolicyBase"]}}, +"SellingPlanFixedPricingPolicyInput":{"i":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType","adjustmentValue":"SellingPlanPricingPolicyValueInput","id":"ID"}}, +"SellingPlanFulfillmentTrigger":{"e":["ANCHOR","ASAP","EXACT_TIME","UNKNOWN"]}, +"SellingPlanGroup":{"o":{"f":{"appId":"String","appliesToProduct":["Boolean!",{"productId":"ID!"}],"appliesToProductVariant":["Boolean!",{"productVariantId":"ID!"}],"appliesToProductVariants":["Boolean!",{"productId":"ID!"}],"createdAt":"DateTime!","description":"String","id":"ID!","merchantCode":"String!","name":"String!","options":"[String!]!","position":"Int","productVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","productId":"ID","reverse":"Boolean="}],"productVariantsCount":["Count",{"productId":"ID"}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productsCount":"Count","sellingPlans":["SellingPlanConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"summary":"String","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["HasPublishedTranslations","Node"]}}, +"SellingPlanGroupAddProductVariantsPayload":{"o":{"f":{"sellingPlanGroup":"SellingPlanGroup","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupAddProductsPayload":{"o":{"f":{"sellingPlanGroup":"SellingPlanGroup","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupConnection":{"o":{"f":{"edges":"[SellingPlanGroupEdge!]!","nodes":"[SellingPlanGroup!]!","pageInfo":"PageInfo!"}}}, +"SellingPlanGroupCreatePayload":{"o":{"f":{"sellingPlanGroup":"SellingPlanGroup","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupDeletePayload":{"o":{"f":{"deletedSellingPlanGroupId":"ID","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupEdge":{"o":{"f":{"cursor":"String!","node":"SellingPlanGroup!"}}}, +"SellingPlanGroupInput":{"i":{"appId":"String","description":"String","merchantCode":"String","name":"String","options":"[String!]","position":"Int","sellingPlansToCreate":"[SellingPlanInput!]","sellingPlansToDelete":"[ID!]","sellingPlansToUpdate":"[SellingPlanInput!]"}}, +"SellingPlanGroupRemoveProductVariantsPayload":{"o":{"f":{"removedProductVariantIds":"[ID!]","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupRemoveProductsPayload":{"o":{"f":{"removedProductIds":"[ID!]","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupResourceInput":{"i":{"productIds":"[ID!]","productVariantIds":"[ID!]"}}, +"SellingPlanGroupSortKeys":{"e":["CREATED_AT","ID","NAME","UPDATED_AT"]}, +"SellingPlanGroupUpdatePayload":{"o":{"f":{"deletedSellingPlanIds":"[ID!]","sellingPlanGroup":"SellingPlanGroup","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupUserError":{"o":{"f":{"code":"SellingPlanGroupUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SellingPlanGroupUserErrorCode":{"e":["BLANK","EQUAL_TO","GREATER_THAN","GREATER_THAN_OR_EQUAL_TO","INCLUSION","INVALID","LESS_THAN","LESS_THAN_OR_EQUAL_TO","NOT_A_NUMBER","NOT_FOUND","PRESENT","TAKEN","TOO_BIG","TOO_LONG","TOO_SHORT","WRONG_LENGTH","SELLING_PLAN_COUNT_UPPER_BOUND","SELLING_PLAN_COUNT_LOWER_BOUND","SELLING_PLAN_MAX_CYCLES_MUST_BE_GREATER_THAN_MIN_CYCLES","SELLING_PLAN_BILLING_AND_DELIVERY_POLICY_ANCHORS_MUST_BE_EQUAL","SELLING_PLAN_BILLING_CYCLE_MUST_BE_A_MULTIPLE_OF_DELIVERY_CYCLE","SELLING_PLAN_PRICING_POLICIES_MUST_CONTAIN_A_FIXED_PRICING_POLICY","SELLING_PLAN_MISSING_OPTION2_LABEL_ON_PARENT_GROUP","SELLING_PLAN_MISSING_OPTION3_LABEL_ON_PARENT_GROUP","SELLING_PLAN_OPTION2_REQUIRED_AS_DEFINED_ON_PARENT_GROUP","SELLING_PLAN_OPTION3_REQUIRED_AS_DEFINED_ON_PARENT_GROUP","SELLING_PLAN_PRICING_POLICIES_LIMIT","RESOURCE_LIST_CONTAINS_INVALID_IDS","RESOURCE_LIST_IS_EMPTY","PRODUCT_VARIANT_DOES_NOT_EXIST","PRODUCT_DOES_NOT_EXIST","GROUP_DOES_NOT_EXIST","GROUP_COULD_NOT_BE_DELETED","ERROR_ADDING_RESOURCE_TO_GROUP","SELLING_PLAN_DELIVERY_POLICY_MISSING","SELLING_PLAN_BILLING_POLICY_MISSING","PLAN_DOES_NOT_EXIST","PLAN_ID_MUST_BE_SPECIFIED_TO_UPDATE","ONLY_NEED_ONE_BILLING_POLICY_TYPE","ONLY_NEED_ONE_DELIVERY_POLICY_TYPE","ONLY_NEED_ONE_PRICING_POLICY_TYPE","BILLING_AND_DELIVERY_POLICY_TYPES_MUST_BE_THE_SAME","ONLY_NEED_ONE_PRICING_POLICY_VALUE","PRICING_POLICY_ADJUSTMENT_VALUE_AND_TYPE_MUST_MATCH","SELLING_PLAN_DUPLICATE_NAME","SELLING_PLAN_DUPLICATE_OPTIONS","SELLING_PLAN_FIXED_PRICING_POLICIES_LIMIT","REMAINING_BALANCE_CHARGE_EXACT_TIME_REQUIRED","CHECKOUT_CHARGE_VALUE_AND_TYPE_MUST_MATCH","ONLY_NEED_ONE_CHECKOUT_CHARGE_VALUE","REMAINING_BALANCE_CHARGE_EXACT_TIME_NOT_ALLOWED","REMAINING_BALANCE_CHARGE_TIME_AFTER_CHECKOUT_MUST_BE_GREATER_THAN_ZERO","REMAINING_BALANCE_CHARGE_TRIGGER_ON_FULL_CHECKOUT","REMAINING_BALANCE_CHARGE_TRIGGER_NO_REMAINING_BALANCE_ON_PARTIAL_PERCENTAGE_CHECKOUT_CHARGE","REMAINING_BALANCE_CHARGE_TRIGGER_NO_REMAINING_BALANCE_ON_PRICE_CHECKOUT_CHARGE","FULFILLMENT_EXACT_TIME_REQUIRED","FULFILLMENT_EXACT_TIME_NOT_ALLOWED","SELLING_PLAN_ANCHORS_NOT_ALLOWED","SELLING_PLAN_ANCHORS_REQUIRED","MUST_HAVE_EXACTLY_ONE_ANCHOR","ONLY_ONE_OF_FIXED_OR_RECURRING_BILLING","ONLY_ONE_OF_FIXED_OR_RECURRING_DELIVERY","BILLING_POLICY_INTERVAL_TOO_LARGE","DELIVERY_POLICY_INTERVAL_TOO_LARGE","INVALID_INPUT"]}, +"SellingPlanInput":{"i":{"billingPolicy":"SellingPlanBillingPolicyInput","category":"SellingPlanCategory","deliveryPolicy":"SellingPlanDeliveryPolicyInput","description":"String","id":"ID","inventoryPolicy":"SellingPlanInventoryPolicyInput","metafields":"[MetafieldInput!]","name":"String","options":"[String!]","position":"Int","pricingPolicies":"[SellingPlanPricingPolicyInput!]"}}, +"SellingPlanInterval":{"e":["DAY","WEEK","MONTH","YEAR"]}, +"SellingPlanInventoryPolicy":{"o":{"f":{"reserve":"SellingPlanReserve!"}}}, +"SellingPlanInventoryPolicyInput":{"i":{"reserve":"SellingPlanReserve"}}, +"SellingPlanPricingPolicy":{"u":["SellingPlanFixedPricingPolicy","SellingPlanRecurringPricingPolicy"]}, +"SellingPlanPricingPolicyAdjustmentType":{"e":["PERCENTAGE","FIXED_AMOUNT","PRICE"]}, +"SellingPlanPricingPolicyAdjustmentValue":{"u":["MoneyV2","SellingPlanPricingPolicyPercentageValue"]}, +"SellingPlanPricingPolicyBase":{"n":{"f":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyAdjustmentValue!"},"t":["SellingPlanFixedPricingPolicy","SellingPlanRecurringPricingPolicy"]}}, +"SellingPlanPricingPolicyInput":{"i":{"fixed":"SellingPlanFixedPricingPolicyInput","recurring":"SellingPlanRecurringPricingPolicyInput"}}, +"SellingPlanPricingPolicyPercentageValue":{"o":{"f":{"percentage":"Float!"}}}, +"SellingPlanPricingPolicyValueInput":{"i":{"fixedValue":"Decimal","percentage":"Float"}}, +"SellingPlanRecurringBillingPolicy":{"o":{"f":{"anchors":"[SellingPlanAnchor!]!","createdAt":"DateTime!","interval":"SellingPlanInterval!","intervalCount":"Int!","maxCycles":"Int","minCycles":"Int"}}}, +"SellingPlanRecurringBillingPolicyInput":{"i":{"anchors":"[SellingPlanAnchorInput!]","interval":"SellingPlanInterval","intervalCount":"Int","maxCycles":"Int","minCycles":"Int"}}, +"SellingPlanRecurringDeliveryPolicy":{"o":{"f":{"anchors":"[SellingPlanAnchor!]!","createdAt":"DateTime!","cutoff":"Int","intent":"SellingPlanRecurringDeliveryPolicyIntent!","interval":"SellingPlanInterval!","intervalCount":"Int!","preAnchorBehavior":"SellingPlanRecurringDeliveryPolicyPreAnchorBehavior!"}}}, +"SellingPlanRecurringDeliveryPolicyInput":{"i":{"anchors":"[SellingPlanAnchorInput!]","cutoff":"Int","intent":"SellingPlanRecurringDeliveryPolicyIntent","interval":"SellingPlanInterval","intervalCount":"Int","preAnchorBehavior":"SellingPlanRecurringDeliveryPolicyPreAnchorBehavior"}}, +"SellingPlanRecurringDeliveryPolicyIntent":{"e":["FULFILLMENT_BEGIN"]}, +"SellingPlanRecurringDeliveryPolicyPreAnchorBehavior":{"e":["ASAP","NEXT"]}, +"SellingPlanRecurringPricingPolicy":{"o":{"f":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyAdjustmentValue!","afterCycle":"Int","createdAt":"DateTime!"},"t":["SellingPlanPricingPolicyBase"]}}, +"SellingPlanRecurringPricingPolicyInput":{"i":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType","adjustmentValue":"SellingPlanPricingPolicyValueInput","afterCycle":"Int!","id":"ID"}}, +"SellingPlanRemainingBalanceChargeTrigger":{"e":["NO_REMAINING_BALANCE","EXACT_TIME","TIME_AFTER_CHECKOUT","ON_FULFILLMENT"]}, +"SellingPlanReserve":{"e":["ON_FULFILLMENT","ON_SALE"]}, +"ServerPixel":{"o":{"f":{"id":"ID!","status":"ServerPixelStatus","webhookEndpointAddress":"String"},"t":["Node"]}}, +"ServerPixelCreatePayload":{"o":{"f":{"serverPixel":"ServerPixel","userErrors":"[ErrorsServerPixelUserError!]!"}}}, +"ServerPixelDeletePayload":{"o":{"f":{"deletedServerPixelId":"ID","userErrors":"[ErrorsServerPixelUserError!]!"}}}, +"ServerPixelStatus":{"e":["CONNECTED","DISCONNECTED_UNCONFIGURED","DISCONNECTED_CONFIGURED"]}, +"ShipmentLineItemSortKeys":{"e":["ID"]}, +"ShippingCarrierPackageInput":{"i":{"carrierCode":"String!","carrierPackageCode":"String!","name":"String"}}, +"ShippingConfiguration":{"o":{"f":{"isEnabled":"Boolean!","optionDefinitions":["DeliveryOptionDefinitionConnection!",{"active":"Boolean","after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"optionDefinitionsCount":["Count!",{"active":"Boolean"}]}}}, +"ShippingConfigurationCreateInput":{"i":{"isEnabled":"Boolean!","optionDefinitions":"[DeliveryOptionDefinitionCreateInput!]"}}, +"ShippingConfigurationUpdateInput":{"i":{"isEnabled":"Boolean","optionDefinitionsToCreate":"[DeliveryOptionDefinitionCreateInput!]","optionDefinitionsToDelete":"[ID!]","optionDefinitionsToUpdate":"[DeliveryOptionDefinitionUpdateInput!]"}}, +"ShippingDiscountClass":{"e":["SHIPPING"]}, +"ShippingDocumentType":{"e":["LABEL","CUSTOMS_FORM"]}, +"ShippingEnumsFileFormat":{"e":["PDF","ZPL"]}, +"ShippingLabel":{"o":{"f":{"cancellable":"Boolean!","id":"ID!","location":"Location","printed":"Boolean!","shippingDocuments":"[ShippingObjectsShippingDocument!]!","trackingInfo":"FulfillmentTrackingInfo"},"t":["Node"]}}, +"ShippingLabelPurchaseCustomPackageInput":{"i":{"dimensions":"ObjectDimensionsInput!","type":"ShippingPackageType=","weight":"WeightInput!"}}, +"ShippingLabelPurchaseError":{"o":{"f":{"code":"ShippingLabelPurchaseErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ShippingLabelPurchaseErrorCode":{"e":["JOB_NOT_ENQUEUED","PURCHASE_IN_PROGRESS","PURCHASE_LABEL_VALIDATION_ERROR","KILL_SWITCH","CARRIER_NOT_AVAILABLE","DISABLED_SHIPPING_ACCOUNT","CONNECTION_ERROR","TRANSIENT_ERROR","PERMANENT_ERROR","UNKNOWN_ERROR"]}, +"ShippingLabelPurchaseInput":{"i":{"fulfillmentOrderId":"ID!","notifyCustomer":"Boolean=","originAddress":"MailingAddressInput","packageInfo":"PackageInfoInput","preferredRateSelection":"PreferredRateSelectionInput","shippingDatetime":"DateTime!","totalWeight":"WeightInput"}}, +"ShippingLabelPurchasePayload":{"o":{"f":{"shippingLabelPurchaseResult":"ShippingLabelPurchaseResult","userErrors":"[ShippingLabelPurchaseUserError!]!"}}}, +"ShippingLabelPurchaseResult":{"o":{"f":{"done":"Boolean!","errors":"[ShippingLabelPurchaseError!]!","id":"ID!","shippingLabels":"[ShippingLabel!]!","status":"ShippingLabelPurchaseResultStatus!"},"t":["JobResult","Node"]}}, +"ShippingLabelPurchaseResultStatus":{"e":["PENDING_PURCHASE","PURCHASE_FAILED","PURCHASED"]}, +"ShippingLabelPurchaseUserError":{"o":{"f":{"code":"ShippingLabelPurchaseUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ShippingLabelPurchaseUserErrorCode":{"e":["NOT_FOUND","TOTAL_WEIGHT_ZERO","SHIPPING_DATE_IN_THE_PAST","MISSING_SHIPPING_RATE","MISSING_SHIPPING_DATE","MISSING_INSURANCE_COVERAGE_AMOUNT","MISSING_INSURANCE_COVERAGE_CURRENCY","INVALID_PACKAGE_DIMENSIONS","MISSING_HS_CODE","MISSING_COUNTRY_OF_ORIGIN","AT_LEAST_1_ITEM_REQUIRED","PHONE_NUMBER_NOT_FULLY_QUALIFIED_ORIGIN","PHONE_NUMBER_NOT_FULLY_QUALIFIED_DESTINATION","ADAPTIVE_SHIPPING_STATE_INVALID","FULFILLMENT_ORDER_INVALID","KILL_SWITCH","PURCHASE_FAILED","RATES_NOT_FOUND","TERMS_OF_SERVICE_NOT_ACCEPTED","CARRIER_NOT_SUPPORTED","ACCESS_DENIED","PACKAGE_CARRIER_MISMATCH","PICKUP_POINT_NOT_SUPPORTED"]}, +"ShippingLine":{"o":{"f":{"carrierIdentifier":"String","code":"String","createdAt":"DateTime!","currentDiscountedPriceSet":"MoneyBag!","custom":"Boolean!","deliveryCategory":"String","discountAllocations":"[DiscountAllocation!]!","discountedPrice":"MoneyV2!","discountedPriceSet":"MoneyBag!","id":"ID","isRemoved":"Boolean!","originalPrice":"MoneyV2!","originalPriceSet":"MoneyBag!","phone":"String","price":"Money!","requestedFulfillmentService":"FulfillmentService","shippingRateHandle":"String","source":"String","taxLines":"[TaxLine!]!","title":"String!"},"d":{"discountedPrice":"Use `discountedPriceSet` instead.","originalPrice":"Use `originalPriceSet` instead.","price":"Use `originalPriceSet` instead.","requestedFulfillmentService":"requestedFulfillmentService is no longer in use. Order routing does not use the requestedFulfillmentService during order and fulfillment order creation."}}}, +"ShippingLineConnection":{"o":{"f":{"edges":"[ShippingLineEdge!]!","nodes":"[ShippingLine!]!","pageInfo":"PageInfo!"}}}, +"ShippingLineEdge":{"o":{"f":{"cursor":"String!","node":"ShippingLine!"}}}, +"ShippingLineInput":{"i":{"f":{"price":"Money","priceWithCurrency":"MoneyInput","shippingRateHandle":"String","title":"String"},"d":{"price":"`priceWithCurrency` should be used instead, where currencies can be specified."}}}, +"ShippingLineSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","shippingLine":"ShippingLine","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"ShippingObjectsShippingDocument":{"o":{"f":{"documentType":"ShippingDocumentType!","format":"ShippingEnumsFileFormat","printedAt":"DateTime","shippingLabelId":"ID!","url":"URL"}}}, +"ShippingPackageDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[UserError!]!"}}}, +"ShippingPackageMakeDefaultPayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"ShippingPackageType":{"e":["BOX","FLAT_RATE","ENVELOPE","SOFT_PACK"]}, +"ShippingPackageUpdatePayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"ShippingRate":{"o":{"f":{"handle":"String!","price":"MoneyV2!","title":"String!"}}}, +"ShippingRefund":{"o":{"f":{"amount":"Money!","amountSet":"MoneyBag!","maximumRefundable":"Money!","maximumRefundableSet":"MoneyBag!","tax":"Money!","taxSet":"MoneyBag!"},"d":{"amount":"Use `amountSet` instead.","maximumRefundable":"Use `maximumRefundableSet` instead.","tax":"Use `taxSet` instead."}}}, +"ShippingRefundInput":{"i":{"amount":"Money","fullRefund":"Boolean"}}, +"Shop":{"o":{"f":{"accountOwner":"StaffMember!","alerts":"[ShopAlert!]!","allProductCategories":"[ProductCategory!]!","allProductCategoriesList":"[TaxonomyCategory!]!","analyticsAnnotations":["AnalyticsAnnotationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"AnalyticsAnnotationSortKeys="}],"analyticsToken":"String!","assignedFulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","assignmentStatus":"FulfillmentOrderAssignmentStatus","before":"String","first":"Int","last":"Int","locationIds":"[ID!]","reverse":"Boolean=","sortKey":"FulfillmentOrderSortKeys="}],"availableChannelApps":["AppConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"billingAddress":"ShopAddress!","channelDefinitionsForInstalledChannels":"[AvailableChannelDefinitionsByChannel!]!","channels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"checkoutApiSupported":"Boolean!","collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"CollectionSortKeys="}],"contactEmail":"String!","countriesInShippingZones":"CountriesInShippingZones!","createdAt":"DateTime!","currencyCode":"CurrencyCode!","currencyFormats":"CurrencyFormats!","currencySettings":["CurrencySettingConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"customerAccounts":"ShopCustomerAccountsSetting!","customerAccountsV2":"CustomerAccountsV2!","customerTags":["StringConnection!",{"first":"Int!"}],"customers":["CustomerConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CustomerSortKeys="}],"description":"String","domains":"[Domain!]!","draftOrderTags":["StringConnection!",{"first":"Int!"}],"email":"String!","enabledPresentmentCurrencies":"[CurrencyCode!]!","entitlements":"EntitlementsType!","features":"ShopFeatures!","fulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","includeClosed":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","sortKey":"FulfillmentOrderSortKeys="}],"fulfillmentServices":"[FulfillmentService!]!","ianaTimezone":"String!","id":"ID!","inventoryItems":["InventoryItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"limitedPendingOrderCount":"LimitedPendingOrderCount!","locations":["LocationConnection!",{"after":"String","before":"String","first":"Int","includeInactive":"Boolean=","includeLegacy":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","sortKey":"LocationSortKeys="}],"marketingSmsConsentEnabledAtCheckout":"Boolean!","merchantApprovalSignals":"MerchantApprovalSignals","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"myshopifyDomain":"String!","name":"String!","navigationSettings":"[NavigationItem!]!","orderNumberFormatPrefix":"String!","orderNumberFormatSuffix":"String!","orderTags":["StringConnection!",{"first":"Int!","sort":"ShopTagSort="}],"orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"paymentSettings":"PaymentSettings!","plan":"ShopPlan!","primaryDomain":"Domain!","productImages":["ImageConnection!",{"after":"String","before":"String","crop":"CropRegion","first":"Int","last":"Int","maxHeight":"Int","maxWidth":"Int","reverse":"Boolean=","scale":"Int=","sortKey":"ProductImageSortKeys="}],"productTags":["StringConnection!",{"first":"Int!"}],"productTypes":["StringConnection!",{"first":"Int!"}],"productVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ProductVariantSortKeys="}],"productVendors":["StringConnection!",{"first":"Int!"}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"ProductSortKeys="}],"publicationCount":"Int!","resourceLimits":"ShopResourceLimits!","richTextEditorUrl":"URL!","search":["SearchResultConnection!",{"after":"String","first":"Int!","query":"String!","types":"[SearchResultType!]"}],"searchFilters":"SearchFilterOptions!","setupRequired":"Boolean!","shipsToCountries":"[CountryCode!]!","shopAddress":"ShopAddress!","shopOwnerName":"String!","shopPolicies":"[ShopPolicy!]!","staffMembers":["StaffMemberConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"storefrontAccessTokens":["StorefrontAccessTokenConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"storefrontUrl":"URL!","taxShipping":"Boolean!","taxesIncluded":"Boolean!","timezoneAbbreviation":"String!","timezoneOffset":"String!","timezoneOffsetMinutes":"Int!","transactionalSmsDisabled":"Boolean!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"unitSystem":"UnitSystem!","updatedAt":"DateTime!","url":"URL!","weightUnit":"WeightUnit!"},"t":["HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Node"],"d":{"allProductCategories":"Use `allProductCategoriesList` instead.","analyticsToken":"Not supported anymore.","assignedFulfillmentOrders":"Use `QueryRoot.assignedFulfillmentOrders` instead. Details: https://shopify.dev/changelog/moving-the-shop-assignedfulfillmentorders-connection-to-queryroot","billingAddress":"Use `shopAddress` instead.","channelDefinitionsForInstalledChannels":"Use [`QueryRoot.orderAttributionDefinitions`](https://shopify.dev/docs/api/admin-graphql/latest/queries/orderAttributionDefinitions) and select `id`, `handle`, `displayName`, and `icon` instead.","channels":"Use `QueryRoot.channels` instead.","collections":"Use `QueryRoot.collections` instead.","customers":"Use `QueryRoot.customers` instead.","domains":"Use `domainsPaginated` instead.","fulfillmentOrders":"Use `QueryRoot.fulfillmentOrders` instead.","inventoryItems":"Use `QueryRoot.inventoryItems` instead.","limitedPendingOrderCount":"Use `QueryRoot.pendingOrdersCount` instead.","locations":"Use `QueryRoot.locations` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","orders":"Use `QueryRoot.orders` instead.","productImages":"Use `files` instead. See [filesQuery](https://shopify.dev/docs/api/admin-graphql/latest/queries/files) and its [query](https://shopify.dev/docs/api/admin-graphql/latest/queries/files#argument-query) argument for more information.","productImages(crop)":"Use `Image.url(transform: { crop:})` instead.","productImages(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","productImages(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","productImages(scale)":"Use `Image.url(transform: { scale:})` instead.","productTags":"Use `QueryRoot.productTags` instead.","productTypes":"Use `QueryRoot.productTypes` instead.","productVariants":"Use `QueryRoot.productVariants` instead.","productVendors":"Use `QueryRoot.productVendors` instead.","products":"Use `QueryRoot.products`.","publicationCount":"Use `QueryRoot.publicationsCount` instead.","staffMembers":"Use `QueryRoot.staffMembers` instead.","storefrontUrl":"Use `url` instead."}}}, +"ShopAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","company":"String","coordinatesValidated":"Boolean!","country":"String","countryCode":"String","countryCodeV2":"CountryCode","firstName":"String","formatted":["[String!]!",{"withCompany":"Boolean="}],"formattedArea":"String","id":"ID!","lastName":"String","latitude":"Float","longitude":"Float","name":"String","phone":"String","province":"String","provinceCode":"String","zip":"String"},"t":["Node"],"d":{"countryCode":"Use `countryCodeV2` instead.","firstName":"Always null in this context.","lastName":"Always null in this context.","name":"Always null in this context."}}}, +"ShopAlert":{"o":{"f":{"action":"ShopAlertAction!","description":"String!"}}}, +"ShopAlertAction":{"o":{"f":{"title":"String!","url":"URL!"}}}, +"ShopBillingPreferences":{"o":{"f":{"currency":"CurrencyCode!"}}}, +"ShopBranding":{"e":["SHOPIFY_GOLD","SHOPIFY_PLUS","ROGERS","SHOPIFY"]}, +"ShopCustomerAccountsSetting":{"e":["REQUIRED","OPTIONAL","DISABLED"]}, +"ShopFeatures":{"o":{"f":{"avalaraAvatax":"Boolean!","branding":"ShopBranding!","bundles":"BundlesFeature!","buyerExperienceDepositEnabled":"Boolean!","captcha":"Boolean!","captchaExternalDomains":"Boolean!","cartTransform":"CartTransformFeature!","deliveryProfiles":"Boolean!","directConnectionCatalogAssignmentEnabled":"Boolean!","dynamicRemarketing":"Boolean!","eligibleForSubscriptionMigration":"Boolean!","eligibleForSubscriptions":"Boolean!","giftCards":"Boolean!","harmonizedSystemCode":"Boolean!","internationalDomains":"Boolean!","internationalPriceOverrides":"Boolean!","internationalPriceRules":"Boolean!","legacySubscriptionGatewayEnabled":"Boolean!","liveView":"Boolean!","marketDrivenShipping":"Boolean!","onboardingVisual":"Boolean!","paypalExpressSubscriptionGatewayStatus":"PaypalExpressSubscriptionsGatewayStatus!","reports":"Boolean!","sellsSubscriptions":"Boolean!","shopifyPlus":"Boolean!","showMetrics":"Boolean!","storefront":"Boolean!","subCountryMarketsEnabled":"Boolean!","unifiedMarkets":"Boolean!","usingShopifyBalance":"Boolean!"},"d":{"captchaExternalDomains":"No longer required for external domains","deliveryProfiles":"Delivery profiles are now 100% enabled across Shopify.","internationalDomains":"All shops have international domains through Shopify Markets.","internationalPriceOverrides":"Use the `markets` field on `EntitlementsType`.\nEach market entitlement has a `catalogs` field that indicates\nwhether the shop's markets have access to catalogs and price overrides.","internationalPriceRules":"Use the `markets` field on `EntitlementsType`.\nEach market entitlement has a `catalogs` field that indicates\nwhether the shop's markets have access to catalogs and price overrides.","onboardingVisual":"No longer supported.","shopifyPlus":"Use Shop.plan.shopifyPlus instead.","unifiedMarkets":"Unified Markets is enabled for all shops. Remove checks against this field."}}}, +"ShopLocale":{"o":{"f":{"locale":"String!","marketWebPresences":"[MarketWebPresence!]!","name":"String!","primary":"Boolean!","published":"Boolean!"}}}, +"ShopLocaleDisablePayload":{"o":{"f":{"locale":"String","userErrors":"[UserError!]!"}}}, +"ShopLocaleEnablePayload":{"o":{"f":{"shopLocale":"ShopLocale","userErrors":"[UserError!]!"}}}, +"ShopLocaleInput":{"i":{"marketWebPresenceIds":"[ID!]","published":"Boolean"}}, +"ShopLocaleUpdatePayload":{"o":{"f":{"shopLocale":"ShopLocale","userErrors":"[UserError!]!"}}}, +"ShopPayInstallmentsPaymentDetails":{"o":{"f":{"paymentMethodName":"String"},"t":["BasePaymentDetails"]}}, +"ShopPayPaymentRequest":{"o":{"f":{"discounts":"[ShopPayPaymentRequestDiscount!]","lineItems":"[ShopPayPaymentRequestLineItem!]!","presentmentCurrency":"CurrencyCode!","selectedDeliveryMethodType":"ShopPayPaymentRequestDeliveryMethodType!","shippingAddress":"ShopPayPaymentRequestContactField","shippingLines":"[ShopPayPaymentRequestShippingLine!]!","subtotal":"MoneyV2!","total":"MoneyV2!","totalShippingPrice":"ShopPayPaymentRequestTotalShippingPrice","totalTax":"MoneyV2"}}}, +"ShopPayPaymentRequestContactField":{"o":{"f":{"address1":"String!","address2":"String","city":"String!","companyName":"String","countryCode":"String!","email":"String","firstName":"String!","lastName":"String!","phone":"String","postalCode":"String","provinceCode":"String"}}}, +"ShopPayPaymentRequestDeliveryMethodType":{"e":["SHIPPING","PICKUP"]}, +"ShopPayPaymentRequestDiscount":{"o":{"f":{"amount":"MoneyV2!","label":"String!"}}}, +"ShopPayPaymentRequestImage":{"o":{"f":{"alt":"String","url":"String!"}}}, +"ShopPayPaymentRequestLineItem":{"o":{"f":{"finalItemPrice":"MoneyV2!","finalLinePrice":"MoneyV2!","image":"ShopPayPaymentRequestImage","itemDiscounts":"[ShopPayPaymentRequestDiscount!]","label":"String!","lineDiscounts":"[ShopPayPaymentRequestDiscount!]","originalItemPrice":"MoneyV2","originalLinePrice":"MoneyV2","quantity":"Int!","requiresShipping":"Boolean","sku":"String"}}}, +"ShopPayPaymentRequestReceipt":{"o":{"f":{"createdAt":"DateTime!","order":"Order","paymentRequest":"ShopPayPaymentRequest!","processingStatus":"ShopPayPaymentRequestReceiptProcessingStatus!","sourceIdentifier":"String!","token":"String!"}}}, +"ShopPayPaymentRequestReceiptConnection":{"o":{"f":{"edges":"[ShopPayPaymentRequestReceiptEdge!]!","nodes":"[ShopPayPaymentRequestReceipt!]!","pageInfo":"PageInfo!"}}}, +"ShopPayPaymentRequestReceiptEdge":{"o":{"f":{"cursor":"String!","node":"ShopPayPaymentRequestReceipt!"}}}, +"ShopPayPaymentRequestReceiptProcessingStatus":{"o":{"f":{"errorCode":"ShopPayPaymentRequestReceiptProcessingStatusErrorCode","message":"String","state":"ShopPayPaymentRequestReceiptProcessingStatusState!"}}}, +"ShopPayPaymentRequestReceiptProcessingStatusErrorCode":{"e":["INCORRECT_NUMBER","INVALID_NUMBER","INVALID_EXPIRY_DATE","INVALID_CVC","EXPIRED_CARD","INCORRECT_CVC","INCORRECT_ZIP","INCORRECT_ADDRESS","INCORRECT_PIN","AMOUNT_TOO_SMALL","CARD_DECLINED","PROCESSING_ERROR","CALL_ISSUER","THREE_D_SECURE_FAILED","FRAUD_SUSPECTED","PICK_UP_CARD","CONFIG_ERROR","TEST_MODE_LIVE_CARD","UNSUPPORTED_FEATURE","CVV_ATTEMPTS_EXCEEDED","GENERIC_ERROR","INVALID_COUNTRY","INVALID_AMOUNT","PAYMENT_METHOD_UNAVAILABLE"]}, +"ShopPayPaymentRequestReceiptProcessingStatusState":{"e":["READY","PROCESSING","FAILED","COMPLETED","ACTION_REQUIRED"]}, +"ShopPayPaymentRequestReceiptsSortKeys":{"e":["CREATED_AT","ID"]}, +"ShopPayPaymentRequestShippingLine":{"o":{"f":{"amount":"MoneyV2!","code":"String!","label":"String!"}}}, +"ShopPayPaymentRequestTotalShippingPrice":{"o":{"f":{"discounts":"[ShopPayPaymentRequestDiscount!]!","finalTotal":"MoneyV2!","originalTotal":"MoneyV2"}}}, +"ShopPlan":{"o":{"f":{"displayName":"String!","partnerDevelopment":"Boolean!","publicDisplayName":"String!","shopifyPlus":"Boolean!"},"d":{"displayName":"Use `publicDisplayName` instead."}}}, +"ShopPolicy":{"o":{"f":{"body":"HTML!","createdAt":"DateTime!","id":"ID!","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"type":"ShopPolicyType!","updatedAt":"DateTime!","url":"URL!"},"t":["HasPublishedTranslations","Node"]}}, +"ShopPolicyErrorCode":{"e":["TOO_BIG"]}, +"ShopPolicyInput":{"i":{"body":"String!","type":"ShopPolicyType!"}}, +"ShopPolicyType":{"e":["REFUND_POLICY","SHIPPING_POLICY","PRIVACY_POLICY","TERMS_OF_SERVICE","TERMS_OF_SALE","LEGAL_NOTICE","SUBSCRIPTION_POLICY","CONTACT_INFORMATION"]}, +"ShopPolicyUpdatePayload":{"o":{"f":{"shopPolicy":"ShopPolicy","userErrors":"[ShopPolicyUserError!]!"}}}, +"ShopPolicyUserError":{"o":{"f":{"code":"ShopPolicyErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ShopResourceFeedbackCreatePayload":{"o":{"f":{"feedback":"AppFeedback","userErrors":"[ShopResourceFeedbackCreateUserError!]!"}}}, +"ShopResourceFeedbackCreateUserError":{"o":{"f":{"code":"ShopResourceFeedbackCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ShopResourceFeedbackCreateUserErrorCode":{"e":["OUTDATED_FEEDBACK","FEEDBACK_DATE_IN_FUTURE","INVALID","BLANK","PRESENT","NOT_FOUND"]}, +"ShopResourceLimits":{"o":{"f":{"locationLimit":"Int!","maxProductOptions":"Int!","maxProductVariants":"Int!","redirectLimitReached":"Boolean!"}}}, +"ShopTagSort":{"e":["ALPHABETICAL","POPULAR"]}, +"ShopifyFunction":{"o":{"f":{"apiType":"String!","apiVersion":"String!","app":"App!","appBridge":"FunctionsAppBridge!","appKey":"String!","description":"String","handle":"String!","id":"String!","inputQuery":"String","title":"String!","useCreationUi":"Boolean!"}}}, +"ShopifyFunctionConnection":{"o":{"f":{"edges":"[ShopifyFunctionEdge!]!","nodes":"[ShopifyFunction!]!","pageInfo":"PageInfo!"}}}, +"ShopifyFunctionEdge":{"o":{"f":{"cursor":"String!","node":"ShopifyFunction!"}}}, +"ShopifyPaymentsAccount":{"o":{"f":{"accountOpenerName":"String","activated":"Boolean!","balance":"[MoneyV2!]!","balanceTransactions":["ShopifyPaymentsBalanceTransactionConnection!",{"after":"String","before":"String","first":"Int","hideTransfers":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"BalanceTransactionSortKeys="}],"bankAccounts":["ShopifyPaymentsBankAccountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"chargeStatementDescriptor":"String","chargeStatementDescriptors":"ShopifyPaymentsChargeStatementDescriptor","country":"String!","defaultCurrency":"CurrencyCode!","disputes":["ShopifyPaymentsDisputeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"id":"ID!","onboardable":"Boolean!","payoutSchedule":"ShopifyPaymentsPayoutSchedule!","payoutStatementDescriptor":"String","payouts":["ShopifyPaymentsPayoutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"PayoutSortKeys=","transactionType":"ShopifyPaymentsPayoutTransactionType"}]},"t":["Node"],"d":{"chargeStatementDescriptor":"Use `chargeStatementDescriptors` instead."}}}, +"ShopifyPaymentsAddressBasic":{"o":{"f":{"addressLine1":"String","addressLine2":"String","city":"String","country":"String","postalCode":"String","zone":"String"}}}, +"ShopifyPaymentsAdjustmentOrder":{"o":{"f":{"amount":"MoneyV2!","fees":"MoneyV2!","link":"URL!","name":"String!","net":"MoneyV2!","orderTransactionId":"BigInt!"}}}, +"ShopifyPaymentsAssociatedOrder":{"o":{"f":{"id":"ID!","name":"String!"}}}, +"ShopifyPaymentsBalanceTransaction":{"o":{"f":{"adjustmentReason":"String","adjustmentsOrders":"[ShopifyPaymentsAdjustmentOrder!]!","amount":"MoneyV2!","associatedOrder":"ShopifyPaymentsAssociatedOrder","associatedPayout":"ShopifyPaymentsBalanceTransactionAssociatedPayout!","fee":"MoneyV2!","id":"ID!","net":"MoneyV2!","sourceId":"BigInt","sourceOrderTransactionId":"BigInt","sourceType":"ShopifyPaymentsSourceType","test":"Boolean!","transactionDate":"DateTime!","type":"ShopifyPaymentsTransactionType!"},"t":["Node"]}}, +"ShopifyPaymentsBalanceTransactionAssociatedPayout":{"o":{"f":{"id":"ID","status":"ShopifyPaymentsBalanceTransactionPayoutStatus"}}}, +"ShopifyPaymentsBalanceTransactionConnection":{"o":{"f":{"edges":"[ShopifyPaymentsBalanceTransactionEdge!]!","nodes":"[ShopifyPaymentsBalanceTransaction!]!","pageInfo":"PageInfo!"}}}, +"ShopifyPaymentsBalanceTransactionEdge":{"o":{"f":{"cursor":"String!","node":"ShopifyPaymentsBalanceTransaction!"}}}, +"ShopifyPaymentsBalanceTransactionPayoutStatus":{"e":{"v":["SCHEDULED","IN_TRANSIT","PAID","FAILED","CANCELED","PENDING","ACTION_REQUIRED"],"d":{"IN_TRANSIT":"Use `SCHEDULED` instead."}}}, +"ShopifyPaymentsBankAccount":{"o":{"f":{"accountNumberLastDigits":"String!","bankName":"String","country":"CountryCode!","createdAt":"DateTime!","currency":"CurrencyCode!","id":"ID!","payouts":["ShopifyPaymentsPayoutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"PayoutSortKeys=","transactionType":"ShopifyPaymentsPayoutTransactionType"}],"status":"ShopifyPaymentsBankAccountStatus!"},"t":["Node"]}}, +"ShopifyPaymentsBankAccountConnection":{"o":{"f":{"edges":"[ShopifyPaymentsBankAccountEdge!]!","nodes":"[ShopifyPaymentsBankAccount!]!","pageInfo":"PageInfo!"}}}, +"ShopifyPaymentsBankAccountEdge":{"o":{"f":{"cursor":"String!","node":"ShopifyPaymentsBankAccount!"}}}, +"ShopifyPaymentsBankAccountStatus":{"e":["NEW","VALIDATED","VERIFIED","ERRORED"]}, +"ShopifyPaymentsBusinessType":{"e":["CORPORATION","GOVERNMENT","INCORPORATED_PARTNERSHIP","INDIVIDUAL","LLC","NON_PROFIT","NON_PROFIT_INCORPORATED","NON_PROFIT_UNINCORPORATED","NON_PROFIT_UNINCORPORATED_ASSOCIATION","NON_PROFIT_REGISTERED_CHARITY","PARTNERSHIP","PRIVATE_CORPORATION","PUBLIC_COMPANY","PUBLIC_CORPORATION","SOLE_PROP","UNINCORPORATED_PARTNERSHIP","PRIVATE_MULTI_MEMBER_LLC","PRIVATE_SINGLE_MEMBER_LLC","PRIVATE_UNINCORPORATED_ASSOCIATION","PRIVATE_PARTNERSHIP","PUBLIC_PARTNERSHIP","FREE_ZONE_ESTABLISHMENT","FREE_ZONE_LLC","SOLE_ESTABLISHMENT","NOT_SET"]}, +"ShopifyPaymentsChargeStatementDescriptor":{"n":{"f":{"default":"String","prefix":"String!"},"t":["ShopifyPaymentsDefaultChargeStatementDescriptor","ShopifyPaymentsJpChargeStatementDescriptor"]}}, +"ShopifyPaymentsDefaultChargeStatementDescriptor":{"o":{"f":{"default":"String","prefix":"String!"},"t":["ShopifyPaymentsChargeStatementDescriptor"]}}, +"ShopifyPaymentsDispute":{"o":{"f":{"amount":"MoneyV2!","disputeEvidence":"ShopifyPaymentsDisputeEvidence!","evidenceDueBy":"DateTime","evidenceSentOn":"DateTime","finalizedOn":"DateTime","id":"ID!","initiatedAt":"DateTime!","legacyResourceId":"UnsignedInt64!","order":"Order","reasonDetails":"ShopifyPaymentsDisputeReasonDetails!","status":"DisputeStatus!","type":"DisputeType!"},"t":["LegacyInteroperability","Node"]}}, +"ShopifyPaymentsDisputeConnection":{"o":{"f":{"edges":"[ShopifyPaymentsDisputeEdge!]!","nodes":"[ShopifyPaymentsDispute!]!","pageInfo":"PageInfo!"}}}, +"ShopifyPaymentsDisputeEdge":{"o":{"f":{"cursor":"String!","node":"ShopifyPaymentsDispute!"}}}, +"ShopifyPaymentsDisputeEvidence":{"o":{"f":{"accessActivityLog":"String","billingAddress":"MailingAddress","cancellationPolicyDisclosure":"String","cancellationPolicyFile":"ShopifyPaymentsDisputeFileUpload","cancellationRebuttal":"String","customerCommunicationFile":"ShopifyPaymentsDisputeFileUpload","customerEmailAddress":"String","customerFirstName":"String","customerLastName":"String","customerPurchaseIp":"String","dispute":"ShopifyPaymentsDispute!","disputeFileUploads":"[ShopifyPaymentsDisputeFileUpload!]!","fulfillments":"[ShopifyPaymentsDisputeFulfillment!]!","id":"ID!","productDescription":"String","refundPolicyDisclosure":"String","refundPolicyFile":"ShopifyPaymentsDisputeFileUpload","refundRefusalExplanation":"String","serviceDocumentationFile":"ShopifyPaymentsDisputeFileUpload","shippingAddress":"MailingAddress","shippingDocumentationFile":"ShopifyPaymentsDisputeFileUpload","submitted":"Boolean!","uncategorizedFile":"ShopifyPaymentsDisputeFileUpload","uncategorizedText":"String"},"t":["Node"]}}, +"ShopifyPaymentsDisputeEvidenceFileType":{"e":["CUSTOMER_COMMUNICATION_FILE","REFUND_POLICY_FILE","CANCELLATION_POLICY_FILE","UNCATEGORIZED_FILE","SHIPPING_DOCUMENTATION_FILE","SERVICE_DOCUMENTATION_FILE","RESPONSE_SUMMARY_FILE"]}, +"ShopifyPaymentsDisputeEvidenceUpdateInput":{"i":{"f":{"accessActivityLog":"String","cancellationPolicyDisclosure":"String","cancellationPolicyFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","cancellationRebuttal":"String","customerCommunicationFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","customerEmailAddress":"String","customerFirstName":"String","customerLastName":"String","refundPolicyDisclosure":"String","refundPolicyFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","refundRefusalExplanation":"String","serviceDocumentationFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","shippingAddress":"MailingAddressInput","shippingDocumentationFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","submitEvidence":"Boolean=","uncategorizedFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","uncategorizedText":"String"},"d":{"submitEvidence":"Dispute evidence can't be submitted through the API. Submissions go directly to the bank and are final, so merchants must confirm them in the Shopify admin."}}}, +"ShopifyPaymentsDisputeFileUpload":{"o":{"f":{"disputeEvidenceType":"ShopifyPaymentsDisputeEvidenceFileType","fileSize":"Int!","fileType":"String!","id":"ID!","originalFileName":"String","url":"URL!"},"t":["Node"]}}, +"ShopifyPaymentsDisputeFileUploadUpdateInput":{"i":{"destroy":"Boolean=","id":"ID!"}}, +"ShopifyPaymentsDisputeFulfillment":{"o":{"f":{"id":"ID!","shippingCarrier":"String","shippingDate":"Date","shippingTrackingNumber":"String"},"t":["Node"]}}, +"ShopifyPaymentsDisputeReason":{"e":["FRAUDULENT","GENERAL","UNRECOGNIZED","DUPLICATE","SUBSCRIPTION_CANCELLED","PRODUCT_UNACCEPTABLE","PRODUCT_NOT_RECEIVED","CREDIT_NOT_PROCESSED","INCORRECT_ACCOUNT_DETAILS","INSUFFICIENT_FUNDS","BANK_CANNOT_PROCESS","DEBIT_NOT_AUTHORIZED","CUSTOMER_INITIATED","NONCOMPLIANT"]}, +"ShopifyPaymentsDisputeReasonDetails":{"o":{"f":{"networkReasonCode":"String","reason":"ShopifyPaymentsDisputeReason!"}}}, +"ShopifyPaymentsExtendedAuthorization":{"o":{"f":{"extendedAuthorizationExpiresAt":"DateTime!","standardAuthorizationExpiresAt":"DateTime!"}}}, +"ShopifyPaymentsJpChargeStatementDescriptor":{"o":{"f":{"default":"String","kana":"String","kanji":"String","prefix":"String!"},"t":["ShopifyPaymentsChargeStatementDescriptor"],"d":{"kana":"This field is deprecated and will be removed in a future release.","kanji":"This field is deprecated and will be removed in a future release."}}}, +"ShopifyPaymentsMerchantCategoryCode":{"o":{"f":{"category":"String!","categoryLabel":"String!","code":"Int!","id":"Int!","subcategoryLabel":"String!"}}}, +"ShopifyPaymentsPayout":{"o":{"f":{"bankAccount":"ShopifyPaymentsBankAccount","businessEntity":"BusinessEntity!","externalTraceId":"String","gross":"MoneyV2!","id":"ID!","issuedAt":"DateTime!","legacyResourceId":"UnsignedInt64!","net":"MoneyV2!","status":"ShopifyPaymentsPayoutStatus!","summary":"ShopifyPaymentsPayoutSummary!","transactionType":"ShopifyPaymentsPayoutTransactionType!"},"t":["LegacyInteroperability","Node"],"d":{"bankAccount":"Use `destinationAccount` instead.","gross":"Use `net` instead."}}}, +"ShopifyPaymentsPayoutAlternateCurrencyCreatePayload":{"o":{"f":{"payout":"ShopifyPaymentsToolingProviderPayout","success":"Boolean","userErrors":"[ShopifyPaymentsPayoutAlternateCurrencyCreateUserError!]!"}}}, +"ShopifyPaymentsPayoutAlternateCurrencyCreateUserError":{"o":{"f":{"code":"ShopifyPaymentsPayoutAlternateCurrencyCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ShopifyPaymentsPayoutAlternateCurrencyCreateUserErrorCode":{"e":["MISSING_PROVIDER_ACCOUNT","ALTERNATE_CURRENCY_PAYOUT_FAILED_STRIPE_ERROR","UNKNOWN_CORE_ERROR","ALTERNATE_CURRENCY_PAYOUT_FAILED_NO_ELIGIBLE_BALANCE"]}, +"ShopifyPaymentsPayoutConnection":{"o":{"f":{"edges":"[ShopifyPaymentsPayoutEdge!]!","nodes":"[ShopifyPaymentsPayout!]!","pageInfo":"PageInfo!"}}}, +"ShopifyPaymentsPayoutEdge":{"o":{"f":{"cursor":"String!","node":"ShopifyPaymentsPayout!"}}}, +"ShopifyPaymentsPayoutInterval":{"e":["DAILY","WEEKLY","MONTHLY","MANUAL"]}, +"ShopifyPaymentsPayoutSchedule":{"o":{"f":{"interval":"ShopifyPaymentsPayoutInterval!","monthlyAnchor":"Int","weeklyAnchor":"DayOfTheWeek"}}}, +"ShopifyPaymentsPayoutStatus":{"e":{"v":["SCHEDULED","IN_TRANSIT","PAID","FAILED","CANCELED"],"d":{"IN_TRANSIT":"Use `SCHEDULED` instead."}}}, +"ShopifyPaymentsPayoutSummary":{"o":{"f":{"adjustmentsFee":"MoneyV2!","adjustmentsGross":"MoneyV2!","advanceFees":"MoneyV2!","advanceGross":"MoneyV2!","chargesFee":"MoneyV2!","chargesGross":"MoneyV2!","refundsFee":"MoneyV2!","refundsFeeGross":"MoneyV2!","reservedFundsFee":"MoneyV2!","reservedFundsGross":"MoneyV2!","retriedPayoutsFee":"MoneyV2!","retriedPayoutsGross":"MoneyV2!","usdcRebateCreditAmount":"MoneyV2!"}}}, +"ShopifyPaymentsPayoutTransactionType":{"e":["DEPOSIT","WITHDRAWAL"]}, +"ShopifyPaymentsRefundSet":{"o":{"f":{"acquirerReferenceNumber":"String"}}}, +"ShopifyPaymentsSourceType":{"e":["ADJUSTMENT_REVERSAL","CHARGE","REFUND","SYSTEM_ADJUSTMENT","DISPUTE","ADJUSTMENT","TRANSFER"]}, +"ShopifyPaymentsTaxIdentification":{"o":{"f":{"taxIdentificationType":"ShopifyPaymentsTaxIdentificationType!","value":"String!"}}}, +"ShopifyPaymentsTaxIdentificationType":{"e":["SSN_LAST4_DIGITS","FULL_SSN","EIN"]}, +"ShopifyPaymentsToolingProviderPayout":{"o":{"f":{"amount":"MoneyV2!","arrivalDate":"DateTime","createdAt":"DateTime","currency":"String!","remoteId":"String!"}}}, +"ShopifyPaymentsTransactionSet":{"o":{"f":{"extendedAuthorizationSet":"ShopifyPaymentsExtendedAuthorization","refundSet":"ShopifyPaymentsRefundSet"}}}, +"ShopifyPaymentsTransactionType":{"e":["ACH_BANK_FAILURE_DEBIT_FEE","ACH_BANK_FAILURE_DEBIT_REVERSAL_FEE","ADS_PUBLISHER_CREDIT","ADS_PUBLISHER_CREDIT_REVERSAL","CHARGEBACK_PROTECTION_CREDIT","CHARGEBACK_PROTECTION_CREDIT_REVERSAL","CHARGEBACK_PROTECTION_DEBIT","CHARGEBACK_PROTECTION_DEBIT_REVERSAL","COLLECTIONS_CREDIT","COLLECTIONS_CREDIT_REVERSAL","PROMOTION_CREDIT","PROMOTION_CREDIT_REVERSAL","ANOMALY_CREDIT","ANOMALY_CREDIT_REVERSAL","ANOMALY_DEBIT","ANOMALY_DEBIT_REVERSAL","VAT_REFUND_CREDIT","VAT_REFUND_CREDIT_REVERSAL","CHANNEL_CREDIT","CHANNEL_CREDIT_REVERSAL","CHANNEL_TRANSFER_CREDIT","CHANNEL_TRANSFER_CREDIT_REVERSAL","CHANNEL_TRANSFER_DEBIT","CHANNEL_TRANSFER_DEBIT_REVERSAL","CHANNEL_PROMOTION_CREDIT","CHANNEL_PROMOTION_CREDIT_REVERSAL","MARKETPLACE_FEE_CREDIT","MARKETPLACE_FEE_CREDIT_REVERSAL","MERCHANT_GOODWILL_CREDIT","MERCHANT_GOODWILL_CREDIT_REVERSAL","TAX_ADJUSTMENT_DEBIT","TAX_ADJUSTMENT_DEBIT_REVERSAL","TAX_ADJUSTMENT_CREDIT","TAX_ADJUSTMENT_CREDIT_REVERSAL","BILLING_DEBIT","BILLING_DEBIT_REVERSAL","SHOP_CASH_CREDIT","SHOP_CASH_CREDIT_REVERSAL","SHOP_CASH_BILLING_DEBIT","SHOP_CASH_BILLING_DEBIT_REVERSAL","SHOP_CASH_REFUND_DEBIT","SHOP_CASH_REFUND_DEBIT_REVERSAL","SHOP_CASH_CAMPAIGN_BILLING_DEBIT","SHOP_CASH_CAMPAIGN_BILLING_DEBIT_REVERSAL","SHOP_CASH_CAMPAIGN_BILLING_CREDIT","SHOP_CASH_CAMPAIGN_BILLING_CREDIT_REVERSAL","SELLER_PROTECTION_CREDIT","SELLER_PROTECTION_CREDIT_REVERSAL","SHOPIFY_COLLECTIVE_DEBIT","SHOPIFY_COLLECTIVE_DEBIT_REVERSAL","SHOPIFY_COLLECTIVE_CREDIT","SHOPIFY_COLLECTIVE_CREDIT_REVERSAL","LENDING_DEBIT","LENDING_DEBIT_REVERSAL","LENDING_CREDIT","LENDING_CREDIT_REVERSAL","LENDING_CAPITAL_REMITTANCE","LENDING_CAPITAL_REMITTANCE_REVERSAL","LENDING_CREDIT_REMITTANCE","LENDING_CREDIT_REMITTANCE_REVERSAL","LENDING_CAPITAL_REFUND","LENDING_CAPITAL_REFUND_REVERSAL","LENDING_CREDIT_REFUND","LENDING_CREDIT_REFUND_REVERSAL","BALANCE_TRANSFER_INBOUND","BALANCE_TRANSFER_OUTBOUND","MARKETS_PRO_CREDIT","CUSTOMS_DUTY_ADJUSTMENT","IMPORT_TAX_ADJUSTMENT","SHIPPING_LABEL_ADJUSTMENT","SHIPPING_LABEL_ADJUSTMENT_BASE","SHIPPING_LABEL_ADJUSTMENT_SURCHARGE","SHIPPING_RETURN_TO_ORIGIN_ADJUSTMENT","SHIPPING_OTHER_CARRIER_CHARGE_ADJUSTMENT","CHARGE_ADJUSTMENT","REFUND_ADJUSTMENT","CHARGEBACK_FEE","CHARGEBACK_FEE_REFUND","TRANSFER","TRANSFER_FAILURE","TRANSFER_CANCEL","RESERVED_FUNDS_WITHDRAWAL","RESERVED_FUNDS_REVERSAL","RISK_REVERSAL","RISK_WITHDRAWAL","REFERRAL_FEE","REFERRAL_FEE_TAX","MERCHANT_TO_MERCHANT_DEBIT","MERCHANT_TO_MERCHANT_DEBIT_REVERSAL","MERCHANT_TO_MERCHANT_CREDIT","MERCHANT_TO_MERCHANT_CREDIT_REVERSAL","SHOPIFY_SOURCE_DEBIT","SHOPIFY_SOURCE_DEBIT_REVERSAL","SHOPIFY_SOURCE_CREDIT","SHOPIFY_SOURCE_CREDIT_REVERSAL","CHARGE","REFUND","REFUND_FAILURE","APPLICATION_FEE_REFUND","ADJUSTMENT","DISPUTE_WITHDRAWAL","DISPUTE_REVERSAL","SHIPPING_LABEL","CUSTOMS_DUTY","IMPORT_TAX","CHARGEBACK_HOLD","CHARGEBACK_HOLD_RELEASE","CURRENCY_CONVERSION","RESERVED_FUNDS","STRIPE_FEE","TRANSFER_REFUND","ADVANCE","ADVANCE_FUNDING","IMPORT_TAX_REFUND"]}, +"ShopifyProtectEligibilityStatus":{"e":["PENDING","ELIGIBLE","NOT_ELIGIBLE"]}, +"ShopifyProtectOrderEligibility":{"o":{"f":{"status":"ShopifyProtectEligibilityStatus!"}}}, +"ShopifyProtectOrderSummary":{"o":{"f":{"eligibility":"ShopifyProtectOrderEligibility!","status":"ShopifyProtectStatus!"}}}, +"ShopifyProtectStatus":{"e":["PENDING","ACTIVE","INACTIVE","PROTECTED","NOT_PROTECTED"]}, +"ShopifyqlColumnOrigin":{"e":["UNSPECIFIED","REQUESTED","GENERATED"]}, +"ShopifyqlDynamicColumnMetadata":{"o":{"f":{"aggregatedBy":"[String!]!","comparisonReference":"String","originalColumnName":"String","type":"ShopifyqlDynamicColumnType!"}}}, +"ShopifyqlDynamicColumnType":{"e":["UNSPECIFIED","TOTALS","COMPARISON","PERCENT_CHANGE","COMPARISON_TOTALS","BENCHMARKS","BENCHMARK_TOTALS","CUMULATIVE","COMPARISON_CUMULATIVE","ATTRIBUTION","ATTRIBUTION_TOTALS","ATTRIBUTION_COMPARISON","ATTRIBUTION_PERCENT_CHANGE","ATTRIBUTION_COMPARISON_TOTALS","ATTRIBUTION_CUMULATIVE","ATTRIBUTION_COMPARISON_CUMULATIVE","ROLLOUT_RESULTS","PERCENT_OF_TOTAL"]}, +"ShopifyqlNullCellTranslation":{"o":{"f":{"columnName":"String!","displayText":"String!"}}}, +"ShopifyqlQueryResponse":{"o":{"f":{"analyticsTargets":"[AnalyticsTarget!]!","parseErrors":"[String!]!","parseWarnings":"[String!]!","tableData":"ShopifyqlTableData"}}}, +"ShopifyqlRowMetadata":{"o":{"f":{"nullCellTranslations":"[ShopifyqlNullCellTranslation!]!","rawResourceIds":"[[String!]!]!","topNRemainderColumnNames":"[String!]!"}}}, +"ShopifyqlTableData":{"o":{"f":{"columns":"[ShopifyqlTableDataColumn!]!","rowMetadata":"[ShopifyqlRowMetadata!]!","rows":"JSON!"}}}, +"ShopifyqlTableDataColumn":{"o":{"f":{"columnOrigin":"ShopifyqlColumnOrigin!","dataType":"ColumnDataType!","displayName":"String!","dynamicColumnMetadata":"ShopifyqlDynamicColumnMetadata","name":"String!","shortDisplayName":"String","subType":"ColumnDataType"}}}, +"StaffMember":{"o":{"f":{"accountType":"AccountType","active":"Boolean!","avatar":["Image!",{"fallback":"StaffMemberDefaultImage=","maxHeight":"Int","maxWidth":"Int"}],"email":"String!","exists":"Boolean!","firstName":"String","id":"ID!","initials":"[String!]","isShopOwner":"Boolean!","lastName":"String","locale":"String!","name":"String!","phone":"String","privateData":"StaffMemberPrivateData!"},"t":["Node"],"d":{"avatar(maxHeight)":"Use `maxHeight` argument on `image` instead.","avatar(maxWidth)":"Use `maxWidth` on argument `image` instead."}}}, +"StaffMemberConnection":{"o":{"f":{"edges":"[StaffMemberEdge!]!","nodes":"[StaffMember!]!","pageInfo":"PageInfo!"}}}, +"StaffMemberDefaultImage":{"e":["DEFAULT","TRANSPARENT","NOT_FOUND"]}, +"StaffMemberEdge":{"o":{"f":{"cursor":"String!","node":"StaffMember!"}}}, +"StaffMemberPermission":{"e":{"v":["APPLICATIONS","CHANNELS","CREATE_AND_EDIT_CUSTOMERS","CREATE_AND_EDIT_GIFT_CARDS","CUSTOMERS","DASHBOARD","DEACTIVATE_GIFT_CARDS","DELETE_CUSTOMERS","DOMAINS","DRAFT_ORDERS","EDIT_ORDERS","ERASE_CUSTOMER_DATA","EXPORT_CUSTOMERS","EXPORT_GIFT_CARDS","FULL","GIFT_CARDS","LINKS","LOCATIONS","VIEW_MARKETS","CREATE_AND_EDIT_MARKETS","DELETE_MARKETS","MARKETING","MARKETING_SECTION","MERGE_CUSTOMERS","ORDERS","OVERVIEWS","PAGES","PAY_ORDERS_BY_VAULTED_CARD","PREFERENCES","PRODUCTS","REPORTS","REQUEST_CUSTOMER_DATA","THEMES","TRANSLATIONS"],"d":{"FULL":"Use the list of the staff member's explicit permissions returned in the `StaffMember.permissions.userPermissions` field instead of `full` permission.","TRANSLATIONS":"Unused."}}}, +"StaffMemberPrivateData":{"o":{"f":{"accountSettingsUrl":"URL!","createdAt":"DateTime!","permissions":"[StaffMemberPermission!]!"},"d":{"permissions":"There's no alternative field to use instead."}}}, +"StaffMembersSortKeys":{"e":["EMAIL","FIRST_NAME","ID","LAST_NAME"]}, +"StageImageInput":{"i":{"filename":"String!","httpMethod":"StagedUploadHttpMethodType=","mimeType":"String!","resource":"StagedUploadTargetGenerateUploadResource!"}}, +"StagedMediaUploadTarget":{"o":{"f":{"parameters":"[StagedUploadParameter!]!","resourceUrl":"URL","url":"URL"}}}, +"StagedUploadHttpMethodType":{"e":["POST","PUT"]}, +"StagedUploadInput":{"i":{"fileSize":"UnsignedInt64","filename":"String!","httpMethod":"StagedUploadHttpMethodType=","mimeType":"String!","resource":"StagedUploadTargetGenerateUploadResource!"}}, +"StagedUploadParameter":{"o":{"f":{"name":"String!","value":"String!"}}}, +"StagedUploadTarget":{"o":{"f":{"parameters":"[ImageUploadParameter!]!","url":"String!"}}}, +"StagedUploadTargetGenerateInput":{"i":{"fileSize":"UnsignedInt64","filename":"String!","httpMethod":"StagedUploadHttpMethodType=","mimeType":"String!","resource":"StagedUploadTargetGenerateUploadResource!"}}, +"StagedUploadTargetGeneratePayload":{"o":{"f":{"parameters":"[MutationsStagedUploadTargetGenerateUploadParameter!]!","url":"String!","userErrors":"[UserError!]!"}}}, +"StagedUploadTargetGenerateUploadResource":{"e":{"v":["COLLECTION_IMAGE","FILE","IMAGE","MODEL_3D","PRODUCT_IMAGE","SHOP_IMAGE","VIDEO","BULK_MUTATION_VARIABLES","RETURN_LABEL","URL_REDIRECT_IMPORT","DISPUTE_FILE_UPLOAD"],"d":{"PRODUCT_IMAGE":"Use IMAGE instead. This resource type will be removed in a future version."}}}, +"StagedUploadTargetsGeneratePayload":{"o":{"f":{"urls":"[StagedUploadTarget!]","userErrors":"[UserError!]!"}}}, +"StagedUploadsCreatePayload":{"o":{"f":{"stagedTargets":"[StagedMediaUploadTarget!]","userErrors":"[UserError!]!"}}}, +"StandardMetafieldDefinitionAccessInput":{"i":{"admin":"MetafieldAdminAccessInput","customerAccount":"MetafieldCustomerAccountAccessInput","storefront":"MetafieldStorefrontAccessInput"}}, +"StandardMetafieldDefinitionEnablePayload":{"o":{"f":{"createdDefinition":"MetafieldDefinition","userErrors":"[StandardMetafieldDefinitionEnableUserError!]!"}}}, +"StandardMetafieldDefinitionEnableUserError":{"o":{"f":{"code":"StandardMetafieldDefinitionEnableUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"StandardMetafieldDefinitionEnableUserErrorCode":{"e":["INVALID","TAKEN","TEMPLATE_NOT_FOUND","LIMIT_EXCEEDED","UNSTRUCTURED_ALREADY_EXISTS","TYPE_NOT_ALLOWED_FOR_CONDITIONS","INVALID_CAPABILITY","CAPABILITY_CANNOT_BE_DISABLED","OWNER_TYPE_LIMIT_EXCEEDED_FOR_USE_AS_ADMIN_FILTERS","INVALID_STANDARD_METAOBJECT","UNSUPPORTED_PINNING","ADMIN_ACCESS_INPUT_NOT_ALLOWED","INVALID_INPUT_COMBINATION"]}, +"StandardMetafieldDefinitionTemplate":{"o":{"f":{"description":"String","id":"ID!","key":"String!","name":"String!","namespace":"String!","ownerTypes":"[MetafieldOwnerType!]!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!","visibleToStorefrontApi":"Boolean!"},"t":["Node"]}}, +"StandardMetafieldDefinitionTemplateConnection":{"o":{"f":{"edges":"[StandardMetafieldDefinitionTemplateEdge!]!","nodes":"[StandardMetafieldDefinitionTemplate!]!","pageInfo":"PageInfo!"}}}, +"StandardMetafieldDefinitionTemplateEdge":{"o":{"f":{"cursor":"String!","node":"StandardMetafieldDefinitionTemplate!"}}}, +"StandardMetaobjectCapabilityTemplate":{"o":{"f":{"capabilityType":"MetaobjectCapabilityType!"}}}, +"StandardMetaobjectDefinitionEnablePayload":{"o":{"f":{"metaobjectDefinition":"MetaobjectDefinition","userErrors":"[MetaobjectUserError!]!"}}}, +"StandardMetaobjectDefinitionFieldTemplate":{"o":{"f":{"description":"String","key":"String!","name":"String!","required":"Boolean!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!","visibleToStorefrontApi":"Boolean!"},"d":{"visibleToStorefrontApi":"Access control at the metaobject field definition level is deprecated and will be removed in 2027-01. Use the access field on the definition instead."}}}, +"StandardMetaobjectDefinitionTemplate":{"o":{"f":{"access":"MetaobjectAccess!","description":"String","displayNameKey":"String","enabledCapabilities":"[StandardMetaobjectCapabilityTemplate!]!","fieldDefinitions":"[StandardMetaobjectDefinitionFieldTemplate!]!","name":"String!","type":"String!"}}}, +"StandardizedProductType":{"o":{"f":{"productTaxonomyNode":"ProductTaxonomyNode"}}}, +"StoreCreditAccount":{"o":{"f":{"balance":"MoneyV2!","id":"ID!","owner":"HasStoreCreditAccounts!","transactions":["StoreCreditAccountTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"TransactionSortKeys="}]},"t":["Node"]}}, +"StoreCreditAccountConnection":{"o":{"f":{"edges":"[StoreCreditAccountEdge!]!","nodes":"[StoreCreditAccount!]!","pageInfo":"PageInfo!"}}}, +"StoreCreditAccountCreditInput":{"i":{"creditAmount":"MoneyInput!","expiresAt":"DateTime","notify":"Boolean="}}, +"StoreCreditAccountCreditPayload":{"o":{"f":{"storeCreditAccountTransaction":"StoreCreditAccountCreditTransaction","userErrors":"[StoreCreditAccountCreditUserError!]!"}}}, +"StoreCreditAccountCreditTransaction":{"o":{"f":{"account":"StoreCreditAccount!","amount":"MoneyV2!","balanceAfterTransaction":"MoneyV2!","createdAt":"DateTime!","event":"StoreCreditSystemEvent!","expiresAt":"DateTime","id":"ID!","origin":"StoreCreditAccountTransactionOrigin","remainingAmount":"MoneyV2!"},"t":["Node","StoreCreditAccountTransaction"]}}, +"StoreCreditAccountCreditUserError":{"o":{"f":{"code":"StoreCreditAccountCreditUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"StoreCreditAccountCreditUserErrorCode":{"e":["ACCOUNT_NOT_FOUND","OWNER_NOT_FOUND","NEGATIVE_OR_ZERO_AMOUNT","MISMATCHING_CURRENCY","EXPIRES_AT_IN_PAST","CREDIT_LIMIT_EXCEEDED","UNSUPPORTED_CURRENCY"]}, +"StoreCreditAccountDebitInput":{"i":{"debitAmount":"MoneyInput!"}}, +"StoreCreditAccountDebitPayload":{"o":{"f":{"storeCreditAccountTransaction":"StoreCreditAccountDebitTransaction","userErrors":"[StoreCreditAccountDebitUserError!]!"}}}, +"StoreCreditAccountDebitRevertTransaction":{"o":{"f":{"account":"StoreCreditAccount!","amount":"MoneyV2!","balanceAfterTransaction":"MoneyV2!","createdAt":"DateTime!","debitTransaction":"StoreCreditAccountDebitTransaction!","event":"StoreCreditSystemEvent!","id":"ID!","origin":"StoreCreditAccountTransactionOrigin"},"t":["Node","StoreCreditAccountTransaction"]}}, +"StoreCreditAccountDebitTransaction":{"o":{"f":{"account":"StoreCreditAccount!","amount":"MoneyV2!","balanceAfterTransaction":"MoneyV2!","createdAt":"DateTime!","event":"StoreCreditSystemEvent!","id":"ID!","origin":"StoreCreditAccountTransactionOrigin"},"t":["Node","StoreCreditAccountTransaction"]}}, +"StoreCreditAccountDebitUserError":{"o":{"f":{"code":"StoreCreditAccountDebitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"StoreCreditAccountDebitUserErrorCode":{"e":["ACCOUNT_NOT_FOUND","NEGATIVE_OR_ZERO_AMOUNT","INSUFFICIENT_FUNDS","MISMATCHING_CURRENCY"]}, +"StoreCreditAccountEdge":{"o":{"f":{"cursor":"String!","node":"StoreCreditAccount!"}}}, +"StoreCreditAccountExpirationTransaction":{"o":{"f":{"account":"StoreCreditAccount!","amount":"MoneyV2!","balanceAfterTransaction":"MoneyV2!","createdAt":"DateTime!","creditTransaction":"StoreCreditAccountCreditTransaction!","event":"StoreCreditSystemEvent!","origin":"StoreCreditAccountTransactionOrigin"},"t":["StoreCreditAccountTransaction"]}}, +"StoreCreditAccountTransaction":{"n":{"f":{"account":"StoreCreditAccount!","amount":"MoneyV2!","balanceAfterTransaction":"MoneyV2!","createdAt":"DateTime!","event":"StoreCreditSystemEvent!","origin":"StoreCreditAccountTransactionOrigin"},"t":["StoreCreditAccountCreditTransaction","StoreCreditAccountDebitRevertTransaction","StoreCreditAccountDebitTransaction","StoreCreditAccountExpirationTransaction"]}}, +"StoreCreditAccountTransactionConnection":{"o":{"f":{"edges":"[StoreCreditAccountTransactionEdge!]!","nodes":"[StoreCreditAccountTransaction!]!","pageInfo":"PageInfo!"}}}, +"StoreCreditAccountTransactionEdge":{"o":{"f":{"cursor":"String!","node":"StoreCreditAccountTransaction!"}}}, +"StoreCreditAccountTransactionOrigin":{"u":["OrderTransaction"]}, +"StoreCreditConfiguration":{"o":{"f":{"storeCreditEnabled":"Boolean!"}}}, +"StoreCreditRefundInput":{"i":{"amount":"MoneyInput!","expiresAt":"DateTime"}}, +"StoreCreditSystemEvent":{"e":["ADJUSTMENT","ORDER_PAYMENT","ORDER_REFUND","PAYMENT_FAILURE","PAYMENT_RETURNED","ORDER_CANCELLATION","TAX_FINALIZATION","RECURRING_PAYMENT"]}, +"StorefrontAccessToken":{"o":{"f":{"accessScopes":"[AccessScope!]!","accessToken":"String!","createdAt":"DateTime!","id":"ID!","title":"String!","updatedAt":"DateTime!"},"t":["Node"]}}, +"StorefrontAccessTokenConnection":{"o":{"f":{"edges":"[StorefrontAccessTokenEdge!]!","nodes":"[StorefrontAccessToken!]!","pageInfo":"PageInfo!"}}}, +"StorefrontAccessTokenCreatePayload":{"o":{"f":{"shop":"Shop!","storefrontAccessToken":"StorefrontAccessToken","userErrors":"[UserError!]!"}}}, +"StorefrontAccessTokenDeleteInput":{"i":{"id":"ID!"}}, +"StorefrontAccessTokenDeletePayload":{"o":{"f":{"deletedStorefrontAccessTokenId":"ID","userErrors":"[UserError!]!"}}}, +"StorefrontAccessTokenEdge":{"o":{"f":{"cursor":"String!","node":"StorefrontAccessToken!"}}}, +"StorefrontAccessTokenInput":{"i":{"title":"String!"}}, +"StorefrontID":"s", +"String":"s", +"StringConnection":{"o":{"f":{"edges":"[StringEdge!]!","nodes":"[String!]!","pageInfo":"PageInfo!"}}}, +"StringEdge":{"o":{"f":{"cursor":"String!","node":"String!"}}}, +"SubCollectionIneligibleReason":{"e":["INVALID_COLLECTION_REFERENCE","SELF_REFERENCE","CHAIN_REFERENCE"]}, +"SubscriptionActor":{"e":["CUSTOMER","MERCHANT","PARTNER"]}, +"SubscriptionAppliedCodeDiscount":{"o":{"f":{"id":"ID!","redeemCode":"String!","rejectionReason":"SubscriptionDiscountRejectionReason"}}}, +"SubscriptionAtomicLineInput":{"i":{"discounts":"[SubscriptionAtomicManualDiscountInput!]","line":"SubscriptionLineInput!"}}, +"SubscriptionAtomicManualDiscountInput":{"i":{"recurringCycleLimit":"Int","title":"String","value":"SubscriptionManualDiscountValueInput"}}, +"SubscriptionBillingAttempt":{"o":{"f":{"completedAt":"DateTime","createdAt":"DateTime!","errorCode":"SubscriptionBillingAttemptErrorCode","errorMessage":"String","id":"ID!","idempotencyKey":"String!","nextActionUrl":"URL","order":"Order","originTime":"DateTime","paymentGroupId":"String","paymentSessionId":"String","processingError":"SubscriptionBillingAttemptProcessingError","ready":"Boolean!","respectInventoryPolicy":"Boolean!","state":"SubscriptionBillingAttemptState!","subscriptionContract":"SubscriptionContract!","transactions":["OrderTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Node"],"d":{"errorCode":"Use `state` instead.","errorMessage":"Use `state` instead.","nextActionUrl":"Use `state` instead.","order":"Use `state` instead.","processingError":"Use `state` instead.","ready":"Use `state` instead."}}}, +"SubscriptionBillingAttemptAction":{"u":["SubscriptionBillingAttemptPaymentChallenge"]}, +"SubscriptionBillingAttemptActionRequiredState":{"o":{"f":{"action":"SubscriptionBillingAttemptAction!"}}}, +"SubscriptionBillingAttemptConnection":{"o":{"f":{"edges":"[SubscriptionBillingAttemptEdge!]!","nodes":"[SubscriptionBillingAttempt!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionBillingAttemptCreatePayload":{"o":{"f":{"subscriptionBillingAttempt":"SubscriptionBillingAttempt","userErrors":"[BillingAttemptUserError!]!"}}}, +"SubscriptionBillingAttemptEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionBillingAttempt!"}}}, +"SubscriptionBillingAttemptError":{"u":["SubscriptionBillingAttemptGeneralError","SubscriptionBillingAttemptInventoryError","SubscriptionBillingAttemptPaymentError","SubscriptionBillingAttemptUnexpectedError"]}, +"SubscriptionBillingAttemptErrorCode":{"e":["PAYMENT_METHOD_NOT_FOUND","PAYMENT_PROVIDER_IS_NOT_ENABLED","INVALID_PAYMENT_METHOD","UNEXPECTED_ERROR","EXPIRED_PAYMENT_METHOD","PAYMENT_METHOD_DECLINED","AUTHENTICATION_ERROR","TEST_MODE","BUYER_CANCELED_PAYMENT_METHOD","CUSTOMER_NOT_FOUND","CUSTOMER_INVALID","INVALID_SHIPPING_ADDRESS","INVALID_CUSTOMER_BILLING_AGREEMENT","INVOICE_ALREADY_PAID","PAYMENT_METHOD_INCOMPATIBLE_WITH_GATEWAY_CONFIG","AMOUNT_TOO_SMALL","AMOUNT_TOO_LARGE","MERCHANT_ACCOUNT_ERROR","INVENTORY_ALLOCATIONS_NOT_FOUND","INSUFFICIENT_INVENTORY","TRANSIENT_ERROR","INSUFFICIENT_FUNDS","PURCHASE_TYPE_NOT_SUPPORTED","PAYPAL_ERROR_GENERAL","CARD_NUMBER_INCORRECT","FRAUD_SUSPECTED","NON_TEST_ORDER_LIMIT_REACHED","FREE_GIFT_CARD_NOT_ALLOWED","PAYMENT_METHOD_NOT_SPECIFIED","INVALID_BILLING_ADDRESS","AUTHENTICATION_FAILED","AUTHENTICATION_REQUIRED","CALL_ISSUER","CARD_DECLINED","CONFIRMATION_REJECTED","DO_NOT_HONOR","MERCHANT_RULE","OFF_SESSION_REJECTED","RETRY_DECLINED","TRANSACTION_LIMIT_EXCEEDED","INCORRECT_ZIP","INVALID_AMOUNT","INVALID_CURRENCY","INVALID_CVC","INVALID_NUMBER","PAYMENT_METHOD_UNSUPPORTED","INCORRECT_ADDRESS","INCORRECT_CVC","INCORRECT_NUMBER","INCORRECT_PIN","EXPIRED_CARD","INVALID_EXPIRY_DATE","EXPIRED_BUYER_ACTION","PROCESSING_ERROR","PAYMENT_PROVIDER_ERROR","GENERIC_ERROR","CANCELLED_PAYMENT","INVALID_PURCHASE_TYPE","INVALID_REQUEST"]}, +"SubscriptionBillingAttemptFailedState":{"o":{"f":{"error":"SubscriptionBillingAttemptError!"}}}, +"SubscriptionBillingAttemptGeneralError":{"o":{"f":{"code":"SubscriptionBillingAttemptGeneralErrorCode!"}}}, +"SubscriptionBillingAttemptGeneralErrorCode":{"e":["NON_TEST_ORDER_LIMIT_REACHED","FREE_GIFT_CARD_NOT_ALLOWED","CUSTOMER_NOT_FOUND","CUSTOMER_INVALID","INVALID_BILLING_ADDRESS","MERCHANT_ACCOUNT_ERROR","PAYMENT_METHOD_NOT_FOUND","PAYMENT_METHOD_NOT_SPECIFIED","PAYMENT_METHOD_INCOMPATIBLE_WITH_GATEWAY_CONFIG","PAYMENT_PROVIDER_IS_NOT_ENABLED"]}, +"SubscriptionBillingAttemptGenericError":{"o":{"f":{"code":"SubscriptionBillingAttemptErrorCode!","message":"String!"},"t":["SubscriptionBillingAttemptProcessingError"]}}, +"SubscriptionBillingAttemptInput":{"i":{"actor":"SubscriptionActor","billingCycleSelector":"SubscriptionBillingCycleSelector","idempotencyKey":"String!","inventoryPolicy":"SubscriptionBillingAttemptInventoryPolicy=","originTime":"DateTime","paymentProcessingPolicy":"SubscriptionBillingAttemptPaymentProcessingPolicy="}}, +"SubscriptionBillingAttemptInsufficientStockProductVariantsError":{"o":{"f":{"code":"SubscriptionBillingAttemptErrorCode!","insufficientStockProductVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"message":"String!"},"t":["SubscriptionBillingAttemptProcessingError"]}}, +"SubscriptionBillingAttemptInventoryError":{"o":{"f":{"code":"SubscriptionBillingAttemptInventoryErrorCode!","insufficientStockProductVariants":["ProductVariantConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"SubscriptionBillingAttemptInventoryErrorCode":{"e":["INSUFFICIENT_INVENTORY","INVENTORY_ALLOCATIONS_NOT_FOUND"]}, +"SubscriptionBillingAttemptInventoryPolicy":{"e":["PRODUCT_VARIANT_INVENTORY_POLICY","ALLOW_OVERSELLING"]}, +"SubscriptionBillingAttemptOutOfStockProductVariantsError":{"o":{"f":{"code":"SubscriptionBillingAttemptErrorCode!","message":"String!","outOfStockProductVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["SubscriptionBillingAttemptProcessingError"],"d":{"outOfStockProductVariants":"Use `subscriptionBillingAttemptInsufficientStockProductVariantsError` type instead."}}}, +"SubscriptionBillingAttemptPaymentChallenge":{"o":{"f":{"nextActionUrl":"URL!","status":"SubscriptionBillingAttemptPaymentChallengeStatus!"}}}, +"SubscriptionBillingAttemptPaymentChallengeStatus":{"e":["OFF_SESSION_REJECTED","ON_SESSION_CHALLENGED"]}, +"SubscriptionBillingAttemptPaymentError":{"o":{"f":{"code":"SubscriptionBillingAttemptPaymentErrorCode!"}}}, +"SubscriptionBillingAttemptPaymentErrorCode":{"e":["PAYMENT_METHOD_DECLINED","EXPIRED_PAYMENT_METHOD","INSUFFICIENT_FUNDS","AUTHENTICATION_ERROR","INVALID_PAYMENT_METHOD","BUYER_CANCELED_PAYMENT_METHOD","INVALID_CUSTOMER_BILLING_AGREEMENT","AMOUNT_TOO_SMALL","AMOUNT_TOO_LARGE","CARD_NUMBER_INCORRECT","FRAUD_SUSPECTED","INVOICE_ALREADY_PAID","TEST_MODE","PAYPAL_ERROR_GENERAL","INVALID_SHIPPING_ADDRESS","TRANSIENT_ERROR","PURCHASE_TYPE_NOT_SUPPORTED","AUTHENTICATION_FAILED","AUTHENTICATION_REQUIRED","CALL_ISSUER","CARD_DECLINED","CONFIRMATION_REJECTED","DO_NOT_HONOR","MERCHANT_RULE","OFF_SESSION_REJECTED","RETRY_DECLINED","TRANSACTION_LIMIT_EXCEEDED","INCORRECT_ZIP","INVALID_AMOUNT","INVALID_CURRENCY","INVALID_CVC","INVALID_NUMBER","PAYMENT_METHOD_UNSUPPORTED","PAYMENT_PROVIDER_ERROR","INCORRECT_ADDRESS","INCORRECT_CVC","INCORRECT_NUMBER","INCORRECT_PIN","EXPIRED_CARD","INVALID_EXPIRY_DATE","EXPIRED_BUYER_ACTION","PROCESSING_ERROR","GENERIC_ERROR","CANCELLED_PAYMENT","INVALID_PURCHASE_TYPE","INVALID_REQUEST"]}, +"SubscriptionBillingAttemptPaymentProcessingPolicy":{"e":["FAIL_UNLESS_VALID_PAYMENT_METHOD","SKIP_PAYMENT_AND_CREATE_UNPAID_ORDER"]}, +"SubscriptionBillingAttemptPendingState":{"o":{"f":{"processing":"Boolean!"}}}, +"SubscriptionBillingAttemptProcessingError":{"n":{"f":{"code":"SubscriptionBillingAttemptErrorCode!","message":"String!"},"t":["SubscriptionBillingAttemptGenericError","SubscriptionBillingAttemptInsufficientStockProductVariantsError","SubscriptionBillingAttemptOutOfStockProductVariantsError"]}}, +"SubscriptionBillingAttemptState":{"u":["SubscriptionBillingAttemptActionRequiredState","SubscriptionBillingAttemptFailedState","SubscriptionBillingAttemptPendingState","SubscriptionBillingAttemptSuccessState"]}, +"SubscriptionBillingAttemptSuccessState":{"o":{"f":{"order":"Order"}}}, +"SubscriptionBillingAttemptUnexpectedError":{"o":{"f":{"message":"String!"}}}, +"SubscriptionBillingAttemptsSortKeys":{"e":["CREATED_AT","ID"]}, +"SubscriptionBillingCycle":{"o":{"f":{"billingAttemptExpectedDate":"DateTime!","billingAttempts":["SubscriptionBillingAttemptConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"cycleEndAt":"DateTime!","cycleIndex":"Int!","cycleStartAt":"DateTime!","edited":"Boolean!","editedContract":"SubscriptionBillingCycleEditedContract","skipped":"Boolean!","sourceContract":"SubscriptionContract!","status":"SubscriptionBillingCycleBillingCycleStatus!"}}}, +"SubscriptionBillingCycleBillingAttemptStatus":{"e":["HAS_ATTEMPT","NO_ATTEMPT","ANY"]}, +"SubscriptionBillingCycleBillingCycleStatus":{"e":["BILLED","UNBILLED"]}, +"SubscriptionBillingCycleBulkChargePayload":{"o":{"f":{"job":"Job","userErrors":"[SubscriptionBillingCycleBulkUserError!]!"}}}, +"SubscriptionBillingCycleBulkFilters":{"i":{"billingAttemptStatus":"SubscriptionBillingCycleBillingAttemptStatus=","billingCycleStatus":"[SubscriptionBillingCycleBillingCycleStatus!]","contractStatus":"[SubscriptionContractSubscriptionStatus!]"}}, +"SubscriptionBillingCycleBulkSearchPayload":{"o":{"f":{"job":"Job","userErrors":"[SubscriptionBillingCycleBulkUserError!]!"}}}, +"SubscriptionBillingCycleBulkUserError":{"o":{"f":{"code":"SubscriptionBillingCycleBulkUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionBillingCycleBulkUserErrorCode":{"e":["INVALID","BLANK","END_DATE_IN_THE_FUTURE","INVALID_DATE_RANGE","START_DATE_BEFORE_END_DATE"]}, +"SubscriptionBillingCycleChargePayload":{"o":{"f":{"subscriptionBillingAttempt":"SubscriptionBillingAttempt","userErrors":"[BillingAttemptUserError!]!"}}}, +"SubscriptionBillingCycleConnection":{"o":{"f":{"edges":"[SubscriptionBillingCycleEdge!]!","nodes":"[SubscriptionBillingCycle!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionBillingCycleContractDraftCommitPayload":{"o":{"f":{"contract":"SubscriptionBillingCycleEditedContract","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionBillingCycleContractDraftConcatenatePayload":{"o":{"f":{"draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionBillingCycleContractEditCalculatePayload":{"o":{"f":{"subscriptionContractCalculation":"SubscriptionContractCalculation","userErrors":"[SubscriptionBillingCycleContractEditCalculateUserError!]!"}}}, +"SubscriptionBillingCycleContractEditCalculateUserError":{"o":{"f":{"code":"SubscriptionBillingCycleContractEditCalculateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionBillingCycleContractEditCalculateUserErrorCode":{"e":["INVALID"]}, +"SubscriptionBillingCycleContractEditPayload":{"o":{"f":{"draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionBillingCycleEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionBillingCycle!"}}}, +"SubscriptionBillingCycleEditDeletePayload":{"o":{"f":{"billingCycles":"[SubscriptionBillingCycle!]","userErrors":"[SubscriptionBillingCycleUserError!]!"}}}, +"SubscriptionBillingCycleEditedContract":{"o":{"f":{"app":"App","appAdminUrl":"URL","billingCycles":["SubscriptionBillingCycleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"SubscriptionBillingCyclesSortKeys="}],"createdAt":"DateTime!","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryPrice":"MoneyV2!","discounts":["SubscriptionManualDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"groupedLines":["SubscriptionGroupedLineConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"latestCommittedProjectedOrderTotals":"SubscriptionContractCalculationProjectedOrderTotals","lineCount":"Int!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesCount":"Count","note":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["SubscriptionContractBase"],"d":{"lineCount":"Use `linesCount` instead."}}}, +"SubscriptionBillingCycleEditsDeletePayload":{"o":{"f":{"billingCycles":"[SubscriptionBillingCycle!]","userErrors":"[SubscriptionBillingCycleUserError!]!"}}}, +"SubscriptionBillingCycleErrorCode":{"e":["INVALID","CYCLE_NOT_FOUND","NO_CYCLE_EDITS","INVALID_CYCLE_INDEX","INVALID_DATE","EMPTY_BILLING_CYCLE_EDIT_SCHEDULE_INPUT","BILLING_DATE_SET_ON_SKIPPED","OUT_OF_BOUNDS","UPCOMING_CYCLE_LIMIT_EXCEEDED","CYCLE_INDEX_OUT_OF_RANGE","CYCLE_START_DATE_OUT_OF_RANGE","INCOMPLETE_BILLING_ATTEMPTS"]}, +"SubscriptionBillingCycleInput":{"i":{"contractId":"ID!","selector":"SubscriptionBillingCycleSelector!"}}, +"SubscriptionBillingCycleScheduleEditInput":{"i":{"billingDate":"DateTime","reason":"SubscriptionBillingCycleScheduleEditInputScheduleEditReason!","skip":"Boolean"}}, +"SubscriptionBillingCycleScheduleEditInputScheduleEditReason":{"e":["BUYER_INITIATED","MERCHANT_INITIATED","DEV_INITIATED"]}, +"SubscriptionBillingCycleScheduleEditPayload":{"o":{"f":{"billingCycle":"SubscriptionBillingCycle","userErrors":"[SubscriptionBillingCycleUserError!]!"}}}, +"SubscriptionBillingCycleSelector":{"i":{"date":"DateTime","index":"Int"}}, +"SubscriptionBillingCycleSkipPayload":{"o":{"f":{"billingCycle":"SubscriptionBillingCycle","userErrors":"[SubscriptionBillingCycleSkipUserError!]!"}}}, +"SubscriptionBillingCycleSkipUserError":{"o":{"f":{"code":"SubscriptionBillingCycleSkipUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionBillingCycleSkipUserErrorCode":{"e":["INVALID"]}, +"SubscriptionBillingCycleUnskipPayload":{"o":{"f":{"billingCycle":"SubscriptionBillingCycle","userErrors":"[SubscriptionBillingCycleUnskipUserError!]!"}}}, +"SubscriptionBillingCycleUnskipUserError":{"o":{"f":{"code":"SubscriptionBillingCycleUnskipUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionBillingCycleUnskipUserErrorCode":{"e":["INVALID"]}, +"SubscriptionBillingCycleUserError":{"o":{"f":{"code":"SubscriptionBillingCycleErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionBillingCyclesDateRangeSelector":{"i":{"endDate":"DateTime!","startDate":"DateTime!"}}, +"SubscriptionBillingCyclesIndexRangeSelector":{"i":{"endIndex":"Int!","startIndex":"Int!"}}, +"SubscriptionBillingCyclesSortKeys":{"e":["CYCLE_INDEX","ID"]}, +"SubscriptionBillingCyclesTargetSelection":{"e":["ALL"]}, +"SubscriptionBillingPolicy":{"o":{"f":{"anchors":"[SellingPlanAnchor!]!","cadence":"SubscriptionContractCalculationCadence!","interval":"SellingPlanInterval!","intervalCount":"Int!","maxCycles":"Int","minCycles":"Int"}}}, +"SubscriptionBillingPolicyInput":{"i":{"anchors":"[SellingPlanAnchorInput!]=","interval":"SellingPlanInterval!","intervalCount":"Int!","maxCycles":"Int","minCycles":"Int"}}, +"SubscriptionCalculatedContract":{"o":{"f":{"billingPolicy":"SubscriptionBillingPolicy!","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer!","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryPolicy":"SubscriptionDeliveryPolicy!","deliveryPrice":"MoneyV2!","discounts":["SubscriptionManualDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"groupedLines":["SubscriptionGroupedLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"note":"String"}}}, +"SubscriptionCommittedContract":{"u":["SubscriptionBillingCycleEditedContract","SubscriptionContract"]}, +"SubscriptionContract":{"o":{"f":{"app":"App","appAdminUrl":"URL","billingAttempts":["SubscriptionBillingAttemptConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"billingPolicy":"SubscriptionBillingPolicy!","createdAt":"DateTime!","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryPolicy":"SubscriptionDeliveryPolicy!","deliveryPrice":"MoneyV2!","discounts":["SubscriptionManualDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"groupedLines":["SubscriptionGroupedLineConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"id":"ID!","lastBillingAttemptErrorType":"SubscriptionContractLastBillingErrorType","lastPaymentStatus":"SubscriptionContractLastPaymentStatus","latestCommittedProjectedOrderTotals":"SubscriptionContractCalculationProjectedOrderTotals","lineCount":"Int!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesCount":"Count","nextBillingDate":"DateTime","note":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"originOrder":"Order","revisionId":"UnsignedInt64!","status":"SubscriptionContractSubscriptionStatus!","updatedAt":"DateTime!"},"t":["Node","SubscriptionContractBase"],"d":{"lineCount":"Use `linesCount` instead."}}}, +"SubscriptionContractActivatePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractStatusUpdateUserError!]!"}}}, +"SubscriptionContractAtomicCreateInput":{"i":{"actor":"SubscriptionActor","contract":"SubscriptionDraftInput!","currencyCode":"CurrencyCode!","customerId":"ID!","discountCodes":"[String!]=","lines":"[SubscriptionAtomicLineInput!]!","nextBillingDate":"DateTime!"}}, +"SubscriptionContractAtomicCreatePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionContractBase":{"n":{"f":{"app":"App","appAdminUrl":"URL","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryPrice":"MoneyV2!","discounts":["SubscriptionManualDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"groupedLines":["SubscriptionGroupedLineConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"lineCount":"Int!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesCount":"Count","note":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["SubscriptionBillingCycleEditedContract","SubscriptionContract"],"d":{"lineCount":"Use `linesCount` instead."}}}, +"SubscriptionContractCalculation":{"u":["SubscriptionContractCalculationFailure","SubscriptionContractCalculationPending","SubscriptionContractCalculationSuccess"]}, +"SubscriptionContractCalculationAnchorInput":{"i":{"monthday":"SubscriptionContractCalculationMonthdayAnchorInput","weekday":"SubscriptionContractCalculationWeekdayAnchorInput","yearday":"SubscriptionContractCalculationYeardayAnchorInput"}}, +"SubscriptionContractCalculationAppManagedBillingConfigInput":{"i":{"maxCycles":"Int","minCycles":"Int"}}, +"SubscriptionContractCalculationAppManagedPricingPolicyInput":{"i":{"basePrice":"MoneyInput!","cyclePriceAdjustments":"[SubscriptionContractCalculationCyclePriceAdjustmentInput!]!"}}, +"SubscriptionContractCalculationBillingCycleEditInput":{"i":{"customAttributes":"[AttributeInput!]","deliveryMethod":"SubscriptionContractCalculationDeliveryMethodInput","discountCodes":"[SubscriptionContractCalculationDiscountCodeInput!]!=","lines":"[SubscriptionContractCalculationLineInput!]","manualDiscounts":"[SubscriptionContractCalculationManualDiscountInput!]","note":"String","withMerchandiseCustomizations":"Boolean!"}}, +"SubscriptionContractCalculationBillingPolicyInput":{"i":{"anchors":"[SubscriptionContractCalculationAnchorInput!]!=","cadence":"SubscriptionContractCalculationCadenceInput!"}}, +"SubscriptionContractCalculationCadence":{"o":{"f":{"count":"Int!","unit":"SubscriptionContractCalculationCadenceUnit!"}}}, +"SubscriptionContractCalculationCadenceInput":{"i":{"count":"Int!","unit":"SubscriptionContractCalculationCadenceUnit!"}}, +"SubscriptionContractCalculationCadenceUnit":{"e":["DAY","WEEK","MONTH","YEAR"]}, +"SubscriptionContractCalculationCommitPayload":{"o":{"f":{"contract":"SubscriptionCommittedContract","userErrors":"[SubscriptionContractCalculationCommitUserError!]!"}}}, +"SubscriptionContractCalculationCommitUserError":{"o":{"f":{"code":"SubscriptionContractCalculationCommitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionContractCalculationCommitUserErrorCode":{"e":["INVALID","NOT_READY_TO_COMMIT","DISCOVERY_CALCULATION_NOT_COMMITTABLE","CALCULATION_NOT_FOUND","STALE_CONTRACT","INVALID_BILLING_DATE","CONTRACT_TERMINATED"]}, +"SubscriptionContractCalculationComponentLineInput":{"i":{"productVariantLine":"SubscriptionContractCalculationProductVariantLineInput"}}, +"SubscriptionContractCalculationContractCreateInput":{"i":{"actor":"SubscriptionActor","appManagedBillingConfig":"SubscriptionContractCalculationAppManagedBillingConfigInput","billingPolicy":"SubscriptionContractCalculationBillingPolicyInput!","currencyCode":"CurrencyCode!","customAttributes":"[AttributeInput!]!=","customerId":"ID!","deliveryMethod":"SubscriptionContractCalculationDeliveryMethodInput!","deliveryPolicy":"SubscriptionContractCalculationDeliveryPolicyInput!","discountCodes":"[SubscriptionContractCalculationDiscountCodeInput!]!=","lines":"[SubscriptionContractCalculationLineInput!]!","manualDiscounts":"[SubscriptionContractCalculationManualDiscountInput!]!","note":"String","paymentMethod":"SubscriptionContractCalculationPaymentMethodInput!","withMerchandiseCustomizations":"Boolean!"}}, +"SubscriptionContractCalculationContractUpdateInput":{"i":{"appManagedBillingConfig":"SubscriptionContractCalculationAppManagedBillingConfigInput","billingPolicy":"SubscriptionContractCalculationBillingPolicyInput","customAttributes":"[AttributeInput!]","deliveryMethod":"SubscriptionContractCalculationDeliveryMethodInput","deliveryPolicy":"SubscriptionContractCalculationDeliveryPolicyInput","discountCodes":"[SubscriptionContractCalculationDiscountCodeInput!]!=","lines":"[SubscriptionContractCalculationLineInput!]","manualDiscounts":"[SubscriptionContractCalculationManualDiscountInput!]","note":"String","paymentMethod":"SubscriptionContractCalculationPaymentMethodInput","withMerchandiseCustomizations":"Boolean!"}}, +"SubscriptionContractCalculationCustomLineInput":{"i":{"appManagedPricingPolicy":"SubscriptionContractCalculationAppManagedPricingPolicyInput","customAttributes":"[AttributeInput!]!=","discounts":"[SubscriptionContractCalculationLineDiscountInput!]!","id":"ID","originSellingPlanId":"ID","price":"MoneyInput!","quantity":"Int!","requiresShipping":"Boolean!","sellingPlanName":"String","sku":"String","taxable":"Boolean!","title":"String!","variantTitle":"String","weight":"WeightInput"}}, +"SubscriptionContractCalculationCustomerPaymentMethodInput":{"i":{"id":"ID!"}}, +"SubscriptionContractCalculationCyclePriceAdjustmentInput":{"i":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyValueInput!","afterCycle":"Int!","computedPrice":"MoneyInput!"}}, +"SubscriptionContractCalculationDeliveryDiscountInput":{"i":{"id":"ID","recurringCycleLimit":"Int!","title":"String!","value":"SubscriptionContractCalculationDiscountValueInput!"}}, +"SubscriptionContractCalculationDeliveryMethodInput":{"i":{"fetchAvailableDeliveryOptions":"SubscriptionContractCalculationFetchDeliveryOptionsInput","localDelivery":"SubscriptionContractCalculationDeliveryMethodLocalDeliveryInput","none":"Boolean","pickup":"SubscriptionContractCalculationDeliveryMethodPickupInput","shipping":"SubscriptionContractCalculationDeliveryMethodShippingInput"}}, +"SubscriptionContractCalculationDeliveryMethodLocalDeliveryInput":{"i":{"address":"MailingAddressInput!","code":"String","deliveryPrice":"MoneyInput!","description":"String","instructions":"String","phone":"String!","presentmentTitle":"String","title":"String"}}, +"SubscriptionContractCalculationDeliveryMethodPickupInput":{"i":{"code":"String","deliveryPrice":"MoneyInput!","description":"String","locationId":"ID!","presentmentTitle":"String","title":"String"}}, +"SubscriptionContractCalculationDeliveryMethodShippingInput":{"i":{"address":"MailingAddressInput!","carrierServiceId":"ID","code":"String","deliveryPrice":"MoneyInput!","description":"String","presentmentTitle":"String","title":"String"}}, +"SubscriptionContractCalculationDeliveryOption":{"u":["SubscriptionContractCalculationLocalDeliveryOption","SubscriptionContractCalculationPickupOption","SubscriptionContractCalculationShippingOption"]}, +"SubscriptionContractCalculationDeliveryPolicyInput":{"i":{"anchors":"[SubscriptionContractCalculationAnchorInput!]!=","multiFulfillment":"SubscriptionContractCalculationMultipleFulfillmentConfigInput"}}, +"SubscriptionContractCalculationDiagnostic":{"o":{"f":{"code":"SubscriptionContractCalculationDiagnosticCode!","field":"[String!]","message":"String"}}}, +"SubscriptionContractCalculationDiagnosticCode":{"e":["INVALID","MERCHANDISE_NOT_FOUND","DELIVERY_ADDRESS_INVALID","CURRENCY_NOT_SUPPORTED","DELIVERY_NO_LOCATION_SHIPS_TO_ADDRESS","DELIVERY_PICKUP_LOCATION_UNAVAILABLE","PAYMENT_METHOD_NOT_FOUND","CUSTOM_VALIDATION","DELIVERY_METHOD_REQUIRED","DELIVERY_METHOD_UNUSED","CUSTOMER_CONTACT_METHOD_REQUIRED","BUNDLE_REQUIRES_MERCHANDISE_CUSTOMIZATIONS","MERCHANDISE_GIFT_CARD_INVALID","DISCOUNT_CODE_NOT_APPLIED","CALCULATION_TIMEOUT","LINE_PRICE_ADJUSTED_FOR_FULFILLMENTS","PROCESSING_ERROR"]}, +"SubscriptionContractCalculationDiscountCodeInput":{"i":{"redeemCode":"String!"}}, +"SubscriptionContractCalculationDiscountFixedAmountInput":{"i":{"amount":"MoneyInput!","appliesOnEachItem":"Boolean!"}}, +"SubscriptionContractCalculationDiscountValueInput":{"i":{"fixedAmount":"SubscriptionContractCalculationDiscountFixedAmountInput","percentage":"Int"}}, +"SubscriptionContractCalculationFailure":{"o":{"f":{"errors":"[SubscriptionContractCalculationDiagnostic!]!","id":"ID!"}}}, +"SubscriptionContractCalculationFetchDeliveryOptionsInput":{"i":{"address":"MailingAddressInput!","withDeliveryCustomizations":"Boolean="}}, +"SubscriptionContractCalculationLineDiscountInput":{"i":{"id":"ID","recurringCycleLimit":"Int!","title":"String!","value":"SubscriptionContractCalculationDiscountValueInput!"}}, +"SubscriptionContractCalculationLineInput":{"i":{"customLine":"SubscriptionContractCalculationCustomLineInput","productVariantLine":"SubscriptionContractCalculationProductVariantLineInput","productVariantParentLine":"SubscriptionContractCalculationProductVariantParentLineInput"}}, +"SubscriptionContractCalculationLocalDeliveryOption":{"o":{"f":{"code":"String!","description":"String","phoneRequired":"Boolean!","presentmentTitle":"String","price":"MoneyV2!","title":"String!"}}}, +"SubscriptionContractCalculationManualDiscountInput":{"i":{"deliveryDiscount":"SubscriptionContractCalculationDeliveryDiscountInput","orderDiscount":"SubscriptionContractCalculationOrderDiscountInput"}}, +"SubscriptionContractCalculationMonthdayAnchorInput":{"i":{"dayOfMonth":"Int!"}}, +"SubscriptionContractCalculationMultipleFulfillmentConfig":{"o":{"f":{"cadence":"SubscriptionContractCalculationCadence!","numberOfFulfillments":"Int!"}}}, +"SubscriptionContractCalculationMultipleFulfillmentConfigInput":{"i":{"cadence":"SubscriptionContractCalculationCadenceInput!","numberOfFulfillments":"Int!"}}, +"SubscriptionContractCalculationOrderDiscountInput":{"i":{"id":"ID","recurringCycleLimit":"Int!","title":"String!","value":"SubscriptionContractCalculationDiscountValueInput!"}}, +"SubscriptionContractCalculationPaymentMethodInput":{"i":{"customerPaymentMethod":"SubscriptionContractCalculationCustomerPaymentMethodInput","none":"Boolean"}}, +"SubscriptionContractCalculationPending":{"o":{"f":{"id":"ID!"}}}, +"SubscriptionContractCalculationPickupOption":{"o":{"f":{"code":"String!","description":"String","location":"Location!","phoneRequired":"Boolean!","pickupTime":"String","presentmentTitle":"String","price":"MoneyV2!","title":"String!"}}}, +"SubscriptionContractCalculationProductVariantLineInput":{"i":{"appManagedPricingPolicy":"SubscriptionContractCalculationAppManagedPricingPolicyInput","customAttributes":"[AttributeInput!]!=","discounts":"[SubscriptionContractCalculationLineDiscountInput!]!","id":"ID","originSellingPlanId":"ID","priceOverride":"MoneyInput","productVariantId":"ID!","quantity":"Int!","sellingPlanName":"String"}}, +"SubscriptionContractCalculationProductVariantParentLineInput":{"i":{"components":"[SubscriptionContractCalculationComponentLineInput!]!","customAttributes":"[AttributeInput!]!=","id":"ID","productVariantId":"ID!","quantity":"Int!"}}, +"SubscriptionContractCalculationProjectedOrderTotals":{"o":{"f":{"subtotal":"MoneyV2!","total":"MoneyV2!","totalDelivery":"MoneyV2!","totalDeliveryDiscounts":"MoneyV2!","totalMerchandiseDiscounts":"MoneyV2!","totalTax":"MoneyV2!"}}}, +"SubscriptionContractCalculationShippingOption":{"o":{"f":{"code":"String!","description":"String","phoneRequired":"Boolean!","presentmentTitle":"String","price":"MoneyV2!","title":"String!"}}}, +"SubscriptionContractCalculationSuccess":{"o":{"f":{"calculatedContract":"SubscriptionCalculatedContract!","deliveryOptions":"[SubscriptionContractCalculationDeliveryOption!]!","id":"ID!","projectedOrderTotals":"SubscriptionContractCalculationProjectedOrderTotals","warnings":"[SubscriptionContractCalculationDiagnostic!]!","withMerchandiseCustomizations":"Boolean!"}}}, +"SubscriptionContractCalculationWeekdayAnchorInput":{"i":{"dayOfWeek":"DayOfTheWeek!"}}, +"SubscriptionContractCalculationYeardayAnchorInput":{"i":{"dayOfMonth":"Int!","month":"Int!"}}, +"SubscriptionContractCancelPayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractStatusUpdateUserError!]!"}}}, +"SubscriptionContractConnection":{"o":{"f":{"edges":"[SubscriptionContractEdge!]!","nodes":"[SubscriptionContract!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionContractCreateCalculatePayload":{"o":{"f":{"subscriptionContractCalculation":"SubscriptionContractCalculation","userErrors":"[SubscriptionContractCreateCalculateUserError!]!"}}}, +"SubscriptionContractCreateCalculateUserError":{"o":{"f":{"code":"SubscriptionContractCreateCalculateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionContractCreateCalculateUserErrorCode":{"e":["INVALID"]}, +"SubscriptionContractCreateInput":{"i":{"actor":"SubscriptionActor","contract":"SubscriptionDraftInput!","currencyCode":"CurrencyCode!","customerId":"ID!","nextBillingDate":"DateTime!"}}, +"SubscriptionContractCreatePayload":{"o":{"f":{"draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionContractEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionContract!"}}}, +"SubscriptionContractErrorCode":{"e":["INVALID"]}, +"SubscriptionContractExpirePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractStatusUpdateUserError!]!"}}}, +"SubscriptionContractFailPayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractStatusUpdateUserError!]!"}}}, +"SubscriptionContractLastBillingErrorType":{"e":["PAYMENT_ERROR","CUSTOMER_ERROR","INVENTORY_ERROR","OTHER"]}, +"SubscriptionContractLastPaymentStatus":{"e":["SUCCEEDED","FAILED"]}, +"SubscriptionContractPausePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractStatusUpdateUserError!]!"}}}, +"SubscriptionContractProductChangeInput":{"i":{"currentPrice":"Decimal","productVariantId":"ID"}}, +"SubscriptionContractProductChangePayload":{"o":{"f":{"contract":"SubscriptionContract","lineUpdated":"SubscriptionLine","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionContractSetNextBillingDatePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractUserError!]!"}}}, +"SubscriptionContractStatusUpdateErrorCode":{"e":["INVALID","CONTRACT_TERMINATED"]}, +"SubscriptionContractStatusUpdateUserError":{"o":{"f":{"code":"SubscriptionContractStatusUpdateErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionContractSubscriptionStatus":{"e":["ACTIVE","PAUSED","CANCELLED","EXPIRED","FAILED"]}, +"SubscriptionContractUpdateCalculatePayload":{"o":{"f":{"subscriptionContractCalculation":"SubscriptionContractCalculation","userErrors":"[SubscriptionContractUpdateCalculateUserError!]!"}}}, +"SubscriptionContractUpdateCalculateUserError":{"o":{"f":{"code":"SubscriptionContractUpdateCalculateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionContractUpdateCalculateUserErrorCode":{"e":["INVALID","CONTRACT_TERMINATED","CONTRACT_HAS_FUTURE_EDITS"]}, +"SubscriptionContractUpdatePayload":{"o":{"f":{"draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionContractUserError":{"o":{"f":{"code":"SubscriptionContractErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionContractsSortKeys":{"e":["CREATED_AT","ID","STATUS","UPDATED_AT"]}, +"SubscriptionCyclePriceAdjustment":{"o":{"f":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyAdjustmentValue!","afterCycle":"Int!","computedPrice":"MoneyV2!"}}}, +"SubscriptionDeliveryMethod":{"u":["SubscriptionDeliveryMethodLocalDelivery","SubscriptionDeliveryMethodPickup","SubscriptionDeliveryMethodShipping"]}, +"SubscriptionDeliveryMethodInput":{"i":{"localDelivery":"SubscriptionDeliveryMethodLocalDeliveryInput","pickup":"SubscriptionDeliveryMethodPickupInput","shipping":"SubscriptionDeliveryMethodShippingInput"}}, +"SubscriptionDeliveryMethodLocalDelivery":{"o":{"f":{"address":"MailingAddress!","localDeliveryOption":"SubscriptionDeliveryMethodLocalDeliveryOption!"}}}, +"SubscriptionDeliveryMethodLocalDeliveryInput":{"i":{"address":"MailingAddressInput","localDeliveryOption":"SubscriptionDeliveryMethodLocalDeliveryOptionInput"}}, +"SubscriptionDeliveryMethodLocalDeliveryOption":{"o":{"f":{"code":"String","description":"String","instructions":"String","phone":"String!","presentmentTitle":"String","title":"String"}}}, +"SubscriptionDeliveryMethodLocalDeliveryOptionInput":{"i":{"code":"String","description":"String","instructions":"String","phone":"String!","presentmentTitle":"String","title":"String"}}, +"SubscriptionDeliveryMethodPickup":{"o":{"f":{"pickupOption":"SubscriptionDeliveryMethodPickupOption!"}}}, +"SubscriptionDeliveryMethodPickupInput":{"i":{"pickupOption":"SubscriptionDeliveryMethodPickupOptionInput"}}, +"SubscriptionDeliveryMethodPickupOption":{"o":{"f":{"code":"String","description":"String","location":"Location!","presentmentTitle":"String","title":"String"}}}, +"SubscriptionDeliveryMethodPickupOptionInput":{"i":{"code":"String","description":"String","locationId":"ID!","presentmentTitle":"String","title":"String"}}, +"SubscriptionDeliveryMethodShipping":{"o":{"f":{"address":"MailingAddress!","shippingOption":"SubscriptionDeliveryMethodShippingOption!"}}}, +"SubscriptionDeliveryMethodShippingInput":{"i":{"address":"MailingAddressInput","shippingOption":"SubscriptionDeliveryMethodShippingOptionInput"}}, +"SubscriptionDeliveryMethodShippingOption":{"o":{"f":{"carrierService":"DeliveryCarrierService","code":"String","description":"String","presentmentTitle":"String","title":"String"},"d":{"carrierService":"This field has never been implemented."}}}, +"SubscriptionDeliveryMethodShippingOptionInput":{"i":{"carrierServiceId":"ID","code":"String","description":"String","presentmentTitle":"String","title":"String"}}, +"SubscriptionDeliveryOption":{"u":["SubscriptionLocalDeliveryOption","SubscriptionPickupOption","SubscriptionShippingOption"]}, +"SubscriptionDeliveryOptionResult":{"u":["SubscriptionDeliveryOptionResultFailure","SubscriptionDeliveryOptionResultSuccess"]}, +"SubscriptionDeliveryOptionResultFailure":{"o":{"f":{"message":"String"}}}, +"SubscriptionDeliveryOptionResultSuccess":{"o":{"f":{"deliveryOptions":"[SubscriptionDeliveryOption!]!"}}}, +"SubscriptionDeliveryPolicy":{"o":{"f":{"anchors":"[SellingPlanAnchor!]!","interval":"SellingPlanInterval!","intervalCount":"Int!","multiFulfillment":"SubscriptionContractCalculationMultipleFulfillmentConfig"}}}, +"SubscriptionDeliveryPolicyInput":{"i":{"anchors":"[SellingPlanAnchorInput!]=","interval":"SellingPlanInterval!","intervalCount":"Int!"}}, +"SubscriptionDiscount":{"u":["SubscriptionAppliedCodeDiscount","SubscriptionManualDiscount"]}, +"SubscriptionDiscountAllocation":{"o":{"f":{"amount":"MoneyV2!","discount":"SubscriptionDiscount!"}}}, +"SubscriptionDiscountConnection":{"o":{"f":{"edges":"[SubscriptionDiscountEdge!]!","nodes":"[SubscriptionDiscount!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionDiscountEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionDiscount!"}}}, +"SubscriptionDiscountEntitledLines":{"o":{"f":{"all":"Boolean!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"SubscriptionDiscountFixedAmountValue":{"o":{"f":{"amount":"MoneyV2!","appliesOnEachItem":"Boolean!"}}}, +"SubscriptionDiscountPercentageValue":{"o":{"f":{"percentage":"Int!"}}}, +"SubscriptionDiscountRejectionReason":{"e":["NOT_FOUND","NO_ENTITLED_LINE_ITEMS","QUANTITY_NOT_IN_RANGE","PURCHASE_NOT_IN_RANGE","CUSTOMER_NOT_ELIGIBLE","USAGE_LIMIT_REACHED","CUSTOMER_USAGE_LIMIT_REACHED","CURRENTLY_INACTIVE","NO_ENTITLED_SHIPPING_LINES","INCOMPATIBLE_PURCHASE_TYPE","INTERNAL_ERROR"]}, +"SubscriptionDiscountValue":{"u":["SubscriptionDiscountFixedAmountValue","SubscriptionDiscountPercentageValue"]}, +"SubscriptionDraft":{"o":{"f":{"billingCycle":"SubscriptionBillingCycle","billingPolicy":"SubscriptionBillingPolicy!","concatenatedBillingCycles":["SubscriptionBillingCycleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"SubscriptionBillingCyclesSortKeys="}],"currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer!","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryOptions":["SubscriptionDeliveryOptionResult",{"deliveryAddress":"MailingAddressInput"}],"deliveryPolicy":"SubscriptionDeliveryPolicy!","deliveryPrice":"MoneyV2","discounts":["SubscriptionDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountsAdded":["SubscriptionDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountsRemoved":["SubscriptionDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountsUpdated":["SubscriptionDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"id":"ID!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesAdded":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesRemoved":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"nextBillingDate":"DateTime","note":"String","originalContract":"SubscriptionContract","shippingOptions":["SubscriptionShippingOptionResult",{"deliveryAddress":"MailingAddressInput"}],"status":"SubscriptionContractSubscriptionStatus"},"t":["Node"],"d":{"shippingOptions":"Use `deliveryOptions` instead."}}}, +"SubscriptionDraftCommitPayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftDiscountAddPayload":{"o":{"f":{"discountAdded":"SubscriptionManualDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftDiscountCodeApplyPayload":{"o":{"f":{"appliedDiscount":"SubscriptionAppliedCodeDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftDiscountRemovePayload":{"o":{"f":{"discountRemoved":"SubscriptionDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftDiscountUpdatePayload":{"o":{"f":{"discountUpdated":"SubscriptionManualDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftErrorCode":{"e":["ALREADY_REMOVED","PRESENCE","COMMITTED","NOT_IN_RANGE","NOT_AN_INTEGER","SELLING_PLAN_MAX_CYCLES_MUST_BE_GREATER_THAN_MIN_CYCLES","DELIVERY_MUST_BE_MULTIPLE_OF_BILLING","INVALID_BILLING_DATE","INVALID_NOTE_LENGTH","INVALID_LINES","NO_ENTITLED_LINES","CUSTOMER_DOES_NOT_EXIST","CUSTOMER_MISMATCH","DELIVERY_METHOD_REQUIRED","MISSING_LOCAL_DELIVERY_OPTIONS","CYCLE_DISCOUNTS_UNIQUE_AFTER_CYCLE","INVALID_ADJUSTMENT_TYPE","INVALID_ADJUSTMENT_VALUE","STALE_CONTRACT","TOO_MANY_LINES","TOO_MANY_DISCOUNTS","CURRENCY_NOT_ENABLED","HAS_FUTURE_EDITS","BILLING_CYCLE_PRESENT","BILLING_CYCLE_ABSENT","BILLING_CYCLE_CONTRACT_DRAFT_DELIVERY_POLICY_INVALID","BILLING_CYCLE_CONTRACT_DRAFT_BILLING_POLICY_INVALID","CONCATENATION_BILLING_CYCLE_CONTRACT_DRAFT_REQUIRED","CONCATENATION_UNCOMMITTED_CONTRACT_DRAFT","DUPLICATE_CONCATENATED_CONTRACTS","UPCOMING_CYCLE_LIMIT_EXCEEDED","CYCLE_INDEX_OUT_OF_RANGE","CYCLE_START_DATE_OUT_OF_RANGE","CYCLE_SELECTOR_VALIDATE_ONE_OF","EXCEEDED_MAX_CONCATENATED_CONTRACTS","CUSTOMER_REDACTED","MISSING_CUSTOMER_PAYMENT_METHOD","INVALID","BLANK","GREATER_THAN","GREATER_THAN_OR_EQUAL_TO","LESS_THAN","LESS_THAN_OR_EQUAL_TO","TOO_LONG","TOO_SHORT"]}, +"SubscriptionDraftFreeShippingDiscountAddPayload":{"o":{"f":{"discountAdded":"SubscriptionManualDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftFreeShippingDiscountUpdatePayload":{"o":{"f":{"discountUpdated":"SubscriptionManualDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftInput":{"i":{"billingPolicy":"SubscriptionBillingPolicyInput","customAttributes":"[AttributeInput!]","deliveryMethod":"SubscriptionDeliveryMethodInput","deliveryPolicy":"SubscriptionDeliveryPolicyInput","deliveryPrice":"Decimal","nextBillingDate":"DateTime","note":"String","paymentMethodId":"ID","status":"SubscriptionContractSubscriptionStatus"}}, +"SubscriptionDraftLineAddPayload":{"o":{"f":{"draft":"SubscriptionDraft","lineAdded":"SubscriptionLine","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftLineRemovePayload":{"o":{"f":{"discountsUpdated":"[SubscriptionManualDiscount!]","draft":"SubscriptionDraft","lineRemoved":"SubscriptionLine","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftLineUpdatePayload":{"o":{"f":{"draft":"SubscriptionDraft","lineUpdated":"SubscriptionLine","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftUpdatePayload":{"o":{"f":{"draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftUserError":{"o":{"f":{"code":"SubscriptionDraftErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionFreeShippingDiscountInput":{"i":{"recurringCycleLimit":"Int","title":"String"}}, +"SubscriptionGroupedLine":{"u":["SubscriptionLine","SubscriptionParentLine"]}, +"SubscriptionGroupedLineConnection":{"o":{"f":{"edges":"[SubscriptionGroupedLineEdge!]!","nodes":"[SubscriptionGroupedLine!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionGroupedLineEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionGroupedLine!"}}}, +"SubscriptionLine":{"o":{"f":{"concatenatedOriginContract":"SubscriptionContract","currentPrice":"MoneyV2!","customAttributes":"[Attribute!]!","discountAllocations":"[SubscriptionDiscountAllocation!]!","id":"ID!","lineDiscountedPrice":"MoneyV2!","pricingPolicy":"SubscriptionPricingPolicy","productId":"ID","quantity":"Int!","requiresShipping":"Boolean!","sellingPlanId":"ID","sellingPlanName":"String","sku":"String","taxable":"Boolean!","title":"String!","variantId":"ID","variantImage":"Image","variantTitle":"String","weight":"Weight"}}}, +"SubscriptionLineConnection":{"o":{"f":{"edges":"[SubscriptionLineEdge!]!","nodes":"[SubscriptionLine!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionLineEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionLine!"}}}, +"SubscriptionLineInput":{"i":{"currentPrice":"Decimal!","customAttributes":"[AttributeInput!]","pricingPolicy":"SubscriptionPricingPolicyInput","productVariantId":"ID!","quantity":"Int!","sellingPlanId":"ID","sellingPlanName":"String"}}, +"SubscriptionLineUpdateInput":{"i":{"currentPrice":"Decimal","customAttributes":"[AttributeInput!]","pricingPolicy":"SubscriptionPricingPolicyInput","productVariantId":"ID","quantity":"Int","sellingPlanId":"ID","sellingPlanName":"String"}}, +"SubscriptionLocalDeliveryOption":{"o":{"f":{"code":"String!","description":"String","phoneRequired":"Boolean!","presentmentTitle":"String","price":"MoneyV2","title":"String!"}}}, +"SubscriptionManualDiscount":{"o":{"f":{"entitledLines":"SubscriptionDiscountEntitledLines!","id":"ID!","recurringCycleLimit":"Int","rejectionReason":"SubscriptionDiscountRejectionReason","targetType":"DiscountTargetType!","title":"String","type":"DiscountType!","usageCount":"Int!","value":"SubscriptionDiscountValue!"}}}, +"SubscriptionManualDiscountConnection":{"o":{"f":{"edges":"[SubscriptionManualDiscountEdge!]!","nodes":"[SubscriptionManualDiscount!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionManualDiscountEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionManualDiscount!"}}}, +"SubscriptionManualDiscountEntitledLinesInput":{"i":{"all":"Boolean","lines":"SubscriptionManualDiscountLinesInput"}}, +"SubscriptionManualDiscountFixedAmountInput":{"i":{"amount":"Float","appliesOnEachItem":"Boolean"}}, +"SubscriptionManualDiscountInput":{"i":{"entitledLines":"SubscriptionManualDiscountEntitledLinesInput","recurringCycleLimit":"Int","title":"String","value":"SubscriptionManualDiscountValueInput"}}, +"SubscriptionManualDiscountLinesInput":{"i":{"add":"[ID!]","remove":"[ID!]"}}, +"SubscriptionManualDiscountValueInput":{"i":{"fixedAmount":"SubscriptionManualDiscountFixedAmountInput","percentage":"Int"}}, +"SubscriptionParentLine":{"o":{"f":{"bundledBy":"App","components":"[SubscriptionLine!]!","customAttributes":"[Attribute!]!","id":"ID!","presentmentTitle":"String","productId":"ID","quantity":"Int!","sourceType":"String","title":"String!","variantId":"ID"}}}, +"SubscriptionPickupOption":{"o":{"f":{"code":"String!","description":"String","location":"Location!","phoneRequired":"Boolean!","pickupTime":"String!","presentmentTitle":"String","price":"MoneyV2","title":"String!"}}}, +"SubscriptionPricingPolicy":{"o":{"f":{"basePrice":"MoneyV2!","cycleDiscounts":"[SubscriptionCyclePriceAdjustment!]!"}}}, +"SubscriptionPricingPolicyCycleDiscountsInput":{"i":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyValueInput!","afterCycle":"Int!","computedPrice":"Decimal!"}}, +"SubscriptionPricingPolicyInput":{"i":{"basePrice":"Decimal!","cycleDiscounts":"[SubscriptionPricingPolicyCycleDiscountsInput!]!"}}, +"SubscriptionShippingOption":{"o":{"f":{"carrierService":"DeliveryCarrierService","code":"String!","description":"String","phoneRequired":"Boolean","presentmentTitle":"String","price":"MoneyV2","title":"String!"},"d":{"carrierService":"This field has never been implemented."}}}, +"SubscriptionShippingOptionResult":{"u":["SubscriptionShippingOptionResultFailure","SubscriptionShippingOptionResultSuccess"]}, +"SubscriptionShippingOptionResultFailure":{"o":{"f":{"message":"String"}}}, +"SubscriptionShippingOptionResultSuccess":{"o":{"f":{"shippingOptions":"[SubscriptionShippingOption!]!"}}}, +"SuggestedOrderTransaction":{"o":{"f":{"accountNumber":"String","amount":"Money!","amountSet":"MoneyBag!","formattedGateway":"String","gateway":"String","kind":"SuggestedOrderTransactionKind!","maximumRefundable":"Money","maximumRefundableSet":"MoneyBag","parentTransaction":"OrderTransaction","paymentDetails":"PaymentDetails"},"d":{"amount":"Use `amountSet` instead.","maximumRefundable":"Use `maximumRefundableSet` instead."}}}, +"SuggestedOrderTransactionKind":{"e":["SUGGESTED_REFUND"]}, +"SuggestedOutcomeExchangeLineItemInput":{"i":{"id":"ID!","quantity":"Int!"}}, +"SuggestedOutcomeReturnLineItemInput":{"i":{"id":"ID!","quantity":"Int!"}}, +"SuggestedRefund":{"o":{"f":{"amount":"Money!","amountSet":"MoneyBag!","discountedSubtotalSet":"MoneyBag!","maximumRefundable":"Money!","maximumRefundableSet":"MoneyBag!","refundDuties":"[RefundDuty!]!","refundLineItems":"[RefundLineItem!]!","shipping":"ShippingRefund!","subtotal":"Money!","subtotalSet":"MoneyBag!","suggestedRefundMethods":"[SuggestedRefundMethod!]!","suggestedTransactions":"[SuggestedOrderTransaction!]!","totalCartDiscountAmountSet":"MoneyBag!","totalDutiesSet":"MoneyBag!","totalTaxSet":"MoneyBag!","totalTaxes":"Money!"},"d":{"amount":"Use `amountSet` instead.","maximumRefundable":"Use `maximumRefundableSet` instead.","subtotal":"Use `subtotalSet` instead.","totalTaxes":"Use `totalTaxSet` instead."}}}, +"SuggestedRefundMethod":{"n":{"f":{"amount":"MoneyBag!","maximumRefundable":"MoneyBag!"},"t":["SuggestedStoreCreditRefund"]}}, +"SuggestedReturnFinancialOutcome":{"o":{"f":{"discountedSubtotal":"MoneyBag!","financialTransfer":"ReturnOutcomeFinancialTransfer","maximumRefundable":"MoneyBag!","refundDuties":"[RefundDuty!]!","shipping":"ShippingRefund!","totalAdditionalFees":"MoneyBag!","totalCartDiscountAmount":"MoneyBag!","totalDuties":"MoneyBag!","totalTax":"MoneyBag!"}}}, +"SuggestedReturnRefund":{"o":{"f":{"amount":"MoneyBag!","discountedSubtotal":"MoneyBag!","maximumRefundable":"MoneyBag!","refundDuties":"[RefundDuty!]!","shipping":"ShippingRefund!","subtotal":"MoneyBag!","suggestedTransactions":"[SuggestedOrderTransaction!]!","totalCartDiscountAmount":"MoneyBag!","totalDuties":"MoneyBag!","totalTax":"MoneyBag!"}}}, +"SuggestedStoreCreditRefund":{"o":{"f":{"amount":"MoneyBag!","expiresAt":"DateTime","maximumRefundable":"MoneyBag!"},"t":["SuggestedRefundMethod"]}}, +"TagsAddPayload":{"o":{"f":{"node":"Node","userErrors":"[UserError!]!"}}}, +"TagsRemovePayload":{"o":{"f":{"node":"Node","userErrors":"[UserError!]!"}}}, +"TaxAppConfiguration":{"o":{"f":{"state":"TaxPartnerState!"}}}, +"TaxAppConfigurePayload":{"o":{"f":{"taxAppConfiguration":"TaxAppConfiguration","userErrors":"[TaxAppConfigureUserError!]!"}}}, +"TaxAppConfigureUserError":{"o":{"f":{"code":"TaxAppConfigureUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"TaxAppConfigureUserErrorCode":{"e":["TAX_PARTNER_NOT_FOUND","TAX_PARTNER_STATE_UPDATE_FAILED","TAX_PARTNER_ALREADY_ACTIVE"]}, +"TaxExemption":{"e":["CA_STATUS_CARD_EXEMPTION","CA_BC_RESELLER_EXEMPTION","CA_MB_RESELLER_EXEMPTION","CA_SK_RESELLER_EXEMPTION","CA_SK_VPT_RESELLER_EXEMPTION","CA_NL_VPT_RESELLER_EXEMPTION","CA_DIPLOMAT_EXEMPTION","CA_BC_COMMERCIAL_FISHERY_EXEMPTION","CA_MB_COMMERCIAL_FISHERY_EXEMPTION","CA_NS_COMMERCIAL_FISHERY_EXEMPTION","CA_PE_COMMERCIAL_FISHERY_EXEMPTION","CA_SK_COMMERCIAL_FISHERY_EXEMPTION","CA_BC_PRODUCTION_AND_MACHINERY_EXEMPTION","CA_SK_PRODUCTION_AND_MACHINERY_EXEMPTION","CA_BC_SUB_CONTRACTOR_EXEMPTION","CA_SK_SUB_CONTRACTOR_EXEMPTION","CA_BC_CONTRACTOR_EXEMPTION","CA_SK_CONTRACTOR_EXEMPTION","CA_ON_PURCHASE_EXEMPTION","CA_MB_FARMER_EXEMPTION","CA_NS_FARMER_EXEMPTION","CA_SK_FARMER_EXEMPTION","EU_REVERSE_CHARGE_EXEMPTION_RULE","US_AL_RESELLER_EXEMPTION","US_AK_RESELLER_EXEMPTION","US_AZ_RESELLER_EXEMPTION","US_AR_RESELLER_EXEMPTION","US_CA_RESELLER_EXEMPTION","US_CO_RESELLER_EXEMPTION","US_CT_RESELLER_EXEMPTION","US_DE_RESELLER_EXEMPTION","US_FL_RESELLER_EXEMPTION","US_GA_RESELLER_EXEMPTION","US_HI_RESELLER_EXEMPTION","US_ID_RESELLER_EXEMPTION","US_IL_RESELLER_EXEMPTION","US_IN_RESELLER_EXEMPTION","US_IA_RESELLER_EXEMPTION","US_KS_RESELLER_EXEMPTION","US_KY_RESELLER_EXEMPTION","US_LA_RESELLER_EXEMPTION","US_ME_RESELLER_EXEMPTION","US_MD_RESELLER_EXEMPTION","US_MA_RESELLER_EXEMPTION","US_MI_RESELLER_EXEMPTION","US_MN_RESELLER_EXEMPTION","US_MS_RESELLER_EXEMPTION","US_MO_RESELLER_EXEMPTION","US_MT_RESELLER_EXEMPTION","US_NE_RESELLER_EXEMPTION","US_NV_RESELLER_EXEMPTION","US_NH_RESELLER_EXEMPTION","US_NJ_RESELLER_EXEMPTION","US_NM_RESELLER_EXEMPTION","US_NY_RESELLER_EXEMPTION","US_NC_RESELLER_EXEMPTION","US_ND_RESELLER_EXEMPTION","US_OH_RESELLER_EXEMPTION","US_OK_RESELLER_EXEMPTION","US_OR_RESELLER_EXEMPTION","US_PA_RESELLER_EXEMPTION","US_RI_RESELLER_EXEMPTION","US_SC_RESELLER_EXEMPTION","US_SD_RESELLER_EXEMPTION","US_TN_RESELLER_EXEMPTION","US_TX_RESELLER_EXEMPTION","US_UT_RESELLER_EXEMPTION","US_VT_RESELLER_EXEMPTION","US_VA_RESELLER_EXEMPTION","US_WA_RESELLER_EXEMPTION","US_WV_RESELLER_EXEMPTION","US_WI_RESELLER_EXEMPTION","US_WY_RESELLER_EXEMPTION","US_DC_RESELLER_EXEMPTION"]}, +"TaxLine":{"o":{"f":{"channelLiable":"Boolean","price":"Money!","priceSet":"MoneyBag!","rate":"Float","ratePercentage":"Float","source":"String","title":"String!"},"d":{"price":"Use `priceSet` instead."}}}, +"TaxPartnerState":{"e":["PENDING","READY","ACTIVE"]}, +"TaxSettings":{"o":{"f":{"taxId":"String"}}}, +"TaxSummaryCreatePayload":{"o":{"f":{"enqueuedOrders":"[Order!]","userErrors":"[TaxSummaryCreateUserError!]!"}}}, +"TaxSummaryCreateUserError":{"o":{"f":{"code":"TaxSummaryCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"TaxSummaryCreateUserErrorCode":{"e":["ORDER_NOT_FOUND","GENERAL_ERROR"]}, +"Taxonomy":{"o":{"f":{"categories":["TaxonomyCategoryConnection!",{"after":"String","before":"String","childrenOf":"ID","descendantsOf":"ID","first":"Int","last":"Int","search":"String","siblingsOf":"ID"}]}}}, +"TaxonomyAttribute":{"o":{"f":{"id":"ID!"},"t":["Node"]}}, +"TaxonomyCategory":{"o":{"f":{"ancestorIds":"[ID!]!","attributes":["TaxonomyCategoryAttributeConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}],"childrenIds":"[ID!]!","fullName":"String!","id":"ID!","isArchived":"Boolean!","isLeaf":"Boolean!","isRoot":"Boolean!","level":"Int!","name":"String!","parentId":"ID"},"t":["Node"]}}, +"TaxonomyCategoryAttribute":{"u":["TaxonomyAttribute","TaxonomyChoiceListAttribute","TaxonomyMeasurementAttribute"]}, +"TaxonomyCategoryAttributeConnection":{"o":{"f":{"edges":"[TaxonomyCategoryAttributeEdge!]!","nodes":"[TaxonomyCategoryAttribute!]!","pageInfo":"PageInfo!"}}}, +"TaxonomyCategoryAttributeEdge":{"o":{"f":{"cursor":"String!","node":"TaxonomyCategoryAttribute!"}}}, +"TaxonomyCategoryConnection":{"o":{"f":{"edges":"[TaxonomyCategoryEdge!]!","nodes":"[TaxonomyCategory!]!","pageInfo":"PageInfo!"}}}, +"TaxonomyCategoryEdge":{"o":{"f":{"cursor":"String!","node":"TaxonomyCategory!"}}}, +"TaxonomyChoiceListAttribute":{"o":{"f":{"id":"ID!","name":"String!","values":["TaxonomyValueConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}]},"t":["Node"]}}, +"TaxonomyMeasurementAttribute":{"o":{"f":{"id":"ID!","name":"String!","options":"[Attribute!]!"},"t":["Node"]}}, +"TaxonomyValue":{"o":{"f":{"id":"ID!","name":"String!"},"t":["Node"]}}, +"TaxonomyValueConnection":{"o":{"f":{"edges":"[TaxonomyValueEdge!]!","nodes":"[TaxonomyValue!]!","pageInfo":"PageInfo!"}}}, +"TaxonomyValueEdge":{"o":{"f":{"cursor":"String!","node":"TaxonomyValue!"}}}, +"TenderTransaction":{"o":{"f":{"amount":"MoneyV2!","id":"ID!","order":"Order","paymentMethod":"String","processedAt":"DateTime","remoteReference":"String","test":"Boolean!","transactionDetails":"TenderTransactionDetails","user":"StaffMember"},"t":["Node"]}}, +"TenderTransactionConnection":{"o":{"f":{"edges":"[TenderTransactionEdge!]!","nodes":"[TenderTransaction!]!","pageInfo":"PageInfo!"}}}, +"TenderTransactionCreditCardDetails":{"o":{"f":{"creditCardCompany":"String","creditCardNumber":"String"}}}, +"TenderTransactionDetails":{"u":["TenderTransactionCreditCardDetails"]}, +"TenderTransactionEdge":{"o":{"f":{"cursor":"String!","node":"TenderTransaction!"}}}, +"ThemeCreatePayload":{"o":{"f":{"theme":"OnlineStoreTheme","userErrors":"[ThemeCreateUserError!]!"}}}, +"ThemeCreateUserError":{"o":{"f":{"code":"ThemeCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ThemeCreateUserErrorCode":{"e":["INVALID_ZIP","ZIP_IS_EMPTY","ZIP_TOO_LARGE","THEME_CREATION_NOT_ALLOWED_FOR_THEME_LIMITED_PLAN","INVALID_THEME_ROLE_FOR_THEME_CREATION"]}, +"ThemeDeletePayload":{"o":{"f":{"deletedThemeId":"ID","userErrors":"[ThemeDeleteUserError!]!"}}}, +"ThemeDeleteUserError":{"o":{"f":{"code":"ThemeDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ThemeDeleteUserErrorCode":{"e":["NOT_FOUND"]}, +"ThemeDuplicatePayload":{"o":{"f":{"newTheme":"OnlineStoreTheme","userErrors":"[ThemeDuplicateUserError!]!"}}}, +"ThemeDuplicateUserError":{"o":{"f":{"code":"ThemeDuplicateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ThemeDuplicateUserErrorCode":{"e":["NOT_FOUND"]}, +"ThemeFilesCopyFileInput":{"i":{"dstFilename":"String!","srcFilename":"String!"}}, +"ThemeFilesCopyPayload":{"o":{"f":{"copiedThemeFiles":"[OnlineStoreThemeFileOperationResult!]","userErrors":"[OnlineStoreThemeFilesUserErrors!]!"}}}, +"ThemeFilesDeletePayload":{"o":{"f":{"deletedThemeFiles":"[OnlineStoreThemeFileOperationResult!]","userErrors":"[OnlineStoreThemeFilesUserErrors!]!"}}}, +"ThemeFilesUpsertPayload":{"o":{"f":{"job":"Job","upsertedThemeFiles":"[OnlineStoreThemeFileOperationResult!]","userErrors":"[OnlineStoreThemeFilesUserErrors!]!"}}}, +"ThemePublishPayload":{"o":{"f":{"theme":"OnlineStoreTheme","userErrors":"[ThemePublishUserError!]!"}}}, +"ThemePublishUserError":{"o":{"f":{"code":"ThemePublishUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ThemePublishUserErrorCode":{"e":["NOT_FOUND","CANNOT_PUBLISH_THEME_DURING_INSTALL","THEME_PUBLISH_NOT_AVAILABLE_FOR_THEME_LIMITED_PLAN"]}, +"ThemeRole":{"e":{"v":["MAIN","UNPUBLISHED","DEMO","DEVELOPMENT","ARCHIVED","LOCKED","MOBILE"],"d":{"MOBILE":"The feature for this role has been deprecated."}}}, +"ThemeUpdatePayload":{"o":{"f":{"theme":"OnlineStoreTheme","userErrors":"[ThemeUpdateUserError!]!"}}}, +"ThemeUpdateUserError":{"o":{"f":{"code":"ThemeUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ThemeUpdateUserErrorCode":{"e":["NOT_FOUND","TOO_LONG","INVALID"]}, +"TipSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineItem":"LineItem!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"TransactionFee":{"o":{"f":{"amount":"MoneyV2!","createdAt":"DateTime!","flatFee":"MoneyV2!","flatFeeName":"String","id":"ID!","rate":"Decimal!","rateName":"String","taxAmount":"MoneyV2!","type":"String!"},"t":["Node"]}}, +"TransactionSortKeys":{"e":["CREATED_AT","EXPIRES_AT"]}, +"TransactionVoidPayload":{"o":{"f":{"transaction":"OrderTransaction","userErrors":"[TransactionVoidUserError!]!"}}}, +"TransactionVoidUserError":{"o":{"f":{"code":"TransactionVoidUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"TransactionVoidUserErrorCode":{"e":["TRANSACTION_NOT_FOUND","AUTH_NOT_SUCCESSFUL","AUTH_NOT_VOIDABLE","GENERIC_ERROR"]}, +"TransferSortKeys":{"e":["CREATED_AT","DESTINATION_NAME","EXPECTED_SHIPMENT_ARRIVAL","ID","NAME","ORIGIN_NAME","SOURCE_NAME","STATUS"]}, +"TranslatableContent":{"o":{"f":{"digest":"String","key":"String!","locale":"String!","type":"LocalizableContentType!","value":"String"}}}, +"TranslatableResource":{"o":{"f":{"nestedTranslatableResources":["TranslatableResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","resourceType":"TranslatableResourceType","reverse":"Boolean="}],"resourceId":"ID!","translatableContent":["[TranslatableContent!]!",{"marketId":"ID"}],"translations":["[Translation!]!",{"locale":"String!","marketId":"ID","outdated":"Boolean"}]}}}, +"TranslatableResourceConnection":{"o":{"f":{"edges":"[TranslatableResourceEdge!]!","nodes":"[TranslatableResource!]!","pageInfo":"PageInfo!"}}}, +"TranslatableResourceEdge":{"o":{"f":{"cursor":"String!","node":"TranslatableResource!"}}}, +"TranslatableResourceType":{"e":{"v":["ARTICLE","ARTICLE_IMAGE","BLOG","COLLECTION","COLLECTION_IMAGE","DELIVERY_METHOD_DEFINITION","EMAIL_TEMPLATE","FILTER","LINK","MEDIA_IMAGE","MENU","METAFIELD","METAOBJECT","ONLINE_STORE_THEME","ONLINE_STORE_THEME_APP_EMBED","ONLINE_STORE_THEME_JSON_TEMPLATE","ONLINE_STORE_THEME_LOCALE_CONTENT","ONLINE_STORE_THEME_SECTION_GROUP","ONLINE_STORE_THEME_SETTINGS_CATEGORY","ONLINE_STORE_THEME_SETTINGS_DATA_SECTIONS","PACKING_SLIP_TEMPLATE","PAGE","PAYMENT_GATEWAY","PRODUCT","PRODUCT_OPTION","PRODUCT_OPTION_VALUE","SELLING_PLAN","SELLING_PLAN_GROUP","SHOP","SHOP_POLICY"],"d":{"METAFIELD":"Query metafields via their respective resource owners and use `Metafield.translatable` to determine which is translatable."}}}, +"Translation":{"o":{"f":{"key":"String!","locale":"String!","market":"Market","outdated":"Boolean!","updatedAt":"DateTime","value":"String"}}}, +"TranslationErrorCode":{"e":{"v":["BLANK","INVALID","RESOURCE_NOT_FOUND","RESOURCE_NOT_TRANSLATABLE","TOO_MANY_KEYS_FOR_RESOURCE","INVALID_KEY_FOR_MODEL","FAILS_RESOURCE_VALIDATION","INVALID_TRANSLATABLE_CONTENT","INVALID_MARKET_LOCALIZABLE_CONTENT","INVALID_LOCALE_FOR_SHOP","INVALID_CODE","INVALID_FORMAT","MARKET_CUSTOM_CONTENT_NOT_ALLOWED","MARKET_DOES_NOT_EXIST","MARKET_LOCALE_CREATION_FAILED","RESOURCE_NOT_MARKET_CUSTOMIZABLE","INVALID_LOCALE_FOR_MARKET","INVALID_VALUE_FOR_HANDLE_TRANSLATION"],"d":{"INVALID_LOCALE_FOR_MARKET":"`invalid_locale_for_market` is deprecated because the creation of a locale that's specific to a market no longer needs to be tied to that market's URL."}}}, +"TranslationInput":{"i":{"key":"String!","locale":"String!","marketId":"ID","translatableContentDigest":"String!","value":"String!"}}, +"TranslationUserError":{"o":{"f":{"code":"TranslationErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"TranslationsRegisterPayload":{"o":{"f":{"translations":"[Translation!]","userErrors":"[TranslationUserError!]!"}}}, +"TranslationsRemovePayload":{"o":{"f":{"translations":"[Translation!]","userErrors":"[TranslationUserError!]!"}}}, +"TypedAttribute":{"o":{"f":{"key":"String!","value":"String!"}}}, +"URL":"s", +"UTMInput":{"i":{"campaign":"String!","medium":"String!","source":"String!"}}, +"UTMParameters":{"o":{"f":{"campaign":"String","content":"String","medium":"String","source":"String","term":"String"}}}, +"UniqueMetafieldValueInput":{"i":{"key":"String!","namespace":"String","value":"String!"}}, +"UnitPriceMeasurement":{"o":{"f":{"measuredType":"UnitPriceMeasurementMeasuredType","quantityUnit":"UnitPriceMeasurementMeasuredUnit","quantityValue":"Float!","referenceUnit":"UnitPriceMeasurementMeasuredUnit","referenceValue":"Int!"}}}, +"UnitPriceMeasurementInput":{"i":{"quantityUnit":"UnitPriceMeasurementMeasuredUnit","quantityValue":"Float","referenceUnit":"UnitPriceMeasurementMeasuredUnit","referenceValue":"Int"}}, +"UnitPriceMeasurementMeasuredType":{"e":["VOLUME","WEIGHT","LENGTH","AREA","COUNT","UNKNOWN"]}, +"UnitPriceMeasurementMeasuredUnit":{"e":["ML","CL","L","M3","FLOZ","PT","QT","GAL","MG","G","KG","OZ","LB","MM","CM","M","IN","FT","YD","M2","FT2","ITEM","UNKNOWN"]}, +"UnitSystem":{"e":["IMPERIAL_SYSTEM","METRIC_SYSTEM"]}, +"UnknownSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"UnsignedInt64":"s", +"UnverifiedReturnLineItem":{"o":{"f":{"customerNote":"String","id":"ID!","processableQuantity":"Int!","processedQuantity":"Int!","quantity":"Int!","refundableQuantity":"Int!","refundedQuantity":"Int!","returnReason":"ReturnReason!","returnReasonDefinition":"ReturnReasonDefinition","returnReasonNote":"String!","unitPrice":"MoneyV2!","unprocessedQuantity":"Int!"},"t":["Node","ReturnLineItemType"],"d":{"returnReason":"Use `returnReasonDefinition` instead. This field will be removed in the future."}}}, +"UpdateMediaInput":{"i":{"alt":"String","id":"ID!","previewImageSource":"String"}}, +"UrlRedirect":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","path":"String!","target":"String!"},"t":["Node"]}}, +"UrlRedirectBulkDeleteAllPayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"UrlRedirectBulkDeleteByIdsPayload":{"o":{"f":{"job":"Job","userErrors":"[UrlRedirectBulkDeleteByIdsUserError!]!"}}}, +"UrlRedirectBulkDeleteByIdsUserError":{"o":{"f":{"code":"UrlRedirectBulkDeleteByIdsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UrlRedirectBulkDeleteByIdsUserErrorCode":{"e":["IDS_EMPTY"]}, +"UrlRedirectBulkDeleteBySavedSearchPayload":{"o":{"f":{"job":"Job","userErrors":"[UrlRedirectBulkDeleteBySavedSearchUserError!]!"}}}, +"UrlRedirectBulkDeleteBySavedSearchUserError":{"o":{"f":{"code":"UrlRedirectBulkDeleteBySavedSearchUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UrlRedirectBulkDeleteBySavedSearchUserErrorCode":{"e":["SAVED_SEARCH_NOT_FOUND","INVALID_SAVED_SEARCH_QUERY"]}, +"UrlRedirectBulkDeleteBySearchPayload":{"o":{"f":{"job":"Job","userErrors":"[UrlRedirectBulkDeleteBySearchUserError!]!"}}}, +"UrlRedirectBulkDeleteBySearchUserError":{"o":{"f":{"code":"UrlRedirectBulkDeleteBySearchUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UrlRedirectBulkDeleteBySearchUserErrorCode":{"e":["INVALID_SEARCH_ARGUMENT"]}, +"UrlRedirectConnection":{"o":{"f":{"edges":"[UrlRedirectEdge!]!","nodes":"[UrlRedirect!]!","pageInfo":"PageInfo!"}}}, +"UrlRedirectCreatePayload":{"o":{"f":{"urlRedirect":"UrlRedirect","userErrors":"[UrlRedirectUserError!]!"}}}, +"UrlRedirectDeletePayload":{"o":{"f":{"deletedUrlRedirectId":"ID","userErrors":"[UrlRedirectUserError!]!"}}}, +"UrlRedirectEdge":{"o":{"f":{"cursor":"String!","node":"UrlRedirect!"}}}, +"UrlRedirectErrorCode":{"e":["DOES_NOT_EXIST","CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED"]}, +"UrlRedirectImport":{"o":{"f":{"count":"Int","createdCount":"Int","failedCount":"Int","finished":"Boolean!","finishedAt":"DateTime","id":"ID!","previewRedirects":"[UrlRedirectImportPreview!]!","updatedCount":"Int"},"t":["Node"]}}, +"UrlRedirectImportCreatePayload":{"o":{"f":{"urlRedirectImport":"UrlRedirectImport","userErrors":"[UrlRedirectImportUserError!]!"}}}, +"UrlRedirectImportErrorCode":{"e":{"v":["FILE_DOES_NOT_EXIST","NOT_FOUND","ALREADY_IMPORTED","IN_PROGRESS"],"d":{"FILE_DOES_NOT_EXIST":"This error code is never returned"}}}, +"UrlRedirectImportPreview":{"o":{"f":{"path":"String!","target":"String!"}}}, +"UrlRedirectImportSubmitPayload":{"o":{"f":{"job":"Job","userErrors":"[UrlRedirectImportUserError!]!"}}}, +"UrlRedirectImportUserError":{"o":{"f":{"code":"UrlRedirectImportErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UrlRedirectInput":{"i":{"path":"String","target":"String"}}, +"UrlRedirectSortKeys":{"e":["ID","PATH","RELEVANCE"]}, +"UrlRedirectUpdatePayload":{"o":{"f":{"urlRedirect":"UrlRedirect","userErrors":"[UrlRedirectUserError!]!"}}}, +"UrlRedirectUserError":{"o":{"f":{"code":"UrlRedirectErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UserError":{"o":{"f":{"field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UtcOffset":"s", +"Validation":{"o":{"f":{"blockOnFailure":"Boolean!","enabled":"Boolean!","errorHistory":"FunctionsErrorHistory","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"shopifyFunction":"ShopifyFunction!","title":"String!"},"t":["HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"ValidationConnection":{"o":{"f":{"edges":"[ValidationEdge!]!","nodes":"[Validation!]!","pageInfo":"PageInfo!"}}}, +"ValidationCreateInput":{"i":{"f":{"blockOnFailure":"Boolean=","enable":"Boolean=","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]=","title":"String"},"d":{"functionId":"Use `functionHandle` instead."}}}, +"ValidationCreatePayload":{"o":{"f":{"userErrors":"[ValidationUserError!]!","validation":"Validation"}}}, +"ValidationDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[ValidationUserError!]!"}}}, +"ValidationEdge":{"o":{"f":{"cursor":"String!","node":"Validation!"}}}, +"ValidationSortKeys":{"e":["ID"]}, +"ValidationUpdateInput":{"i":{"blockOnFailure":"Boolean=","enable":"Boolean=","metafields":"[MetafieldInput!]=","title":"String"}}, +"ValidationUpdatePayload":{"o":{"f":{"userErrors":"[ValidationUserError!]!","validation":"Validation"}}}, +"ValidationUserError":{"o":{"f":{"code":"ValidationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ValidationUserErrorCode":{"e":["NOT_FOUND","FUNCTION_NOT_FOUND","CUSTOM_APP_FUNCTION_NOT_ELIGIBLE","FUNCTION_DOES_NOT_IMPLEMENT","PUBLIC_APP_NOT_ALLOWED","FUNCTION_PENDING_DELETION","MAX_VALIDATIONS_ACTIVATED","MISSING_FUNCTION_IDENTIFIER","MULTIPLE_FUNCTION_IDENTIFIERS","INVALID_TYPE","INVALID_VALUE","APP_NOT_AUTHORIZED","UNSTRUCTURED_RESERVED_NAMESPACE","DISALLOWED_OWNER_TYPE","INCLUSION","TAKEN","PRESENT","BLANK","TOO_LONG","TOO_SHORT","INVALID","CAPABILITY_VIOLATION","INTERNAL_ERROR"]}, +"VariantOptionValueInput":{"i":{"id":"ID","linkedMetafieldValue":"String","name":"String","optionId":"ID","optionName":"String"}}, +"VaultCreditCard":{"o":{"f":{"billingAddress":"CustomerCreditCardBillingAddress","brand":"String!","expired":"Boolean!","expiryMonth":"Int!","expiryYear":"Int!","lastDigits":"String!","name":"String!"}}}, +"VaultPaypalBillingAgreement":{"o":{"f":{"inactive":"Boolean!","name":"String!","paypalAccountEmail":"String!"}}}, +"Vector3":{"o":{"f":{"x":"Float!","y":"Float!","z":"Float!"}}}, +"Video":{"o":{"f":{"alt":"String","createdAt":"DateTime!","duration":"Int","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","filename":"String!","id":"ID!","mediaContentType":"MediaContentType!","mediaErrors":"[MediaError!]!","mediaWarnings":"[MediaWarning!]!","originalSource":"VideoSource","preview":"MediaPreviewImage","sources":"[VideoSource!]!","status":"MediaStatus!","updatedAt":"DateTime!"},"t":["File","Media","Node"]}}, +"VideoSource":{"o":{"f":{"fileSize":"Int","format":"String!","height":"Int!","mimeType":"String!","url":"String!","width":"Int!"}}}, +"WebPixel":{"o":{"f":{"id":"ID!","settings":"JSON!"},"t":["Node"]}}, +"WebPixelCreatePayload":{"o":{"f":{"userErrors":"[ErrorsWebPixelUserError!]!","webPixel":"WebPixel"}}}, +"WebPixelDeletePayload":{"o":{"f":{"deletedWebPixelId":"ID","userErrors":"[ErrorsWebPixelUserError!]!"}}}, +"WebPixelInput":{"i":{"settings":"JSON!"}}, +"WebPixelUpdatePayload":{"o":{"f":{"userErrors":"[ErrorsWebPixelUserError!]!","webPixel":"WebPixel"}}}, +"WebPresenceCreateInput":{"i":{"alternateLocales":"[String!]","defaultLocale":"String!","domainId":"ID","subfolderSuffix":"String"}}, +"WebPresenceCreatePayload":{"o":{"f":{"userErrors":"[MarketUserError!]!","webPresence":"MarketWebPresence"}}}, +"WebPresenceDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[MarketUserError!]!"}}}, +"WebPresenceUpdateInput":{"i":{"alternateLocales":"[String!]","defaultLocale":"String","subfolderSuffix":"String"}}, +"WebPresenceUpdatePayload":{"o":{"f":{"userErrors":"[MarketUserError!]!","webPresence":"MarketWebPresence"}}}, +"WebhookEventBridgeEndpoint":{"o":{"f":{"arn":"ARN!"}}}, +"WebhookHttpEndpoint":{"o":{"f":{"callbackUrl":"URL!"}}}, +"WebhookPubSubEndpoint":{"o":{"f":{"pubSubProject":"String!","pubSubTopic":"String!"}}}, +"WebhookSubscription":{"o":{"f":{"apiVersion":"ApiVersion!","callbackUrl":"URL!","createdAt":"DateTime!","endpoint":"WebhookSubscriptionEndpoint!","filter":"String","format":"WebhookSubscriptionFormat!","id":"ID!","includeFields":"[String!]!","legacyResourceId":"UnsignedInt64!","metafieldNamespaces":"[String!]!","metafields":"[WebhookSubscriptionMetafieldIdentifier!]!","name":"String","topic":"WebhookSubscriptionTopic!","updatedAt":"DateTime!","uri":"String!"},"t":["LegacyInteroperability","Node"],"d":{"callbackUrl":"Use `uri` instead.","endpoint":"Use `uri` instead."}}}, +"WebhookSubscriptionConnection":{"o":{"f":{"edges":"[WebhookSubscriptionEdge!]!","nodes":"[WebhookSubscription!]!","pageInfo":"PageInfo!"}}}, +"WebhookSubscriptionCreatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"WebhookSubscriptionDeletePayload":{"o":{"f":{"deletedWebhookSubscriptionId":"ID","userErrors":"[UserError!]!"}}}, +"WebhookSubscriptionEdge":{"o":{"f":{"cursor":"String!","node":"WebhookSubscription!"}}}, +"WebhookSubscriptionEndpoint":{"u":["WebhookEventBridgeEndpoint","WebhookHttpEndpoint","WebhookPubSubEndpoint"]}, +"WebhookSubscriptionFormat":{"e":["JSON","XML"]}, +"WebhookSubscriptionInput":{"i":{"f":{"callbackUrl":"URL","filter":"String","format":"WebhookSubscriptionFormat","includeFields":"[String!]","metafieldNamespaces":"[String!]","metafields":"[HasMetafieldsMetafieldIdentifierInput!]","name":"String","uri":"String"},"d":{"callbackUrl":"Use `uri` instead."}}}, +"WebhookSubscriptionMetafieldIdentifier":{"o":{"f":{"key":"String!","namespace":"String!"}}}, +"WebhookSubscriptionSortKeys":{"e":["CREATED_AT","ID"]}, +"WebhookSubscriptionTopic":{"e":["TAX_SUMMARIES_CREATE","APP_UNINSTALLED","APP_SCOPES_UPDATE","CARTS_CREATE","CARTS_UPDATE","CHANNELS_DELETE","CHECKOUTS_CREATE","CHECKOUTS_DELETE","CHECKOUTS_UPDATE","CUSTOMER_PAYMENT_METHODS_CREATE","CUSTOMER_PAYMENT_METHODS_UPDATE","CUSTOMER_PAYMENT_METHODS_REVOKE","COLLECTION_LISTINGS_ADD","COLLECTION_LISTINGS_REMOVE","COLLECTION_LISTINGS_UPDATE","COLLECTION_PUBLICATIONS_CREATE","COLLECTION_PUBLICATIONS_DELETE","COLLECTION_PUBLICATIONS_UPDATE","COLLECTIONS_CREATE","COLLECTIONS_DELETE","COLLECTIONS_UPDATE","CUSTOMER_GROUPS_CREATE","CUSTOMER_GROUPS_DELETE","CUSTOMER_GROUPS_UPDATE","CUSTOMERS_CREATE","CUSTOMERS_DELETE","CUSTOMERS_DISABLE","CUSTOMERS_ENABLE","CUSTOMERS_UPDATE","CUSTOMERS_PURCHASING_SUMMARY","CUSTOMERS_MARKETING_CONSENT_UPDATE","CUSTOMERS_WHATS_APP_MARKETING_CONSENT_UPDATE","CUSTOMER_TAGS_ADDED","CUSTOMER_TAGS_REMOVED","CUSTOMERS_EMAIL_MARKETING_CONSENT_UPDATE","DISPUTES_CREATE","DISPUTES_UPDATE","DRAFT_ORDERS_CREATE","DRAFT_ORDERS_DELETE","DRAFT_ORDERS_UPDATE","FULFILLMENT_EVENTS_CREATE","FULFILLMENT_EVENTS_DELETE","FULFILLMENTS_CREATE","FULFILLMENTS_UPDATE","ATTRIBUTED_SESSIONS_FIRST","ATTRIBUTED_SESSIONS_LAST","ORDER_TRANSACTIONS_CREATE","ORDERS_CANCELLED","ORDERS_CREATE","ORDERS_DELETE","ORDERS_EDITED","ORDERS_FULFILLED","ORDERS_PAID","ORDERS_PARTIALLY_FULFILLED","ORDERS_UPDATED","ORDERS_LINK_REQUESTED","FULFILLMENT_ORDERS_MOVED","FULFILLMENT_ORDERS_HOLD_RELEASED","FULFILLMENT_ORDERS_SCHEDULED_FULFILLMENT_ORDER_READY","FULFILLMENT_HOLDS_RELEASED","FULFILLMENT_ORDERS_ORDER_ROUTING_COMPLETE","FULFILLMENT_ORDERS_CANCELLED","FULFILLMENT_ORDERS_FULFILLMENT_SERVICE_FAILED_TO_COMPLETE","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_REJECTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_SUBMITTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_ACCEPTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_REJECTED","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_SUBMITTED","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_ACCEPTED","FULFILLMENT_HOLDS_ADDED","FULFILLMENT_ORDERS_LINE_ITEMS_PREPARED_FOR_LOCAL_DELIVERY","FULFILLMENT_ORDERS_PLACED_ON_HOLD","FULFILLMENT_ORDERS_MERGED","FULFILLMENT_ORDERS_SPLIT","FULFILLMENT_ORDERS_PROGRESS_REPORTED","FULFILLMENT_ORDERS_MANUALLY_REPORTED_PROGRESS_STOPPED","PRODUCT_LISTINGS_ADD","PRODUCT_LISTINGS_REMOVE","PRODUCT_LISTINGS_UPDATE","SCHEDULED_PRODUCT_LISTINGS_ADD","SCHEDULED_PRODUCT_LISTINGS_UPDATE","SCHEDULED_PRODUCT_LISTINGS_REMOVE","PRODUCT_PUBLICATIONS_CREATE","PRODUCT_PUBLICATIONS_DELETE","PRODUCT_PUBLICATIONS_UPDATE","PRODUCTS_CREATE","PRODUCTS_DELETE","PRODUCTS_UPDATE","REFUNDS_CREATE","SEGMENTS_CREATE","SEGMENTS_DELETE","SEGMENTS_UPDATE","SHIPPING_ADDRESSES_CREATE","SHIPPING_ADDRESSES_UPDATE","SHOP_UPDATE","TAX_PARTNERS_UPDATE","TAX_SERVICES_CREATE","TAX_SERVICES_UPDATE","THEMES_CREATE","THEMES_DELETE","THEMES_PUBLISH","THEMES_UPDATE","VARIANTS_IN_STOCK","VARIANTS_OUT_OF_STOCK","INVENTORY_LEVELS_CONNECT","INVENTORY_LEVELS_UPDATE","INVENTORY_LEVELS_DISCONNECT","INVENTORY_ITEMS_CREATE","INVENTORY_ITEMS_UPDATE","INVENTORY_ITEMS_DELETE","LOCATIONS_ACTIVATE","LOCATIONS_DEACTIVATE","LOCATIONS_CREATE","LOCATIONS_UPDATE","LOCATIONS_DELETE","TENDER_TRANSACTIONS_CREATE","APP_PURCHASES_ONE_TIME_UPDATE","APP_SUBSCRIPTIONS_APPROACHING_CAPPED_AMOUNT","APP_SUBSCRIPTIONS_UPDATE","LOCALES_CREATE","LOCALES_UPDATE","LOCALES_DESTROY","MACHINE_TRANSLATION_BATCH_COMPLETED","DOMAINS_CREATE","DOMAINS_UPDATE","DOMAINS_DESTROY","SUBSCRIPTION_CONTRACTS_CREATE","SUBSCRIPTION_CONTRACTS_UPDATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_CREATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_UPDATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_DELETE","PROFILES_CREATE","PROFILES_UPDATE","PROFILES_DELETE","SUBSCRIPTION_BILLING_ATTEMPTS_SUCCESS","SUBSCRIPTION_BILLING_ATTEMPTS_FAILURE","SUBSCRIPTION_BILLING_ATTEMPTS_CHALLENGED","RETURNS_CANCEL","RETURNS_CLOSE","RETURNS_REOPEN","RETURNS_REQUEST","RETURNS_APPROVE","RETURNS_UPDATE","RETURNS_PROCESS","RETURNS_DECLINE","REVERSE_DELIVERIES_ATTACH_DELIVERABLE","REVERSE_FULFILLMENT_ORDERS_DISPOSE","PAYMENT_TERMS_CREATE","PAYMENT_TERMS_DELETE","PAYMENT_TERMS_UPDATE","PAYMENT_SCHEDULES_DUE","SELLING_PLAN_GROUPS_CREATE","SELLING_PLAN_GROUPS_UPDATE","SELLING_PLAN_GROUPS_DELETE","BULK_OPERATIONS_FINISH","PRODUCT_FEEDS_CREATE","PRODUCT_FEEDS_UPDATE","PRODUCT_FEEDS_INCREMENTAL_SYNC","PRODUCT_FEEDS_FULL_SYNC","PRODUCT_FEEDS_FULL_SYNC_FINISH","MARKETS_CREATE","MARKETS_UPDATE","MARKETS_DELETE","ORDERS_RISK_ASSESSMENT_CHANGED","ORDERS_SHOPIFY_PROTECT_ELIGIBILITY_CHANGED","FINANCE_KYC_INFORMATION_UPDATE","FULFILLMENT_ORDERS_RESCHEDULED","PUBLICATIONS_DELETE","AUDIT_EVENTS_ADMIN_API_ACTIVITY","FULFILLMENT_ORDERS_LINE_ITEMS_PREPARED_FOR_PICKUP","COMPANIES_CREATE","COMPANIES_UPDATE","COMPANIES_DELETE","COMPANY_LOCATIONS_CREATE","COMPANY_LOCATIONS_UPDATE","COMPANY_LOCATIONS_DELETE","COMPANY_CONTACTS_CREATE","COMPANY_CONTACTS_UPDATE","COMPANY_CONTACTS_DELETE","CUSTOMERS_MERGE","INVENTORY_TRANSFERS_ADD_ITEMS","INVENTORY_TRANSFERS_UPDATE_ITEM_QUANTITIES","INVENTORY_TRANSFERS_REMOVE_ITEMS","INVENTORY_TRANSFERS_READY_TO_SHIP","INVENTORY_TRANSFERS_CANCEL","INVENTORY_TRANSFERS_COMPLETE","INVENTORY_TRANSFERS_UPDATED","INVENTORY_SHIPMENTS_DELETE","INVENTORY_SHIPMENTS_CREATE","INVENTORY_SHIPMENTS_MARK_IN_TRANSIT","INVENTORY_SHIPMENTS_UPDATE_TRACKING","INVENTORY_SHIPMENTS_ADD_ITEMS","INVENTORY_SHIPMENTS_UPDATE_ITEM_QUANTITIES","INVENTORY_SHIPMENTS_REMOVE_ITEMS","INVENTORY_SHIPMENTS_RECEIVE_ITEMS","CUSTOMER_ACCOUNT_SETTINGS_UPDATE","CUSTOMER_JOINED_SEGMENT","CUSTOMER_LEFT_SEGMENT","COMPANY_CONTACT_ROLES_ASSIGN","COMPANY_CONTACT_ROLES_REVOKE","SUBSCRIPTION_CONTRACTS_ACTIVATE","SUBSCRIPTION_CONTRACTS_PAUSE","SUBSCRIPTION_CONTRACTS_CANCEL","SUBSCRIPTION_CONTRACTS_FAIL","SUBSCRIPTION_CONTRACTS_EXPIRE","SUBSCRIPTION_CONTRACT_CALCULATIONS_SUCCEED","SUBSCRIPTION_CONTRACT_CALCULATIONS_FAIL","SUBSCRIPTION_BILLING_CYCLES_SKIP","SUBSCRIPTION_BILLING_CYCLES_UNSKIP","METAOBJECTS_CREATE","METAOBJECTS_UPDATE","METAOBJECTS_DELETE","FINANCE_APP_STAFF_MEMBER_GRANT","FINANCE_APP_STAFF_MEMBER_REVOKE","FINANCE_APP_STAFF_MEMBER_DELETE","FINANCE_APP_STAFF_MEMBER_UPDATE","ROLLOUTS_CREATE","ROLLOUTS_DELETE","ROLLOUTS_RESOURCE_CHANGE_ADDED","ROLLOUTS_RESOURCE_CHANGE_REMOVED","ROLLOUTS_RESOURCE_CHANGE_UPDATED","ROLLOUTS_UPDATE","DISCOUNTS_CREATE","DISCOUNTS_UPDATE","DISCOUNTS_DELETE","DISCOUNTS_REDEEMCODE_ADDED","DISCOUNTS_REDEEMCODE_REMOVED","METAFIELD_DEFINITIONS_CREATE","METAFIELD_DEFINITIONS_UPDATE","METAFIELD_DEFINITIONS_DELETE","DELIVERY_PROMISE_SETTINGS_UPDATE","MARKETS_BACKUP_REGION_UPDATE","CHECKOUT_AND_ACCOUNTS_CONFIGURATIONS_UPDATE","REQUESTED_ORDER_EDIT_CREATED","REQUESTED_ORDER_EDIT_RESOLVED","REQUESTED_ORDER_EDIT_DECLINED"]}, +"WebhookSubscriptionUpdatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"Weight":{"o":{"f":{"unit":"WeightUnit!","value":"Float!"}}}, +"WeightInput":{"i":{"unit":"WeightUnit!","value":"Float!"}}, +"WeightUnit":{"e":["KILOGRAMS","GRAMS","POUNDS","OUNCES"]} +}} diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs new file mode 100644 index 0000000..29681e1 --- /dev/null +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -0,0 +1,1134 @@ +//! Checks a GraphQL operation against a schema and describes the shape of +//! its variables and of its result. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; + +use graphql_parser::Pos; +use graphql_parser::query as ast; + +use crate::schema::{Field, InputValue, Schema, TypeDef, TypeRef}; + +type Document<'a> = ast::Document<'a, String>; +type SelectionSet<'a> = ast::SelectionSet<'a, String>; +type Value<'a> = ast::Value<'a, String>; +type Directive<'a> = ast::Directive<'a, String>; + +/// An operation that does not parse or does not fit the schema. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Error { + pub message: String, + /// Line and column in the operation text, both starting at 1. + pub position: Option<(usize, usize)>, +} + +impl fmt::Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.position { + Some((line, column)) => { + write!(formatter, "{} (line {line}, column {column})", self.message) + } + None => formatter.write_str(&self.message), + } + } +} + +impl std::error::Error for Error {} + +type Result = std::result::Result; + +fn error_at(position: Pos, message: impl Into) -> Result { + Err(Error { + message: message.into(), + position: Some((position.line, position.column)), + }) +} + +fn error(message: impl Into) -> Result { + Err(Error { + message: message.into(), + position: None, + }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OperationKind { + Query, + Mutation, +} + +/// How a scalar travels in JSON. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum Scalar { + /// `String`, `ID`, enum values, and Shopify's string-encoded scalars such + /// as `DateTime`, `Decimal`, `Money`, `URL` and `UnsignedInt64`. + String, + Int, + Float, + Boolean, + /// `JSON`: any value. + Json, +} + +impl Scalar { + /// How the scalar, or the enum, of this name travels. + pub(crate) fn of(name: &str) -> Self { + match name { + "Int" => Self::Int, + "Float" => Self::Float, + "Boolean" => Self::Boolean, + "JSON" => Self::Json, + _ => Self::String, + } + } +} + +/// What a variable holds, lists and nullability set aside. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum VariableBase { + Scalar(Scalar), + Enum, + /// An input object, named by the variable's type. + Input, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Variable { + pub name: String, + pub ty: TypeRef, + pub has_default: bool, + pub base: VariableBase, +} + +impl Variable { + /// The operation cannot run without a value for this variable. + pub fn is_required(&self) -> bool { + self.ty.is_non_null() && !self.has_default + } +} + +/// The fields selected on an object, interface or union. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Selection { + pub type_name: String, + pub fields: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct SelectedField { + /// The key of the field in the response: its alias, or its name. + pub key: String, + pub ty: TypeRef, + /// The field may be absent: it is selected in a fragment that does not + /// always apply, or under `@include` / `@skip`. + pub conditional: bool, + pub base: FieldBase, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum FieldBase { + Scalar(Scalar), + Object(Selection), +} + +/// A deprecated field, argument, input field or enum value that an +/// operation uses. `graphql!` turns each one into a compiler warning. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Deprecation { + /// What is deprecated: `Product.bodyHtml`, `Collection.image(maxWidth:)`, + /// `CollectionInput.publications` or `OrderSortKeys.CREATED_AT`. + pub coordinate: String, + /// Shopify's reason, which usually names what replaces it. + pub reason: String, + /// Line and column in the operation text, both starting at 1. + pub position: (usize, usize), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Operation { + pub kind: OperationKind, + pub name: Option, + pub variables: Vec, + pub data: Selection, + /// What the operation uses that the schema deprecates, in the order of the text. + pub deprecations: Vec, +} + +/// Parses `source`, checks it against `schema` and returns its shape. +/// +/// `source` contains exactly one query or mutation, and the fragments it uses. +pub fn analyze(schema: &Schema, source: &str) -> Result { + let document: Document = match graphql_parser::parse_query(source) { + Ok(document) => document, + Err(parse_error) => { + let text = parse_error.to_string(); + let detail = text.strip_prefix("query parse error: ").unwrap_or(&text); + return error(format!( + "Invalid GraphQL: {}", + detail.trim().replace('\n', " ") + )); + } + }; + + let mut operations = Vec::new(); + let mut fragments = BTreeMap::new(); + for definition in &document.definitions { + match definition { + ast::Definition::Operation(operation) => operations.push(operation), + ast::Definition::Fragment(fragment) => { + if fragments.insert(fragment.name.as_str(), fragment).is_some() { + return error_at( + fragment.position, + format!("Fragment `{}` is defined twice", fragment.name), + ); + } + } + } + } + let operation = match operations.as_slice() { + [operation] => *operation, + [] => return error("The document contains no query or mutation"), + [_, second, ..] => { + return error_at( + operation_position(second), + "The document contains several operations; `graphql!` takes one", + ); + } + }; + + let (kind, name, definitions, directives, selection_set, position) = match operation { + ast::OperationDefinition::SelectionSet(set) => ( + OperationKind::Query, + None, + &[][..], + &[][..], + set, + set.span.0, + ), + ast::OperationDefinition::Query(query) => ( + OperationKind::Query, + query.name.clone(), + &query.variable_definitions[..], + &query.directives[..], + &query.selection_set, + query.position, + ), + ast::OperationDefinition::Mutation(mutation) => ( + OperationKind::Mutation, + mutation.name.clone(), + &mutation.variable_definitions[..], + &mutation.directives[..], + &mutation.selection_set, + mutation.position, + ), + ast::OperationDefinition::Subscription(subscription) => { + return error_at(subscription.position, "Subscriptions are not supported"); + } + }; + let root = match kind { + OperationKind::Query => schema.query.as_str(), + OperationKind::Mutation => match &schema.mutation { + Some(mutation) => mutation.as_str(), + None => return error_at(position, "The schema has no mutations"), + }, + }; + + let mut analyzer = Analyzer { + schema, + fragments, + variables: Vec::new(), + used_variables: BTreeSet::new(), + used_fragments: BTreeSet::new(), + fragment_stack: Vec::new(), + deprecations: Vec::new(), + }; + + for definition in definitions { + let ty = type_ref(&definition.var_type); + let base = match schema.get(ty.name()) { + Some(TypeDef::Scalar) => VariableBase::Scalar(Scalar::of(ty.name())), + Some(TypeDef::Enum { .. }) => VariableBase::Enum, + Some(TypeDef::Input { .. }) => VariableBase::Input, + Some(other) => { + return error_at( + definition.position, + format!( + "Variable `${}` cannot have the type `{ty}`: `{}` is {}, not an input type", + definition.name, + ty.name(), + other.kind_name() + ), + ); + } + None => { + return error_at( + definition.position, + format!( + "Variable `${}` has the unknown type `{}`{}", + definition.name, + ty.name(), + did_you_mean(ty.name(), schema.types.keys().map(String::as_str)) + ), + ); + } + }; + if analyzer + .variables + .iter() + .any(|declared| declared.name == definition.name) + { + return error_at( + definition.position, + format!("Variable `${}` is declared twice", definition.name), + ); + } + analyzer.variables.push(Variable { + name: definition.name.clone(), + ty: ty.clone(), + has_default: definition.default_value.is_some(), + base, + }); + if let Some(default) = &definition.default_value { + // The parser refuses a variable here. + let expected = InputValue::of(ty); + let place = format!("the default value of `${}`", definition.name); + analyzer.check_value(default, &expected, &place, definition.position)?; + } + } + + let location = match kind { + OperationKind::Query => "QUERY", + OperationKind::Mutation => "MUTATION", + }; + analyzer.check_directives(directives, location)?; + let data = analyzer.selection(root, &[(selection_set, false)], position)?; + + if let Some(unused) = analyzer + .variables + .iter() + .find(|variable| !analyzer.used_variables.contains(&variable.name)) + { + return error(format!( + "Variable `${}` is declared but never used", + unused.name + )); + } + if let Some((unused, fragment)) = analyzer + .fragments + .iter() + .find(|(name, _)| !analyzer.used_fragments.contains(**name)) + { + return error_at( + fragment.position, + format!("Fragment `{unused}` is defined but never used"), + ); + } + + let mut deprecations = analyzer.deprecations; + deprecations.sort_by(|left, right| { + (left.position, &left.coordinate).cmp(&(right.position, &right.coordinate)) + }); + deprecations.dedup(); + Ok(Operation { + kind, + name, + variables: analyzer.variables, + data, + deprecations, + }) +} + +fn operation_position(operation: &ast::OperationDefinition<'_, String>) -> Pos { + match operation { + ast::OperationDefinition::SelectionSet(set) => set.span.0, + ast::OperationDefinition::Query(query) => query.position, + ast::OperationDefinition::Mutation(mutation) => mutation.position, + ast::OperationDefinition::Subscription(subscription) => subscription.position, + } +} + +fn type_ref(ty: &ast::Type<'_, String>) -> TypeRef { + match ty { + ast::Type::NamedType(name) => TypeRef::Named(name.clone()), + ast::Type::ListType(inner) => TypeRef::List(Box::new(type_ref(inner))), + ast::Type::NonNullType(inner) => TypeRef::NonNull(Box::new(type_ref(inner))), + } +} + +/// A field being assembled from every place that selects its response key. +struct Pending<'a> { + key: String, + field: String, + ty: TypeRef, + /// The arguments, written the same way for every place that gives the same ones. + arguments: String, + /// The field may be absent from a value of the parent. + conditional: bool, + /// The subfields selected at each place, with whether that place may + /// be absent when the field is present. + sets: Vec<(&'a SelectionSet<'a>, bool)>, + /// The selections of the parent (see [`Analyzer::selection`]) that select + /// the field unconditionally. + unconditional_in: BTreeSet, + position: Pos, +} + +/// Which of the sets merged into one selection a field comes from. +#[derive(Clone, Copy)] +struct Place { + index: usize, + /// The set may be absent while the value is present. + uncertain: bool, +} + +/// The arguments of a field in one canonical text, to compare two places +/// that select the same response key. +fn arguments_key(arguments: &[(String, Value<'_>)]) -> String { + let mut written: Vec = arguments + .iter() + .map(|(name, value)| format!("{name}: {value}")) + .collect(); + written.sort(); + written.join(", ") +} + +struct Analyzer<'a> { + schema: &'a Schema, + fragments: BTreeMap<&'a str, &'a ast::FragmentDefinition<'a, String>>, + /// The declared variables, in the order of the operation. + variables: Vec, + used_variables: BTreeSet, + used_fragments: BTreeSet<&'a str>, + fragment_stack: Vec<&'a str>, + deprecations: Vec, +} + +impl<'a> Analyzer<'a> { + fn deprecated(&mut self, coordinate: String, reason: Option<&String>, position: Pos) { + if let Some(reason) = reason { + self.deprecations.push(Deprecation { + coordinate, + reason: reason.clone(), + position: (position.line, position.column), + }); + } + } + + /// Resolves the merged selection sets of one value of type `parent`. + /// + /// Each set comes with whether the place that selected it may be absent + /// while the value is present. When one place is always there, what the + /// others select is conditional. When none is, any of them may be the + /// one that is there: a subfield is then certain only if every place + /// selects it. + fn selection( + &mut self, + parent: &str, + sets: &[(&'a SelectionSet<'a>, bool)], + position: Pos, + ) -> Result { + let any_certain = sets.iter().any(|(_, conditional)| !conditional); + let mut pending = Vec::new(); + for (index, (set, conditional)) in sets.iter().enumerate() { + let place = Place { + index, + // Several places that may each be the one there: what each + // brings below its fields is only there with it. + uncertain: !any_certain && sets.len() > 1, + }; + self.collect( + parent, + set, + any_certain && *conditional, + place, + &mut pending, + )?; + } + if !any_certain && sets.len() > 1 { + for field in &mut pending { + field.conditional |= field.unconditional_in.len() < sets.len(); + } + } + if pending.is_empty() { + return error_at(position, format!("The selection on `{parent}` is empty")); + } + + let mut fields = Vec::new(); + for field in pending { + let named = field.ty.name(); + let base = match self.schema.get(named) { + Some(definition) if definition.is_composite() => { + if field.sets.is_empty() { + return error_at( + field.position, + format!( + "Field `{}` has the type `{}`: select the subfields you need, `{} {{ … }}`", + field.field, field.ty, field.field + ), + ); + } + FieldBase::Object(self.selection(named, &field.sets, field.position)?) + } + Some(_) => { + if !field.sets.is_empty() { + return error_at( + field.position, + format!( + "Field `{}` has the type `{}`, which has no subfields", + field.field, field.ty + ), + ); + } + FieldBase::Scalar(Scalar::of(named)) + } + None => { + return error_at( + field.position, + format!("The schema does not define the type `{named}`"), + ); + } + }; + fields.push(SelectedField { + key: field.key, + ty: field.ty, + conditional: field.conditional, + base, + }); + } + + Ok(Selection { + type_name: parent.to_string(), + fields, + }) + } + + /// Collects the fields `set` selects on `parent`, from `place` among + /// the sets [`Analyzer::selection`] merges. + fn collect( + &mut self, + parent: &str, + set: &'a SelectionSet<'a>, + conditional: bool, + place: Place, + pending: &mut Vec>, + ) -> Result<()> { + for item in &set.items { + match item { + ast::Selection::Field(field) => { + let conditional = + conditional | self.check_directives(&field.directives, "FIELD")?; + let ty = self.field_type(parent, field)?; + let key = field.alias.as_ref().unwrap_or(&field.name).clone(); + let arguments = arguments_key(&field.arguments); + let sets = (!field.selection_set.items.is_empty()) + .then_some((&field.selection_set, conditional || place.uncertain)); + + match pending.iter_mut().find(|existing| existing.key == key) { + Some(existing) => { + if existing.field != field.name || existing.ty != ty { + return error_at( + field.position, + format!( + "`{key}` is selected twice with different fields or types (`{}: {}` and `{}: {ty}`); give one of them an alias", + existing.field, existing.ty, field.name + ), + ); + } + if existing.arguments != arguments { + return error_at( + field.position, + format!( + "`{key}` is selected twice with different arguments (`({})` and `({arguments})`); give one of them an alias", + existing.arguments + ), + ); + } + existing.conditional &= conditional; + existing.sets.extend(sets); + if !conditional { + existing.unconditional_in.insert(place.index); + } + } + None => pending.push(Pending { + key, + field: field.name.clone(), + ty, + arguments, + conditional, + sets: sets.into_iter().collect(), + unconditional_in: (!conditional) + .then_some(place.index) + .into_iter() + .collect(), + position: field.position, + }), + } + } + ast::Selection::InlineFragment(fragment) => { + let conditional = conditional + | self.check_directives(&fragment.directives, "INLINE_FRAGMENT")?; + let (target, always) = match &fragment.type_condition { + Some(ast::TypeCondition::On(condition)) => ( + condition.as_str(), + self.fragment_always_applies(parent, condition, fragment.position)?, + ), + None => (parent, true), + }; + self.collect( + target, + &fragment.selection_set, + conditional | !always, + place, + pending, + )?; + } + ast::Selection::FragmentSpread(spread) => { + let conditional = conditional + | self.check_directives(&spread.directives, "FRAGMENT_SPREAD")?; + let name = spread.fragment_name.as_str(); + let Some(fragment) = self.fragments.get(name).copied() else { + return error_at( + spread.position, + format!( + "Fragment `{name}` is not defined{}; a `graphql!` document contains the fragments it uses", + did_you_mean(name, self.fragments.keys().copied()) + ), + ); + }; + if self.fragment_stack.contains(&name) { + return error_at( + spread.position, + format!("Fragment `{name}` includes itself"), + ); + } + self.used_fragments.insert(fragment.name.as_str()); + self.check_directives(&fragment.directives, "FRAGMENT_DEFINITION")?; + + let ast::TypeCondition::On(condition) = &fragment.type_condition; + let always = + self.fragment_always_applies(parent, condition, spread.position)?; + self.fragment_stack.push(fragment.name.as_str()); + let collected = self.collect( + condition, + &fragment.selection_set, + conditional | !always, + place, + pending, + ); + self.fragment_stack.pop(); + collected?; + } + } + } + Ok(()) + } + + /// Whether every value of type `parent` matches a fragment on `condition`. + /// Fails when none can. + fn fragment_always_applies( + &self, + parent: &str, + condition: &str, + position: Pos, + ) -> Result { + match self.schema.get(condition) { + Some(definition) if definition.is_composite() => {} + Some(definition) => { + return error_at( + position, + format!( + "A fragment cannot be on `{condition}`, which is {}", + definition.kind_name() + ), + ); + } + None => { + return error_at( + position, + format!( + "A fragment is on the unknown type `{condition}`{}", + did_you_mean(condition, self.schema.possible_types(parent).into_iter()) + ), + ); + } + } + let of_parent = self.schema.possible_types(parent); + let of_condition = self.schema.possible_types(condition); + if !of_parent.iter().any(|ty| of_condition.contains(ty)) { + return error_at( + position, + format!("A fragment on `{condition}` never applies to a `{parent}`"), + ); + } + Ok(of_parent.iter().all(|ty| of_condition.contains(ty))) + } + + /// The type of `field` on `parent`, after checking its arguments. + fn field_type(&mut self, parent: &str, field: &'a ast::Field<'a, String>) -> Result { + if field.name == "__typename" { + if let Some((argument, _)) = field.arguments.first() { + return error_at( + field.position, + format!("Field `__typename` has no argument `{argument}`"), + ); + } + return Ok(TypeRef::NonNull(Box::new(TypeRef::Named( + "String".to_string(), + )))); + } + + let fields = match self.schema.get(parent) { + Some(TypeDef::Object { fields, .. } | TypeDef::Interface { fields, .. }) => fields, + Some(TypeDef::Union { possible_types }) => { + return error_at( + field.position, + format!( + "`{parent}` is a union: select `{}` inside a fragment such as `... on {} {{ {} }}`", + field.name, + possible_types.first().map_or("Type", String::as_str), + field.name + ), + ); + } + _ => { + return error_at( + field.position, + format!("`{parent}` has no fields to select"), + ); + } + }; + let Some(definition) = fields.get(&field.name) else { + return error_at( + field.position, + format!( + "Type `{parent}` has no field `{}`{}", + field.name, + did_you_mean(&field.name, fields.keys().map(String::as_str)) + ), + ); + }; + self.deprecated( + format!("{parent}.{}", field.name), + definition.deprecation.as_ref(), + field.position, + ); + self.check_arguments(parent, field, definition)?; + Ok(definition.ty.clone()) + } + + fn check_arguments( + &mut self, + parent: &str, + field: &'a ast::Field<'a, String>, + definition: &Field, + ) -> Result<()> { + for (index, (name, value)) in field.arguments.iter().enumerate() { + if field.arguments[..index] + .iter() + .any(|(earlier, _)| earlier == name) + { + return error_at( + field.position, + format!( + "Field `{parent}.{}` is given the argument `{name}` twice", + field.name + ), + ); + } + let Some(argument) = definition.args.get(name) else { + return error_at( + field.position, + format!( + "Field `{parent}.{}` has no argument `{name}`{}", + field.name, + did_you_mean(name, definition.args.keys().map(String::as_str)) + ), + ); + }; + self.deprecated( + format!("{parent}.{}({name}:)", field.name), + argument.deprecation.as_ref(), + field.position, + ); + let place = format!("argument `{name}` of `{parent}.{}`", field.name); + self.check_value(value, argument, &place, field.position)?; + } + for (name, argument) in &definition.args { + if argument.is_required() && !field.arguments.iter().any(|(given, _)| given == name) { + return error_at( + field.position, + format!( + "Field `{parent}.{}` requires the argument `{name}: {}`", + field.name, argument.ty + ), + ); + } + } + Ok(()) + } + + /// Checks the directives written at `location` (`FIELD`, `QUERY`…) + /// against those of the schema. Returns whether they make the selection + /// conditional: `@include` and `@skip`. + fn check_directives( + &mut self, + directives: &'a [Directive<'a>], + location: &str, + ) -> Result { + let schema = self.schema; + let mut conditional = false; + for (index, directive) in directives.iter().enumerate() { + let name = directive.name.as_str(); + let Some(definition) = schema.directive(name) else { + return error_at( + directive.position, + format!( + "The schema has no directive `@{name}`{}", + did_you_mean(name, schema.directives.keys().map(String::as_str)) + .replacen('`', "`@", 1) + ), + ); + }; + if !definition + .locations + .iter() + .any(|allowed| allowed == location) + { + let place = location.to_lowercase().replace('_', " "); + return error_at( + directive.position, + format!("`@{name}` cannot be written on a {place}"), + ); + } + if !definition.repeatable + && directives[..index] + .iter() + .any(|earlier| earlier.name == name) + { + return error_at( + directive.position, + format!("`@{name}` is written twice at the same place"), + ); + } + for (position, (argument, value)) in directive.arguments.iter().enumerate() { + if directive.arguments[..position] + .iter() + .any(|(earlier, _)| earlier == argument) + { + return error_at( + directive.position, + format!("`@{name}` is given the argument `{argument}` twice"), + ); + } + let Some(expected) = definition.args.get(argument) else { + return error_at( + directive.position, + format!( + "`@{name}` has no argument `{argument}`{}", + did_you_mean(argument, definition.args.keys().map(String::as_str)) + ), + ); + }; + let place = format!("argument `{argument}` of `@{name}`"); + self.check_value(value, expected, &place, directive.position)?; + } + if let Some((missing, expected)) = + definition.args.iter().find(|(argument, expected)| { + expected.is_required() + && !directive + .arguments + .iter() + .any(|(given, _)| given == *argument) + }) + { + return error_at( + directive.position, + format!( + "`@{name}` requires the argument `{missing}: {}`", + expected.ty + ), + ); + } + conditional |= matches!(name, "include" | "skip"); + } + Ok(conditional) + } + + /// Marks the variables of a value whose type is not known. + fn mark_variables(&mut self, value: &Value<'a>, position: Pos) -> Result<()> { + match value { + ast::Value::Variable(name) => { + self.variable(name, position)?; + } + ast::Value::List(items) => { + for item in items { + self.mark_variables(item, position)?; + } + } + ast::Value::Object(fields) => { + for item in fields.values() { + self.mark_variables(item, position)?; + } + } + _ => {} + } + Ok(()) + } + + /// The declared variable of this name, which is thereby used. + fn variable(&mut self, name: &str, position: Pos) -> Result<&Variable> { + let Some(variable) = self.variables.iter().find(|variable| variable.name == name) else { + let declared = self.variables.iter().map(|variable| variable.name.as_str()); + return error_at( + position, + format!( + "Variable `${name}` is not declared{}", + did_you_mean(name, declared) + ), + ); + }; + self.used_variables.insert(name.to_string()); + Ok(variable) + } + + /// Checks a literal or a variable given where `expected` is wanted. + fn check_value( + &mut self, + value: &Value<'a>, + expected: &InputValue, + place: &str, + position: Pos, + ) -> Result<()> { + let inner = expected.ty.nullable(); + // A custom scalar, `JSON` among them, defines its own literals: an object + // or a list is a value of it, not an input object or a list of the schema. + if let TypeRef::Named(name) = inner + && !matches!(value, ast::Value::Variable(_) | ast::Value::Null) + && !matches!(name.as_str(), "Int" | "Float" | "String" | "Boolean" | "ID") + && matches!(self.schema.get(name), Some(TypeDef::Scalar)) + { + return self.mark_variables(value, position); + } + match value { + ast::Value::Variable(name) => { + let variable = self.variable(name, position)?; + if !variable_fits(variable, expected) { + return error_at( + position, + format!( + "Variable `${name}` of type `{}` cannot be used for {place}, which expects `{}`", + variable.ty, expected.ty + ), + ); + } + } + ast::Value::Null => { + if expected.ty.is_non_null() { + return error_at( + position, + format!( + "`null` is not allowed for {place}, of type `{}`", + expected.ty + ), + ); + } + } + ast::Value::List(items) => { + // GraphQL accepts a single value where a list is expected, not the opposite. + let TypeRef::List(item_type) = inner else { + return error_at( + position, + format!("A list is given for {place}, of type `{}`", expected.ty), + ); + }; + let item = InputValue::of((**item_type).clone()); + for value in items { + self.check_value(value, &item, place, position)?; + } + } + ast::Value::Object(given) => { + let named = inner.name(); + let Some(TypeDef::Input { fields }) = self.schema.get(named) else { + return error_at( + position, + format!("An object is given for {place}, of type `{}`", expected.ty), + ); + }; + for (name, value) in given { + let Some(field) = fields.get(name) else { + return error_at( + position, + format!( + "Input type `{named}` has no field `{name}`{} (in {place})", + did_you_mean(name, fields.keys().map(String::as_str)) + ), + ); + }; + self.deprecated( + format!("{named}.{name}"), + field.deprecation.as_ref(), + position, + ); + self.check_value( + value, + field, + &format!("field `{name}` of `{named}`"), + position, + )?; + } + if let Some((missing, field)) = fields + .iter() + .find(|(name, field)| field.is_required() && !given.contains_key(*name)) + { + return error_at( + position, + format!( + "Input type `{named}` requires the field `{missing}: {}` (in {place})", + field.ty + ), + ); + } + } + ast::Value::Enum(given) => match self.schema.get(inner.name()) { + Some(TypeDef::Enum { values, deprecated }) + if matches!(inner, TypeRef::Named(_)) => + { + if !values.contains(given) { + return error_at( + position, + format!( + "`{given}` is not a value of the enum `{}`{} (in {place})", + inner.name(), + did_you_mean(given, values.iter().map(String::as_str)) + ), + ); + } + let reason = deprecated.get(given).cloned(); + self.deprecated( + format!("{}.{given}", inner.name()), + reason.as_ref(), + position, + ); + } + // A single value where a list of enum values is expected. + Some(TypeDef::Enum { .. }) => { + let item = InputValue::of(TypeRef::Named(inner.name().to_string())); + self.check_value(value, &item, place, position)?; + } + _ => { + return error_at( + position, + format!( + "The enum value `{given}` is given for {place}, of type `{}`", + expected.ty + ), + ); + } + }, + ast::Value::Int(number) if inner.name() == "Int" && !fits_int(number) => { + return error_at( + position, + format!( + "The integer is outside the range of `Int`, a 32-bit integer, given for {place}" + ), + ); + } + literal => { + let given = match literal { + ast::Value::Int(_) => "an integer", + ast::Value::Float(_) => "a float", + ast::Value::String(_) => "a string", + _ => "a boolean", + }; + let accepted = match (inner.name(), literal) { + ("Int", ast::Value::Int(_)) => true, + ("Float", ast::Value::Int(_) | ast::Value::Float(_)) => true, + ("String", ast::Value::String(_)) => true, + ("Boolean", ast::Value::Boolean(_)) => true, + ("ID", ast::Value::String(_) | ast::Value::Int(_)) => true, + ("Int" | "Float" | "String" | "Boolean" | "ID", _) => false, + // Custom scalars define their own literals; enums and input objects do not accept these. + (name, _) => matches!(self.schema.get(name), Some(TypeDef::Scalar)), + }; + if !accepted { + return error_at( + position, + format!("{given} is given for {place}, of type `{}`", expected.ty), + ); + } + } + } + Ok(()) + } +} + +/// `Int` is a signed 32-bit integer in GraphQL. +fn fits_int(number: &ast::Number) -> bool { + number + .as_i64() + .is_some_and(|number| i32::try_from(number).is_ok()) +} + +/// The rule of the GraphQL specification for using a variable at a location. +fn variable_fits(variable: &Variable, location: &InputValue) -> bool { + fn compatible(variable: &TypeRef, location: &TypeRef) -> bool { + match (variable, location) { + (TypeRef::NonNull(variable), TypeRef::NonNull(location)) => { + compatible(variable, location) + } + (_, TypeRef::NonNull(_)) => false, + (TypeRef::NonNull(variable), location) => compatible(variable, location), + (TypeRef::List(variable), TypeRef::List(location)) => compatible(variable, location), + (TypeRef::Named(variable), TypeRef::Named(location)) => variable == location, + _ => false, + } + } + if location.ty.is_non_null() && !variable.ty.is_non_null() { + // A nullable variable is accepted when a default value fills the gap. + return (variable.has_default || location.has_default) + && compatible(&variable.ty, location.ty.nullable()); + } + compatible(&variable.ty, &location.ty) +} + +/// ` (did you mean `x`?)` for the candidate closest to `name`, or nothing. +fn did_you_mean<'a>(name: &str, candidates: impl Iterator) -> String { + let lowered = name.to_lowercase(); + // Half of the name may differ, within three edits: `frist` → `first`, `CREATED` → `CREATED_AT`. + let limit = (name.len() / 2).clamp(1, 3); + candidates + .map(|candidate| { + ( + edit_distance(&lowered, &candidate.to_lowercase()), + candidate, + ) + }) + .filter(|(distance, _)| *distance <= limit) + .min() + .map(|(_, candidate)| format!(" (did you mean `{candidate}`?)")) + .unwrap_or_default() +} + +fn edit_distance(left: &str, right: &str) -> usize { + let right: Vec = right.chars().collect(); + let mut row: Vec = (0..=right.len()).collect(); + for (i, a) in left.chars().enumerate() { + let mut previous = row[0]; + row[0] = i + 1; + for (j, b) in right.iter().enumerate() { + let substitution = previous + usize::from(a != *b); + previous = row[j + 1]; + row[j + 1] = substitution.min(previous + 1).min(row[j] + 1); + } + } + row[right.len()] +} diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs new file mode 100644 index 0000000..236bf27 --- /dev/null +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -0,0 +1,449 @@ +//! Rust types for the result and the variables of an analyzed operation. + +use std::collections::{BTreeMap, BTreeSet}; + +use proc_macro2::{Ident, Span, TokenStream}; +use quote::quote; + +use crate::analyze::{ + FieldBase, Operation, Scalar, SelectedField, Selection, Variable, VariableBase, +}; +use crate::schema::{InputValue, Schema, TypeDef, TypeRef}; + +/// The name of the type generated for the `data` of an operation. +pub const DATA_TYPE: &str = "Data"; +/// The name of the type generated for the variables of an operation. +pub const VARIABLES_TYPE: &str = "Variables"; + +/// Identifiers that cannot be written `r#name`. +const UNRAWABLE: [&str; 5] = ["self", "Self", "super", "crate", "_"]; +const KEYWORDS: &[&str] = &[ + "abstract", "as", "async", "await", "become", "box", "break", "const", "continue", "do", "dyn", + "else", "enum", "extern", "false", "final", "fn", "for", "gen", "if", "impl", "in", "let", + "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref", "return", + "static", "struct", "trait", "true", "try", "type", "typeof", "unsafe", "unsized", "use", + "virtual", "where", "while", "yield", +]; + +/// `lineItems` → `line_items`, `__typename` → `typename`, `HTMLBody` → `html_body`. +fn snake_case(name: &str) -> String { + let characters: Vec = name.trim_matches('_').chars().collect(); + let mut snake = String::new(); + for (index, character) in characters.iter().enumerate() { + if character.is_uppercase() { + let after_lower = index > 0 + && (characters[index - 1].is_lowercase() || characters[index - 1].is_ascii_digit()); + let before_lower = index > 0 + && characters[index - 1].is_uppercase() + && characters + .get(index + 1) + .is_some_and(|next| next.is_lowercase()); + if (after_lower || before_lower) && !snake.ends_with('_') { + snake.push('_'); + } + snake.extend(character.to_lowercase()); + } else { + snake.push(*character); + } + } + if snake.is_empty() || snake.starts_with(|first: char| first.is_ascii_digit()) { + snake.insert(0, '_'); + } + snake +} + +/// `lineItems` → `LineItems`, `line_items` → `LineItems`, `__typename` → `Typename`. +fn pascal_case(name: &str) -> String { + let mut pascal = String::new(); + let mut capitalize = true; + for character in name.chars() { + if character == '_' { + capitalize = true; + } else if capitalize { + pascal.extend(character.to_uppercase()); + capitalize = false; + } else { + pascal.push(character); + } + } + pascal +} + +/// The Rust field for a GraphQL name: snake case, raw when it is a keyword, +/// with the `serde` attribute that restores the name when it differs. +fn field_ident(name: &str, taken: &mut BTreeSet) -> (Ident, Option) { + let mut snake = snake_case(name); + if UNRAWABLE.contains(&snake.as_str()) { + snake.push('_'); + } + while !taken.insert(snake.clone()) { + snake.push('_'); + } + let rename = (snake != name).then(|| quote!(#[serde(rename = #name)])); + let ident = if KEYWORDS.contains(&snake.as_str()) { + Ident::new_raw(&snake, Span::call_site()) + } else { + Ident::new(&snake, Span::call_site()) + }; + (ident, rename) +} + +fn scalar_type(scalar: Scalar, krate: &TokenStream) -> TokenStream { + match scalar { + Scalar::String => quote!(::std::string::String), + Scalar::Int => quote!(::core::primitive::i64), + Scalar::Float => quote!(::core::primitive::f64), + Scalar::Boolean => quote!(::core::primitive::bool), + Scalar::Json => quote!(#krate::__private::serde_json::Value), + } +} + +/// Wraps `base` in the `Option`s and `Vec`s of a GraphQL type. +fn wrap(ty: &TypeRef, base: &TokenStream) -> TokenStream { + match ty { + TypeRef::NonNull(inner) => wrap_non_null(inner, base), + nullable => { + let inner = wrap_non_null(nullable, base); + quote!(::core::option::Option<#inner>) + } + } +} + +fn wrap_non_null(ty: &TypeRef, base: &TokenStream) -> TokenStream { + match ty { + TypeRef::Named(_) => base.clone(), + TypeRef::NonNull(inner) => wrap_non_null(inner, base), + TypeRef::List(item) => { + let item = wrap(item, base); + quote!(::std::vec::Vec<#item>) + } + } +} + +/// The path of `serde` in the generated code, as `#[serde(crate = "…")]` takes it. +fn serde_path(krate: &TokenStream) -> String { + format!("{krate}::__private::serde").replace(' ', "") +} + +// ─── Result ────────────────────────────────────────────────────────── + +struct DataTypes<'a> { + krate: &'a TokenStream, + names: BTreeSet, + items: Vec, +} + +impl DataTypes<'_> { + fn object(&mut self, selection: &Selection, name: String) -> Ident { + let mut name = name; + while !self.names.insert(name.clone()) { + name.push('_'); + } + let ident = Ident::new(&name, Span::call_site()); + + let mut taken = BTreeSet::new(); + let fields: Vec = selection + .fields + .iter() + .map(|field| self.field(field, &name, &mut taken)) + .collect(); + + let krate = self.krate; + let serde = serde_path(krate); + let doc = if name == DATA_TYPE { + format!( + " The `data` of the operation, selected on `{}`.", + selection.type_name + ) + } else { + format!(" Selection on `{}`.", selection.type_name) + }; + self.items.push(quote! { + #[doc = #doc] + #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq, #krate::__private::serde::Serialize, #krate::__private::serde::Deserialize)] + #[serde(crate = #serde)] + #[allow(dead_code)] + pub struct #ident { + #(#fields)* + } + }); + ident + } + + fn field( + &mut self, + field: &SelectedField, + parent: &str, + taken: &mut BTreeSet, + ) -> TokenStream { + let (ident, rename) = field_ident(&field.key, taken); + let base = match &field.base { + FieldBase::Scalar(scalar) => scalar_type(*scalar, self.krate), + FieldBase::Object(selection) => { + let nested = self.object(selection, format!("{parent}{}", pascal_case(&field.key))); + quote!(#nested) + } + }; + let optional = field.conditional || !field.ty.is_non_null(); + let ty = if field.conditional && field.ty.is_non_null() { + let inner = wrap(&field.ty, &base); + quote!(::core::option::Option<#inner>) + } else { + wrap(&field.ty, &base) + }; + + let default = optional.then(|| quote!(#[serde(default)])); + let doc = format!(" `{}: {}`", field.key, field.ty); + quote! { + #[doc = #doc] + #rename + #default + pub #ident: #ty, + } + } +} + +/// The public structs describing the `data` of `operation`: [`DATA_TYPE`] and +/// one struct per nested selection, named after its path (`DataOrdersNodes`). +/// +/// `krate` is the path of the `shopify_api` crate in the generated code. +pub fn data_types(operation: &Operation, krate: &TokenStream) -> TokenStream { + let mut types = DataTypes { + krate, + names: BTreeSet::new(), + items: Vec::new(), + }; + types.object(&operation.data, DATA_TYPE.to_string()); + let items = types.items; + quote!(#(#items)*) +} + +// ─── Variables ─────────────────────────────────────────────────────── + +/// The Rust type a variable value is converted to, or `None` when the variable +/// holds an input object, which has no type outside a `graphql!` module. +pub fn variable_type(variable: &Variable, krate: &TokenStream) -> Option { + let base = match variable.base { + VariableBase::Scalar(scalar) => scalar_type(scalar, krate), + VariableBase::Enum => scalar_type(Scalar::String, krate), + VariableBase::Input => return None, + }; + Some(wrap(&variable.ty, &base)) +} + +struct InputTypes<'a> { + schema: &'a Schema, + krate: &'a TokenStream, + generated: BTreeSet, + items: Vec, +} + +impl InputTypes<'_> { + /// The Rust type of a named input type, generating input objects on the way. + fn named(&mut self, name: &str) -> TokenStream { + match self.schema.get(name) { + Some(TypeDef::Input { fields }) => { + if self.generated.insert(name.to_string()) { + self.input_object(name, fields); + } + let ident = Ident::new(name, Span::call_site()); + quote!(#ident) + } + Some(TypeDef::Enum { .. }) => scalar_type(Scalar::String, self.krate), + _ => scalar_type(Scalar::of(name), self.krate), + } + } + + fn input_object(&mut self, name: &str, fields: &BTreeMap) { + let mut taken = BTreeSet::new(); + let fields: Vec = fields + .iter() + .map(|(field, value)| { + let mut base = self.named(value.ty.name()); + // A value cannot contain itself: break direct cycles with a box. + let nested_directly = !contains_list(&value.ty); + if nested_directly && self.reaches(value.ty.name(), name) { + base = quote!(::std::boxed::Box<#base>); + } + let note = value.deprecation.as_ref().map(|reason| { + format!( + "`{name}.{field}` is deprecated in the Shopify Admin API {}: {reason}", + self.schema.api_version + ) + }); + input_field(field, value, note, &base, &mut taken) + }) + .collect(); + + let doc = format!(" The input object `{name}`. Fields left to `None` are not sent."); + self.items + .push(input_struct(name, &doc, &fields, self.krate)); + } + + /// Whether a value of input type `from` can hold one of type `to` without a list in between. + fn reaches(&self, from: &str, to: &str) -> bool { + let mut seen = BTreeSet::new(); + let mut stack = vec![from]; + while let Some(name) = stack.pop() { + if name == to { + return true; + } + if !seen.insert(name) { + continue; + } + if let Some(TypeDef::Input { fields }) = self.schema.get(name) { + stack.extend( + fields + .values() + .filter(|value| !contains_list(&value.ty)) + .map(|value| value.ty.name()), + ); + } + } + false + } +} + +fn contains_list(ty: &TypeRef) -> bool { + match ty { + TypeRef::Named(_) => false, + TypeRef::List(_) => true, + TypeRef::NonNull(inner) => contains_list(inner), + } +} + +/// A field of an input object or of the variables. A value that may be left +/// out is an `Option` that is not sent when `None`. A deprecated input field +/// is marked `#[deprecated]` with `note`, so that setting it warns. +fn input_field( + name: &str, + value: &InputValue, + note: Option, + base: &TokenStream, + taken: &mut BTreeSet, +) -> TokenStream { + let (ident, rename) = field_ident(name, taken); + let ty = &value.ty; + let doc = format!(" `{name}: {ty}`"); + let deprecated = note.map(|note| quote!(#[deprecated(note = #note)])); + if value.is_required() { + let ty = wrap(ty, base); + quote! { + #[doc = #doc] + #deprecated + #rename + pub #ident: #ty, + } + } else { + // `wrap` of a nullable type is already an `Option`. + let ty = wrap(ty.nullable(), base); + quote! { + #[doc = #doc] + #deprecated + #rename + #[serde(skip_serializing_if = "::core::option::Option::is_none")] + pub #ident: #ty, + } + } +} + +/// A struct that is only sent: an input object, or the variables. +fn input_struct(name: &str, doc: &str, fields: &[TokenStream], krate: &TokenStream) -> TokenStream { + let ident = Ident::new(name, Span::call_site()); + let serde = serde_path(krate); + quote! { + #[doc = #doc] + #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq, ::core::default::Default, #krate::__private::serde::Serialize)] + #[serde(crate = #serde)] + pub struct #ident { + #(#fields)* + } + } +} + +/// [`VARIABLES_TYPE`] and the input objects it refers to, named as in the schema. +pub fn variables_types(schema: &Schema, operation: &Operation, krate: &TokenStream) -> TokenStream { + let mut inputs = InputTypes { + schema, + krate, + generated: BTreeSet::new(), + items: Vec::new(), + }; + let mut taken = BTreeSet::new(); + let fields: Vec = operation + .variables + .iter() + .map(|variable| { + let base = inputs.named(variable.ty.name()); + let value = InputValue { + ty: variable.ty.clone(), + // A variable with a default may be left out, as an argument with one. + has_default: variable.has_default, + deprecation: None, + }; + input_field(&variable.name, &value, None, &base, &mut taken) + }) + .collect(); + + let items = inputs.items; + let variables = input_struct( + VARIABLES_TYPE, + " The variables of the operation. Those left to `None` are not sent.", + &fields, + krate, + ); + quote! { + #(#items)* + + #variables + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn converts_names() { + for (name, snake, pascal) in [ + ("id", "id", "Id"), + ("lineItems", "line_items", "LineItems"), + ("totalPriceSet", "total_price_set", "TotalPriceSet"), + ("__typename", "typename", "Typename"), + ("HTMLBody", "html_body", "HTMLBody"), + ("sku2", "sku2", "Sku2"), + ("address1", "address1", "Address1"), + ("already_snake", "already_snake", "AlreadySnake"), + ("iOS", "i_os", "IOS"), + ("2fa", "_2fa", "2fa"), + ] { + assert_eq!(snake_case(name), snake, "{name}"); + assert_eq!(pascal_case(name), pascal, "{name}"); + } + } + + #[test] + fn field_identifiers_avoid_keywords_and_duplicates() { + let mut taken = BTreeSet::new(); + let mut field = |name: &str| { + let (ident, rename) = field_ident(name, &mut taken); + ( + ident.to_string(), + rename.map(|attribute| attribute.to_string()), + ) + }; + // A raw identifier still has the name of the field: nothing to restore. + assert_eq!(field("type"), ("r#type".to_string(), None)); + assert_eq!(field("id"), ("id".to_string(), None)); + let renamed = |key: &str| Some(format!("# [serde (rename = \"{key}\")]")); + assert_eq!(field("self"), ("self_".to_string(), renamed("self"))); + assert_eq!( + field("lineItems"), + ("line_items".to_string(), renamed("lineItems")) + ); + assert_eq!( + field("line_items"), + ("line_items_".to_string(), renamed("line_items")) + ); + } +} diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs new file mode 100644 index 0000000..0caa303 --- /dev/null +++ b/crates/shopify_api_graphql/src/lib.rs @@ -0,0 +1,49 @@ +//! Compile-time support for the typed Shopify Admin GraphQL operations of +//! [`shopify_api`](https://docs.rs/shopify_api). +//! +//! [`analyze`](fn@analyze) checks an operation against a [`Schema`] and describes the +//! shape of its variables and of its result; [`codegen`] turns that +//! description into Rust types. The `graphql!` macro is a thin layer over +//! both, and the `shopify-api schema download` command uses +//! [`Schema::from_introspection`] and [`Schema::to_json`] to store the schema +//! of another API version. +#![forbid(unsafe_code)] + +pub mod analyze; +pub mod codegen; +pub mod schema; + +pub use analyze::{ + Deprecation, Error, FieldBase, Operation, OperationKind, Scalar, SelectedField, Selection, + Variable, VariableBase, analyze, +}; +pub use schema::{ + BUNDLED_API_VERSION, Field, INTROSPECTION_QUERY, InputValue, Schema, SchemaError, TypeDef, + TypeRef, +}; + +/// The oldest Admin API version `shopify_api` calls. +pub const MINIMUM_API_VERSION: &str = "2026-04"; + +/// Whether `version` is an Admin API version `shopify_api` calls: a quarterly +/// release such as `2026-10`, from [`MINIMUM_API_VERSION`] on, or `unstable`. +pub fn is_supported_api_version(version: &str) -> bool { + if version == "unstable" { + return true; + } + let bytes = version.as_bytes(); + let well_formed = bytes.len() == 7 + && bytes[4] == b'-' + && bytes[..4].iter().chain(&bytes[5..]).all(u8::is_ascii_digit) + && matches!(&version[5..], "01" | "04" | "07" | "10"); + // Same length and form: the text orders as the dates do. + well_formed && version >= MINIMUM_API_VERSION +} + +/// Where a crate keeps the schema of another API version than the bundled +/// one, relative to its `Cargo.toml`. `graphql!` uses it when it exists. +pub const PROJECT_SCHEMA_PATH: &str = "graphql/admin.schema.json"; + +/// The environment variable naming another schema file for `graphql!`, +/// relative to the `Cargo.toml` of the crate being compiled, or absolute. +pub const SCHEMA_ENV: &str = "SHOPIFY_GRAPHQL_SCHEMA"; diff --git a/crates/shopify_api_graphql/src/schema.rs b/crates/shopify_api_graphql/src/schema.rs new file mode 100644 index 0000000..41cdea2 --- /dev/null +++ b/crates/shopify_api_graphql/src/schema.rs @@ -0,0 +1,1140 @@ +//! The part of a GraphQL schema that checking and typing an operation needs: +//! type kinds, fields, arguments, enum values and deprecations, without +//! descriptions. + +use std::collections::BTreeMap; +use std::fmt; +use std::sync::OnceLock; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// The introspection query whose result [`Schema::from_introspection`] reads. +/// +/// It asks for deprecated fields, arguments, input fields and enum values +/// too: an operation may still use them, and `graphql!` warns when it does. +pub const INTROSPECTION_QUERY: &str = "\ +query IntrospectionQuery { + __schema { + queryType { name } + mutationType { name } + types { + kind + name + fields(includeDeprecated: true) { + name + args(includeDeprecated: true) { ...InputValue } + type { ...TypeRef } + isDeprecated + deprecationReason + } + inputFields(includeDeprecated: true) { ...InputValue } + interfaces { name } + enumValues(includeDeprecated: true) { name isDeprecated deprecationReason } + possibleTypes { name } + } + directives { + name + locations + isRepeatable + args(includeDeprecated: true) { ...InputValue } + } + } +} +fragment InputValue on __InputValue { + name + type { ...TypeRef } + defaultValue + isDeprecated + deprecationReason +} +fragment TypeRef on __Type { + kind name + ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } +} +"; + +/// The Admin API version of the schema bundled with this crate. +pub const BUNDLED_API_VERSION: &str = "2026-10"; + +/// Shopify's Admin GraphQL schema for [`BUNDLED_API_VERSION`]. +const BUNDLED_SCHEMA: &str = include_str!("../schema/admin-2026-10.json"); + +/// The version of the stored form written by [`Schema::to_json`]. +const FORMAT: u32 = 1; + +/// The reason GraphQL gives when a deprecation has none. +const NO_REASON: &str = "No longer supported"; + +/// A reference to a type, as written in GraphQL: `[Order!]!`. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum TypeRef { + Named(String), + List(Box), + NonNull(Box), +} + +impl TypeRef { + /// Parses `[Order!]!`. Returns `None` for malformed input. + pub fn parse(text: &str) -> Option { + let text = text.trim(); + if let Some(inner) = text.strip_suffix('!') { + return Some(Self::NonNull(Box::new(Self::parse(inner)?))); + } + if let Some(inner) = text.strip_prefix('[') { + return Some(Self::List(Box::new(Self::parse(inner.strip_suffix(']')?)?))); + } + let is_name = !text.is_empty() + && text + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_'); + is_name.then(|| Self::Named(text.to_string())) + } + + /// The innermost named type: `Order` for `[Order!]!`. + pub fn name(&self) -> &str { + match self { + Self::Named(name) => name, + Self::List(inner) | Self::NonNull(inner) => inner.name(), + } + } + + pub fn is_non_null(&self) -> bool { + matches!(self, Self::NonNull(_)) + } + + /// The same type without its outer `!`. + pub fn nullable(&self) -> &TypeRef { + match self { + Self::NonNull(inner) => inner, + other => other, + } + } +} + +impl fmt::Display for TypeRef { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Named(name) => formatter.write_str(name), + Self::List(inner) => write!(formatter, "[{inner}]"), + Self::NonNull(inner) => write!(formatter, "{inner}!"), + } + } +} + +/// An argument or an input field. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct InputValue { + pub ty: TypeRef, + /// The schema gives it a default value. + pub has_default: bool, + /// Why it is deprecated, when it is. + pub deprecation: Option, +} + +impl InputValue { + /// A value of type `ty`, without default and not deprecated. + pub fn of(ty: TypeRef) -> Self { + Self { + ty, + has_default: false, + deprecation: None, + } + } + + /// A value must be provided: the type is non-null and has no default. + pub fn is_required(&self) -> bool { + self.ty.is_non_null() && !self.has_default + } +} + +/// The places of an operation where a directive may be written. +pub const EXECUTABLE_LOCATIONS: [&str; 8] = [ + "QUERY", + "MUTATION", + "SUBSCRIPTION", + "FIELD", + "FRAGMENT_DEFINITION", + "FRAGMENT_SPREAD", + "INLINE_FRAGMENT", + "VARIABLE_DEFINITION", +]; + +/// A directive an operation may use, such as `@include` or `@idempotent`. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Directive { + /// Where it may be written: [`EXECUTABLE_LOCATIONS`] only. + pub locations: Vec, + pub args: BTreeMap, + /// It may be written more than once at the same place. + pub repeatable: bool, +} + +impl Directive { + /// `@include` and `@skip`, which every GraphQL schema has: what a schema + /// stored without its directives gets. + fn conditions() -> BTreeMap { + let condition = Directive { + locations: ["FIELD", "FRAGMENT_SPREAD", "INLINE_FRAGMENT"] + .map(str::to_string) + .to_vec(), + args: [( + "if".to_string(), + InputValue::of(TypeRef::NonNull(Box::new(TypeRef::Named( + "Boolean".to_string(), + )))), + )] + .into(), + repeatable: false, + }; + [ + ("include".to_string(), condition.clone()), + ("skip".to_string(), condition), + ] + .into() + } +} + +/// A field of an object or an interface. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Field { + pub ty: TypeRef, + pub args: BTreeMap, + /// Why it is deprecated, when it is. + pub deprecation: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum TypeDef { + Scalar, + Enum { + values: Vec, + /// The deprecated values, with their reason. + deprecated: BTreeMap, + }, + Object { + fields: BTreeMap, + interfaces: Vec, + }, + Interface { + fields: BTreeMap, + possible_types: Vec, + }, + Union { + possible_types: Vec, + }, + Input { + fields: BTreeMap, + }, +} + +impl TypeDef { + /// The kind of type, with its article, for error messages. + pub fn kind_name(&self) -> &'static str { + match self { + Self::Scalar => "a scalar", + Self::Enum { .. } => "an enum", + Self::Object { .. } => "an object", + Self::Interface { .. } => "an interface", + Self::Union { .. } => "a union", + Self::Input { .. } => "an input object", + } + } + + /// Objects, interfaces and unions: types that need a selection of subfields. + pub fn is_composite(&self) -> bool { + matches!( + self, + Self::Object { .. } | Self::Interface { .. } | Self::Union { .. } + ) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Schema { + /// The Shopify API version the schema was downloaded for, such as `2026-10`. + pub api_version: String, + pub query: String, + pub mutation: Option, + pub types: BTreeMap, + /// The directives operations may use, by name. + pub directives: BTreeMap, +} + +/// A schema file or an introspection result is malformed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SchemaError(pub String); + +impl fmt::Display for SchemaError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } +} + +impl std::error::Error for SchemaError {} + +fn schema_error(message: impl Into) -> SchemaError { + SchemaError(message.into()) +} + +// ─── Stored form ───────────────────────────────────────────────────── +// +// One JSON object per type, with one-letter keys: the Admin schema has +// thousands of types, and it is parsed each time a crate using it compiles. +// +// A field is `"ID!"`, or `["OrderConnection!", { "first": "Int", "reverse": "Boolean=" }]` +// with its arguments. An input value is its type, followed by `=` when it has +// a default. Deprecations are kept apart, in `d`, by name: the reason of a +// field, of an enum value or of an input field, and `"field(argument)"` for +// an argument. + +#[derive(Serialize, Deserialize)] +struct StoredSchema { + format: u32, + #[serde(rename = "apiVersion")] + api_version: String, + query: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + mutation: Option, + #[serde(default)] + directives: BTreeMap, + types: BTreeMap, +} + +/// `{ "l": ["FIELD"], "a": { "key": "String!" } }`, with `"r": true` when repeatable. +#[derive(Serialize, Deserialize)] +struct StoredDirective { + #[serde(rename = "l")] + locations: Vec, + #[serde(rename = "a", default, skip_serializing_if = "BTreeMap::is_empty")] + args: BTreeMap, + #[serde(rename = "r", default, skip_serializing_if = "std::ops::Not::not")] + repeatable: bool, +} + +type Deprecations = BTreeMap; + +#[derive(Serialize, Deserialize)] +enum StoredType { + #[serde(rename = "s")] + Scalar, + #[serde(rename = "e")] + Enum(StoredEnum), + #[serde(rename = "o")] + Object(StoredComposite), + #[serde(rename = "n")] + Interface(StoredComposite), + #[serde(rename = "u")] + Union(Vec), + #[serde(rename = "i")] + Input(StoredInput), +} + +/// `["PAID", "PENDING"]`, or `{ "v": […], "d": { "PENDING": "reason" } }`. +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum StoredEnum { + Plain(Vec), + WithDeprecations { v: Vec, d: Deprecations }, +} + +/// `{ "id": "ID!" }`, or `{ "f": { … }, "d": { "id": "reason" } }`. +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum StoredInput { + WithDeprecations { + f: BTreeMap, + d: Deprecations, + }, + Plain(BTreeMap), +} + +#[derive(Serialize, Deserialize)] +struct StoredComposite { + #[serde(rename = "f")] + fields: BTreeMap, + /// Interfaces of an object, possible types of an interface. + #[serde(rename = "t", default, skip_serializing_if = "Vec::is_empty")] + types: Vec, + #[serde(rename = "d", default, skip_serializing_if = "BTreeMap::is_empty")] + deprecated: Deprecations, +} + +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum StoredField { + Plain(String), + WithArgs(String, BTreeMap), +} + +fn store_input(value: &InputValue) -> String { + if value.has_default { + format!("{}=", value.ty) + } else { + value.ty.to_string() + } +} + +fn load_input( + owner: &str, + name: &str, + text: &str, + deprecation: Option<&String>, +) -> Result { + let (ty, has_default) = match text.strip_suffix('=') { + Some(ty) => (ty, true), + None => (text, false), + }; + let ty = TypeRef::parse(ty) + .ok_or_else(|| schema_error(format!("Invalid type \"{text}\" for {owner}.{name}")))?; + Ok(InputValue { + ty, + has_default, + deprecation: deprecation.cloned(), + }) +} + +fn argument_key(field: &str, argument: &str) -> String { + format!("{field}({argument})") +} + +fn store_fields(fields: &BTreeMap) -> (BTreeMap, Deprecations) { + let mut deprecated = Deprecations::new(); + let stored = fields + .iter() + .map(|(name, field)| { + if let Some(reason) = &field.deprecation { + deprecated.insert(name.clone(), reason.clone()); + } + let ty = field.ty.to_string(); + let stored = if field.args.is_empty() { + StoredField::Plain(ty) + } else { + let args = field + .args + .iter() + .map(|(argument, value)| { + if let Some(reason) = &value.deprecation { + deprecated.insert(argument_key(name, argument), reason.clone()); + } + (argument.clone(), store_input(value)) + }) + .collect(); + StoredField::WithArgs(ty, args) + }; + (name.clone(), stored) + }) + .collect(); + (stored, deprecated) +} + +fn load_fields( + owner: &str, + fields: BTreeMap, + deprecated: &Deprecations, +) -> Result, SchemaError> { + fields + .into_iter() + .map(|(name, stored)| { + let (ty, args) = match stored { + StoredField::Plain(ty) => (ty, BTreeMap::new()), + StoredField::WithArgs(ty, args) => (ty, args), + }; + let field = Field { + ty: TypeRef::parse(&ty).ok_or_else(|| { + schema_error(format!("Invalid type \"{ty}\" for {owner}.{name}")) + })?, + args: args + .into_iter() + .map(|(argument, text)| { + let reason = deprecated.get(&argument_key(&name, &argument)); + let value = + load_input(&format!("{owner}.{name}"), &argument, &text, reason)?; + Ok((argument, value)) + }) + .collect::>()?, + deprecation: deprecated.get(&name).cloned(), + }; + Ok((name, field)) + }) + .collect() +} + +fn load_inputs( + owner: &str, + fields: BTreeMap, + deprecated: &Deprecations, +) -> Result, SchemaError> { + fields + .into_iter() + .map(|(field, text)| { + let value = load_input(owner, &field, &text, deprecated.get(&field))?; + Ok((field, value)) + }) + .collect() +} + +impl Schema { + /// The Shopify Admin schema bundled with this crate, for [`BUNDLED_API_VERSION`]. + pub fn bundled() -> &'static Schema { + static BUNDLED: OnceLock = OnceLock::new(); + BUNDLED + .get_or_init(|| Schema::from_json(BUNDLED_SCHEMA).expect("the bundled schema is valid")) + } + + /// Reads the form written by [`Schema::to_json`]. + pub fn from_json(json: &str) -> Result { + let format = serde_json::from_str::(json) + .map_err(|error| schema_error(format!("Invalid schema file: {error}")))? + .get("format") + .and_then(Value::as_u64); + if format != Some(u64::from(FORMAT)) { + return Err(schema_error(match format { + Some(format) => format!( + "Unsupported schema file format {format}, this version reads format {FORMAT}" + ), + None => "Not a schema file of shopify_api: it has no `format`".to_string(), + })); + } + let stored: StoredSchema = serde_json::from_str(json) + .map_err(|error| schema_error(format!("Invalid schema file: {error}")))?; + let types = stored + .types + .into_iter() + .map(|(name, stored)| { + let definition = match stored { + StoredType::Scalar => TypeDef::Scalar, + StoredType::Enum(StoredEnum::Plain(values)) => TypeDef::Enum { + values, + deprecated: Deprecations::new(), + }, + StoredType::Enum(StoredEnum::WithDeprecations { v, d }) => TypeDef::Enum { + values: v, + deprecated: d, + }, + StoredType::Object(object) => TypeDef::Object { + fields: load_fields(&name, object.fields, &object.deprecated)?, + interfaces: object.types, + }, + StoredType::Interface(interface) => TypeDef::Interface { + fields: load_fields(&name, interface.fields, &interface.deprecated)?, + possible_types: interface.types, + }, + StoredType::Union(possible_types) => TypeDef::Union { possible_types }, + StoredType::Input(StoredInput::Plain(fields)) => TypeDef::Input { + fields: load_inputs(&name, fields, &Deprecations::new())?, + }, + StoredType::Input(StoredInput::WithDeprecations { f, d }) => TypeDef::Input { + fields: load_inputs(&name, f, &d)?, + }, + }; + Ok((name, definition)) + }) + .collect::>()?; + let mut directives: BTreeMap = stored + .directives + .into_iter() + .map(|(name, stored)| { + let owner = format!("@{name}"); + let args = stored + .args + .into_iter() + .map(|(argument, text)| { + let value = load_input(&owner, &argument, &text, None)?; + Ok((argument, value)) + }) + .collect::>()?; + let directive = Directive { + locations: stored.locations, + args, + repeatable: stored.repeatable, + }; + Ok((name, directive)) + }) + .collect::>()?; + if directives.is_empty() { + directives = Directive::conditions(); + } + Ok(Self { + api_version: stored.api_version, + query: stored.query, + mutation: stored.mutation, + types, + directives, + }) + } + + /// The stored form: one type per line, so that a new API version gives a readable diff. + pub fn to_json(&self) -> String { + let types: BTreeMap<&String, StoredType> = self + .types + .iter() + .map(|(name, definition)| { + let stored = match definition { + TypeDef::Scalar => StoredType::Scalar, + TypeDef::Enum { values, deprecated } if deprecated.is_empty() => { + StoredType::Enum(StoredEnum::Plain(values.clone())) + } + TypeDef::Enum { values, deprecated } => { + StoredType::Enum(StoredEnum::WithDeprecations { + v: values.clone(), + d: deprecated.clone(), + }) + } + TypeDef::Object { fields, interfaces } => { + let (fields, deprecated) = store_fields(fields); + StoredType::Object(StoredComposite { + fields, + types: interfaces.clone(), + deprecated, + }) + } + TypeDef::Interface { + fields, + possible_types, + } => { + let (fields, deprecated) = store_fields(fields); + StoredType::Interface(StoredComposite { + fields, + types: possible_types.clone(), + deprecated, + }) + } + TypeDef::Union { possible_types } => StoredType::Union(possible_types.clone()), + TypeDef::Input { fields } => { + let stored = fields + .iter() + .map(|(name, value)| (name.clone(), store_input(value))) + .collect(); + let deprecated: Deprecations = fields + .iter() + .filter_map(|(name, value)| { + Some((name.clone(), value.deprecation.clone()?)) + }) + .collect(); + StoredType::Input(if deprecated.is_empty() { + StoredInput::Plain(stored) + } else { + StoredInput::WithDeprecations { + f: stored, + d: deprecated, + } + }) + } + }; + (name, stored) + }) + .collect(); + + let quoted = |text: &str| Value::from(text).to_string(); + let mut json = format!( + "{{\"format\":{FORMAT},\"apiVersion\":{},\"query\":{}", + quoted(&self.api_version), + quoted(&self.query) + ); + if let Some(mutation) = &self.mutation { + json.push_str(&format!(",\"mutation\":{}", quoted(mutation))); + } + let directives: BTreeMap<&String, StoredDirective> = self + .directives + .iter() + .map(|(name, directive)| { + let stored = StoredDirective { + locations: directive.locations.clone(), + args: directive + .args + .iter() + .map(|(argument, value)| (argument.clone(), store_input(value))) + .collect(), + repeatable: directive.repeatable, + }; + (name, stored) + }) + .collect(); + let directives = serde_json::to_string(&directives).expect("directives serialize"); + json.push_str(&format!(",\n\"directives\":{directives}")); + json.push_str(",\"types\":{"); + for (index, (name, stored)) in types.iter().enumerate() { + json.push_str(if index == 0 { "\n" } else { ",\n" }); + let stored = serde_json::to_string(stored).expect("schema types serialize"); + json.push_str(&format!("{}:{stored}", quoted(name))); + } + json.push_str("\n}}\n"); + json + } + + /// Builds a schema from the answer to [`INTROSPECTION_QUERY`]: the whole + /// response, its `data`, or the `__schema` object. + pub fn from_introspection(response: &Value, api_version: &str) -> Result { + if let Some(errors) = response.get("errors").and_then(Value::as_array) + && !errors.is_empty() + { + let messages: Vec<&str> = errors + .iter() + .filter_map(|error| error.get("message").and_then(Value::as_str)) + .collect(); + return Err(schema_error(format!( + "Introspection failed: {}", + messages.join("; ") + ))); + } + let schema = response + .pointer("/data/__schema") + .or_else(|| response.get("__schema")) + .unwrap_or(response); + let name_of = |pointer: &str| { + schema + .pointer(pointer) + .and_then(Value::as_str) + .map(str::to_string) + }; + let query = name_of("/queryType/name") + .ok_or_else(|| schema_error("The introspection result has no `queryType`"))?; + let listed = schema + .get("types") + .and_then(Value::as_array) + .ok_or_else(|| schema_error("The introspection result has no `types`"))?; + + let mut types = BTreeMap::new(); + for entry in listed { + let name = text(entry, "name")?; + if name.starts_with("__") { + continue; + } + let names = |key: &str| -> Vec { + let listed = entry.get(key).and_then(Value::as_array); + listed + .into_iter() + .flatten() + .filter_map(|item| item.get("name").and_then(Value::as_str)) + .map(str::to_string) + .collect() + }; + let definition = match text(entry, "kind")? { + "SCALAR" => TypeDef::Scalar, + "ENUM" => { + let values = entry.get("enumValues").and_then(Value::as_array); + let deprecated = values + .into_iter() + .flatten() + .filter_map(|value| { + Some(( + value.get("name")?.as_str()?.to_string(), + deprecation(value)?, + )) + }) + .collect(); + TypeDef::Enum { + values: names("enumValues"), + deprecated, + } + } + "OBJECT" => TypeDef::Object { + fields: introspected_fields(entry)?, + interfaces: names("interfaces"), + }, + "INTERFACE" => TypeDef::Interface { + fields: introspected_fields(entry)?, + possible_types: names("possibleTypes"), + }, + "UNION" => TypeDef::Union { + possible_types: names("possibleTypes"), + }, + "INPUT_OBJECT" => TypeDef::Input { + fields: introspected_inputs(entry.get("inputFields"))?, + }, + other => { + return Err(schema_error(format!( + "Unknown kind \"{other}\" for type {name}" + ))); + } + }; + types.insert(name.to_string(), definition); + } + + if !matches!(types.get(&query), Some(TypeDef::Object { .. })) { + return Err(schema_error(format!( + "The query type `{query}` is not an object of the schema" + ))); + } + + let mut directives = BTreeMap::new(); + for entry in schema + .get("directives") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + let locations: Vec = entry + .get("locations") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter(|location| EXECUTABLE_LOCATIONS.contains(location)) + .map(str::to_string) + .collect(); + if locations.is_empty() { + continue; + } + let directive = Directive { + locations, + args: introspected_inputs(entry.get("args"))?, + repeatable: entry.get("isRepeatable").and_then(Value::as_bool) == Some(true), + }; + directives.insert(text(entry, "name")?.to_string(), directive); + } + if directives.is_empty() { + directives = Directive::conditions(); + } + + Ok(Self { + api_version: api_version.to_string(), + query, + mutation: name_of("/mutationType/name"), + types, + directives, + }) + } + + pub fn get(&self, name: &str) -> Option<&TypeDef> { + self.types.get(name) + } + + pub fn directive(&self, name: &str) -> Option<&Directive> { + self.directives.get(name) + } + + /// The object types a value of `name` can be at run time. + pub fn possible_types(&self, name: &str) -> Vec<&str> { + match self.types.get_key_value(name) { + Some((name, TypeDef::Object { .. })) => vec![name.as_str()], + Some(( + _, + TypeDef::Interface { possible_types, .. } | TypeDef::Union { possible_types }, + )) => possible_types.iter().map(String::as_str).collect(), + _ => Vec::new(), + } + } +} + +fn text<'a>(entry: &'a Value, key: &str) -> Result<&'a str, SchemaError> { + entry + .get(key) + .and_then(Value::as_str) + .ok_or_else(|| schema_error(format!("An introspected entry has no `{key}`"))) +} + +/// The reason of a deprecated entry, `None` when it is not deprecated. +fn deprecation(entry: &Value) -> Option { + if entry.get("isDeprecated").and_then(Value::as_bool) != Some(true) { + return None; + } + let reason = entry.get("deprecationReason").and_then(Value::as_str); + Some( + reason + .filter(|reason| !reason.trim().is_empty()) + .unwrap_or(NO_REASON) + .trim() + .to_string(), + ) +} + +fn introspected_type(value: Option<&Value>) -> Result { + let value = value.ok_or_else(|| schema_error("An introspected entry has no `type`"))?; + let inner = || introspected_type(value.get("ofType").filter(|inner| !inner.is_null())); + Ok(match text(value, "kind")? { + "NON_NULL" => TypeRef::NonNull(Box::new(inner()?)), + "LIST" => TypeRef::List(Box::new(inner()?)), + _ => TypeRef::Named(text(value, "name")?.to_string()), + }) +} + +fn introspected_inputs( + values: Option<&Value>, +) -> Result, SchemaError> { + values + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|value| { + let input = InputValue { + ty: introspected_type(value.get("type"))?, + has_default: value + .get("defaultValue") + .is_some_and(|default| !default.is_null()), + deprecation: deprecation(value), + }; + Ok((text(value, "name")?.to_string(), input)) + }) + .collect() +} + +fn introspected_fields(entry: &Value) -> Result, SchemaError> { + entry + .get("fields") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|field| { + let definition = Field { + ty: introspected_type(field.get("type"))?, + args: introspected_inputs(field.get("args"))?, + deprecation: deprecation(field), + }; + Ok((text(field, "name")?.to_string(), definition)) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn parses_and_prints_type_references() { + for text in ["Order", "Order!", "[Order]", "[Order!]!", "[[Int!]]!"] { + assert_eq!(TypeRef::parse(text).unwrap().to_string(), text); + } + let list = TypeRef::parse("[Order!]!").unwrap(); + assert_eq!(list.name(), "Order"); + assert!(list.is_non_null()); + assert_eq!(list.nullable().to_string(), "[Order!]"); + for invalid in ["", "!", "[Order", "Order]", "Or der", "[]"] { + assert_eq!(TypeRef::parse(invalid), None, "{invalid}"); + } + } + + fn introspection() -> Value { + let named = |kind: &str, name: &str| json!({ "kind": kind, "name": name, "ofType": null }); + let non_null = |inner: Value| json!({ "kind": "NON_NULL", "name": null, "ofType": inner }); + let list = |inner: Value| json!({ "kind": "LIST", "name": null, "ofType": inner }); + json!({ "data": { "__schema": { + "queryType": { "name": "QueryRoot" }, + "mutationType": { "name": "Mutation" }, + "types": [ + { "kind": "OBJECT", "name": "QueryRoot", "interfaces": [], "fields": [{ + "name": "orders", + "type": non_null(list(non_null(named("OBJECT", "Order")))), + "isDeprecated": false, + "deprecationReason": null, + "args": [ + { "name": "first", "type": named("SCALAR", "Int"), "defaultValue": null }, + { "name": "reverse", "type": named("SCALAR", "Boolean"), "defaultValue": "false" }, + { + "name": "savedSearchId", + "type": named("SCALAR", "ID"), + "defaultValue": null, + "isDeprecated": true, + "deprecationReason": "Use `query` instead.", + }, + ], + }] }, + { "kind": "OBJECT", "name": "Mutation", "interfaces": [], "fields": [] }, + { "kind": "OBJECT", "name": "Order", "interfaces": [{ "name": "Node" }], "fields": [ + { "name": "id", "type": non_null(named("SCALAR", "ID")), "args": [] }, + { + "name": "legacyName", + "type": named("SCALAR", "String"), + "args": [], + "isDeprecated": true, + "deprecationReason": null, + }, + ] }, + { "kind": "INTERFACE", "name": "Node", "possibleTypes": [{ "name": "Order" }], "fields": [ + { "name": "id", "type": non_null(named("SCALAR", "ID")), "args": [] }, + ] }, + { "kind": "UNION", "name": "Resource", "possibleTypes": [{ "name": "Order" }] }, + { "kind": "ENUM", "name": "SortKey", "enumValues": [ + { "name": "ID", "isDeprecated": false }, + { "name": "CREATED_AT", "isDeprecated": true, "deprecationReason": "Use `ID`." }, + ] }, + { "kind": "INPUT_OBJECT", "name": "OrderInput", "inputFields": [ + { "name": "id", "type": non_null(named("SCALAR", "ID")), "defaultValue": null }, + { "name": "tags", "type": list(non_null(named("SCALAR", "String"))), "defaultValue": "[]" }, + { + "name": "note", + "type": named("SCALAR", "String"), + "defaultValue": null, + "isDeprecated": true, + "deprecationReason": "Use `notes`.", + }, + ] }, + { "kind": "SCALAR", "name": "ID" }, + { "kind": "OBJECT", "name": "__Type", "interfaces": [], "fields": [] }, + ], + } } }) + } + + #[test] + fn reads_an_introspection_result() { + let schema = Schema::from_introspection(&introspection(), "2026-10").unwrap(); + + assert_eq!(schema.api_version, "2026-10"); + assert_eq!(schema.query, "QueryRoot"); + assert_eq!(schema.mutation.as_deref(), Some("Mutation")); + assert!(schema.get("__Type").is_none()); + + let Some(TypeDef::Object { fields, .. }) = schema.get("QueryRoot") else { + panic!("QueryRoot is an object"); + }; + let orders = &fields["orders"]; + assert_eq!(orders.ty.to_string(), "[Order!]!"); + assert!(!orders.args["first"].has_default); + assert!(orders.args["reverse"].has_default); + assert_eq!( + orders.args["savedSearchId"].deprecation.as_deref(), + Some("Use `query` instead.") + ); + assert_eq!(orders.deprecation, None); + + let Some(TypeDef::Object { fields, .. }) = schema.get("Order") else { + panic!("Order is an object"); + }; + // A deprecation without a reason gets the one GraphQL gives. + assert_eq!( + fields["legacyName"].deprecation.as_deref(), + Some("No longer supported") + ); + + let Some(TypeDef::Input { fields }) = schema.get("OrderInput") else { + panic!("OrderInput is an input object"); + }; + assert!(fields["id"].is_required()); + assert!(!fields["tags"].is_required()); + assert_eq!(fields["note"].deprecation.as_deref(), Some("Use `notes`.")); + + assert_eq!(schema.possible_types("Node"), ["Order"]); + assert_eq!(schema.possible_types("Resource"), ["Order"]); + assert_eq!(schema.possible_types("Order"), ["Order"]); + assert!(schema.possible_types("SortKey").is_empty()); + assert_eq!( + schema.get("SortKey"), + Some(&TypeDef::Enum { + values: vec!["ID".to_string(), "CREATED_AT".to_string()], + deprecated: [("CREATED_AT".to_string(), "Use `ID`.".to_string())].into(), + }) + ); + } + + #[test] + fn the_stored_form_round_trips() { + let schema = Schema::from_introspection(&introspection(), "2026-10").unwrap(); + let json = schema.to_json(); + + assert_eq!(Schema::from_json(&json).unwrap(), schema); + assert!(json.starts_with("{\"format\":1,\"apiVersion\":\"2026-10\",")); + // One type per line, in name order. + assert!(json.contains( + "\n\"Order\":{\"o\":{\"f\":{\"id\":\"ID!\",\"legacyName\":\"String\"},\"t\":[\"Node\"],\"d\":{\"legacyName\":\"No longer supported\"}}},\n" + )); + assert!(json.contains("\"orders\":[\"[Order!]!\",{\"first\":\"Int\",\"reverse\":\"Boolean=\",\"savedSearchId\":\"ID\"}]")); + assert!(json.contains("\"d\":{\"orders(savedSearchId)\":\"Use `query` instead.\"}")); + assert!(json.contains("\n\"ID\":\"s\",\n")); + // The last type ends the object. + assert!(json.ends_with("\n\"SortKey\":{\"e\":{\"v\":[\"ID\",\"CREATED_AT\"],\"d\":{\"CREATED_AT\":\"Use `ID`.\"}}}\n}}\n")); + assert!(json.contains("\"OrderInput\":{\"i\":{\"f\":{\"id\":\"ID!\",\"note\":\"String\",\"tags\":\"[String!]=\"},\"d\":{\"note\":\"Use `notes`.\"}}}")); + } + + #[test] + fn keeps_the_directives_an_operation_may_use() { + let mut response = introspection(); + response["data"]["__schema"]["directives"] = json!([ + { + "name": "idempotent", + "locations": ["FIELD"], + "isRepeatable": false, + "args": [{ "name": "key", "type": { "kind": "NON_NULL", "name": null, "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } }, "defaultValue": null }], + }, + { "name": "deprecated", "locations": ["FIELD_DEFINITION", "ENUM_VALUE"], "isRepeatable": false, "args": [] }, + { "name": "tag", "locations": ["FIELD", "OBJECT"], "isRepeatable": true, "args": [] }, + ]); + let schema = Schema::from_introspection(&response, "2026-10").unwrap(); + + // A directive of the schema's definitions is left out; only executable places are kept. + assert!(schema.directive("deprecated").is_none()); + assert_eq!(schema.directive("tag").unwrap().locations, ["FIELD"]); + assert!(schema.directive("tag").unwrap().repeatable); + assert!(schema.directive("idempotent").unwrap().args["key"].is_required()); + // Without `@include` and `@skip` in the answer, none are added. + assert!(schema.directive("include").is_none()); + + let json = schema.to_json(); + assert!(json.contains("\n\"directives\":{\"idempotent\":{\"l\":[\"FIELD\"],\"a\":{\"key\":\"String!\"}},\"tag\":{\"l\":[\"FIELD\"],\"r\":true}},\"types\":{")); + assert_eq!(Schema::from_json(&json).unwrap(), schema); + + // A schema without directives has `@include` and `@skip`. + let bare = Schema::from_introspection(&introspection(), "2026-10").unwrap(); + assert_eq!( + bare.directives.keys().collect::>(), + ["include", "skip"] + ); + assert!(Schema::bundled().directive("idempotent").is_some()); + } + + #[test] + fn reports_malformed_input() { + assert_eq!( + Schema::from_introspection( + &json!({ "errors": [{ "message": "Throttled" }] }), + "2026-10" + ), + Err(SchemaError("Introspection failed: Throttled".to_string())) + ); + assert_eq!( + Schema::from_introspection(&json!({ "data": { "__schema": {} } }), "2026-10"), + Err(SchemaError( + "The introspection result has no `queryType`".to_string() + )) + ); + assert_eq!( + Schema::from_introspection( + &json!({ "__schema": { "queryType": { "name": "Missing" }, "types": [] } }), + "2026-10" + ), + Err(SchemaError( + "The query type `Missing` is not an object of the schema".to_string() + )) + ); + assert!( + Schema::from_json("{") + .unwrap_err() + .0 + .starts_with("Invalid schema file: ") + ); + assert_eq!( + Schema::from_json(r#"{"apiVersion":"2026-10","query":"Q","types":{}}"#), + Err(SchemaError( + "Not a schema file of shopify_api: it has no `format`".to_string() + )) + ); + assert_eq!( + Schema::from_json(r#"{"format":9,"apiVersion":"2026-10","query":"Q","types":{}}"#), + Err(SchemaError( + "Unsupported schema file format 9, this version reads format 1".to_string() + )) + ); + assert_eq!( + Schema::from_json( + r#"{"format":1,"apiVersion":"2026-10","query":"Q","types":{"Q":{"o":{"f":{"a":"[Int"}}}}}"# + ), + Err(SchemaError("Invalid type \"[Int\" for Q.a".to_string())) + ); + } + + #[test] + fn the_bundled_schema_is_the_admin_api() { + let schema = Schema::bundled(); + assert_eq!(schema.api_version, BUNDLED_API_VERSION); + assert_eq!(schema.query, "QueryRoot"); + assert_eq!(schema.mutation.as_deref(), Some("Mutation")); + assert!(schema.types.len() > 1000); + } +} diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs new file mode 100644 index 0000000..931050c --- /dev/null +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -0,0 +1,695 @@ +//! Operations checked against the bundled Shopify Admin schema: what is +//! refused, with which message, and the shape of what is accepted. + +use shopify_api_graphql::{ + FieldBase, Operation, OperationKind, Scalar, Schema, Selection, VariableBase, analyze, +}; + +fn check(source: &str) -> Operation { + analyze(Schema::bundled(), source).unwrap_or_else(|error| panic!("{error}\n{source}")) +} + +fn refusal(source: &str) -> String { + match analyze(Schema::bundled(), source) { + Ok(_) => panic!("accepted: {source}"), + Err(error) => error.to_string(), + } +} + +/// `key: Type` of each field, `?` marking those that may be absent. +fn fields(selection: &Selection) -> Vec { + selection + .fields + .iter() + .map(|field| { + format!( + "{}{}: {}", + field.key, + if field.conditional { "?" } else { "" }, + field.ty + ) + }) + .collect() +} + +fn child<'a>(selection: &'a Selection, key: &str) -> &'a Selection { + match selection + .fields + .iter() + .find(|field| field.key == key) + .map(|field| &field.base) + { + Some(FieldBase::Object(selection)) => selection, + _ => panic!("`{key}` is not a selection of `{}`", selection.type_name), + } +} + +// ─── Accepted ──────────────────────────────────────────────────────── + +#[test] +fn describes_variables_and_nested_selections() { + let operation = check( + "query Recent($first: Int!, $query: String, $sortKey: OrderSortKeys = CREATED_AT) { + orders(first: $first, query: $query, sortKey: $sortKey) { nodes { id name note } } + }", + ); + + assert_eq!(operation.kind, OperationKind::Query); + assert_eq!(operation.name.as_deref(), Some("Recent")); + let variables: Vec<(&str, String, bool, VariableBase)> = operation + .variables + .iter() + .map(|variable| { + ( + variable.name.as_str(), + variable.ty.to_string(), + variable.is_required(), + variable.base, + ) + }) + .collect(); + assert_eq!( + variables, + [ + ( + "first", + "Int!".to_string(), + true, + VariableBase::Scalar(Scalar::Int) + ), + ( + "query", + "String".to_string(), + false, + VariableBase::Scalar(Scalar::String) + ), + ( + "sortKey", + "OrderSortKeys".to_string(), + false, + VariableBase::Enum + ), + ] + ); + + assert_eq!(operation.data.type_name, "QueryRoot"); + assert_eq!(fields(&operation.data), ["orders: OrderConnection!"]); + let orders = child(&operation.data, "orders"); + assert_eq!(fields(orders), ["nodes: [Order!]!"]); + let nodes = child(orders, "nodes"); + assert_eq!(nodes.type_name, "Order"); + assert_eq!(fields(nodes), ["id: ID!", "name: String!", "note: String"]); +} + +#[test] +fn accepts_the_shorthand_query_and_mutations() { + let operation = check("{ shop { name } }"); + assert_eq!( + (operation.kind, operation.name), + (OperationKind::Query, None) + ); + + let operation = check( + "mutation($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { userErrors { message } } + }", + ); + assert_eq!(operation.kind, OperationKind::Mutation); + assert_eq!(operation.data.type_name, "Mutation"); + assert_eq!(operation.variables[0].base, VariableBase::Input); + assert_eq!( + fields(&operation.data), + ["metafieldsSet: MetafieldsSetPayload"] + ); +} + +#[test] +fn maps_scalars_to_their_json_form() { + let operation = check( + "{ shop { name } order(id: \"gid://shopify/Order/1\") { + createdAt + subtotalLineItemsQuantity + totalWeight + confirmed + metafield(key: \"k\") { jsonValue } + totalPriceSet { shopMoney { amount } } + } }", + ); + let order = child(&operation.data, "order"); + let scalar = |selection: &Selection, key: &str| match selection + .fields + .iter() + .find(|field| field.key == key) + .map(|field| &field.base) + { + Some(FieldBase::Scalar(scalar)) => *scalar, + _ => panic!("`{key}` is not a scalar"), + }; + assert_eq!(scalar(order, "createdAt"), Scalar::String); + assert_eq!(scalar(order, "subtotalLineItemsQuantity"), Scalar::Int); + // `UnsignedInt64` travels as a string. + assert_eq!(scalar(order, "totalWeight"), Scalar::String); + assert_eq!(scalar(order, "confirmed"), Scalar::Boolean); + assert_eq!(scalar(child(order, "metafield"), "jsonValue"), Scalar::Json); + let money = child(child(order, "totalPriceSet"), "shopMoney"); + assert_eq!(scalar(money, "amount"), Scalar::String); +} + +#[test] +fn merges_selections_of_the_same_field_and_marks_conditional_ones() { + let operation = check( + "query($withTags: Boolean!, $ids: [ID!]!) { + nodes(ids: $ids) { + id + __typename + ... on Node { id } + ... on Product { title handle ...ProductBits } + ... on Order { name tags @include(if: $withTags) } + ... on HasMetafields { metafield(key: \"k\") { value } } + } + } + fragment ProductBits on Product { title vendor featuredMedia { id } }", + ); + let nodes = child(&operation.data, "nodes"); + assert_eq!(nodes.type_name, "Node"); + assert_eq!( + fields(nodes), + [ + "id: ID!", + "__typename: String!", + "title?: String!", + "handle?: String!", + "vendor?: String!", + "featuredMedia?: Media", + "name?: String!", + "tags?: [String!]!", + "metafield?: Metafield", + ] + ); + + // On the object itself, a fragment on one of its interfaces always applies. + let operation = check( + "{ shop { ... on Node { id } ... on Shop { name } ...Meta } } + fragment Meta on HasMetafields { metafield(key: \"k\") { value } }", + ); + assert_eq!( + fields(child(&operation.data, "shop")), + ["id: ID!", "name: String!", "metafield: Metafield"] + ); + + // The same field selected twice is one field with both selections. + let operation = + check("{ shop { plan { publicDisplayName } plan { partnerDevelopment } name name } }"); + let shop = child(&operation.data, "shop"); + assert_eq!(fields(shop), ["plan: ShopPlan!", "name: String!"]); + assert_eq!( + fields(child(shop, "plan")), + ["publicDisplayName: String!", "partnerDevelopment: Boolean!"] + ); +} + +#[test] +fn accepts_literals_of_every_kind() { + check( + "mutation { + metafieldsSet(metafields: [{ ownerId: \"gid://shopify/Product/1\", key: \"k\", value: \"v\", namespace: null }]) { + userErrors { message } + } + }", + ); + check( + "{ orders(first: 5, reverse: true, sortKey: UPDATED_AT, query: \"status:open\") { nodes { id } } }", + ); + // An integer where an ID is expected, and a variable with a default for a non-null argument. + check("query($id: ID = 1) { product(id: $id) { id } node(id: 2) { id } }"); + // A single value where a list is expected. + check("{ nodes(ids: \"gid://shopify/Product/1\") { id } }"); +} + +// ─── Refused ───────────────────────────────────────────────────────── + +#[test] +fn refuses_unknown_fields_and_arguments_with_a_suggestion() { + assert_eq!( + refusal("{ orders(first: 1) { nodes { id nam } } }"), + "Type `Order` has no field `nam` (did you mean `name`?) (line 1, column 33)" + ); + assert_eq!( + refusal("{ orders(frist: 1) { nodes { id } } }"), + "Field `QueryRoot.orders` has no argument `frist` (did you mean `first`?) (line 1, column 3)" + ); + assert_eq!( + refusal("{ shop { zzzzzz } }"), + "Type `Shop` has no field `zzzzzz` (line 1, column 10)" + ); + assert_eq!( + refusal("{ shop { __typename(x: 1) } }"), + "Field `__typename` has no argument `x` (line 1, column 10)" + ); +} + +#[test] +fn refuses_missing_arguments_and_selections() { + assert_eq!( + refusal("{ product { id } }"), + "Field `QueryRoot.product` requires the argument `id: ID!` (line 1, column 3)" + ); + assert_eq!( + refusal("{ shop }"), + "Field `shop` has the type `Shop!`: select the subfields you need, `shop { … }` (line 1, column 3)" + ); + assert_eq!( + refusal("{ shop { name { length } } }"), + "Field `name` has the type `String!`, which has no subfields (line 1, column 10)" + ); +} + +#[test] +fn refuses_variables_that_do_not_fit() { + assert_eq!( + refusal("query($first: String!) { orders(first: $first) { nodes { id } } }"), + "Variable `$first` of type `String!` cannot be used for argument `first` of `QueryRoot.orders`, which expects `Int` (line 1, column 26)" + ); + assert_eq!( + refusal("query($id: ID) { product(id: $id) { id } }"), + "Variable `$id` of type `ID` cannot be used for argument `id` of `QueryRoot.product`, which expects `ID!` (line 1, column 18)" + ); + assert_eq!( + refusal("query($ids: [ID]!) { nodes(ids: $ids) { id } }"), + "Variable `$ids` of type `[ID]!` cannot be used for argument `ids` of `QueryRoot.nodes`, which expects `[ID!]!` (line 1, column 22)" + ); + assert_eq!( + refusal("{ orders(first: $first) { nodes { id } } }"), + "Variable `$first` is not declared (line 1, column 3)" + ); + assert_eq!( + refusal("query($first: Int!, $frist: Int) { orders(first: $firs) { nodes { id } } }"), + "Variable `$firs` is not declared (did you mean `first`?) (line 1, column 36)" + ); + assert_eq!( + refusal("query($first: Int!, $after: String) { orders(first: $first) { nodes { id } } }"), + "Variable `$after` is declared but never used" + ); + assert_eq!( + refusal("query($first: Int!, $first: Int!) { orders(first: $first) { nodes { id } } }"), + "Variable `$first` is declared twice (line 1, column 21)" + ); + assert_eq!( + refusal("query($sort: OrderSortKey) { orders(first: 1, sortKey: $sort) { nodes { id } } }"), + "Variable `$sort` has the unknown type `OrderSortKey` (did you mean `OrderSortKeys`?) (line 1, column 7)" + ); + assert_eq!( + refusal("query($order: Order) { shop { name } }"), + "Variable `$order` cannot have the type `Order`: `Order` is an object, not an input type (line 1, column 7)" + ); + assert_eq!( + refusal("query($flag: String!) { shop { name @include(if: $flag) } }"), + "Variable `$flag` of type `String!` cannot be used for argument `if` of `@include`, which expects `Boolean!` (line 1, column 37)" + ); +} + +#[test] +fn refuses_literals_that_do_not_fit() { + assert_eq!( + refusal("{ orders(first: \"1\") { nodes { id } } }"), + "a string is given for argument `first` of `QueryRoot.orders`, of type `Int` (line 1, column 3)" + ); + assert_eq!( + refusal("{ orders(first: 1, reverse: 1) { nodes { id } } }"), + "an integer is given for argument `reverse` of `QueryRoot.orders`, of type `Boolean` (line 1, column 3)" + ); + assert_eq!( + refusal("{ orders(first: 1, sortKey: CREATED) { nodes { id } } }"), + "`CREATED` is not a value of the enum `OrderSortKeys` (did you mean `CREATED_AT`?) (in argument `sortKey` of `QueryRoot.orders`) (line 1, column 3)" + ); + assert_eq!( + refusal("{ orders(first: 1, sortKey: \"CREATED_AT\") { nodes { id } } }"), + "a string is given for argument `sortKey` of `QueryRoot.orders`, of type `OrderSortKeys` (line 1, column 3)" + ); + assert_eq!( + refusal("{ orders(first: FIVE) { nodes { id } } }"), + "The enum value `FIVE` is given for argument `first` of `QueryRoot.orders`, of type `Int` (line 1, column 3)" + ); + assert_eq!( + refusal("{ product(id: null) { id } }"), + "`null` is not allowed for argument `id` of `QueryRoot.product`, of type `ID!` (line 1, column 3)" + ); + assert_eq!( + refusal("{ product(id: [\"a\"]) { id } }"), + "A list is given for argument `id` of `QueryRoot.product`, of type `ID!` (line 1, column 3)" + ); + assert_eq!( + refusal("{ product(id: { value: 1 }) { id } }"), + "An object is given for argument `id` of `QueryRoot.product`, of type `ID!` (line 1, column 3)" + ); +} + +#[test] +fn int_literals_are_32_bit_integers() { + check("{ orders(first: 2147483647) { nodes { id } } }"); + check("query($first: Int = -2147483648) { orders(first: $first) { nodes { id } } }"); + assert_eq!( + refusal("{ orders(first: 2147483648) { nodes { id } } }"), + "The integer is outside the range of `Int`, a 32-bit integer, given for argument `first` of `QueryRoot.orders` (line 1, column 3)" + ); + assert_eq!( + refusal("{ orders(first: -2147483649) { nodes { id } } }"), + "The integer is outside the range of `Int`, a 32-bit integer, given for argument `first` of `QueryRoot.orders` (line 1, column 3)" + ); + // A float, an ID or a custom scalar is not bounded by `Int`. + check("{ orders(first: 1) { nodes { id } } product(id: 99999999999) { id } }"); +} + +#[test] +fn default_values_fit_the_type_of_their_variable() { + check( + "query($first: Int! = 10, $sort: OrderSortKeys = CREATED_AT, $ids: [ID!] = [\"1\"]) { orders(first: $first, sortKey: $sort) { nodes { id } } nodes(ids: $ids) { id } }", + ); + assert_eq!( + refusal("query($first: Int = \"ten\") { orders(first: $first) { nodes { id } } }"), + "a string is given for the default value of `$first`, of type `Int` (line 1, column 7)" + ); + assert_eq!( + refusal("query($first: Int! = null) { orders(first: $first) { nodes { id } } }"), + "`null` is not allowed for the default value of `$first`, of type `Int!` (line 1, column 7)" + ); + assert_eq!( + refusal( + "query($sort: OrderSortKeys = CREATED) { orders(first: 1, sortKey: $sort) { nodes { id } } }" + ), + "`CREATED` is not a value of the enum `OrderSortKeys` (did you mean `CREATED_AT`?) (in the default value of `$sort`) (line 1, column 7)" + ); + assert_eq!( + refusal("query($first: Int = 3000000000) { orders(first: $first) { nodes { id } } }"), + "The integer is outside the range of `Int`, a 32-bit integer, given for the default value of `$first` (line 1, column 7)" + ); +} + +#[test] +fn json_and_custom_scalars_accept_any_literal() { + // `JSON` takes an object, a list or a scalar, in a default value and in an argument. + let operation = check( + "mutation($payload: JSON = {Amount: \"30\", customer_id: 12345, tags: [\"a\", {nested: true}]}) { + flowTriggerReceive(handle: \"h\", payload: $payload) { userErrors { message } } + }", + ); + assert_eq!(operation.variables.len(), 1); + check( + "mutation($items: JSON = [1, \"two\", null]) { flowTriggerReceive(handle: \"h\", payload: $items) { userErrors { message } } }", + ); + check( + "mutation { flowTriggerReceive(handle: \"h\", payload: {Amount: \"30\", list: [1, 2], none: null}) { userErrors { message } } }", + ); + check( + "mutation($id: String) { flowTriggerReceive(handle: \"h\", payload: {customer: $id}) { userErrors { message } } }", + ); + check( + "mutation { flowTriggerReceive(handle: \"h\", payload: [1, 2]) { userErrors { message } } }", + ); + // A variable inside the literal is declared like any other. + assert_eq!( + refusal( + "mutation { flowTriggerReceive(handle: \"h\", payload: {customer: $id}) { userErrors { message } } }" + ), + "Variable `$id` is not declared (line 1, column 12)" + ); + // An object stays refused for a built-in scalar. + assert_eq!( + refusal( + "mutation { flowTriggerReceive(handle: {a: 1}, payload: {}) { userErrors { message } } }" + ), + "An object is given for argument `handle` of `Mutation.flowTriggerReceive`, of type `String` (line 1, column 12)" + ); +} + +#[test] +fn checks_input_object_literals() { + assert_eq!( + refusal( + "mutation { metafieldsSet(metafields: [{ ownerId: \"x\", key: \"k\", valeu: \"v\" }]) { userErrors { message } } }" + ), + "Input type `MetafieldsSetInput` has no field `valeu` (did you mean `value`?) (in argument `metafields` of `Mutation.metafieldsSet`) (line 1, column 12)" + ); + assert_eq!( + refusal( + "mutation { metafieldsSet(metafields: [{ ownerId: \"x\", key: \"k\" }]) { userErrors { message } } }" + ), + "Input type `MetafieldsSetInput` requires the field `value: String!` (in argument `metafields` of `Mutation.metafieldsSet`) (line 1, column 12)" + ); + assert_eq!( + refusal( + "mutation { metafieldsSet(metafields: [{ ownerId: \"x\", key: 1, value: \"v\" }]) { userErrors { message } } }" + ), + "an integer is given for field `key` of `MetafieldsSetInput`, of type `String!` (line 1, column 12)" + ); +} + +#[test] +fn refuses_fragments_that_cannot_apply() { + assert_eq!( + refusal("{ shop { ... on Order { id } } }"), + "A fragment on `Order` never applies to a `Shop` (line 1, column 14)" + ); + assert_eq!( + refusal("{ node(id: 1) { ... on Prodct { title } } }"), + "A fragment is on the unknown type `Prodct` (did you mean `Product`?) (line 1, column 21)" + ); + assert_eq!( + refusal("{ shop { ... on ID { length } } }"), + "A fragment cannot be on `ID`, which is a scalar (line 1, column 14)" + ); + assert_eq!( + refusal("{ shop { ...Missing } }"), + "Fragment `Missing` is not defined; a `graphql!` document contains the fragments it uses (line 1, column 13)" + ); + assert_eq!( + refusal("{ shop { name } } fragment Unused on Shop { id }"), + "Fragment `Unused` is defined but never used (line 1, column 19)" + ); + assert_eq!( + refusal("{ shop { ...A } } fragment A on Shop { name ...B } fragment B on Shop { ...A }"), + "Fragment `A` includes itself (line 1, column 76)" + ); + assert_eq!( + refusal("{ shop { ...A } } fragment A on Shop { id } fragment A on Shop { name }"), + "Fragment `A` is defined twice (line 1, column 45)" + ); +} + +#[test] +fn refuses_ambiguous_keys_and_unions_without_fragments() { + assert_eq!( + refusal("{ shop { name name: email } }"), + "`name` is selected twice with different fields or types (`name: String!` and `email: String!`); give one of them an alias (line 1, column 15)" + ); + assert_eq!( + refusal( + "{ nodes(ids: []) { ... on Product { value: title } ... on Order { value: subtotalLineItemsQuantity } } }" + ), + "`value` is selected twice with different fields or types (`title: String!` and `subtotalLineItemsQuantity: Int!`); give one of them an alias (line 1, column 67)" + ); + let message = refusal("{ order(id: 1) { metafield(key: \"k\") { reference { id } } } }"); + assert!( + message.starts_with( + "`MetafieldReference` is a union: select `id` inside a fragment such as `... on " + ), + "{message}" + ); +} + +#[test] +fn refuses_documents_that_are_not_one_operation() { + assert_eq!( + refusal("{ shop { name } } query Other { shop { id } }"), + "The document contains several operations; `graphql!` takes one (line 1, column 19)" + ); + assert_eq!( + refusal("fragment A on Shop { id }"), + "The document contains no query or mutation" + ); + assert_eq!( + refusal("subscription { shop { name } }"), + "Subscriptions are not supported (line 1, column 1)" + ); + let message = refusal("{ shop { name }"); + assert!(message.starts_with("Invalid GraphQL: "), "{message}"); +} + +// ─── Deprecations ──────────────────────────────────────────────────── + +/// `coordinate @ line:column` of each deprecation. +fn deprecations(source: &str) -> Vec { + check(source) + .deprecations + .iter() + .map(|deprecation| { + let (line, column) = deprecation.position; + format!("{} @ {line}:{column}", deprecation.coordinate) + }) + .collect() +} + +#[test] +fn reports_the_deprecated_fields_arguments_and_values_used() { + assert!(deprecations("{ shop { name } }").is_empty()); + + let operation = check("{ product(id: 1) { bodyHtml descriptionHtml } }"); + assert_eq!(operation.deprecations.len(), 1); + let deprecation = &operation.deprecations[0]; + assert_eq!(deprecation.coordinate, "Product.bodyHtml"); + assert_eq!(deprecation.reason, "Use `descriptionHtml` instead."); + assert_eq!(deprecation.position, (1, 20)); + + // An argument, an enum value, an input field, and fields inside fragments. + assert_eq!( + deprecations( + "query { + collection(id: 1) { image(maxWidth: 10) { url } } + shop { currencyCode ...Legacy } + } + fragment Legacy on Shop { analyticsToken }" + ), + [ + "Collection.image(maxWidth:) @ 2:36", + "Shop.analyticsToken @ 5:40", + ] + ); + assert_eq!( + deprecations( + "mutation { productVariantsBulkCreate(productId: 1, variants: [{ price: 1 }], strategy: DEFAULT) { userErrors { message } } }" + ), + Vec::::new() + ); + let operation = check( + "mutation($id: ID!) { + collectionUpdate(input: { id: $id, publications: [] }) { userErrors { message } } + }", + ); + assert_eq!( + operation + .deprecations + .iter() + .map(|deprecation| deprecation.coordinate.as_str()) + .collect::>(), + // `input` itself is deprecated in 2026-10, for `collection`. + [ + "CollectionInput.publications", + "Mutation.collectionUpdate(input:)" + ] + ); +} + +#[test] +fn reports_deprecated_enum_values_written_in_the_operation() { + let operation = + check("{ shop { name } discountNodes(first: 1, query: \"x\") { nodes { id } } }"); + assert!(operation.deprecations.is_empty()); + let deprecated = Schema::bundled() + .types + .iter() + .find_map(|(name, definition)| match definition { + shopify_api_graphql::TypeDef::Enum { deprecated, .. } if name == "CurrencyCode" => { + deprecated.keys().next().cloned() + } + _ => None, + }) + .expect("a deprecated currency code"); + let source = format!( + "mutation {{ shopLocaleUpdate(locale: \"fr\", shopLocale: {{ published: true }}) {{ userErrors {{ message }} }} \ + priceListCreate(input: {{ name: \"x\", currency: {deprecated}, parent: {{ adjustment: {{ type: PERCENTAGE_DECREASE, value: 1 }} }} }}) {{ userErrors {{ message }} }} }}" + ); + let operation = check(&source); + assert_eq!( + operation + .deprecations + .iter() + .map(|deprecation| deprecation.coordinate.clone()) + .collect::>(), + [format!("CurrencyCode.{deprecated}")] + ); +} + +// ─── Merging, arguments and directives ─────────────────────────────── + +#[test] +fn a_subfield_of_a_conditional_place_stays_conditional() { + // `name` is only there when `$withName` is true. + let operation = + check("query($withName: Boolean!) { shop { id } shop @include(if: $withName) { name } }"); + assert_eq!( + fields(child(&operation.data, "shop")), + ["id: ID!", "name?: String!"] + ); + + // Two fragments that may each be the one that applies: a subfield is + // certain only when both select it. + let operation = check( + "query($id: ID!) { node(id: $id) { + ... on HasMetafields { metafields(first: 1) { nodes { id } } } + ... on Product { metafields(first: 1) { nodes { id key } } } + } }", + ); + let metafields = child(child(&operation.data, "node"), "metafields"); + assert_eq!(fields(metafields), ["nodes: [Metafield!]!"]); + assert_eq!( + fields(child(metafields, "nodes")), + ["id: ID!", "key?: String!"] + ); + + // A field selected alone under a condition keeps its subfields certain. + let operation = check("query($b: Boolean!) { shop @include(if: $b) { name } }"); + assert_eq!(fields(&operation.data), ["shop?: Shop!"]); + assert_eq!(fields(child(&operation.data, "shop")), ["name: String!"]); +} + +#[test] +fn the_same_key_with_other_arguments_needs_an_alias() { + assert_eq!( + refusal("{ a: product(id: \"1\") { title } a: product(id: \"2\") { handle } }"), + "`a` is selected twice with different arguments (`(id: \"1\")` and `(id: \"2\")`); give one of them an alias (line 1, column 33)" + ); + // The same arguments, in another order, merge. + check( + "{ orders(first: 1, reverse: true) { nodes { id } } orders(reverse: true, first: 1) { nodes { name } } }", + ); + assert_eq!( + refusal("{ product(id: \"1\", id: \"2\") { title } }"), + "Field `QueryRoot.product` is given the argument `id` twice (line 1, column 3)" + ); +} + +#[test] +fn directives_come_from_the_schema() { + // Shopify's `@idempotent`, on a mutation field. + check( + "mutation($key: String!) { + inventorySetQuantities(input: { name: \"available\", reason: \"correction\", quantities: [] }) @idempotent(key: $key) { + userErrors { message } + } + }", + ); + assert_eq!( + refusal("{ shop @inclde(if: true) { name } }"), + "The schema has no directive `@inclde` (did you mean `@include`?) (line 1, column 8)" + ); + assert_eq!( + refusal("query Q @include(if: true) { shop { name } }"), + "`@include` cannot be written on a query (line 1, column 9)" + ); + assert_eq!( + refusal("{ shop @include(if: true, unless: false) { name } }"), + "`@include` has no argument `unless` (line 1, column 8)" + ); + assert_eq!( + refusal("{ shop @include(if: true) @include(if: false) { name } }"), + "`@include` is written twice at the same place (line 1, column 27)" + ); + assert_eq!( + refusal("{ shop @skip { name } }"), + "`@skip` requires the argument `if: Boolean!` (line 1, column 8)" + ); + assert_eq!( + refusal("query($flag: String!) { shop { name @include(if: $flag) } }"), + "Variable `$flag` of type `String!` cannot be used for argument `if` of `@include`, which expects `Boolean!` (line 1, column 37)" + ); +} diff --git a/crates/shopify_api_macros/Cargo.toml b/crates/shopify_api_macros/Cargo.toml new file mode 100644 index 0000000..42c7154 --- /dev/null +++ b/crates/shopify_api_macros/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "shopify_api_macros" +description = "The `graphql!` macro of `shopify_api`: Shopify Admin GraphQL operations checked at compile time, with typed variables and results." +documentation = "https://docs.rs/shopify_api" +keywords = ["shopify", "graphql", "macros"] +categories = ["development-tools::procedural-macro-helpers", "api-bindings"] +readme = "README.md" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +include = ["src/**", "Cargo.toml", "README.md"] + +[lib] +proc-macro = true + +[dependencies] +shopify_api_graphql.workspace = true + +proc-macro2.workspace = true +quote.workspace = true +syn.workspace = true + +[lints] +workspace = true diff --git a/crates/shopify_api_macros/README.md b/crates/shopify_api_macros/README.md new file mode 100644 index 0000000..c22e27c --- /dev/null +++ b/crates/shopify_api_macros/README.md @@ -0,0 +1,5 @@ +# shopify_api_macros + +The `graphql!` procedural macro of [`shopify_api`](https://crates.io/crates/shopify_api). +Use it through `shopify_api::graphql!`, which documents it: the generated code +refers to `shopify_api` and does not compile without it. diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs new file mode 100644 index 0000000..5bc64b3 --- /dev/null +++ b/crates/shopify_api_macros/src/lib.rs @@ -0,0 +1,751 @@ +//! The `graphql!` macro of `shopify_api`. Use it through `shopify_api::graphql!`, +//! which re-exports and documents it. +#![forbid(unsafe_code)] + +use std::collections::HashMap; +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::SystemTime; + +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote, quote_spanned}; +use shopify_api_graphql::codegen::{ + DATA_TYPE, VARIABLES_TYPE, data_types, variable_type, variables_types, +}; +use shopify_api_graphql::{ + MINIMUM_API_VERSION, Operation, OperationKind, PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, + Variable, analyze, is_supported_api_version, +}; +use syn::parse::{Parse, ParseStream}; +use syn::spanned::Spanned; +use syn::{Attribute, Expr, Ident, LitStr, Token, Visibility}; + +/// The package whose own operations are always checked against the bundled +/// schema: the schema a crate that depends on it selects is not its own. +const RUNTIME_PACKAGE: &str = "shopify_api"; + +/// Where the text of an operation comes from. +enum Source { + /// `"query { … }"`. + Literal(LitStr), + /// `file("graphql/orders.graphql")`, relative to the crate's `Cargo.toml`. + File(LitStr), +} + +impl Parse for Source { + fn parse(input: ParseStream) -> syn::Result { + if input.peek(Ident) && input.peek2(syn::token::Paren) { + let keyword: Ident = input.parse()?; + if keyword != "file" { + return Err(syn::Error::new( + keyword.span(), + "expected the GraphQL operation as a string literal, or `file(\"path.graphql\")`", + )); + } + let content; + syn::parenthesized!(content in input); + let path: LitStr = content.parse()?; + if !content.is_empty() { + return Err(content.error("`file(…)` takes one path")); + } + return Ok(Self::File(path)); + } + input.parse().map(Self::Literal).map_err(|error| { + syn::Error::new( + error.span(), + "expected the GraphQL operation as a string literal, or `file(\"path.graphql\")`", + ) + }) + } +} + +/// `graphql!(SOURCE, name = value, …)` or `graphql! { pub mod name = SOURCE; }`. +enum Input { + Expression { + source: Source, + variables: Vec<(Ident, Expr)>, + }, + Module { + attributes: Vec, + visibility: Visibility, + name: Ident, + source: Source, + }, +} + +impl Parse for Input { + fn parse(input: ParseStream) -> syn::Result { + let attributes = input.call(Attribute::parse_outer)?; + let visibility: Visibility = input.parse()?; + + if input.peek(Token![mod]) { + input.parse::()?; + let name: Ident = input.parse()?; + input.parse::()?; + let source: Source = input.parse()?; + input.parse::>()?; + if !input.is_empty() { + return Err(input.error("expected the end of the `graphql!` module")); + } + return Ok(Self::Module { + attributes, + visibility, + name, + source, + }); + } + + if let Some(attribute) = attributes.first() { + return Err(syn::Error::new( + attribute.span(), + "attributes need the module form: `mod name = \"…\";`", + )); + } + if !matches!(visibility, Visibility::Inherited) { + return Err(syn::Error::new( + visibility.span(), + "a visibility needs the module form: `pub mod name = \"…\";`", + )); + } + let source: Source = input.parse()?; + let mut variables = Vec::new(); + while !input.is_empty() { + input.parse::()?; + if input.is_empty() { + break; + } + let name: Ident = input.parse().map_err(|error| { + syn::Error::new(error.span(), "expected a variable: `name = value`") + })?; + input.parse::()?; + variables.push((name, input.parse()?)); + } + Ok(Self::Expression { source, variables }) + } +} + +/// The text of an operation, where to point at it, and the file it was read from. +struct Text { + query: LitStr, + file: Option, +} + +impl Text { + fn read(source: &Source) -> syn::Result { + match source { + Source::Literal(query) => Ok(Self { + query: query.clone(), + file: None, + }), + Source::File(path) => { + let file = resolve(manifest_dir().as_deref(), Path::new(&path.value())); + let text = std::fs::read_to_string(&file).map_err(|error| { + syn::Error::new( + path.span(), + format!( + "Cannot read `{}`, relative to the Cargo.toml of the crate: {error}", + path.value() + ), + ) + })?; + Ok(Self { + query: LitStr::new(&text, path.span()), + file: Some(file), + }) + } + } + } + + fn span(&self) -> Span { + self.query.span() + } + + /// Makes the compiler rebuild the crate when the file changes. + fn tracking(&self) -> Option { + let file = self.file.as_ref()?.to_string_lossy().to_string(); + Some(quote!( + const _: &str = ::core::include_str!(#file); + )) + } +} + +fn manifest_dir() -> Option { + std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from) +} + +fn resolve(manifest_dir: Option<&Path>, path: &Path) -> PathBuf { + match manifest_dir { + Some(dir) if path.is_relative() => dir.join(path), + _ => path.to_path_buf(), + } +} + +/// Parsed schema files by path, with the modification time they were read at. +type SchemaCache = HashMap, Arc)>; + +/// The schema operations are checked against. +enum LoadedSchema { + /// The one bundled with `shopify_api_graphql`. + Bundled, + /// The one of the crate being compiled. + File { path: PathBuf, schema: Arc }, +} + +impl LoadedSchema { + /// The schema of the crate being compiled, else the bundled one. + fn load() -> Result { + if std::env::var("CARGO_PKG_NAME").is_ok_and(|name| name == RUNTIME_PACKAGE) { + return Ok(Self::Bundled); + } + // The variable is for the crates being built, not for their + // dependencies, which ship their own schema files. + let primary = std::env::var_os("CARGO_PRIMARY_PACKAGE").is_some(); + let named = std::env::var_os(SCHEMA_ENV).filter(|_| primary); + Ok( + match schema_file(manifest_dir().as_deref(), named.as_deref())? { + Some(path) => { + let schema = read_schema(&path)?; + if !is_supported_api_version(&schema.api_version) { + return Err(format!( + "`{}` is the schema of `{}`, a version shopify_api does not call (from {MINIMUM_API_VERSION}, or `unstable`): \ + download another one with `shopify-api schema download --api-version …`", + path.display(), + schema.api_version + )); + } + Self::File { schema, path } + } + None => Self::Bundled, + }, + ) + } + + fn schema(&self) -> &Schema { + match self { + Self::Bundled => Schema::bundled(), + Self::File { schema, .. } => schema, + } + } + + /// Makes the compiler rebuild the crate when what the expansion depends on changes. + fn tracking(&self) -> TokenStream { + // One operation of the crate is enough to track the file, which is large. + static TRACKED: Mutex> = Mutex::new(Vec::new()); + let file = match self { + Self::File { path, .. } => { + let mut tracked = TRACKED + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + (!tracked.contains(path)).then(|| { + tracked.push(path.clone()); + let path = path.to_string_lossy().to_string(); + quote!( + const _: &[u8] = ::core::include_bytes!(#path); + ) + }) + } + Self::Bundled => None, + }; + quote! { + const _: ::core::option::Option<&str> = ::core::option_env!(#SCHEMA_ENV); + #file + } + } + + /// Checks an operation, pointing a refusal at its text. + fn check(&self, text: &Text) -> syn::Result { + analyze(self.schema(), &text.query.value()).map_err(|error| { + let file = match &text.file { + Some(file) => { + let relative = manifest_dir() + .and_then(|dir| file.strip_prefix(dir).ok().map(Path::to_path_buf)); + format!(" in {}", relative.as_deref().unwrap_or(file).display()) + } + None => String::new(), + }; + syn::Error::new( + text.span(), + format!( + "{error}{file}\n(checked against the Shopify Admin API {})", + self.schema().api_version + ), + ) + }) + } +} + +/// The schema file of the crate being compiled, if it has one: the file named +/// by `SHOPIFY_GRAPHQL_SCHEMA`, else `graphql/admin.schema.json` next to its +/// `Cargo.toml` when that file exists. +fn schema_file( + manifest_dir: Option<&Path>, + named: Option<&OsStr>, +) -> Result, String> { + match named.filter(|value| !value.is_empty()) { + Some(named) => { + let path = resolve(manifest_dir, Path::new(named)); + if !path.is_file() { + return Err(format!( + "{SCHEMA_ENV} names `{}`, which is not a file", + path.display() + )); + } + Ok(Some(path)) + } + None => Ok(Some(resolve(manifest_dir, Path::new(PROJECT_SCHEMA_PATH))) + .filter(|path| path.is_file())), + } +} + +/// Reads a schema file. One compilation expands many operations: each file is +/// parsed once, and again when it changes. +fn read_schema(file: &Path) -> Result, String> { + static CACHE: Mutex> = Mutex::new(None); + let modified = std::fs::metadata(file) + .and_then(|metadata| metadata.modified()) + .ok(); + let mut cache = CACHE + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let cache = cache.get_or_insert_with(HashMap::new); + if let Some((cached, schema)) = cache.get(file) + && *cached == modified + { + return Ok(schema.clone()); + } + let json = std::fs::read_to_string(file) + .map_err(|error| format!("Cannot read the schema `{}`: {error}", file.display()))?; + let schema = Schema::from_json(&json).map(Arc::new).map_err(|error| { + format!( + "`{}`: {error}. Run `shopify-api schema download` to download it again.", + file.display() + ) + })?; + cache.insert(file.to_path_buf(), (modified, schema.clone())); + Ok(schema) +} + +/// One warning per deprecated thing the operation uses: the use of a +/// `#[deprecated]` constant, at the operation, whose note says what and why. +fn deprecation_warnings(schema: &Schema, operation: &Operation, text: &Text) -> TokenStream { + let warnings = operation.deprecations.iter().map(|deprecation| { + let (line, column) = deprecation.position; + let note = format!( + "`{}` is deprecated in the Shopify Admin API {}: {} (line {line}, column {column} of the operation)", + deprecation.coordinate, schema.api_version, deprecation.reason + ); + quote_spanned! {text.span()=> + const _: () = { + #[deprecated(note = #note)] + const SHOPIFY_DEPRECATION: () = (); + SHOPIFY_DEPRECATION + }; + } + }); + quote!(#(#warnings)*) +} + +fn kind(operation: &Operation, krate: &TokenStream) -> TokenStream { + match operation.kind { + OperationKind::Query => quote!(#krate::OperationKind::Query), + OperationKind::Mutation => quote!(#krate::OperationKind::Mutation), + } +} + +/// `Operation::::new(…)` for the checked operation. +fn constructor( + schema: &Schema, + operation: &Operation, + query: &TokenStream, + krate: &TokenStream, +) -> TokenStream { + let data = format_ident!("{}", DATA_TYPE); + let kind = kind(operation, krate); + let api_version = &schema.api_version; + let name = match &operation.name { + Some(name) => quote!(::core::option::Option::Some(#name)), + None => quote!(::core::option::Option::None), + }; + quote!(#krate::Operation::<#data>::__checked(#query, #kind, #name, #api_version)) +} + +/// `graphql!("…", name = value)`: the operation as a value. +fn expand_expression( + schema: &LoadedSchema, + source: &Source, + variables: &[(Ident, Expr)], +) -> syn::Result { + let krate = quote!(::shopify_api); + let text = Text::read(source)?; + let operation = schema.check(&text)?; + + // Each value with the variable it is for. + let mut given: Vec<(&Variable, &Expr)> = Vec::new(); + for (name, value) in variables { + let Some(declared) = operation + .variables + .iter() + .find(|variable| name == &variable.name) + else { + let declared: Vec = operation + .variables + .iter() + .map(|variable| format!("${}", variable.name)) + .collect(); + let known = if declared.is_empty() { + "it declares no variables".to_string() + } else { + format!("it declares {}", declared.join(", ")) + }; + return Err(syn::Error::new( + name.span(), + format!("The operation has no variable `${name}`: {known}"), + )); + }; + if given + .iter() + .any(|(earlier, _)| earlier.name == declared.name) + { + return Err(syn::Error::new( + name.span(), + format!("Variable `${name}` is given twice"), + )); + } + given.push((declared, value)); + } + if let Some(missing) = operation.variables.iter().find(|variable| { + variable.is_required() + && !given + .iter() + .any(|(declared, _)| declared.name == variable.name) + }) { + return Err(syn::Error::new( + text.span(), + format!( + "Variable `${}: {}` needs a value: add `{} = …` after the operation", + missing.name, missing.ty, missing.name + ), + )); + } + + // Evaluated before the generated types are in scope, so that the + // values cannot name them by accident. + let locals: Vec = (0..given.len()) + .map(|index| { + Ident::new( + &format!("__shopify_api_variable_{index}"), + Span::mixed_site(), + ) + }) + .collect(); + let values = given.iter().map(|(_, value)| value); + let setters = given.iter().zip(&locals).map(|((declared, value), local)| { + let key = &declared.name; + match variable_type(declared, &krate) { + Some(ty) => quote_spanned!(value.span()=> .variable::<#ty, _>(#key, #local)), + None => quote_spanned!(value.span()=> .json_variable(#key, #local)), + } + }); + + let tracking = schema.tracking(); + let file = text.tracking(); + let warnings = deprecation_warnings(schema.schema(), &operation, &text); + let types = data_types(&operation, &krate); + let query = &text.query; + let constructor = constructor(schema.schema(), &operation, "e!(#query), &krate); + Ok(quote! {{ + #(let #locals = #values;)* + { + #tracking + #file + #warnings + #types + #constructor + #(#setters)* + } + }}) +} + +/// `graphql! { mod name = "…"; }`: the operation as a module that names its types. +fn expand_module( + schema: &LoadedSchema, + attributes: &[Attribute], + visibility: &Visibility, + name: &Ident, + source: &Source, +) -> syn::Result { + let krate = quote!(::shopify_api); + let text = Text::read(source)?; + let operation = schema.check(&text)?; + let data = format_ident!("{}", DATA_TYPE); + let constructor = constructor(schema.schema(), &operation, "e!(QUERY), &krate); + let (variables, function) = if operation.variables.is_empty() { + let function = quote! { + /// The operation, for `Shopify::execute`. + pub fn operation() -> #krate::Operation<#data> { + #constructor + } + }; + (TokenStream::new(), function) + } else { + let variables = format_ident!("{}", VARIABLES_TYPE); + let function = quote! { + /// The operation with its variables, for `Shopify::execute`. + pub fn operation(variables: #variables) -> #krate::Operation<#data> { + #constructor.variables(variables) + } + }; + ( + variables_types(schema.schema(), &operation, &krate), + function, + ) + }; + + let tracking = schema.tracking(); + let file = text.tracking(); + let warnings = deprecation_warnings(schema.schema(), &operation, &text); + let types = data_types(&operation, &krate); + let query = &text.query; + let api_version = &schema.schema().api_version; + let operation_name = match &operation.name { + Some(name) => quote!(::core::option::Option::Some(#name)), + None => quote!(::core::option::Option::None), + }; + let kind = kind(&operation, &krate); + Ok(quote! { + #(#attributes)* + #visibility mod #name { + #tracking + #file + #warnings + + /// The text of the operation. + pub const QUERY: &str = #query; + /// The name of the operation, when it has one. + pub const NAME: ::core::option::Option<&str> = #operation_name; + /// A query or a mutation. + pub const KIND: #krate::OperationKind = #kind; + /// The Admin API version the operation was checked against. + pub const API_VERSION: &str = #api_version; + + #types + #variables + #function + } + }) +} + +fn expand(input: Input) -> syn::Result { + let schema = + LoadedSchema::load().map_err(|message| syn::Error::new(Span::call_site(), message))?; + match input { + Input::Expression { source, variables } => expand_expression(&schema, &source, &variables), + Input::Module { + attributes, + visibility, + name, + source, + } => expand_module(&schema, &attributes, &visibility, &name, &source), + } +} + +/// See `shopify_api::graphql!`. +#[proc_macro] +pub fn graphql(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as Input); + expand(input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +#[cfg(test)] +mod tests { + use super::*; + + const SCHEMA: &str = r#"{"format":1,"apiVersion":"2026-07","query":"QueryRoot","types":{ +"QueryRoot":{"o":{"f":{"ping":"String"}}}, +"String":"s" +}}"#; + + /// An empty directory removed when the test ends. + struct Project(PathBuf); + + impl Project { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir() + .join(format!("shopify-api-macros-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn write(&self, path: &str, content: &str) -> PathBuf { + let file = self.0.join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, content).unwrap(); + file + } + } + + impl Drop for Project { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn a_crate_without_a_schema_file_uses_the_bundled_schema() { + let project = Project::new("bundled"); + assert_eq!(schema_file(Some(&project.0), None), Ok(None)); + assert_eq!( + schema_file(Some(&project.0), Some(OsStr::new(""))), + Ok(None) + ); + assert_eq!(schema_file(None, None), Ok(None)); + } + + #[test] + fn the_crate_file_and_the_environment_select_another_schema() { + let project = Project::new("selected"); + let downloaded = project.write("graphql/admin.schema.json", SCHEMA); + let other = project.write("schemas/unstable.json", SCHEMA); + + assert_eq!(schema_file(Some(&project.0), None), Ok(Some(downloaded))); + // The environment wins, relative to the manifest or absolute. + let named = OsStr::new("schemas/unstable.json"); + assert_eq!( + schema_file(Some(&project.0), Some(named)), + Ok(Some(other.clone())) + ); + assert_eq!(schema_file(None, Some(other.as_os_str())), Ok(Some(other))); + + let missing = project.0.join("missing.json"); + assert_eq!( + schema_file(Some(&project.0), Some(OsStr::new("missing.json"))), + Err(format!( + "SHOPIFY_GRAPHQL_SCHEMA names `{}`, which is not a file", + missing.display() + )) + ); + } + + #[test] + fn schema_files_are_read_once_and_again_when_they_change() { + let project = Project::new("read"); + let file = project.write("graphql/admin.schema.json", SCHEMA); + + let first = read_schema(&file).unwrap(); + assert_eq!(first.api_version, "2026-07"); + assert!(Arc::ptr_eq(&first, &read_schema(&file).unwrap())); + + // A later modification time, as after `shopify-api schema download`. + std::fs::write(&file, SCHEMA.replace("2026-07", "2026-10")).unwrap(); + let later = SystemTime::now() + std::time::Duration::from_secs(5); + std::fs::File::options() + .write(true) + .open(&file) + .unwrap() + .set_modified(later) + .unwrap(); + assert_eq!(read_schema(&file).unwrap().api_version, "2026-10"); + } + + #[test] + fn a_malformed_schema_file_says_how_to_restore_it() { + let project = Project::new("malformed"); + let file = project.write("graphql/admin.schema.json", "{"); + + let error = read_schema(&file).unwrap_err(); + assert!( + error.starts_with(&format!("`{}`: Invalid schema file: ", file.display())), + "{error}" + ); + assert!( + error.ends_with(". Run `shopify-api schema download` to download it again."), + "{error}" + ); + + let error = read_schema(&project.0.join("absent.json")).unwrap_err(); + assert!(error.starts_with("Cannot read the schema `"), "{error}"); + } + + #[test] + fn parses_both_forms_and_both_sources() { + let expression: Input = + syn::parse_str(r#""{ shop { name } }", first = 1, after = cursor,"#).unwrap(); + let Input::Expression { + source: Source::Literal(query), + variables, + } = expression + else { + panic!("an expression with a literal"); + }; + assert_eq!(query.value(), "{ shop { name } }"); + let names: Vec = variables.iter().map(|(name, _)| name.to_string()).collect(); + assert_eq!(names, ["first", "after"]); + + let expression: Input = syn::parse_str(r#"file("graphql/shop.graphql"), id = id"#).unwrap(); + let Input::Expression { + source: Source::File(path), + variables, + } = expression + else { + panic!("an expression with a file"); + }; + assert_eq!(path.value(), "graphql/shop.graphql"); + assert_eq!(variables.len(), 1); + + let module: Input = + syn::parse_str("#[doc = \"Docs.\"] pub mod shop_name = \"{ shop { name } }\";") + .unwrap(); + let Input::Module { + attributes, name, .. + } = module + else { + panic!("a module"); + }; + assert_eq!(name, "shop_name"); + assert_eq!(attributes.len(), 1); + + let module: Input = + syn::parse_str(r#"pub(crate) mod shop_name = file("graphql/shop.graphql");"#).unwrap(); + assert!(matches!( + module, + Input::Module { + source: Source::File(_), + .. + } + )); + + for (source, message) in [ + ( + "first = 1", + "expected the GraphQL operation as a string literal, or `file(\"path.graphql\")`", + ), + ( + r#"path("x.graphql")"#, + "expected the GraphQL operation as a string literal, or `file(\"path.graphql\")`", + ), + (r#"file("a", "b")"#, "`file(…)` takes one path"), + ( + r#""{ shop { name } }", 1"#, + "expected a variable: `name = value`", + ), + ( + r#"pub "{ shop { name } }""#, + "a visibility needs the module form: `pub mod name = \"…\";`", + ), + ( + r#"mod shop = "{ shop { name } }"; 1"#, + "expected the end of the `graphql!` module", + ), + ] { + let error = syn::parse_str::(source) + .err() + .expect(source) + .to_string(); + assert_eq!(error, message, "{source}"); + } + } +} diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..0cf2e85 --- /dev/null +++ b/deny.toml @@ -0,0 +1,31 @@ +# Policy of `mise run audit`. cargo-deny checks what the workspace depends on; +# `cargo audit` reads the same RustSec database from Cargo.lock alone. + +[graph] +all-features = true + +[advisories] +version = 2 +yanked = "deny" + +[bans] +multiple-versions = "allow" +wildcards = "deny" +allow-wildcard-paths = true + +[sources] +unknown-registry = "deny" +unknown-git = "deny" + +[licenses] +version = 2 +# Permissive licenses only: the crates are MIT. +allow = [ + "MIT", + "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", + "BSD-3-Clause", + "ISC", + "Unicode-3.0", + "CDLA-Permissive-2.0", +] diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..b32807d --- /dev/null +++ b/mise.toml @@ -0,0 +1,59 @@ +# Toolchain and tasks. Run `mise install` once, then `mise run ` (`mise tasks` lists them). +[tools] +rust = { version = "1.99.1", profile = "minimal", components = "clippy,rustfmt" } +"cargo:cargo-audit" = "0.22.2" +cargo-deny = "0.20.2" + +[env] +RUST_BACKTRACE = "1" + +[tasks.fmt] +description = "Format the workspace" +run = "cargo fmt --all" + +[tasks."fmt:check"] +description = "Check the formatting of the workspace" +run = "cargo fmt --all -- --check" + +[tasks.lint] +description = "Clippy on every crate, target and feature, warnings are errors" +run = "cargo clippy --workspace --all-targets --all-features --locked -- -D warnings" + +[tasks.test] +description = "Run every test, with every feature. No network: Shopify is mocked." +run = "cargo test --workspace --all-features --locked" + +[tasks."test:min"] +description = "Build and test the client with its default features only" +run = "cargo test -p shopify_api --locked" + +[tasks.doc] +description = "Build the documentation, warnings are errors" +env = { RUSTDOCFLAGS = "-D warnings --cfg docsrs" } +run = "cargo doc --workspace --all-features --no-deps --locked" + +[tasks.check] +description = "What CI runs: fmt check, clippy, tests, docs" +depends = ["fmt:check", "lint", "test", "test:min", "doc"] + +[tasks.msrv] +description = "Build the workspace with the minimum supported Rust version (1.88)" +run = "cargo +1.88 check --workspace --all-features --locked" + +[tasks."ui:bless"] +description = "Rewrite the expected compiler errors of the `graphql!` compile-fail tests" +env = { TRYBUILD = "overwrite" } +run = "cargo test -p shopify_api --all-features --locked --test compile_fail" + +[tasks."schema:bundle"] +description = "Download the Admin schema bundled with the crates, for the version given (2026-10 by default)" +usage = 'arg "[version]" default="2026-10"' +run = "cargo run -p shopify_api --features cli --locked -- schema download --api-version ${usage_version} --out crates/shopify_api_graphql/schema/admin-${usage_version}.json" + +[tasks."test:live"] +description = "Run the tests against a real development store (needs SHOPIFY_TEST_SHOP and a token, see tests/live.rs)" +run = "cargo test -p shopify_api --all-features --locked --test live -- --ignored --test-threads=1" + +[tasks.audit] +description = "Known vulnerabilities, licenses and sources of the dependencies (needs the network)" +run = ["cargo audit", "cargo deny check"] diff --git a/schema_dl.graphql b/schema_dl.graphql deleted file mode 100644 index 73ad976..0000000 --- a/schema_dl.graphql +++ /dev/null @@ -1,107 +0,0 @@ -query IntrospectionQuery { - __schema { - queryType { - name - } - mutationType { - name - } - subscriptionType { - name - } - types { - ...FullType - } - directives { - name - description - locations - args { - ...InputValue - } - } - } -} - -fragment FullType on __Type { - kind - name - description - fields(includeDeprecated: true) { - name - description - args { - ...InputValue - } - type { - ...TypeRef - } - isDeprecated - deprecationReason - } - inputFields { - ...InputValue - } - interfaces { - ...TypeRef - } - enumValues(includeDeprecated: true) { - name - description - isDeprecated - deprecationReason - } - possibleTypes { - ...TypeRef - } -} - -fragment InputValue on __InputValue { - name - description - type { - ...TypeRef - } - defaultValue -} - -fragment TypeRef on __Type { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - } - } - } - } - } - } - } - } - } -} diff --git a/src/auth.rs b/src/auth.rs deleted file mode 100644 index 283e607..0000000 --- a/src/auth.rs +++ /dev/null @@ -1,293 +0,0 @@ -use std::{future::Future, pin::Pin}; - -use chrono::{DateTime, Utc}; -use serde::{Deserialize, Serialize}; - -use crate::{Shopify, ShopifyAPIError}; - -pub type TokenStoreFuture<'a> = - Pin> + Send + 'a>>; - -pub trait TokenStore: Send + Sync { - fn save_token<'a>(&'a self, shop: &'a str, token: TokenData) -> TokenStoreFuture<'a>; -} - -#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] -pub struct TokenData { - pub access_token: String, - pub scope: Option, - pub expires_at: Option>, - pub refresh_token: Option, - pub refresh_token_expires_at: Option>, -} - -impl std::fmt::Debug for TokenData { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("TokenData") - .field("access_token", &"") - .field("scope", &self.scope) - .field("expires_at", &self.expires_at) - .field( - "refresh_token", - &self.refresh_token.as_ref().map(|_| ""), - ) - .field("refresh_token_expires_at", &self.refresh_token_expires_at) - .finish() - } -} - -impl TokenData { - pub fn never_expiring(access_token: impl Into) -> Self { - Self { - access_token: access_token.into(), - scope: None, - expires_at: None, - refresh_token: None, - refresh_token_expires_at: None, - } - } - - pub fn expires_within(&self, leeway: chrono::Duration) -> bool { - self.expires_at - .map(|expires_at| expires_at <= Utc::now() + leeway) - .unwrap_or(false) - } -} - -#[derive(Clone, Eq, PartialEq)] -pub enum ShopifyAuth { - AccessToken(String), - ClientCredentials { - client_id: String, - client_secret: String, - current_token: Option, - }, - ExpiringOfflineToken { - client_id: String, - client_secret: String, - token: TokenData, - }, -} - -impl std::fmt::Debug for ShopifyAuth { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - ShopifyAuth::AccessToken(_) => { - f.debug_tuple("AccessToken").field(&"").finish() - } - ShopifyAuth::ClientCredentials { current_token, .. } => f - .debug_struct("ClientCredentials") - .field("client_id", &"") - .field("client_secret", &"") - .field("current_token", current_token) - .finish(), - ShopifyAuth::ExpiringOfflineToken { token, .. } => f - .debug_struct("ExpiringOfflineToken") - .field("client_id", &"") - .field("client_secret", &"") - .field("token", token) - .finish(), - } - } -} - -impl ShopifyAuth { - pub fn client_credentials( - client_id: impl Into, - client_secret: impl Into, - ) -> Self { - Self::ClientCredentials { - client_id: client_id.into(), - client_secret: client_secret.into(), - current_token: None, - } - } - - pub fn expiring_offline_token( - client_id: impl Into, - client_secret: impl Into, - token: TokenData, - ) -> Self { - Self::ExpiringOfflineToken { - client_id: client_id.into(), - client_secret: client_secret.into(), - token, - } - } -} - -#[derive(Debug, Deserialize)] -struct TokenResponse { - access_token: String, - scope: Option, - expires_in: Option, - refresh_token: Option, - refresh_token_expires_in: Option, -} - -impl TokenResponse { - fn into_token_data(self) -> TokenData { - TokenData { - access_token: self.access_token, - scope: self.scope, - expires_at: self - .expires_in - .map(|seconds| Utc::now() + chrono::Duration::seconds(seconds)), - refresh_token: self.refresh_token, - refresh_token_expires_at: self - .refresh_token_expires_in - .map(|seconds| Utc::now() + chrono::Duration::seconds(seconds)), - } - } -} - -impl Shopify { - pub async fn access_token(&self) -> Result { - let auth = self - .auth - .lock() - .map_err(|_| ShopifyAPIError::Authentication("auth lock poisoned".to_string()))? - .clone(); - - match auth { - ShopifyAuth::AccessToken(token) => Ok(token), - ShopifyAuth::ClientCredentials { - client_id, - client_secret, - current_token, - } => { - if let Some(token) = current_token { - if !token.expires_within(self.token_refresh_leeway) { - return Ok(token.access_token); - } - } - - let token = self - .request_client_credentials_token(&client_id, &client_secret) - .await?; - self.persist_and_replace_auth( - ShopifyAuth::ClientCredentials { - client_id, - client_secret, - current_token: Some(token.clone()), - }, - token.clone(), - ) - .await?; - Ok(token.access_token) - } - ShopifyAuth::ExpiringOfflineToken { - client_id, - client_secret, - token, - } => { - if !token.expires_within(self.token_refresh_leeway) { - return Ok(token.access_token); - } - - let refresh_token = token.refresh_token.as_deref().ok_or_else(|| { - ShopifyAPIError::Authentication( - "expiring offline token is missing refresh_token".to_string(), - ) - })?; - let refreshed = self - .refresh_token_with_credentials(&client_id, &client_secret, refresh_token) - .await?; - self.persist_and_replace_auth( - ShopifyAuth::ExpiringOfflineToken { - client_id, - client_secret, - token: refreshed.clone(), - }, - refreshed.clone(), - ) - .await?; - Ok(refreshed.access_token) - } - } - } - - async fn persist_and_replace_auth( - &self, - auth: ShopifyAuth, - token: TokenData, - ) -> Result<(), ShopifyAPIError> { - self.replace_auth(auth)?; - if let Some(store) = &self.token_store { - store.save_token(self.shop_domain(), token).await?; - } - Ok(()) - } - - pub async fn request_client_credentials_token( - &self, - client_id: &str, - client_secret: &str, - ) -> Result { - let response = self - .client() - .post(self.token_url()) - .form(&[ - ("grant_type", "client_credentials"), - ("client_id", client_id), - ("client_secret", client_secret), - ]) - .send() - .await? - .error_for_status()? - .json::() - .await?; - - Ok(response.into_token_data()) - } - - pub async fn refresh_token_with_credentials( - &self, - client_id: &str, - client_secret: &str, - refresh_token: &str, - ) -> Result { - let response = self - .client() - .post(self.token_url()) - .form(&[ - ("grant_type", "refresh_token"), - ("client_id", client_id), - ("client_secret", client_secret), - ("refresh_token", refresh_token), - ]) - .send() - .await? - .error_for_status()? - .json::() - .await?; - - Ok(response.into_token_data()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn token_expiration_uses_leeway() { - let token = TokenData { - access_token: "token".to_string(), - scope: None, - expires_at: Some(Utc::now() + chrono::Duration::minutes(1)), - refresh_token: None, - refresh_token_expires_at: None, - }; - - assert!(token.expires_within(chrono::Duration::minutes(5))); - assert!(!token.expires_within(chrono::Duration::seconds(1))); - } - - #[test] - fn static_token_never_expires() { - let token = TokenData::never_expiring("token"); - - assert!(!token.expires_within(chrono::Duration::days(365))); - } -} diff --git a/src/bin/shopify-api.rs b/src/bin/shopify-api.rs deleted file mode 100644 index f885f92..0000000 --- a/src/bin/shopify-api.rs +++ /dev/null @@ -1,97 +0,0 @@ -use std::{fs::File, path::PathBuf}; - -use clap::{Parser, Subcommand}; -use shopify_api::{ - download_public_admin_schema, ApiVersion, Shopify, ShopifyAPIError, ShopifyAuth, ShopifyConfig, -}; - -#[derive(Debug, Parser)] -#[command(name = "shopify-api")] -#[command(about = "Shopify API helper commands")] -struct Cli { - #[command(subcommand)] - command: Commands, -} - -#[derive(Debug, Subcommand)] -enum Commands { - Schema { - #[command(subcommand)] - command: SchemaCommands, - }, -} - -#[derive(Debug, Subcommand)] -enum SchemaCommands { - Download { - #[arg(long)] - shop: Option, - #[arg(long)] - access_token: Option, - #[arg(long)] - client_id: Option, - #[arg(long)] - client_secret: Option, - #[arg(long, default_value = shopify_api::DEFAULT_API_VERSION)] - api_version: String, - #[arg(long)] - public: bool, - #[arg(long)] - out: PathBuf, - }, -} - -#[tokio::main] -async fn main() -> Result<(), ShopifyAPIError> { - let cli = Cli::parse(); - - match cli.command { - Commands::Schema { - command: - SchemaCommands::Download { - shop, - access_token, - client_id, - client_secret, - api_version, - public, - out, - }, - } => { - let api_version = ApiVersion::new(api_version)?; - let schema = if public { - download_public_admin_schema(api_version.as_str()).await? - } else { - let shop = shop.ok_or_else(|| { - ShopifyAPIError::Authentication( - "provide --shop unless using --public".to_string(), - ) - })?; - - let auth = match (access_token, client_id, client_secret) { - (Some(token), None, None) => ShopifyAuth::AccessToken(token), - (None, Some(client_id), Some(client_secret)) => { - ShopifyAuth::client_credentials(client_id, client_secret) - } - _ => { - return Err(ShopifyAPIError::Authentication( - "provide either --access-token or both --client-id and --client-secret" - .to_string(), - )); - } - }; - - let config = ShopifyConfig { - api_version, - ..ShopifyConfig::default() - }; - let shopify = Shopify::new(shop, auth, config)?; - shopify.download_admin_schema().await? - }; - let file = File::create(out).map_err(|err| ShopifyAPIError::Other(err.to_string()))?; - serde_json::to_writer_pretty(file, &schema)?; - } - } - - Ok(()) -} diff --git a/src/graphql/bulk_query.rs b/src/graphql/bulk_query.rs deleted file mode 100644 index 8f4075c..0000000 --- a/src/graphql/bulk_query.rs +++ /dev/null @@ -1,562 +0,0 @@ -use std::time::{Duration, Instant}; - -use serde::{Deserialize, Serialize}; -use serde_json::json; - -use crate::{Shopify, ShopifyAPIError}; - -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum StagedUploadResource { - BulkMutationVariables, - CollectionImage, - File, - Image, - Model3D, - ProductImage, - ReturnLabel, - UrlRedirectImport, - Video, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct StagedUploadParameter { - pub name: String, - pub value: String, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct StagedMediaUploadTarget { - pub parameters: Vec, - #[serde(rename = "resourceUrl")] - pub resource_url: String, - pub url: String, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct StagedUploadsCreateInput { - pub filename: String, - pub mime_type: String, - pub resource: StagedUploadResource, - pub http_method: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub file_size: Option, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ShopifyUserError { - pub field: Option>, - pub message: String, -} - -#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum ShopifyBulkErrorCode { - AccessDenied, - InternalServerError, - Timeout, -} - -#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum ShopifyBulkStatus { - Canceled, - Canceling, - Completed, - Created, - Expired, - Failed, - Running, -} - -impl ShopifyBulkStatus { - pub fn is_terminal(&self) -> bool { - matches!( - self, - ShopifyBulkStatus::Canceled - | ShopifyBulkStatus::Completed - | ShopifyBulkStatus::Expired - | ShopifyBulkStatus::Failed - ) - } -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ShopifyBulkOperation { - pub id: String, - pub url: Option, - #[serde(rename = "partialDataUrl")] - pub partial_data_url: Option, - pub status: ShopifyBulkStatus, - #[serde(rename = "errorCode")] - pub error_code: Option, - #[serde(rename = "createdAt")] - pub created_at: Option, - #[serde(rename = "completedAt")] - pub completed_at: Option, - #[serde(rename = "objectCount")] - pub object_count: Option, - #[serde(rename = "fileSize")] - pub file_size: Option, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BulkOperationPayload { - #[serde(rename = "bulkOperation")] - pub bulk_operation: Option, - #[serde(rename = "userErrors")] - pub user_errors: Vec, -} - -#[derive(Debug, Clone)] -pub struct BulkWaitOptions { - pub poll_interval: Duration, - pub timeout: Option, -} - -impl Default for BulkWaitOptions { - fn default() -> Self { - Self { - poll_interval: Duration::from_secs(10), - timeout: None, - } - } -} - -#[derive(Debug, Clone, Default)] -pub struct BulkOperationsFilter { - pub first: u32, - pub query: Option, - pub after: Option, -} - -#[derive(Debug, Clone)] -pub struct BulkConcurrencyOptions { - pub max_concurrent: usize, -} - -impl Default for BulkConcurrencyOptions { - fn default() -> Self { - Self { max_concurrent: 5 } - } -} - -#[derive(Debug, Deserialize)] -struct RunBulkQueryData { - #[serde(rename = "bulkOperationRunQuery")] - payload: BulkOperationPayload, -} - -#[derive(Debug, Deserialize)] -struct RunBulkMutationData { - #[serde(rename = "bulkOperationRunMutation")] - payload: BulkOperationPayload, -} - -#[derive(Debug, Deserialize)] -struct BulkOperationData { - #[serde(rename = "bulkOperation")] - bulk_operation: Option, -} - -#[derive(Debug, Deserialize)] -struct BulkOperationsData { - #[serde(rename = "bulkOperations")] - bulk_operations: BulkOperationConnection, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BulkOperationConnection { - pub edges: Vec, - #[serde(rename = "pageInfo")] - pub page_info: PageInfo, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BulkOperationEdge { - pub cursor: String, - pub node: ShopifyBulkOperation, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct PageInfo { - #[serde(rename = "hasNextPage")] - pub has_next_page: bool, - #[serde(rename = "endCursor")] - pub end_cursor: Option, -} - -#[derive(Debug, Deserialize)] -struct StagedUploadsData { - #[serde(rename = "stagedUploadsCreate")] - staged_uploads_create: StagedUploadsCreatePayload, -} - -#[derive(Debug, Deserialize)] -struct StagedUploadsCreatePayload { - #[serde(rename = "stagedTargets")] - staged_targets: Vec, - #[serde(rename = "userErrors")] - user_errors: Vec, -} - -impl Shopify { - pub async fn run_bulk_queries( - &self, - queries: I, - options: BulkConcurrencyOptions, - ) -> Result, ShopifyAPIError> - where - I: IntoIterator, - S: AsRef, - { - let queries = queries.into_iter().collect::>(); - if queries.len() > options.max_concurrent { - return Err(ShopifyAPIError::Other(format!( - "received {} bulk queries but max_concurrent is {}", - queries.len(), - options.max_concurrent - ))); - } - - let mut operations = Vec::with_capacity(queries.len()); - for query in queries { - operations.push(self.run_bulk_query(query.as_ref()).await?); - } - - Ok(operations) - } - - pub async fn run_bulk_mutations( - &self, - mutations: I, - options: BulkConcurrencyOptions, - ) -> Result, ShopifyAPIError> - where - I: IntoIterator, - M: AsRef, - P: AsRef, - { - let mutations = mutations.into_iter().collect::>(); - if mutations.len() > options.max_concurrent { - return Err(ShopifyAPIError::Other(format!( - "received {} bulk mutations but max_concurrent is {}", - mutations.len(), - options.max_concurrent - ))); - } - - let mut operations = Vec::with_capacity(mutations.len()); - for (mutation, staged_upload_path) in mutations { - operations.push( - self.run_bulk_mutation(mutation.as_ref(), staged_upload_path.as_ref()) - .await?, - ); - } - - Ok(operations) - } - - pub async fn run_bulk_query( - &self, - query: &str, - ) -> Result { - self.run_bulk_query_with_grouping(query, false).await - } - - pub async fn run_bulk_query_with_grouping( - &self, - query: &str, - group_objects: bool, - ) -> Result { - let data: RunBulkQueryData = self - .graphql( - r#" - mutation bulkOperationRunQuery($query: String!, $groupObjects: Boolean!) { - bulkOperationRunQuery(query: $query, groupObjects: $groupObjects) { - bulkOperation { - id - status - url - partialDataUrl - } - userErrors { - field - message - } - } - } - "#, - &json!({ - "query": query, - "groupObjects": group_objects, - }), - ) - .await?; - - Ok(data.payload) - } - - pub async fn run_bulk_mutation( - &self, - mutation: &str, - staged_upload_path: &str, - ) -> Result { - let data: RunBulkMutationData = self - .graphql( - r#" - mutation bulkOperationRunMutation($mutation: String!, $stagedUploadPath: String!) { - bulkOperationRunMutation( - mutation: $mutation, - stagedUploadPath: $stagedUploadPath - ) { - bulkOperation { - id - status - url - partialDataUrl - } - userErrors { - field - message - } - } - } - "#, - &json!({ - "mutation": mutation, - "stagedUploadPath": staged_upload_path, - }), - ) - .await?; - - Ok(data.payload) - } - - pub async fn get_bulk_operation( - &self, - id: &str, - ) -> Result, ShopifyAPIError> { - let data: BulkOperationData = self - .graphql( - r#" - query bulkOperation($id: ID!) { - bulkOperation(id: $id) { - id - status - errorCode - createdAt - completedAt - objectCount - fileSize - url - partialDataUrl - } - } - "#, - &json!({ "id": id }), - ) - .await?; - - Ok(data.bulk_operation) - } - - pub async fn list_bulk_operations( - &self, - filter: BulkOperationsFilter, - ) -> Result { - let first = if filter.first == 0 { 10 } else { filter.first }; - let data: BulkOperationsData = self - .graphql( - r#" - query bulkOperations($first: Int!, $query: String, $after: String) { - bulkOperations(first: $first, query: $query, after: $after) { - edges { - cursor - node { - id - status - errorCode - createdAt - completedAt - objectCount - fileSize - url - partialDataUrl - } - } - pageInfo { - hasNextPage - endCursor - } - } - } - "#, - &json!({ - "first": first, - "query": filter.query, - "after": filter.after, - }), - ) - .await?; - - Ok(data.bulk_operations) - } - - pub async fn wait_for_bulk( - &self, - id: &str, - options: BulkWaitOptions, - ) -> Result { - let started_at = Instant::now(); - - loop { - let operation = self.get_bulk_operation(id).await?.ok_or_else(|| { - ShopifyAPIError::Other(format!("bulk operation `{id}` was not found")) - })?; - - if operation.status.is_terminal() { - return Ok(operation); - } - - if let Some(timeout) = options.timeout { - if started_at.elapsed() >= timeout { - return Err(ShopifyAPIError::Timeout(format!( - "bulk operation `{id}` did not finish within {timeout:?}" - ))); - } - } - - tokio::time::sleep(options.poll_interval).await; - } - } - - pub async fn stage_upload_jsonl(&self, data: &[T]) -> Result - where - T: Serialize, - { - let jsonl_data = data - .iter() - .map(serde_json::to_string) - .collect::, _>>()? - .join("\n"); - - let target = self - .create_staged_upload("bulk_op_vars", "text/jsonl") - .await?; - - let mut staged_upload_path = String::new(); - let mut form = reqwest::multipart::Form::new(); - - for parameter in target.parameters { - if parameter.name == "key" { - staged_upload_path = parameter.value.clone(); - } - form = form.text(parameter.name, parameter.value); - } - - let file_part = reqwest::multipart::Part::bytes(jsonl_data.into_bytes()) - .file_name("bulk_op_vars") - .mime_str("text/jsonl") - .map_err(|err| ShopifyAPIError::Other(err.to_string()))?; - - form = form.part("file", file_part); - self.client() - .post(&target.url) - .multipart(form) - .send() - .await? - .error_for_status()?; - - if staged_upload_path.is_empty() { - return Err(ShopifyAPIError::Other( - "staged upload did not return a key parameter".to_string(), - )); - } - - Ok(staged_upload_path) - } - - pub async fn download_bulk_jsonl(url: &str) -> Result, ShopifyAPIError> - where - T: serde::de::DeserializeOwned, - { - let body = reqwest::get(url).await?.error_for_status()?.text().await?; - parse_jsonl(&body) - } - - async fn create_staged_upload( - &self, - filename: &str, - mime_type: &str, - ) -> Result { - let input = StagedUploadsCreateInput { - filename: filename.to_string(), - mime_type: mime_type.to_string(), - resource: StagedUploadResource::BulkMutationVariables, - http_method: "POST".to_string(), - file_size: None, - }; - - let data: StagedUploadsData = self - .graphql( - r#" - mutation stagedUploadsCreate($input: [StagedUploadInput!]!) { - stagedUploadsCreate(input: $input) { - stagedTargets { - url - resourceUrl - parameters { - name - value - } - } - userErrors { - field - message - } - } - } - "#, - &json!({ "input": [input] }), - ) - .await?; - - if !data.staged_uploads_create.user_errors.is_empty() { - return Err(ShopifyAPIError::Other(format!( - "stagedUploadsCreate returned errors: {:?}", - data.staged_uploads_create.user_errors - ))); - } - - data.staged_uploads_create - .staged_targets - .into_iter() - .next() - .ok_or_else(|| ShopifyAPIError::Other("no staged upload target returned".to_string())) - } -} - -pub fn parse_jsonl(body: &str) -> Result, ShopifyAPIError> -where - T: serde::de::DeserializeOwned, -{ - body.lines() - .filter(|line| !line.trim().is_empty()) - .map(|line| serde_json::from_str(line).map_err(ShopifyAPIError::JsonParseError)) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parses_jsonl_bulk_results() { - let parsed: Vec = parse_jsonl("{\"id\":1}\n{\"id\":2}\n\n").unwrap(); - - assert_eq!(parsed.len(), 2); - assert_eq!(parsed[0]["id"], 1); - } -} diff --git a/src/graphql/mod.rs b/src/graphql/mod.rs deleted file mode 100644 index da7338a..0000000 --- a/src/graphql/mod.rs +++ /dev/null @@ -1,146 +0,0 @@ -mod bulk_query; -pub mod types; - -use serde::{Deserialize, Serialize}; - -use crate::{utils::ReadJsonTreeSteps, Shopify, ShopifyAPIError}; - -pub use bulk_query::*; - -#[cfg(feature = "graphql-client")] -use graphql_client::{GraphQLQuery, Response as GraphQLClientResponse}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct GraphqlResponse { - pub data: Option, - pub errors: Option>, - pub extensions: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct GraphqlError { - pub message: String, - pub locations: Option, - pub path: Option, - pub extensions: Option, -} - -#[derive(Debug, Serialize)] -struct GraphqlRequest<'a, Variables> { - query: &'a str, - variables: &'a Variables, -} - -impl Shopify { - pub async fn graphql_raw( - &self, - query: &str, - variables: &Variables, - ) -> Result, ShopifyAPIError> - where - Variables: serde::Serialize, - { - let token = self.access_token().await?; - let response = self - .client() - .post(self.get_query_url()) - .header("Content-Type", "application/json") - .header("X-Shopify-Access-Token", token) - .json(&GraphqlRequest { query, variables }) - .send() - .await? - .error_for_status()?; - - let status = response.status(); - let body = response.text().await?; - log::debug!("shopify graphql response status: {status}"); - serde_json::from_str(&body).map_err(ShopifyAPIError::JsonParseError) - } - - pub async fn graphql( - &self, - query: &str, - variables: &Variables, - ) -> Result - where - ReturnType: serde::de::DeserializeOwned, - Variables: serde::Serialize, - { - let response = self.graphql_raw(query, variables).await?; - if let Some(errors) = response.errors { - if errors.iter().any(|error| { - error - .extensions - .as_ref() - .and_then(|v| v.get("code")) - .and_then(|v| v.as_str()) - == Some("THROTTLED") - }) { - return Err(ShopifyAPIError::Throttled); - } - return Err(ShopifyAPIError::GraphqlErrors(errors)); - } - - let data = response.data.ok_or(ShopifyAPIError::MissingGraphqlData)?; - serde_json::from_value(data).map_err(ShopifyAPIError::JsonParseError) - } - - pub async fn graphql_at_path( - &self, - query: &str, - variables: &Variables, - json_finder: &[ReadJsonTreeSteps<'_>], - ) -> Result - where - ReturnType: serde::de::DeserializeOwned, - Variables: serde::Serialize, - { - let data = self - .graphql::(query, variables) - .await?; - let value = crate::utils::read_json_tree(&data, json_finder) - .map_err(|_| ShopifyAPIError::NotWantedJsonFormat(data.to_string()))?; - serde_json::from_value(value.to_owned()).map_err(ShopifyAPIError::JsonParseError) - } - - #[cfg(feature = "graphql-client")] - pub async fn post_graphql( - &self, - variables: Q::Variables, - ) -> Result, ShopifyAPIError> { - let token = self.access_token().await?; - let body = Q::build_query(variables); - let response = self - .client() - .post(self.get_query_url()) - .header("Content-Type", "application/json") - .header("X-Shopify-Access-Token", token) - .json(&body) - .send() - .await? - .error_for_status()?; - - response - .json::>() - .await - .map_err(ShopifyAPIError::ConnectionFailed) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn graphql_response_parses_errors_and_extensions() { - let raw = r#"{ - "errors": [{"message": "boom", "extensions": {"code": "THROTTLED"}}], - "extensions": {"cost": {"actualQueryCost": 1}} - }"#; - - let parsed: GraphqlResponse = serde_json::from_str(raw).unwrap(); - - assert_eq!(parsed.errors.unwrap()[0].message, "boom"); - assert!(parsed.extensions.unwrap().get("cost").is_some()); - } -} diff --git a/src/graphql/types.rs b/src/graphql/types.rs deleted file mode 100644 index 58afde7..0000000 --- a/src/graphql/types.rs +++ /dev/null @@ -1,12 +0,0 @@ -// Missing types from the GraphQL schema -#[allow(clippy::upper_case_acronyms)] -pub type Decimal = String; - -#[allow(clippy::upper_case_acronyms)] -pub type JSON = String; - -#[allow(clippy::upper_case_acronyms)] -pub type UnsignedInt64 = String; - -#[allow(clippy::upper_case_acronyms)] -pub type DateTime = String; diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index fae6c0d..0000000 --- a/src/lib.rs +++ /dev/null @@ -1,284 +0,0 @@ -use std::sync::{Arc, Mutex}; - -use thiserror::Error; - -pub mod auth; -pub mod graphql; -pub mod schema; -pub mod utils; -#[cfg(feature = "webhooks")] -pub mod webhooks; - -pub use auth::{ShopifyAuth, TokenData, TokenStore}; -pub use graphql::{ - BulkConcurrencyOptions, BulkOperationPayload, BulkOperationsFilter, BulkWaitOptions, - GraphqlError, GraphqlResponse, ShopifyBulkOperation, ShopifyBulkStatus, -}; -pub use schema::{download_public_admin_schema, SHOPIFY_DEV_ADMIN_SCHEMA_PROXY}; - -pub const DEFAULT_API_VERSION: &str = "2026-04"; -pub const MIN_API_VERSION: &str = "2026-04"; -pub static VERSION: &str = "shopify_api/0.10"; - -#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] -pub struct ApiVersion(String); - -impl ApiVersion { - pub fn new(version: impl Into) -> Result { - let version = version.into(); - validate_api_version(&version)?; - Ok(Self(version)) - } - - pub fn as_str(&self) -> &str { - &self.0 - } -} - -impl Default for ApiVersion { - fn default() -> Self { - Self(DEFAULT_API_VERSION.to_string()) - } -} - -impl std::fmt::Display for ApiVersion { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.0.fmt(f) - } -} - -impl TryFrom<&str> for ApiVersion { - type Error = ShopifyAPIError; - - fn try_from(value: &str) -> Result { - Self::new(value) - } -} - -impl TryFrom for ApiVersion { - type Error = ShopifyAPIError; - - fn try_from(value: String) -> Result { - Self::new(value) - } -} - -#[derive(Clone)] -pub struct ShopifyConfig { - pub api_version: ApiVersion, - #[cfg(feature = "webhooks")] - pub shared_secret: Option, - pub token_store: Option>, - pub token_refresh_leeway: chrono::Duration, - pub user_agent: String, -} - -impl Default for ShopifyConfig { - fn default() -> Self { - Self { - api_version: ApiVersion::default(), - #[cfg(feature = "webhooks")] - shared_secret: None, - token_store: None, - token_refresh_leeway: chrono::Duration::minutes(5), - user_agent: VERSION.to_string(), - } - } -} - -#[derive(Clone)] -pub struct Shopify { - pub api_version: ApiVersion, - #[cfg(feature = "webhooks")] - pub(crate) shared_secret: Option, - auth: Arc>, - client: reqwest::Client, - query_url: String, - token_url: String, - shop: String, - shop_domain: String, - token_store: Option>, - token_refresh_leeway: chrono::Duration, -} - -impl std::fmt::Debug for Shopify { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Shopify") - .field("api_version", &self.api_version) - .field("query_url", &self.query_url) - .field("token_url", &self.token_url) - .field("shop", &self.shop) - .field("shop_domain", &self.shop_domain) - .finish_non_exhaustive() - } -} - -#[derive(Debug, Error)] -pub enum ShopifyAPIError { - #[error("connection failed")] - ConnectionFailed(#[from] reqwest::Error), - - #[error("response body is broken")] - ResponseBroken, - - #[error("not a JSON response: {0}")] - NotJson(String), - - #[error("not wanted JSON format: {0}")] - NotWantedJsonFormat(String), - - #[error("request throttled")] - Throttled, - - #[error("JSON parsing error: {0}")] - JsonParseError(#[from] serde_json::Error), - - #[error("invalid API version `{version}`: minimum supported version is {minimum}")] - InvalidApiVersion { version: String, minimum: String }, - - #[error("authentication error: {0}")] - Authentication(String), - - #[error("GraphQL returned errors: {0:?}")] - GraphqlErrors(Vec), - - #[error("missing GraphQL data")] - MissingGraphqlData, - - #[error("invalid header value: {0}")] - InvalidHeaderValue(#[from] reqwest::header::InvalidHeaderValue), - - #[error("operation timed out: {0}")] - Timeout(String), - - #[error("other error: {0}")] - Other(String), -} - -impl Shopify { - pub fn new( - shop: impl AsRef, - auth: ShopifyAuth, - config: ShopifyConfig, - ) -> Result { - let shop = shop.as_ref().to_string(); - let shop_domain = normalize_shop_domain(&shop); - let query_url = format!( - "https://{}/admin/api/{}/graphql.json", - shop_domain, config.api_version - ); - let token_url = format!("https://{}/admin/oauth/access_token", shop_domain); - let mut headers = reqwest::header::HeaderMap::new(); - headers.insert( - reqwest::header::USER_AGENT, - reqwest::header::HeaderValue::from_str(&config.user_agent)?, - ); - let client = reqwest::Client::builder() - .default_headers(headers) - .build()?; - - Ok(Self { - api_version: config.api_version, - #[cfg(feature = "webhooks")] - shared_secret: config.shared_secret, - auth: Arc::new(Mutex::new(auth)), - client, - query_url, - token_url, - shop, - shop_domain, - token_store: config.token_store, - token_refresh_leeway: config.token_refresh_leeway, - }) - } - - pub fn get_shop(&self) -> &str { - &self.shop - } - - pub fn shop_domain(&self) -> &str { - &self.shop_domain - } - - pub fn get_query_url(&self) -> &str { - &self.query_url - } - - pub fn token_url(&self) -> &str { - &self.token_url - } - - pub(crate) fn client(&self) -> &reqwest::Client { - &self.client - } - - pub fn replace_auth(&self, auth: ShopifyAuth) -> Result<(), ShopifyAPIError> { - let mut current = self - .auth - .lock() - .map_err(|_| ShopifyAPIError::Authentication("auth lock poisoned".to_string()))?; - *current = auth; - Ok(()) - } -} - -fn normalize_shop_domain(shop: &str) -> String { - let shop = shop.trim().trim_start_matches("https://"); - let shop = shop.trim_start_matches("http://").trim_end_matches('/'); - if shop.ends_with(".myshopify.com") { - shop.to_string() - } else { - format!("{shop}.myshopify.com") - } -} - -fn validate_api_version(version: &str) -> Result<(), ShopifyAPIError> { - let parsed = parse_api_version(version); - let minimum = parse_api_version(MIN_API_VERSION); - - match (parsed, minimum) { - (Some(parsed), Some(minimum)) if parsed >= minimum => Ok(()), - _ => Err(ShopifyAPIError::InvalidApiVersion { - version: version.to_string(), - minimum: MIN_API_VERSION.to_string(), - }), - } -} - -fn parse_api_version(version: &str) -> Option<(u16, u8)> { - let (year, month) = version.split_once('-')?; - Some((year.parse().ok()?, month.parse().ok()?)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn api_version_rejects_versions_before_2026_04() { - assert!(ApiVersion::new("2025-10").is_err()); - assert!(ApiVersion::new("2026-01").is_err()); - assert_eq!(ApiVersion::new("2026-04").unwrap().as_str(), "2026-04"); - assert_eq!(ApiVersion::new("2026-07").unwrap().as_str(), "2026-07"); - } - - #[test] - fn endpoints_are_built_from_normalized_shop_and_version() { - let shopify = Shopify::new( - "example", - ShopifyAuth::AccessToken("token".to_string()), - ShopifyConfig::default(), - ) - .unwrap(); - - assert_eq!(shopify.shop_domain(), "example.myshopify.com"); - assert_eq!( - shopify.get_query_url(), - "https://example.myshopify.com/admin/api/2026-04/graphql.json" - ); - assert_eq!( - shopify.token_url(), - "https://example.myshopify.com/admin/oauth/access_token" - ); - } -} diff --git a/src/schema.rs b/src/schema.rs deleted file mode 100644 index 898b64c..0000000 --- a/src/schema.rs +++ /dev/null @@ -1,42 +0,0 @@ -use serde_json::json; - -use crate::{ApiVersion, Shopify, ShopifyAPIError}; - -pub const ADMIN_SCHEMA_INTROSPECTION_QUERY: &str = include_str!("../schema_dl.graphql"); -pub const SHOPIFY_DEV_ADMIN_SCHEMA_PROXY: &str = "https://shopify.dev/admin-graphql-direct-proxy"; - -pub async fn download_public_admin_schema( - api_version: impl AsRef, -) -> Result { - let api_version = ApiVersion::new(api_version.as_ref())?; - let url = format!("{SHOPIFY_DEV_ADMIN_SCHEMA_PROXY}/{api_version}"); - let response = reqwest::Client::new() - .post(url) - .json(&json!({ - "query": ADMIN_SCHEMA_INTROSPECTION_QUERY, - "variables": {}, - })) - .send() - .await? - .error_for_status()?; - - response - .json() - .await - .map_err(ShopifyAPIError::ConnectionFailed) -} - -impl Shopify { - /// Downloads the Admin GraphQL schema through the authenticated shop endpoint. - pub async fn download_admin_schema(&self) -> Result { - let response = self - .graphql_raw(ADMIN_SCHEMA_INTROSPECTION_QUERY, &json!({})) - .await?; - - if let Some(errors) = response.errors { - return Err(ShopifyAPIError::GraphqlErrors(errors)); - } - - serde_json::to_value(response).map_err(ShopifyAPIError::JsonParseError) - } -} diff --git a/src/utils.rs b/src/utils.rs deleted file mode 100644 index b6a5e00..0000000 --- a/src/utils.rs +++ /dev/null @@ -1,228 +0,0 @@ -use std::future::Future; - -/// Retry function for async functions -/// # Example -/// ``` -/// use shopify_api::utils::retry_async; -/// use std::io::{Error, ErrorKind}; -/// -/// async fn my_async_function(args: &(String, u8)) -> Result<(), Error> { -/// Err(Error::new(ErrorKind::Other, "Error")) -/// } -/// -/// #[tokio::main] -/// async fn main() { -/// let result = retry_async(3, my_async_function, &(String::from("test"), 1)).await; -/// assert!(result.is_err()); -/// } -/// ``` -/// # Errors -/// This function returns an error if the async function returns an error -/// # Panics -/// This function panics if the number of retries is 0 -pub async fn retry_async<'a, Fut, F, Args, Out, ErrOut>( - max_retries: u64, - func: Fut, - args: &'a Args, -) -> Result -where - Fut: Fn(&'a Args) -> F, - F: Future>, - ErrOut: std::fmt::Debug, -{ - if max_retries == 0 { - panic!("Max retries cannot be 0"); - } - - let mut count: u64 = 0; - let mut result: Result = func(args).await; - - while count < max_retries - 1 && result.is_err() { - let executed_func = func(args); - - result = executed_func.await; - if result.is_ok() { - return result; - } - - count += 1; - } - - result -} - -/// Retry function for sync functions -/// # Example -/// ``` -/// use shopify_api::utils::retry_sync; -/// use std::io::{Error, ErrorKind}; -/// -/// fn my_sync_function(args: &(String, u8)) -> Result<(), Error> { -/// Err(Error::new(ErrorKind::Other, "Error")) -/// } -/// -/// fn main() { -/// let result = retry_sync(3, my_sync_function, &(String::from("test"), 1)); -/// assert!(result.is_err()); -/// } -/// ``` -/// # Errors -/// This function returns an error if the sync function returns an error -/// # Panics -/// This function panics if the number of retries is 0 -pub fn retry_sync<'a, F, Args, Out, ErrOut>( - max_retries: u64, - func: F, - args: &'a Args, -) -> Result -where - F: Fn(&'a Args) -> Result, - ErrOut: std::fmt::Debug, -{ - if max_retries == 0 { - panic!("Max retries cannot be 0"); - } - - let mut count: u64 = 0; - let mut result: Result = func(args); - - while count < max_retries - 1 && result.is_err() { - let executed_func = func(args); - - result = executed_func; - if result.is_ok() { - return result; - } - - count += 1; - } - - result -} - -#[derive(Clone, Debug)] -pub enum ReadJsonTreeError { - JsonNotFound, -} - -#[derive(Clone, Debug)] -pub enum ReadJsonTreeSteps<'a> { - Key(&'a str), - Index(usize), -} - -/// Read json tree with a path -/// # Example -/// ``` -/// use shopify_api::utils::read_json_tree; -/// use serde_json::json; -/// -/// let json: serde_json::Value = json!({ -/// "a": { -/// "b": { -/// "c": "d" -/// } -/// } -/// }); -/// -/// -/// let success_read = read_json_tree( -/// &json, -/// &vec![ -/// shopify_api::utils::ReadJsonTreeSteps::Key("a"), -/// shopify_api::utils::ReadJsonTreeSteps::Key("b"), -/// shopify_api::utils::ReadJsonTreeSteps::Key("c") -/// ] -/// ); -/// -/// let error_read = read_json_tree( -/// &json, -/// &vec![ -/// shopify_api::utils::ReadJsonTreeSteps::Key("a"), -/// shopify_api::utils::ReadJsonTreeSteps::Key("b"), -/// shopify_api::utils::ReadJsonTreeSteps::Key("d") -/// ] -/// ); -/// -/// println!("{:?}", success_read); -/// assert_eq!(success_read.unwrap(), &json!("d")); -/// assert!(error_read.is_err()); -/// ``` -/// # Errors -/// This function returns an error if the json tree is not found -pub fn read_json_tree<'a>( - json_value: &'a serde_json::Value, - path: &[ReadJsonTreeSteps], -) -> Result<&'a serde_json::Value, ReadJsonTreeError> { - let mut actual_value: &serde_json::Value = json_value; - - for step in path { - match step { - ReadJsonTreeSteps::Key(key) => { - actual_value = actual_value - .get(key) - .ok_or(ReadJsonTreeError::JsonNotFound)?; - } - ReadJsonTreeSteps::Index(index) => { - actual_value = actual_value - .get(*index) - .ok_or(ReadJsonTreeError::JsonNotFound)?; - } - } - } - - Ok(actual_value) -} - -#[cfg(feature = "debug")] -pub fn deserialize_from_value(value: serde_json::Value) -> Result -where - T: serde::de::DeserializeOwned, -{ - let json_string = serde_json::to_string(&value) - .map_err(|err| format!("Error serializing JSON value: {err}"))?; - let jd = &mut serde_json::Deserializer::from_str(&json_string); - - let result: Result = serde_path_to_error::deserialize(jd); - match result { - Ok(customer) => Ok(customer), - Err(err) => Err(format!( - "Error parsing JSON at {}: {}", - err.path(), - err.inner() - )), - } -} - -#[cfg(not(feature = "debug"))] -pub fn deserialize_from_value(value: serde_json::Value) -> Result -where - T: serde::de::DeserializeOwned, -{ - let result: Result = serde_json::from_value(value); - match result { - Ok(customer) => Ok(customer), - Err(err) => Err(format!("Error parsing JSON: {}", err)), - } -} - -#[cfg(feature = "debug")] -pub fn deserialize_from_str(json_string: &str) -> Result -where - T: serde::de::DeserializeOwned, -{ - let value: serde_json::Value = - serde_json::from_str(json_string).map_err(|err| format!("Error parsing JSON: {err}"))?; - deserialize_from_value(value) -} - -#[cfg(not(feature = "debug"))] -pub fn deserialize_from_str(json_string: &str) -> Result -where - T: serde::de::DeserializeOwned, -{ - match serde_json::from_str(json_string) { - Ok(customer) => Ok(customer), - Err(err) => Err(format!("Error parsing JSON: {}", err)), - } -} diff --git a/src/webhooks/frameworks/mod.rs b/src/webhooks/frameworks/mod.rs deleted file mode 100644 index 690add4..0000000 --- a/src/webhooks/frameworks/mod.rs +++ /dev/null @@ -1,325 +0,0 @@ -#![cfg(feature = "warp-wrapper")] -pub mod warp; - -// Webhook payload structs used by the optional warp receiver. - -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -#[derive(Debug)] -pub enum ShopifyWebhook { - InventoryItemCreate(InventoryItem), - InventoryItemUpdate(InventoryItem), - InventoryItemDelete(InventoryItem), - InventoryLevelConnect(InventoryLevel), - InventoryLevelDisconnect(InventoryLevel), - InventoryLevelUpdate(InventoryLevel), - CustomersCreate(Customer), - CustomersUpdate(Customer), - OrdersCreate(Order), - OrdersUpdated(Order), - Other((String, Value)), -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct InventoryLevel { - pub inventory_item_id: u64, - pub location_id: u64, - pub available: Option, - pub updated_at: Option, - pub admin_graphql_api_id: Option, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct InventoryItem { - pub id: u64, - pub sku: String, - pub created_at: String, - pub updated_at: String, - pub requires_shipping: bool, - pub cost: Option, - pub country_code_of_origin: Option, - pub province_code_of_origin: Option, - pub harmonized_system_code: Option, - pub tracked: bool, - pub country_harmonized_system_codes: Vec, - pub admin_graphql_api_id: Option, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct Address { - pub id: u64, - pub customer_id: u64, - pub first_name: Option, - pub last_name: Option, - pub company: Option, - pub address1: Option, - pub address2: Option, - pub city: Option, - pub province: Option, - pub country: Option, - pub zip: Option, - pub phone: Option, - pub province_code: Option, - pub country_code: Option, - pub country_name: Option, - pub default: bool, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct Customer { - pub id: u64, - pub email: String, - pub created_at: String, - pub updated_at: String, - pub first_name: Option, - pub last_name: Option, - pub orders_count: Option, - pub state: String, - pub total_spent: Option, - pub last_order_id: Option, - pub note: Option, - pub verified_email: bool, - pub multipass_identifier: Option, - pub tax_exempt: bool, - pub tags: Option, - pub last_order_name: Option, - pub phone: Option, - pub addresses: Vec
, - pub admin_graphql_api_id: String, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct CountryHarmonizedSystemCode { - pub harmonized_system_code: String, - pub country_code: String, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct Order { - pub id: u64, - pub admin_graphql_api_id: String, - pub app_id: Option, - pub browser_ip: Option, - pub buyer_accepts_marketing: bool, - pub cancel_reason: Option, - pub cancelled_at: Option, - pub cart_token: Option, - pub checkout_id: Option, - pub checkout_token: Option, - pub client_details: Option, - pub closed_at: Option, - pub confirmation_number: Option, - pub confirmed: bool, - pub contact_email: String, - pub created_at: String, - pub currency: String, - pub current_subtotal_price: String, - pub current_subtotal_price_set: OrderPriceSet, - pub current_total_additional_fees_set: Option, - pub current_total_discounts: String, - pub current_total_discounts_set: OrderPriceSet, - pub current_total_duties_set: Option, - pub current_total_price: String, - pub current_total_price_set: OrderPriceSet, - pub current_total_tax: String, - pub current_total_tax_set: OrderPriceSet, - pub customer_locale: Option, - pub device_id: Option, - pub discount_codes: Vec, - pub email: String, - pub estimated_taxes: bool, - pub financial_status: String, - pub fulfillment_status: Option, - pub landing_site: Option, - pub landing_site_ref: Option, - pub location_id: Option, - pub merchant_of_record_app_id: Option, - pub name: String, - pub note: Option, - pub note_attributes: Vec, - pub number: u64, - pub order_number: u64, - pub order_status_url: String, - pub original_total_additional_fees_set: Option, - pub original_total_duties_set: Option, - pub payment_gateway_names: Vec, - pub phone: Option, - pub po_number: Option, - pub presentment_currency: String, - pub processed_at: Option, - pub reference: Option, - pub referring_site: Option, - pub source_identifier: Option, - pub source_name: String, - pub source_url: Option, - pub subtotal_price: String, - pub subtotal_price_set: OrderPriceSet, - pub tags: String, - pub tax_exempt: bool, - pub tax_lines: Vec, - pub taxes_included: bool, - pub test: bool, - pub token: String, - pub total_discounts: String, - pub total_discounts_set: OrderPriceSet, - pub total_line_items_price: String, - pub total_line_items_price_set: OrderPriceSet, - pub total_outstanding: String, - pub total_price: String, - pub total_price_set: OrderPriceSet, - pub total_shipping_price_set: OrderPriceSet, - pub total_tax: String, - pub total_tax_set: OrderPriceSet, - pub total_tip_received: String, - pub total_weight: u64, - pub updated_at: String, - pub user_id: Option, - pub billing_address: Option, - pub customer: OrderCustomer, - pub discount_applications: Vec, - pub fulfillments: Vec, - pub line_items: Vec, - pub payment_terms: Option, - pub refunds: Vec, - pub shipping_address: Option, - pub shipping_lines: Vec, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderClientDetails {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderPriceSet { - pub shop_money: OrderMoney, - pub presentment_money: OrderMoney, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderMoney { - pub amount: String, - pub currency_code: String, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderAdditionalFeesSet {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderDutiesSet {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderDiscountCode { - pub code: Option, - pub amount: Option, - #[serde(rename = "type")] - pub _type: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderNoteAttribute { - pub name: Option, - pub value: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderTaxLine { - pub title: Option, - pub price: Option, - pub rate: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderAddress { - pub first_name: Option, - pub address1: Option, - pub phone: Option, - pub city: Option, - pub zip: Option, - pub province: Option, - pub country: Option, - pub last_name: Option, - pub address2: Option, - pub company: Option, - pub latitude: Option, - pub longitude: Option, - pub name: Option, - pub country_code: Option, - pub province_code: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderCustomer { - pub id: u64, - pub email: Option, - pub created_at: Option, - pub updated_at: Option, - pub first_name: Option, - pub last_name: Option, - pub state: Option, - pub note: Option, - pub verified_email: bool, - pub multipass_identifier: Option, - pub tax_exempt: bool, - pub phone: Option, - pub email_marketing_consent: Option, - pub sms_marketing_consent: Option, - pub tags: Option, - pub currency: String, - pub tax_exemptions: Vec, - pub admin_graphql_api_id: String, - pub default_address: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderConsent { - pub state: Option, - pub opt_in_level: Option, - pub consent_updated_at: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderDiscountApplication {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderFulfillment {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderLineItem { - pub id: u64, - pub admin_graphql_api_id: Option, - pub variant_id: Option, - pub quantity: i32, - pub price: String, - pub grams: i32, - pub name: String, - pub title: String, - pub variant_title: Option, - pub sku: Option, - pub variant_inventory_management: Option, - pub product_id: Option, - pub fulfillment_service: String, - pub product_exists: bool, - pub taxable: bool, - pub total_discount: String, - pub fulfillment_status: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderPaymentTerms {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderRefund {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderShippingLine { - pub id: u64, - pub title: String, - pub price: String, - pub code: Option, - pub source: String, - pub phone: Option, - pub requested_fulfillment_service_id: Option, - pub delivery_category: Option, - pub carrier_identifier: Option, - pub discounted_price: String, -} diff --git a/src/webhooks/frameworks/warp.rs b/src/webhooks/frameworks/warp.rs deleted file mode 100644 index 6979f53..0000000 --- a/src/webhooks/frameworks/warp.rs +++ /dev/null @@ -1,129 +0,0 @@ -use super::{Customer, InventoryItem, InventoryLevel, ShopifyWebhook}; -use crate::Shopify; -use serde_json; -use std::future::Future; -use std::sync::Arc; -use tokio::sync::Mutex; -use warp::http::StatusCode; -use warp::{Filter, Rejection}; - -impl Shopify { - #[cfg(feature = "warp-wrapper")] - pub fn warp_wrapper( - path: &str, - shopify_filter: Arc>, - extra_data: T, - callback: F, - ) -> warp::filters::BoxedFilter<(impl warp::Reply,)> - where - T: Clone + Send + Sync + 'static, - F: Fn(ShopifyWebhook, Arc>, T) -> Fut + Clone + Send + Sync + 'static, - Fut: Future> + Send, - { - let path_clone = path.to_string(); - - warp::path(path_clone) - .and(warp::post()) - .and(warp::any().map(move || shopify_filter.clone())) - .and(warp::any().map(move || extra_data.clone())) - .and(warp::header::("x-shopify-hmac-sha256")) - .and(warp::header::("X-Shopify-Topic")) - .and(warp::body::bytes()) - .and_then( - move |shopify: Arc>, - extra: T, - header: String, - topic: String, - body: bytes::Bytes| { - let callback_clone = callback.clone(); - async move { - let is_valid = shopify.lock().await.verify_hmac(&body, &header); - - if !is_valid { - return Ok::<_, Rejection>(warp::reply::with_status( - warp::reply::html("Invalid HMAC"), - StatusCode::BAD_REQUEST, - )); - } - - let str_body = match std::str::from_utf8(&body) { - Ok(body) => body, - Err(_) => { - return Ok::<_, Rejection>(warp::reply::with_status( - warp::reply::html("Invalid UTF-8 payload"), - StatusCode::BAD_REQUEST, - )); - } - }; - - log::debug!("Received webhook topic: {}", topic); - - let webhook_data = match topic.as_str() { - "inventory_items/create" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryItemCreate) - } - "inventory_items/update" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryItemUpdate) - } - "inventory_items/delete" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryItemDelete) - } - "inventory_levels/connect" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryLevelConnect) - } - "inventory_levels/disconnect" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryLevelDisconnect) - } - "inventory_levels/update" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryLevelUpdate) - } - "customers/create" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::CustomersCreate) - } - "customers/update" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::CustomersUpdate) - } - "orders/create" => crate::utils::deserialize_from_str(str_body) - .map(ShopifyWebhook::OrdersCreate), - "orders/updated" => crate::utils::deserialize_from_str(str_body) - .map(ShopifyWebhook::OrdersUpdated), - _ => serde_json::from_str(str_body) - .map(|value| ShopifyWebhook::Other((topic.clone(), value))) - .map_err(|err| format!("Error parsing JSON: {err}")), - }; - - let webhook_data = match webhook_data { - Ok(webhook_data) => webhook_data, - Err(err) => { - log::info!("Failed to parse webhook payload: {}", err); - return Ok::<_, Rejection>(warp::reply::with_status( - warp::reply::html("Invalid JSON payload"), - StatusCode::BAD_REQUEST, - )); - } - }; - - match callback_clone(webhook_data, shopify.clone(), extra.clone()).await { - Ok(_) => Ok(warp::reply::with_status( - warp::reply::html("Success"), - StatusCode::OK, - )), - Err(_e) => { - let custom_error = warp::reject::reject(); - Err(custom_error) - } - } - } - }, - ) - .boxed() - } -} diff --git a/src/webhooks/mod.rs b/src/webhooks/mod.rs deleted file mode 100644 index 2938721..0000000 --- a/src/webhooks/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub mod frameworks; -pub mod verify; -pub mod webhook; - -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Deserialize, Serialize, Clone, Eq, PartialEq)] -pub struct WebhookSubscription { - pub id: String, - pub topic: String, - pub format: String, - pub uri: String, -} diff --git a/src/webhooks/verify.rs b/src/webhooks/verify.rs deleted file mode 100644 index 3845984..0000000 --- a/src/webhooks/verify.rs +++ /dev/null @@ -1,27 +0,0 @@ -use crate::Shopify; -use base64::prelude::*; -use hmac::{Hmac, KeyInit, Mac}; -use sha2::Sha256; - -impl Shopify { - pub fn verify_hmac(&self, data: &[u8], hmac_header: &str) -> bool { - if let Some(secret) = &self.shared_secret { - let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { - log::info!("Failed to create webhook HMAC"); - return false; - }; - - let Ok(expected_hmac) = BASE64_STANDARD.decode(hmac_header) else { - log::info!("Invalid webhook HMAC header encoding"); - return false; - }; - - mac.update(data); - return mac.verify_slice(&expected_hmac).is_ok(); - } - - log::info!("No shared secret found"); - - false - } -} diff --git a/src/webhooks/webhook.rs b/src/webhooks/webhook.rs deleted file mode 100644 index 6167da5..0000000 --- a/src/webhooks/webhook.rs +++ /dev/null @@ -1,217 +0,0 @@ -use super::WebhookSubscription; -use crate::{Shopify, ShopifyAPIError}; -use serde::Deserialize; -use serde_json::json; - -#[derive(Debug, Deserialize)] -struct WebhookSubscriptionsData { - #[serde(rename = "webhookSubscriptions")] - webhook_subscriptions: WebhookSubscriptionConnection, -} - -#[derive(Debug, Deserialize)] -struct WebhookSubscriptionConnection { - edges: Vec, -} - -#[derive(Debug, Deserialize)] -struct WebhookSubscriptionEdge { - node: WebhookSubscriptionNode, -} - -#[derive(Debug, Deserialize)] -struct WebhookSubscriptionNode { - id: String, - topic: String, - format: String, - uri: String, -} - -#[derive(Debug, Deserialize)] -struct WebhookCreateData { - #[serde(rename = "webhookSubscriptionCreate")] - webhook_subscription_create: WebhookMutationPayload, -} - -#[derive(Debug, Deserialize)] -struct WebhookDeleteData { - #[serde(rename = "webhookSubscriptionDelete")] - webhook_subscription_delete: WebhookDeletePayload, -} - -#[derive(Debug, Deserialize)] -struct WebhookMutationPayload { - #[serde(rename = "webhookSubscription")] - webhook_subscription: Option, - #[serde(rename = "userErrors")] - user_errors: Vec, -} - -#[derive(Debug, Deserialize)] -struct WebhookDeletePayload { - #[serde(rename = "deletedWebhookSubscriptionId")] - deleted_webhook_subscription_id: Option, - #[serde(rename = "userErrors")] - user_errors: Vec, -} - -#[allow(dead_code)] -#[derive(Debug, Deserialize)] -struct WebhookUserError { - field: Option>, - message: String, -} - -impl From for WebhookSubscription { - fn from(node: WebhookSubscriptionNode) -> Self { - Self { - id: node.id, - topic: node.topic, - format: node.format, - uri: node.uri, - } - } -} - -impl Shopify { - pub async fn list_webhooks(&self) -> Result, ShopifyAPIError> { - let data: WebhookSubscriptionsData = self - .graphql( - r#" - query webhookSubscriptions { - webhookSubscriptions(first: 250) { - edges { - node { - id - topic - format - uri - } - } - } - } - "#, - &json!({}), - ) - .await?; - - Ok(data - .webhook_subscriptions - .edges - .into_iter() - .map(|edge| edge.node.into()) - .collect()) - } - - pub async fn add_webhook( - &self, - address: &str, - topic: &str, - format: &str, - ) -> Result { - let data: WebhookCreateData = self - .graphql( - r#" - mutation webhookSubscriptionCreate( - $topic: WebhookSubscriptionTopic!, - $uri: String!, - $format: WebhookSubscriptionFormat! - ) { - webhookSubscriptionCreate( - topic: $topic, - webhookSubscription: { - uri: $uri, - format: $format - } - ) { - webhookSubscription { - id - topic - format - uri - } - userErrors { - field - message - } - } - } - "#, - &json!({ - "topic": topic, - "uri": address, - "format": format, - }), - ) - .await?; - - if !data.webhook_subscription_create.user_errors.is_empty() { - return Err(ShopifyAPIError::Other(format!( - "webhookSubscriptionCreate returned errors: {:?}", - data.webhook_subscription_create.user_errors - ))); - } - - data.webhook_subscription_create - .webhook_subscription - .map(Into::into) - .ok_or_else(|| ShopifyAPIError::Other("no webhook subscription returned".to_string())) - } - - pub async fn delete_webhook(&self, webhook_id: &str) -> Result<(), ShopifyAPIError> { - let data: WebhookDeleteData = self - .graphql( - r#" - mutation webhookSubscriptionDelete($id: ID!) { - webhookSubscriptionDelete(id: $id) { - deletedWebhookSubscriptionId - userErrors { - field - message - } - } - } - "#, - &json!({ "id": webhook_id }), - ) - .await?; - - if !data.webhook_subscription_delete.user_errors.is_empty() { - return Err(ShopifyAPIError::Other(format!( - "webhookSubscriptionDelete returned errors: {:?}", - data.webhook_subscription_delete.user_errors - ))); - } - - data.webhook_subscription_delete - .deleted_webhook_subscription_id - .map(|_| ()) - .ok_or_else(|| ShopifyAPIError::Other("webhook was not deleted".to_string())) - } - - pub async fn webhook_auto_config( - &self, - desired_webhooks: Vec<(&str, &str, &str)>, - ) -> Result<(), ShopifyAPIError> { - let existing_webhooks = self.list_webhooks().await?; - let mut desired = desired_webhooks; - - for webhook in &existing_webhooks { - let matches_desired = desired.iter().position(|(address, topic, format)| { - webhook.uri == *address && webhook.topic == *topic && webhook.format == *format - }); - - if let Some(index) = matches_desired { - desired.remove(index); - } else { - self.delete_webhook(&webhook.id).await?; - } - } - - for (address, topic, format) in desired { - self.add_webhook(address, topic, format).await?; - } - - Ok(()) - } -} diff --git a/tests/live.rs b/tests/live.rs deleted file mode 100644 index dc88553..0000000 --- a/tests/live.rs +++ /dev/null @@ -1,213 +0,0 @@ -use serde::Deserialize; -use std::time::Duration; - -use shopify_api::{ - BulkConcurrencyOptions, BulkOperationsFilter, BulkWaitOptions, Shopify, ShopifyAPIError, - ShopifyAuth, ShopifyBulkStatus, ShopifyConfig, -}; - -fn live_client() -> Option { - let shop = std::env::var("SHOPIFY_TEST_SHOP").ok()?; - let token = std::env::var("SHOPIFY_TEST_ACCESS_TOKEN").ok()?; - Shopify::new( - shop, - ShopifyAuth::AccessToken(token), - ShopifyConfig::default(), - ) - .ok() -} - -fn live_client_credentials_client() -> Option { - let shop = std::env::var("SHOPIFY_TEST_SHOP").ok()?; - let client_id = std::env::var("SHOPIFY_TEST_CLIENT_ID").ok()?; - let client_secret = std::env::var("SHOPIFY_TEST_CLIENT_SECRET").ok()?; - Shopify::new( - shop, - ShopifyAuth::client_credentials(client_id, client_secret), - ShopifyConfig::default(), - ) - .ok() -} - -#[derive(Debug, Deserialize)] -struct ShopQuery { - shop: Shop, -} - -#[derive(Debug, Deserialize)] -struct Shop { - name: String, -} - -#[tokio::test] -async fn live_graphql_shop_query_when_env_is_present() -> Result<(), ShopifyAPIError> { - let Some(shopify) = live_client() else { - return Ok(()); - }; - - let data: ShopQuery = shopify - .graphql("query { shop { name } }", &serde_json::json!({})) - .await?; - - assert!(!data.shop.name.is_empty()); - Ok(()) -} - -#[tokio::test] -async fn live_schema_download_when_env_is_present() -> Result<(), ShopifyAPIError> { - let Some(shopify) = live_client() else { - return Ok(()); - }; - - let schema = shopify.download_admin_schema().await?; - - assert!(schema.pointer("/data/__schema").is_some()); - Ok(()) -} - -#[tokio::test] -async fn live_client_credentials_when_env_is_present() -> Result<(), ShopifyAPIError> { - let Some(shopify) = live_client_credentials_client() else { - return Ok(()); - }; - let token = shopify.access_token().await?; - - assert!(!token.is_empty()); - Ok(()) -} - -#[tokio::test] -async fn live_bulk_query_wait_list_and_download_when_env_is_present() -> Result<(), ShopifyAPIError> -{ - let Some(shopify) = live_client_credentials_client() else { - return Ok(()); - }; - - let payload = shopify - .run_bulk_query( - r#"{ - products { - edges { - node { - id - title - } - } - } - }"#, - ) - .await?; - - assert!( - payload.user_errors.is_empty(), - "bulk query returned user errors: {:?}", - payload.user_errors - ); - - let operation = payload - .bulk_operation - .expect("bulkOperationRunQuery should return a bulk operation"); - - let listed = shopify - .list_bulk_operations(BulkOperationsFilter { - first: 5, - ..BulkOperationsFilter::default() - }) - .await?; - assert!(listed.edges.iter().any(|edge| edge.node.id == operation.id)); - - let operation = shopify - .wait_for_bulk( - &operation.id, - BulkWaitOptions { - poll_interval: Duration::from_secs(5), - timeout: Some(Duration::from_secs(180)), - }, - ) - .await?; - - assert_eq!(operation.status, ShopifyBulkStatus::Completed); - - if let Some(url) = operation.url { - let rows: Vec = Shopify::download_bulk_jsonl(&url).await?; - for row in rows { - assert!(row.get("id").is_some()); - } - } - - Ok(()) -} - -#[tokio::test] -async fn live_five_concurrent_bulk_queries_when_enabled() -> Result<(), ShopifyAPIError> { - if std::env::var("SHOPIFY_TEST_BULK_CONCURRENCY") - .ok() - .as_deref() - != Some("1") - { - return Ok(()); - } - - let Some(shopify) = live_client_credentials_client() else { - return Ok(()); - }; - - let query = r#"{ - products(first: 1) { - edges { - node { - id - title - } - } - } - }"#; - let payloads = shopify - .run_bulk_queries(vec![query; 5], BulkConcurrencyOptions::default()) - .await?; - let operations = payloads - .into_iter() - .map(|payload| { - assert!( - payload.user_errors.is_empty(), - "bulk query returned user errors: {:?}", - payload.user_errors - ); - payload - .bulk_operation - .expect("bulkOperationRunQuery should return a bulk operation") - }) - .collect::>(); - - assert_eq!(operations.len(), 5); - - let running_or_recent = shopify - .list_bulk_operations(BulkOperationsFilter { - first: 10, - query: Some("type:QUERY".to_string()), - ..BulkOperationsFilter::default() - }) - .await?; - for operation in &operations { - assert!(running_or_recent - .edges - .iter() - .any(|edge| edge.node.id == operation.id)); - } - - for operation in operations { - let operation = shopify - .wait_for_bulk( - &operation.id, - BulkWaitOptions { - poll_interval: Duration::from_secs(5), - timeout: Some(Duration::from_secs(180)), - }, - ) - .await?; - - assert_eq!(operation.status, ShopifyBulkStatus::Completed); - } - - Ok(()) -} From 75af06c5b76393fee2d9e03706f88eb97a62df87 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:10:33 +0200 Subject: [PATCH 002/135] feat: download the Admin schema a crate declares in Cargo.toml - Select the Admin API version with `api-version` in `[package.metadata.shopify_api]`; `graphql!` downloads its schema to `graphql/admin.schema.json` on the next build when it is missing or another version - `shopify-api schema download` reads the version from Cargo.toml and no longer takes `--api-version` - Rename the bundled schema file to `admin.schema.json` - Add `shopify_api_graphql::project` (version lookup, schema source, atomic file writes), behind a `download` feature - Add `toml` and `ureq` dependencies --- CHANGELOG.md | 2 +- Cargo.lock | 96 +++++ Cargo.toml | 2 + MIGRATION.md | 5 +- README.md | 29 +- crates/shopify_api/Cargo.toml | 2 +- crates/shopify_api/docs/graphql.md | 24 +- crates/shopify_api/src/bin/shopify-api.rs | 91 +++-- crates/shopify_api/src/client.rs | 2 +- crates/shopify_api/src/lib.rs | 4 +- crates/shopify_api/src/schema.rs | 13 +- crates/shopify_api_graphql/Cargo.toml | 15 + crates/shopify_api_graphql/README.md | 4 +- .../{admin-2026-10.json => admin.schema.json} | 0 crates/shopify_api_graphql/src/lib.rs | 17 +- crates/shopify_api_graphql/src/project.rs | 355 ++++++++++++++++++ crates/shopify_api_graphql/src/schema.rs | 2 +- crates/shopify_api_macros/Cargo.toml | 2 +- crates/shopify_api_macros/src/lib.rs | 164 ++++---- mise.toml | 6 +- 20 files changed, 652 insertions(+), 183 deletions(-) rename crates/shopify_api_graphql/schema/{admin-2026-10.json => admin.schema.json} (100%) create mode 100644 crates/shopify_api_graphql/src/project.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dc0420..175f2e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`, with typed input objects) or read from a file (`file("…graphql")`). - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. -- Add: the Admin schema 2026-10 is bundled (`shopify_api_graphql`); `shopify-api schema download` stores the schema of another version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. +- Add: the Admin schema 2026-10 is bundled (`shopify_api_graphql`). Another version is one line of `Cargo.toml`, `api-version` in `[package.metadata.shopify_api]`: `graphql!` downloads its schema into `graphql/admin.schema.json` on the next build, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file. - Add: `shopify-api check` checks `.graphql` files against the schema. - Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`; queries are retried after a `5xx` or a network failure, mutations never. `RetryPolicy`. - Add: tokens are renewed once for all the clones of a client, before they expire and when Shopify refuses one with a `401`. `Auth::expiring_token` with a `TokenStore`. diff --git a/Cargo.lock b/Cargo.lock index 8cd2a1e..cb656ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "android_system_properties" version = "0.1.6" @@ -284,6 +290,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + [[package]] name = "crypto-common" version = "0.2.2" @@ -359,6 +374,17 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "foreign-types" version = "0.3.2" @@ -876,6 +902,16 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.4" @@ -1189,7 +1225,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", + "log", "once_cell", + "ring", "rustls-pki-types", "rustls-webpki", "subtle", @@ -1440,6 +1478,8 @@ dependencies = [ "quote", "serde", "serde_json", + "toml", + "ureq", ] [[package]] @@ -1452,6 +1492,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -1822,6 +1868,35 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "ureq" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -1834,6 +1909,12 @@ dependencies = [ "serde", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -1962,6 +2043,15 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webpki-roots" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "winapi-util" version = "0.1.11" @@ -2207,6 +2297,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index ee78e6e..8a2d58e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,7 +40,9 @@ syn = { version = "2", features = ["full"] } thiserror = "2.0.21" tokio = { version = "1", default-features = false } tracing = { version = "0.1", default-features = false, features = ["std"] } +toml = { version = "1", default-features = false, features = ["std", "parse", "serde"] } trybuild = "1" +ureq = "3.4" [workspace.lints.rust] unsafe_code = "forbid" diff --git a/MIGRATION.md b/MIGRATION.md index 17b173f..c2b8dc9 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -132,10 +132,9 @@ Topics are accepted as `orders/create` or `ORDERS_CREATE`. | --- | --- | | `download_public_admin_schema("2026-04")` | `schema::download_public_admin_schema(ApiVersion::V2026_04)` | | `shopify.download_admin_schema()` | The same | -| `shopify-api schema download --public --out file` | `shopify-api schema download` (public by default), `--introspection` for the raw result | +| `shopify-api schema download --public --out file` | `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`: `graphql!` downloads it. `shopify-api schema download` refreshes it, `--introspection` for the raw result | -`graphql!` reads the compact form the command writes by default, in -`graphql/admin.schema.json`. +`graphql!` reads the compact form it downloads, in `graphql/admin.schema.json`. ## Removed diff --git a/README.md b/README.md index 59d136e..cbdc4eb 100644 --- a/README.md +++ b/README.md @@ -46,8 +46,8 @@ async fn main() -> shopify_api::Result<()> { then goes again. Queries are retried after a server error; mutations never run twice. - **The rest of an app's Admin API work**: pagination, bulk operations, - webhooks, OAuth and session tokens, a mock transport for tests, and a - command that downloads the schema of any API version. + webhooks, OAuth and session tokens, a mock transport for tests, and any + API version from one line of `Cargo.toml`. ## Install @@ -129,19 +129,24 @@ The full reference of `graphql!`, with the mapping of every GraphQL type, is Every operation is checked against a schema, and **sent to the version of that schema**. Out of the box that is the bundled 2026-10. To work with another -version, download its schema into your crate: +version, declare it in your `Cargo.toml`: -```bash -cargo install shopify_api --features cli -shopify-api schema download --api-version 2026-07 # writes graphql/admin.schema.json +```toml +[package.metadata.shopify_api] +api-version = "2026-07" ``` -`graphql!` then checks your operations against 2026-07, and the client sends -them to the 2026-07 endpoint: nothing else to change. Commit the file. -`ShopifyBuilder::api_version` pins every request to one version instead. +The next build downloads the 2026-07 schema into `graphql/admin.schema.json`, +checks your operations against it, and the client sends them to the 2026-07 +endpoint: nothing else to change. Commit the file, so that builds without +network access have it. Changing `api-version` downloads the new version on +the next build. `ShopifyBuilder::api_version` pins every request to one +version instead. -`shopify-api check graphql/*.graphql` checks `.graphql` files the same way, -for CI or for operations used by other tools. +The `shopify-api` command (`cargo install shopify_api --features cli`) +refreshes the file (`shopify-api schema download`, or `--shop` for the schema +a token sees), and `shopify-api check graphql/*.graphql` checks `.graphql` +files the same way, for CI or for operations used by other tools. ## Tokens @@ -303,7 +308,7 @@ The toolchain and the tasks are in `mise.toml`: ```bash mise install mise run check # what CI runs: fmt, clippy, tests, docs -mise run schema:bundle # download the bundled schema again (another version as argument) +mise run schema:bundle # download the bundled schema again (version in crates/shopify_api_graphql/Cargo.toml) mise tasks # every task ``` diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index e5976b6..b54f4bd 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -55,7 +55,7 @@ oauth = ["dep:hmac", "dep:sha2", "dep:base64", "dep:hex"] ## `MockTransport`, to test code that calls Shopify without the network. testing = [] ## The `shopify-api` command: downloads Admin schemas, checks `.graphql` files. -cli = ["dep:clap", "dep:shopify_api_graphql", "rustls", "tokio/macros", "tokio/rt-multi-thread", "tokio/fs"] +cli = ["dep:clap", "dep:shopify_api_graphql", "shopify_api_graphql/download", "rustls", "tokio/macros", "tokio/rt-multi-thread", "tokio/fs"] full = ["webhooks", "oauth", "testing", "cli"] [[bin]] diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 330e830..20b3973 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -193,21 +193,29 @@ graphql! { The schema bundled with the crate is the one of [`ApiVersion::DEFAULT`], 2026-10. Nothing has to be downloaded to use `graphql!`. -For another version, download its schema next to your `Cargo.toml`: +For another version, declare it in your `Cargo.toml`: -```bash -cargo install shopify_api --features cli -shopify-api schema download --api-version 2026-07 +```toml +[package.metadata.shopify_api] +api-version = "2026-07" ``` -This writes `graphql/admin.schema.json` (from Shopify's public endpoint, or -through a shop with `--shop`), and `graphql!` then checks every operation of -the crate against it. Commit the file: builds need it. +On the next build, `graphql!` downloads that version's schema from Shopify's +public endpoint into `graphql/admin.schema.json`, and checks every operation +of the crate against it. Later builds read the file; a new `api-version` +downloads again. Commit the file: builds without network access (CI +sandboxes, docs.rs) need it, and so does a published crate. + +The `shopify-api` command (`cargo install shopify_api --features cli`) +downloads the file again on demand: `shopify-api schema download`, or +`shopify-api schema download --shop my-shop` for the schema a shop's token +sees. | Source, in order | | | --- | --- | | `SHOPIFY_GRAPHQL_SCHEMA` | Path of a schema file, relative to `Cargo.toml` or absolute. It applies to the packages cargo builds, not to their dependencies, which keep their own schema. | -| `graphql/admin.schema.json` | Written by `shopify-api schema download`. | +| `api-version` in `[package.metadata.shopify_api]` | Kept in `graphql/admin.schema.json`, downloaded when the file is missing or holds another version. The bundled version needs no file. | +| `graphql/admin.schema.json` | Used as it is when `Cargo.toml` declares no version. | | The bundled schema | [`ApiVersion::DEFAULT`]. | An operation goes to the version of the schema it was checked against: a diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index a49a90d..4662d88 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -1,12 +1,18 @@ -//! `shopify-api`: downloads Shopify Admin schemas for `graphql!`, and checks -//! `.graphql` files against them. +//! `shopify-api`: downloads the Shopify Admin schema of the version a crate +//! declares in its `Cargo.toml`, and checks `.graphql` files against it. use std::path::{Path, PathBuf}; use std::process::ExitCode; use clap::{Args, Parser, Subcommand}; use shopify_api::{ApiVersion, Auth, Shopify}; -use shopify_api_graphql::{PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, analyze}; +use shopify_api_graphql::project::{ + configured_api_version, download_schema_file, metadata_snippet, write_atomically, +}; +use shopify_api_graphql::{ + BUNDLED_API_VERSION, PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, SchemaSource, analyze, + schema_source, +}; #[derive(Debug, Parser)] #[command( @@ -32,17 +38,18 @@ enum Command { #[derive(Debug, Subcommand)] enum SchemaCommand { - /// Downloads the Admin schema of a version, where `graphql!` reads it. + /// Downloads the Admin schema of the version in `Cargo.toml` again, where + /// `graphql!` reads it. /// - /// From Shopify's public endpoint by default; through a shop with --shop. + /// The version is `api-version` in `[package.metadata.shopify_api]` of the + /// nearest package. `graphql!` downloads it by itself when the file is + /// missing or holds another version: this command refreshes it, or + /// downloads it through a shop with --shop. Download(DownloadArgs), } #[derive(Debug, Args)] struct DownloadArgs { - /// The Admin API version. - #[arg(long, default_value_t = ApiVersion::DEFAULT.to_string())] - api_version: String, /// Where to write it. By default, `graphql/admin.schema.json` next to the /// nearest `Cargo.toml` of a package, where `graphql!` reads it /// (`graphql/admin.introspection.json` with --introspection). @@ -95,7 +102,17 @@ async fn main() -> ExitCode { } async fn download(args: DownloadArgs) -> Result { - let version = ApiVersion::new(&args.api_version).map_err(|error| error.to_string())?; + let root = package_root().ok_or( + "no Cargo.toml of a package in this directory or above: run it in the crate's directory", + )?; + let declared = configured_api_version(&root)?.ok_or_else(|| { + format!( + "{} declares no Admin API version. Add:\n\n{}", + root.join("Cargo.toml").display(), + metadata_snippet(BUNDLED_API_VERSION) + ) + })?; + let version = ApiVersion::new(&declared).map_err(|error| error.to_string())?; let introspection = match &args.shop { None => { eprintln!("Downloading the Admin schema {version} from Shopify's public endpoint…"); @@ -133,9 +150,6 @@ async fn download(args: DownloadArgs) -> Result { let (out, project) = match &args.out { Some(out) => (out.clone(), false), None => { - let root = package_root().ok_or( - "no Cargo.toml of a package in this directory or above: run it in the crate's directory, or pass --out", - )?; let file = if args.introspection { "graphql/admin.introspection.json" } else { @@ -158,12 +172,7 @@ async fn download(args: DownloadArgs) -> Result { .map_err(|error| error.to_string())?; (schema.to_json(), schema.types.len()) }; - if let Some(parent) = out.parent().filter(|parent| !parent.as_os_str().is_empty()) { - std::fs::create_dir_all(parent) - .map_err(|error| format!("cannot create {}: {error}", parent.display()))?; - } - std::fs::write(&out, contents) - .map_err(|error| format!("cannot write {}: {error}", out.display()))?; + write_atomically(&out, &contents)?; eprintln!("Wrote {} ({types} types).", out.display()); if project { @@ -171,8 +180,8 @@ async fn download(args: DownloadArgs) -> Result { touch_sources(root); } eprintln!( - "`graphql!` now checks the operations of this crate against the Admin API {version}, \ - and sends them to that version. Commit the file: builds need it." + "`graphql!` checks the operations of this crate against the Admin API {version}, \ + and sends them to that version. Commit the file: offline builds need it." ); } else if !args.introspection { eprintln!( @@ -213,29 +222,31 @@ fn package_root() -> Option { /// The schema `graphql!` would use for the nearest package, as it looks for it. fn load_schema(path: Option<&Path>) -> Result<(Schema, String), String> { - let root = package_root(); - let resolve = |path: PathBuf| match &root { - Some(root) if path.is_relative() => root.join(path), - _ => path, + let read = |path: &Path| -> Result { + let json = std::fs::read_to_string(path) + .map_err(|error| format!("cannot read {}: {error}", path.display()))?; + Schema::from_json(&json).map_err(|error| format!("{}: {error}", path.display())) }; - let named = std::env::var_os(SCHEMA_ENV) - .filter(|value| !value.is_empty()) - .map(PathBuf::from) - .map(resolve); - let project = root - .as_ref() - .map(|root| root.join(PROJECT_SCHEMA_PATH)) - .filter(|path| path.is_file()); - let path = path.map(Path::to_path_buf).or(named).or(project); - match path { - Some(path) => { - let json = std::fs::read_to_string(&path) - .map_err(|error| format!("cannot read {}: {error}", path.display()))?; - let schema = - Schema::from_json(&json).map_err(|error| format!("{}: {error}", path.display()))?; + if let Some(path) = path { + return Ok((read(path)?, path.display().to_string())); + } + let named = std::env::var_os(SCHEMA_ENV); + match schema_source(package_root().as_deref(), named.as_deref())? { + SchemaSource::Bundled => Ok((Schema::bundled().clone(), "the bundled schema".to_string())), + SchemaSource::File(path) => Ok((read(&path)?, path.display().to_string())), + SchemaSource::Declared { path, version } => { + let schema = match read(&path) { + Ok(schema) if schema.api_version == version => schema, + _ => { + eprintln!( + "Downloading the Admin schema {version} into {}…", + path.display() + ); + download_schema_file(&path, &version)? + } + }; Ok((schema, path.display().to_string())) } - None => Ok((Schema::bundled().clone(), "the bundled schema".to_string())), } } diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index 4bbfbe6..56f27dd 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -159,7 +159,7 @@ fn warn_mismatch(pinned: ApiVersion, checked: &'static str) { warned.push((pinned, checked)); tracing::warn!( "an operation checked against the Admin API {checked} is sent to {pinned}: \ - download the schema of {pinned} with `shopify-api schema download --api-version {pinned}`, \ + set `api-version = \"{pinned}\"` in `[package.metadata.shopify_api]` of Cargo.toml, \ or let the client follow the schema by not pinning a version" ); } diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index c2826c5..476085f 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -12,8 +12,8 @@ //! - **The rest of the Admin API work:** cursor [pagination](Shopify::paginate), //! [bulk operations](crate::bulk), [webhooks] and //! [OAuth](oauth), a [`MockTransport`](testing::MockTransport) -//! for tests, and the `shopify-api` command, which downloads the schema of -//! another API version. +//! for tests, and the `shopify-api` command, which refreshes the schema +//! and checks `.graphql` files. //! //! ```no_run //! use shopify_api::{Auth, Shopify, graphql}; diff --git a/crates/shopify_api/src/schema.rs b/crates/shopify_api/src/schema.rs index a79de46..3988848 100644 --- a/crates/shopify_api/src/schema.rs +++ b/crates/shopify_api/src/schema.rs @@ -1,10 +1,9 @@ //! Downloading Shopify's Admin GraphQL schema, as an introspection result. //! //! [`graphql!`](crate::graphql!) checks operations against the schema of -//! [`ApiVersion::DEFAULT`], bundled with this crate. For another version, -//! the `shopify-api schema download` command stores the schema where -//! `graphql!` reads it; these functions return the raw introspection result, -//! for other tools. +//! [`ApiVersion::DEFAULT`], bundled with this crate, or against the version +//! a crate declares in its `Cargo.toml`, which it downloads by itself. These +//! functions return the raw introspection result, for other tools. use serde_json::{Value, json}; @@ -125,10 +124,14 @@ fn check(value: Value) -> Result { #[cfg(all(test, feature = "cli"))] mod tests { #[test] - fn the_query_is_the_one_graphql_reads() { + fn the_query_and_the_endpoint_are_the_ones_graphql_uses() { assert_eq!( super::INTROSPECTION_QUERY, shopify_api_graphql::INTROSPECTION_QUERY ); + assert_eq!( + super::PUBLIC_ADMIN_SCHEMA_ENDPOINT, + shopify_api_graphql::project::PUBLIC_ADMIN_SCHEMA_ENDPOINT + ); } } diff --git a/crates/shopify_api_graphql/Cargo.toml b/crates/shopify_api_graphql/Cargo.toml index 52b502d..fc86f64 100644 --- a/crates/shopify_api_graphql/Cargo.toml +++ b/crates/shopify_api_graphql/Cargo.toml @@ -19,6 +19,21 @@ proc-macro2.workspace = true quote.workspace = true serde.workspace = true serde_json.workspace = true +toml.workspace = true +ureq = { workspace = true, optional = true } + +[features] +## `project::download_public_schema` and `project::download_schema_file`. +download = ["dep:ureq"] + +# The version of the bundled schema, `schema/admin.schema.json`: change it +# with `BUNDLED_API_VERSION`, then `mise run schema:bundle`. +[package.metadata.shopify_api] +api-version = "2026-10" + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] [lints] workspace = true diff --git a/crates/shopify_api_graphql/README.md b/crates/shopify_api_graphql/README.md index d94ba9b..dc76ffe 100644 --- a/crates/shopify_api_graphql/README.md +++ b/crates/shopify_api_graphql/README.md @@ -8,4 +8,6 @@ You do not need to depend on it directly: use `shopify_api::graphql!`. It is a separate crate so that the macro and the `shopify-api` command line share it. It also bundles the Admin schema of the API version `shopify_api` calls by -default, in a compact form (one line per type, no descriptions). +default, in a compact form (one line per type, no descriptions), reads the +version a crate declares in `[package.metadata.shopify_api]` of its +`Cargo.toml`, and downloads that version's schema (`download` feature). diff --git a/crates/shopify_api_graphql/schema/admin-2026-10.json b/crates/shopify_api_graphql/schema/admin.schema.json similarity index 100% rename from crates/shopify_api_graphql/schema/admin-2026-10.json rename to crates/shopify_api_graphql/schema/admin.schema.json diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs index 0caa303..79c1c44 100644 --- a/crates/shopify_api_graphql/src/lib.rs +++ b/crates/shopify_api_graphql/src/lib.rs @@ -4,19 +4,22 @@ //! [`analyze`](fn@analyze) checks an operation against a [`Schema`] and describes the //! shape of its variables and of its result; [`codegen`] turns that //! description into Rust types. The `graphql!` macro is a thin layer over -//! both, and the `shopify-api schema download` command uses -//! [`Schema::from_introspection`] and [`Schema::to_json`] to store the schema -//! of another API version. +//! both. [`project`] finds the API version a crate declares in its +//! `Cargo.toml`, and downloads that version's schema (with the `download` +//! feature). #![forbid(unsafe_code)] +#![cfg_attr(docsrs, feature(doc_cfg))] pub mod analyze; pub mod codegen; +pub mod project; pub mod schema; pub use analyze::{ Deprecation, Error, FieldBase, Operation, OperationKind, Scalar, SelectedField, Selection, Variable, VariableBase, analyze, }; +pub use project::{PROJECT_SCHEMA_PATH, SCHEMA_ENV, SchemaSource, schema_source}; pub use schema::{ BUNDLED_API_VERSION, Field, INTROSPECTION_QUERY, InputValue, Schema, SchemaError, TypeDef, TypeRef, @@ -39,11 +42,3 @@ pub fn is_supported_api_version(version: &str) -> bool { // Same length and form: the text orders as the dates do. well_formed && version >= MINIMUM_API_VERSION } - -/// Where a crate keeps the schema of another API version than the bundled -/// one, relative to its `Cargo.toml`. `graphql!` uses it when it exists. -pub const PROJECT_SCHEMA_PATH: &str = "graphql/admin.schema.json"; - -/// The environment variable naming another schema file for `graphql!`, -/// relative to the `Cargo.toml` of the crate being compiled, or absolute. -pub const SCHEMA_ENV: &str = "SHOPIFY_GRAPHQL_SCHEMA"; diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs new file mode 100644 index 0000000..c10d653 --- /dev/null +++ b/crates/shopify_api_graphql/src/project.rs @@ -0,0 +1,355 @@ +//! The Admin API version a crate declares, and the schema file that goes with it. +//! +//! A crate picks its version in its `Cargo.toml`: +//! +//! ```toml +//! [package.metadata.shopify_api] +//! api-version = "2026-07" +//! ``` +//! +//! `graphql!` then checks the crate's operations against that version's +//! schema, kept in [`PROJECT_SCHEMA_PATH`]: downloaded on the first build, +//! and again when the version changes. + +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; + +use crate::{BUNDLED_API_VERSION, MINIMUM_API_VERSION, is_supported_api_version}; + +/// Where a crate keeps the schema of its API version, relative to its `Cargo.toml`. +pub const PROJECT_SCHEMA_PATH: &str = "graphql/admin.schema.json"; + +/// The environment variable naming another schema file for `graphql!`, +/// relative to the `Cargo.toml` of the crate being compiled, or absolute. +pub const SCHEMA_ENV: &str = "SHOPIFY_GRAPHQL_SCHEMA"; + +/// The `[package.metadata]` table `shopify_api` reads. +pub const METADATA_TABLE: &str = "shopify_api"; + +/// The key of the API version in [`METADATA_TABLE`]. +pub const API_VERSION_KEY: &str = "api-version"; + +/// The lines to add to a `Cargo.toml` to select `version`. +pub fn metadata_snippet(version: &str) -> String { + format!("[package.metadata.{METADATA_TABLE}]\n{API_VERSION_KEY} = \"{version}\"") +} + +/// The Admin API version the `Cargo.toml` in `manifest_dir` declares, if any. +pub fn configured_api_version(manifest_dir: &Path) -> Result, String> { + let manifest = manifest_dir.join("Cargo.toml"); + let text = match std::fs::read_to_string(&manifest) { + Ok(text) => text, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(format!("cannot read `{}`: {error}", manifest.display())), + }; + api_version_in(&text).map_err(|error| format!("`{}`: {error}", manifest.display())) +} + +/// The API version a `Cargo.toml` declares, if any. +fn api_version_in(manifest: &str) -> Result, String> { + let table: toml::Table = manifest.parse().map_err(|error| format!("{error}"))?; + let value = table + .get("package") + .and_then(|package| package.get("metadata")) + .and_then(|metadata| metadata.get(METADATA_TABLE)) + .and_then(|ours| ours.get(API_VERSION_KEY)); + let Some(value) = value else { + return Ok(None); + }; + let Some(version) = value.as_str() else { + return Err(format!( + "`{API_VERSION_KEY}` in [package.metadata.{METADATA_TABLE}] must be a string, such as \"{BUNDLED_API_VERSION}\"" + )); + }; + if !is_supported_api_version(version) { + return Err(format!( + "`{API_VERSION_KEY} = \"{version}\"` in [package.metadata.{METADATA_TABLE}] is not a version shopify_api calls: \ + a quarterly release from {MINIMUM_API_VERSION} on, such as \"{BUNDLED_API_VERSION}\", or \"unstable\"" + )); + } + Ok(Some(version.to_string())) +} + +/// Where the schema of a crate comes from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchemaSource { + /// The schema bundled with this crate. + Bundled, + /// A schema file, used as it is. + File(PathBuf), + /// The schema of the version the crate declares, in `path`: to download + /// when the file is missing or holds another version. + Declared { + /// The crate's [`PROJECT_SCHEMA_PATH`]. + path: PathBuf, + /// The version its `Cargo.toml` declares. + version: String, + }, +} + +/// The schema `graphql!` uses for the crate in `manifest_dir`, in order: +/// +/// 1. the file `named` by [`SCHEMA_ENV`]; +/// 2. the version declared in `Cargo.toml`, kept in [`PROJECT_SCHEMA_PATH`] +/// (the bundled schema serves the bundled version until a file exists); +/// 3. [`PROJECT_SCHEMA_PATH`] as it is, when nothing is declared; +/// 4. the bundled schema. +pub fn schema_source( + manifest_dir: Option<&Path>, + named: Option<&OsStr>, +) -> Result { + if let Some(named) = named.filter(|value| !value.is_empty()) { + let path = match manifest_dir { + Some(dir) => dir.join(named), + None => PathBuf::from(named), + }; + if !path.is_file() { + return Err(format!( + "{SCHEMA_ENV} names `{}`, which is not a file", + path.display() + )); + } + return Ok(SchemaSource::File(path)); + } + let Some(dir) = manifest_dir else { + return Ok(SchemaSource::Bundled); + }; + let path = dir.join(PROJECT_SCHEMA_PATH); + Ok(match configured_api_version(dir)? { + Some(version) if version == BUNDLED_API_VERSION && !path.is_file() => SchemaSource::Bundled, + Some(version) => SchemaSource::Declared { path, version }, + None if path.is_file() => SchemaSource::File(path), + None => SchemaSource::Bundled, + }) +} + +/// Shopify's public copy of the Admin schema: a GraphQL endpoint per version +/// that answers introspection without a token. +pub const PUBLIC_ADMIN_SCHEMA_ENDPOINT: &str = "https://shopify.dev/admin-graphql-direct-proxy"; + +/// Downloads the Admin schema of `version` from Shopify's public endpoint. +#[cfg(feature = "download")] +#[cfg_attr(docsrs, doc(cfg(feature = "download")))] +pub fn download_public_schema(version: &str) -> Result { + use std::time::Duration; + + let url = format!("{PUBLIC_ADMIN_SCHEMA_ENDPOINT}/{version}"); + let failed = |error: &dyn std::fmt::Display| { + format!("cannot download the Admin schema {version} from {url}: {error}") + }; + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(120))) + .build() + .into(); + let body = serde_json::json!({ "query": crate::INTROSPECTION_QUERY }).to_string(); + let mut response = agent + .post(&url) + .header("Accept", "application/json") + .header("Content-Type", "application/json") + .header( + "User-Agent", + concat!("shopify_api_graphql/", env!("CARGO_PKG_VERSION")), + ) + .send(body) + .map_err(|error| failed(&error))?; + let text = response + .body_mut() + .with_config() + .limit(256 * 1024 * 1024) + .read_to_string() + .map_err(|error| failed(&error))?; + let value: serde_json::Value = serde_json::from_str(&text).map_err(|error| failed(&error))?; + if let Some(message) = value.get("error").and_then(serde_json::Value::as_str) { + return Err(failed(&message)); + } + crate::Schema::from_introspection(&value, version).map_err(|error| failed(&error)) +} + +/// Downloads the Admin schema of `version` into `path`, and returns it. +/// +/// The file is replaced in one step: a build that reads it meanwhile sees +/// the old schema or the new one, never part of one. +#[cfg(feature = "download")] +#[cfg_attr(docsrs, doc(cfg(feature = "download")))] +pub fn download_schema_file(path: &Path, version: &str) -> Result { + let schema = download_public_schema(version)?; + write_atomically(path, &schema.to_json())?; + Ok(schema) +} + +/// Writes `contents` to `path` through a temporary file in the same directory. +pub fn write_atomically(path: &Path, contents: &str) -> Result<(), String> { + if let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + std::fs::create_dir_all(parent) + .map_err(|error| format!("cannot create `{}`: {error}", parent.display()))?; + } + let mut temporary = path.as_os_str().to_owned(); + temporary.push(format!(".{}.tmp", std::process::id())); + let temporary = PathBuf::from(temporary); + std::fs::write(&temporary, contents) + .and_then(|()| std::fs::rename(&temporary, path)) + .map_err(|error| { + let _ = std::fs::remove_file(&temporary); + format!("cannot write `{}`: {error}", path.display()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An empty directory removed when the test ends. + struct Project(PathBuf); + + impl Project { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir() + .join(format!("shopify-api-graphql-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn write(&self, path: &str, content: &str) -> PathBuf { + let file = self.0.join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, content).unwrap(); + file + } + + fn manifest(&self, version: Option<&str>) { + let mut manifest = "[package]\nname = \"app\"\n".to_string(); + if let Some(version) = version { + manifest.push_str(&format!("\n{}\n", metadata_snippet(version))); + } + self.write("Cargo.toml", &manifest); + } + } + + impl Drop for Project { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn the_bundled_schema_is_the_version_its_crate_declares() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")); + let declared = configured_api_version(dir).unwrap(); + assert_eq!(declared.as_deref(), Some(BUNDLED_API_VERSION)); + assert_eq!(crate::Schema::bundled().api_version, BUNDLED_API_VERSION); + } + + #[test] + fn the_version_is_read_from_the_package_metadata() { + assert_eq!(api_version_in("[package]\nname = \"app\""), Ok(None)); + assert_eq!( + api_version_in("[package.metadata.shopify_api]\napi-version = \"2026-07\""), + Ok(Some("2026-07".to_string())) + ); + assert_eq!( + api_version_in("[package.metadata.shopify_api]\napi-version = \"unstable\""), + Ok(Some("unstable".to_string())) + ); + let old = api_version_in("[package.metadata.shopify_api]\napi-version = \"2025-01\"") + .unwrap_err(); + assert!(old.contains("is not a version shopify_api calls"), "{old}"); + let number = + api_version_in("[package.metadata.shopify_api]\napi-version = 2026").unwrap_err(); + assert!(number.contains("must be a string"), "{number}"); + assert!(api_version_in("[package").is_err()); + } + + #[test] + fn without_a_declared_version_the_file_or_the_bundled_schema_is_used() { + let project = Project::new("undeclared"); + project.manifest(None); + assert_eq!( + schema_source(Some(&project.0), None), + Ok(SchemaSource::Bundled) + ); + let file = project.write(PROJECT_SCHEMA_PATH, "{}"); + assert_eq!( + schema_source(Some(&project.0), None), + Ok(SchemaSource::File(file)) + ); + assert_eq!(schema_source(None, None), Ok(SchemaSource::Bundled)); + } + + #[test] + fn a_declared_version_selects_the_project_file() { + let project = Project::new("declared"); + project.manifest(Some("2026-07")); + assert_eq!( + schema_source(Some(&project.0), None), + Ok(SchemaSource::Declared { + path: project.0.join(PROJECT_SCHEMA_PATH), + version: "2026-07".to_string(), + }) + ); + } + + #[test] + fn the_bundled_version_needs_no_download() { + let project = Project::new("declared-bundled"); + project.manifest(Some(BUNDLED_API_VERSION)); + assert_eq!( + schema_source(Some(&project.0), None), + Ok(SchemaSource::Bundled) + ); + // A file already there is kept up to date like any other version. + let path = project.write(PROJECT_SCHEMA_PATH, "{}"); + assert_eq!( + schema_source(Some(&project.0), None), + Ok(SchemaSource::Declared { + path, + version: BUNDLED_API_VERSION.to_string(), + }) + ); + } + + #[test] + fn the_environment_names_another_file() { + let project = Project::new("named"); + project.manifest(Some("2026-07")); + let other = project.write("schemas/unstable.json", "{}"); + assert_eq!( + schema_source(Some(&project.0), Some(OsStr::new("schemas/unstable.json"))), + Ok(SchemaSource::File(other.clone())) + ); + assert_eq!( + schema_source(None, Some(other.as_os_str())), + Ok(SchemaSource::File(other)) + ); + assert_eq!( + schema_source(Some(&project.0), Some(OsStr::new(""))), + Ok(SchemaSource::Declared { + path: project.0.join(PROJECT_SCHEMA_PATH), + version: "2026-07".to_string(), + }) + ); + assert_eq!( + schema_source(Some(&project.0), Some(OsStr::new("missing.json"))), + Err(format!( + "SHOPIFY_GRAPHQL_SCHEMA names `{}`, which is not a file", + project.0.join("missing.json").display() + )) + ); + } + + #[test] + fn files_are_replaced_in_one_step() { + let project = Project::new("atomic"); + let path = project.0.join("graphql/admin.schema.json"); + write_atomically(&path, "one").unwrap(); + write_atomically(&path, "two").unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "two"); + assert_eq!( + std::fs::read_dir(path.parent().unwrap()).unwrap().count(), + 1 + ); + } +} diff --git a/crates/shopify_api_graphql/src/schema.rs b/crates/shopify_api_graphql/src/schema.rs index 41cdea2..c9cf6cd 100644 --- a/crates/shopify_api_graphql/src/schema.rs +++ b/crates/shopify_api_graphql/src/schema.rs @@ -58,7 +58,7 @@ fragment TypeRef on __Type { pub const BUNDLED_API_VERSION: &str = "2026-10"; /// Shopify's Admin GraphQL schema for [`BUNDLED_API_VERSION`]. -const BUNDLED_SCHEMA: &str = include_str!("../schema/admin-2026-10.json"); +const BUNDLED_SCHEMA: &str = include_str!("../schema/admin.schema.json"); /// The version of the stored form written by [`Schema::to_json`]. const FORMAT: u32 = 1; diff --git a/crates/shopify_api_macros/Cargo.toml b/crates/shopify_api_macros/Cargo.toml index 42c7154..c6e2681 100644 --- a/crates/shopify_api_macros/Cargo.toml +++ b/crates/shopify_api_macros/Cargo.toml @@ -17,7 +17,7 @@ include = ["src/**", "Cargo.toml", "README.md"] proc-macro = true [dependencies] -shopify_api_graphql.workspace = true +shopify_api_graphql = { workspace = true, features = ["download"] } proc-macro2.workspace = true quote.workspace = true diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 5bc64b3..5a23f69 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -3,7 +3,6 @@ #![forbid(unsafe_code)] use std::collections::HashMap; -use std::ffi::OsStr; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::SystemTime; @@ -13,9 +12,10 @@ use quote::{format_ident, quote, quote_spanned}; use shopify_api_graphql::codegen::{ DATA_TYPE, VARIABLES_TYPE, data_types, variable_type, variables_types, }; +use shopify_api_graphql::project::{download_schema_file, metadata_snippet}; use shopify_api_graphql::{ - MINIMUM_API_VERSION, Operation, OperationKind, PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, - Variable, analyze, is_supported_api_version, + BUNDLED_API_VERSION, MINIMUM_API_VERSION, Operation, OperationKind, PROJECT_SCHEMA_PATH, + SCHEMA_ENV, Schema, SchemaSource, Variable, analyze, is_supported_api_version, schema_source, }; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; @@ -202,23 +202,27 @@ impl LoadedSchema { // dependencies, which ship their own schema files. let primary = std::env::var_os("CARGO_PRIMARY_PACKAGE").is_some(); let named = std::env::var_os(SCHEMA_ENV).filter(|_| primary); - Ok( - match schema_file(manifest_dir().as_deref(), named.as_deref())? { - Some(path) => { - let schema = read_schema(&path)?; - if !is_supported_api_version(&schema.api_version) { - return Err(format!( - "`{}` is the schema of `{}`, a version shopify_api does not call (from {MINIMUM_API_VERSION}, or `unstable`): \ - download another one with `shopify-api schema download --api-version …`", - path.display(), - schema.api_version - )); - } - Self::File { schema, path } - } - None => Self::Bundled, - }, - ) + let (path, schema) = match schema_source(manifest_dir().as_deref(), named.as_deref())? { + SchemaSource::Bundled => return Ok(Self::Bundled), + SchemaSource::File(path) => { + let schema = read_schema(&path)?; + (path, schema) + } + SchemaSource::Declared { path, version } => { + let schema = declared_schema(&path, &version)?; + (path, schema) + } + }; + if !is_supported_api_version(&schema.api_version) { + return Err(format!( + "`{}` is the schema of `{}`, a version shopify_api does not call (from {MINIMUM_API_VERSION}, or `unstable`): \ + declare another one in Cargo.toml:\n\n{}", + path.display(), + schema.api_version, + metadata_snippet(BUNDLED_API_VERSION) + )); + } + Ok(Self::File { schema, path }) } fn schema(&self) -> &Schema { @@ -230,26 +234,34 @@ impl LoadedSchema { /// Makes the compiler rebuild the crate when what the expansion depends on changes. fn tracking(&self) -> TokenStream { - // One operation of the crate is enough to track the file, which is large. + // One operation of the crate is enough to track a file, which may be large. static TRACKED: Mutex> = Mutex::new(Vec::new()); - let file = match self { - Self::File { path, .. } => { - let mut tracked = TRACKED - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - (!tracked.contains(path)).then(|| { - tracked.push(path.clone()); - let path = path.to_string_lossy().to_string(); - quote!( - const _: &[u8] = ::core::include_bytes!(#path); - ) - }) - } + let mut tracked = TRACKED + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + // The manifest declares the API version, the schema file holds it. + let manifest = manifest_dir().map(|dir| dir.join("Cargo.toml")); + let schema = match self { + Self::File { path, .. } => Some(path.clone()), Self::Bundled => None, }; + let files = [manifest, schema] + .into_iter() + .flatten() + .filter(|path| path.is_file()); + let files: Vec = files + .filter(|path| { + let new = !tracked.contains(path); + if new { + tracked.push(path.clone()); + } + new + }) + .map(|path| path.to_string_lossy().to_string()) + .collect(); quote! { const _: ::core::option::Option<&str> = ::core::option_env!(#SCHEMA_ENV); - #file + #(const _: &[u8] = ::core::include_bytes!(#files);)* } } @@ -275,27 +287,27 @@ impl LoadedSchema { } } -/// The schema file of the crate being compiled, if it has one: the file named -/// by `SHOPIFY_GRAPHQL_SCHEMA`, else `graphql/admin.schema.json` next to its -/// `Cargo.toml` when that file exists. -fn schema_file( - manifest_dir: Option<&Path>, - named: Option<&OsStr>, -) -> Result, String> { - match named.filter(|value| !value.is_empty()) { - Some(named) => { - let path = resolve(manifest_dir, Path::new(named)); - if !path.is_file() { - return Err(format!( - "{SCHEMA_ENV} names `{}`, which is not a file", - path.display() - )); - } - Ok(Some(path)) - } - None => Ok(Some(resolve(manifest_dir, Path::new(PROJECT_SCHEMA_PATH))) - .filter(|path| path.is_file())), +/// The schema of the version the crate declares: its file when it holds that +/// version, else downloaded into it, once for every operation of the build. +fn declared_schema(path: &Path, version: &str) -> Result, String> { + static DOWNLOAD: Mutex<()> = Mutex::new(()); + let _one_at_a_time = DOWNLOAD + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if path.is_file() + && let Ok(schema) = read_schema(path) + && schema.api_version == version + { + return Ok(schema); } + download_schema_file(path, version).map_err(|error| { + format!( + "{error}\n`graphql!` downloads the schema of the version in Cargo.toml once, into `{}`: \ + build once with network access and commit the file", + PROJECT_SCHEMA_PATH + ) + })?; + read_schema(path) } /// Reads a schema file. One compilation expands many operations: each file is @@ -318,7 +330,7 @@ fn read_schema(file: &Path) -> Result, String> { .map_err(|error| format!("Cannot read the schema `{}`: {error}", file.display()))?; let schema = Schema::from_json(&json).map(Arc::new).map_err(|error| { format!( - "`{}`: {error}. Run `shopify-api schema download` to download it again.", + "`{}`: {error}. Delete it, or run `shopify-api schema download`, to download it again.", file.display() ) })?; @@ -594,42 +606,6 @@ mod tests { } } - #[test] - fn a_crate_without_a_schema_file_uses_the_bundled_schema() { - let project = Project::new("bundled"); - assert_eq!(schema_file(Some(&project.0), None), Ok(None)); - assert_eq!( - schema_file(Some(&project.0), Some(OsStr::new(""))), - Ok(None) - ); - assert_eq!(schema_file(None, None), Ok(None)); - } - - #[test] - fn the_crate_file_and_the_environment_select_another_schema() { - let project = Project::new("selected"); - let downloaded = project.write("graphql/admin.schema.json", SCHEMA); - let other = project.write("schemas/unstable.json", SCHEMA); - - assert_eq!(schema_file(Some(&project.0), None), Ok(Some(downloaded))); - // The environment wins, relative to the manifest or absolute. - let named = OsStr::new("schemas/unstable.json"); - assert_eq!( - schema_file(Some(&project.0), Some(named)), - Ok(Some(other.clone())) - ); - assert_eq!(schema_file(None, Some(other.as_os_str())), Ok(Some(other))); - - let missing = project.0.join("missing.json"); - assert_eq!( - schema_file(Some(&project.0), Some(OsStr::new("missing.json"))), - Err(format!( - "SHOPIFY_GRAPHQL_SCHEMA names `{}`, which is not a file", - missing.display() - )) - ); - } - #[test] fn schema_files_are_read_once_and_again_when_they_change() { let project = Project::new("read"); @@ -662,7 +638,9 @@ mod tests { "{error}" ); assert!( - error.ends_with(". Run `shopify-api schema download` to download it again."), + error.ends_with( + ". Delete it, or run `shopify-api schema download`, to download it again." + ), "{error}" ); diff --git a/mise.toml b/mise.toml index b32807d..df79051 100644 --- a/mise.toml +++ b/mise.toml @@ -46,9 +46,9 @@ env = { TRYBUILD = "overwrite" } run = "cargo test -p shopify_api --all-features --locked --test compile_fail" [tasks."schema:bundle"] -description = "Download the Admin schema bundled with the crates, for the version given (2026-10 by default)" -usage = 'arg "[version]" default="2026-10"' -run = "cargo run -p shopify_api --features cli --locked -- schema download --api-version ${usage_version} --out crates/shopify_api_graphql/schema/admin-${usage_version}.json" +description = "Download the bundled Admin schema again, for the version in crates/shopify_api_graphql/Cargo.toml" +dir = "crates/shopify_api_graphql" +run = "cargo run -p shopify_api --features cli --locked -- schema download --out schema/admin.schema.json" [tasks."test:live"] description = "Run the tests against a real development store (needs SHOPIFY_TEST_SHOP and a token, see tests/live.rs)" From 06d7d08283385f603e25e510204bd50a39d9cd4a Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:27:42 +0200 Subject: [PATCH 003/135] feat!: download the Admin schema instead of bundling it - No schema ships with the crates. `graphql!` downloads the schema of the crate's API version on first build and again when the version changes. - Default version is the latest stable one. `api-version` in `[package.metadata.shopify_api]` pins it. - `shopify-api schema download --only ` keeps only the types and fields those `.graphql` files use. - Crate operations are checked against a trimmed `graphql/internal.schema.json`, and the Admin schema moves to `crates/shopify_api/graphql/`. - Add `.cargo/config.toml` pointing `SHOPIFY_GRAPHQL_SCHEMA` at the test schema. --- .cargo/config.toml | 5 + CHANGELOG.md | 2 +- MIGRATION.md | 4 +- README.md | 26 +- crates/shopify_api/Cargo.toml | 18 +- crates/shopify_api/docs/graphql.md | 26 +- .../graphql}/admin.schema.json | 0 .../shopify_api/graphql/internal.schema.json | 44 +++ .../graphql/operations/bulk_cancel.graphql | 9 + .../graphql/operations/bulk_get.graphql | 6 + .../graphql/operations/bulk_list.graphql | 9 + .../operations/bulk_run_mutation.graphql | 9 + .../graphql/operations/bulk_run_query.graphql | 9 + .../operations/bulk_staged_uploads.graphql | 6 + .../operations/webhooks_create.graphql | 10 + .../operations/webhooks_delete.graphql | 6 + .../graphql/operations/webhooks_list.graphql | 10 + .../operations/webhooks_update.graphql | 10 + crates/shopify_api/src/bin/shopify-api.rs | 185 ++++++++----- crates/shopify_api/src/bulk.rs | 63 +---- crates/shopify_api/src/schema.rs | 6 +- crates/shopify_api/src/version.rs | 6 +- crates/shopify_api/src/webhooks.rs | 47 +--- crates/shopify_api_graphql/Cargo.toml | 9 +- crates/shopify_api_graphql/README.md | 8 +- crates/shopify_api_graphql/src/lib.rs | 14 +- crates/shopify_api_graphql/src/project.rs | 262 +++++++++++++----- crates/shopify_api_graphql/src/restrict.rs | 226 +++++++++++++++ crates/shopify_api_graphql/src/schema.rs | 27 +- crates/shopify_api_graphql/tests/analyze.rs | 18 +- .../tests/internal_schema.rs | 71 +++++ crates/shopify_api_macros/src/lib.rs | 111 ++++---- mise.toml | 13 +- 33 files changed, 914 insertions(+), 361 deletions(-) create mode 100644 .cargo/config.toml rename crates/{shopify_api_graphql/schema => shopify_api/graphql}/admin.schema.json (100%) create mode 100644 crates/shopify_api/graphql/internal.schema.json create mode 100644 crates/shopify_api/graphql/operations/bulk_cancel.graphql create mode 100644 crates/shopify_api/graphql/operations/bulk_get.graphql create mode 100644 crates/shopify_api/graphql/operations/bulk_list.graphql create mode 100644 crates/shopify_api/graphql/operations/bulk_run_mutation.graphql create mode 100644 crates/shopify_api/graphql/operations/bulk_run_query.graphql create mode 100644 crates/shopify_api/graphql/operations/bulk_staged_uploads.graphql create mode 100644 crates/shopify_api/graphql/operations/webhooks_create.graphql create mode 100644 crates/shopify_api/graphql/operations/webhooks_delete.graphql create mode 100644 crates/shopify_api/graphql/operations/webhooks_list.graphql create mode 100644 crates/shopify_api/graphql/operations/webhooks_update.graphql create mode 100644 crates/shopify_api_graphql/src/restrict.rs create mode 100644 crates/shopify_api_graphql/tests/internal_schema.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..ff01aa5 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,5 @@ +# The schema `graphql!` checks the operations of this workspace against, +# tests and examples: the Admin schema 2026-10, without network access. It +# also reaches the projects `trybuild` compiles for the compile-fail tests. +[env] +SHOPIFY_GRAPHQL_SCHEMA = { value = "crates/shopify_api/graphql/admin.schema.json", relative = true } diff --git a/CHANGELOG.md b/CHANGELOG.md index 175f2e6..ad2d567 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`, with typed input objects) or read from a file (`file("…graphql")`). - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. -- Add: the Admin schema 2026-10 is bundled (`shopify_api_graphql`). Another version is one line of `Cargo.toml`, `api-version` in `[package.metadata.shopify_api]`: `graphql!` downloads its schema into `graphql/admin.schema.json` on the next build, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file. +- Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - Add: `shopify-api check` checks `.graphql` files against the schema. - Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`; queries are retried after a `5xx` or a network failure, mutations never. `RetryPolicy`. - Add: tokens are renewed once for all the clones of a client, before they expire and when Shopify refuses one with a `401`. `Auth::expiring_token` with a `TokenStore`. diff --git a/MIGRATION.md b/MIGRATION.md index c2b8dc9..b51fbf9 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -38,8 +38,8 @@ The shop must now be `` or `.myshopify.com` (with or without `https://`): 0.10 accepted any text and appended `.myshopify.com`. Without a pinned version, an operation of `graphql!` goes to the version its -schema was checked against (2026-10, or the version of your -`graphql/admin.schema.json`), and an untyped call to 2026-10. 0.10 sent +schema was checked against (the `api-version` of your `Cargo.toml`, else the +latest), and an untyped call to 2026-10. 0.10 sent everything to 2026-04 by default: pin it with `.api_version(ApiVersion::V2026_04)` to keep that. diff --git a/README.md b/README.md index cbdc4eb..738af1b 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,9 @@ shopify_api = "1" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` -Rust 1.88 or newer. The bundled schema is the Admin API **2026-10**. +Rust 1.88 or newer. The first build downloads the Admin schema of the latest +stable version into `graphql/admin.schema.json`, next to your `Cargo.toml`: +commit it. ## Operations @@ -128,20 +130,23 @@ The full reference of `graphql!`, with the mapping of every GraphQL type, is ## API versions Every operation is checked against a schema, and **sent to the version of that -schema**. Out of the box that is the bundled 2026-10. To work with another -version, declare it in your `Cargo.toml`: +schema**. No schema ships with the crate: `graphql!` downloads the one of your +version into `graphql/admin.schema.json`, and downloads again when the version +changes. Commit the file, so that builds without network access have it. + +Out of the box, the version is **the latest stable one**: when Shopify +releases a new version (each quarter), the next build that recompiles your +crate moves to it, and a field Shopify removed becomes a compile error. To +stay on one version, declare it in your `Cargo.toml`: ```toml [package.metadata.shopify_api] api-version = "2026-07" ``` -The next build downloads the 2026-07 schema into `graphql/admin.schema.json`, -checks your operations against it, and the client sends them to the 2026-07 -endpoint: nothing else to change. Commit the file, so that builds without -network access have it. Changing `api-version` downloads the new version on -the next build. `ShopifyBuilder::api_version` pins every request to one -version instead. +Your operations are then checked against 2026-07, and the client sends them to +the 2026-07 endpoint: nothing else to change. `ShopifyBuilder::api_version` +pins every request to one version instead. The `shopify-api` command (`cargo install shopify_api --features cli`) refreshes the file (`shopify-api schema download`, or `--shop` for the schema @@ -308,7 +313,8 @@ The toolchain and the tasks are in `mise.toml`: ```bash mise install mise run check # what CI runs: fmt, clippy, tests, docs -mise run schema:bundle # download the bundled schema again (version in crates/shopify_api_graphql/Cargo.toml) +mise run schema:test # download the schema the tests use again (version in crates/shopify_api/Cargo.toml) +mise run schema:internal # cut it down to the crate's own operations, graphql/internal.schema.json mise tasks # every task ``` diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index b54f4bd..d76831e 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -11,7 +11,23 @@ rust-version.workspace = true license.workspace = true repository.workspace = true authors.workspace = true -include = ["src/**", "docs/**", "tests/**", "examples/**", "Cargo.toml"] +# `graphql/admin.schema.json`, the whole Admin schema the tests use, stays +# out: the crate's own operations need only `graphql/internal.schema.json`. +include = [ + "src/**", + "docs/**", + "tests/**", + "examples/**", + "graphql/internal.schema.json", + "graphql/operations/**", + "Cargo.toml", +] + +# The version of the tests, the examples and `graphql/internal.schema.json`. +# To move to another: change it, `shopify-api schema download` in this +# directory, then `mise run schema:internal` and `mise run ui:bless`. +[package.metadata.shopify_api] +api-version = "2026-10" [package.metadata.docs.rs] all-features = true diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 20b3973..9fdff98 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -190,21 +190,26 @@ graphql! { # Schema and API version -The schema bundled with the crate is the one of [`ApiVersion::DEFAULT`], -2026-10. Nothing has to be downloaded to use `graphql!`. +No schema ships with the crate. On the first build, `graphql!` downloads the +schema of the crate's version from Shopify's public endpoint into +`graphql/admin.schema.json`, and checks every operation of the crate against +it. Later builds read the file, and download again when the version changes. +Commit the file: builds without network access (CI sandboxes, docs.rs) need +it, and so does a published crate. -For another version, declare it in your `Cargo.toml`: +The version is the one your `Cargo.toml` declares: ```toml [package.metadata.shopify_api] api-version = "2026-07" ``` -On the next build, `graphql!` downloads that version's schema from Shopify's -public endpoint into `graphql/admin.schema.json`, and checks every operation -of the crate against it. Later builds read the file; a new `api-version` -downloads again. Commit the file: builds without network access (CI -sandboxes, docs.rs) need it, and so does a published crate. +Without it, it is the latest stable version: Shopify releases one on the first +day of each quarter (`2026-10` on October 1st), and the next build that +recompiles the crate moves to it. A field the new version removed is then a +compile error. When the new version cannot be downloaded (no network, or +Shopify has not published it yet that day), the build keeps the file it has, +else takes the version before. The `shopify-api` command (`cargo install shopify_api --features cli`) downloads the file again on demand: `shopify-api schema download`, or @@ -214,9 +219,8 @@ sees. | Source, in order | | | --- | --- | | `SHOPIFY_GRAPHQL_SCHEMA` | Path of a schema file, relative to `Cargo.toml` or absolute. It applies to the packages cargo builds, not to their dependencies, which keep their own schema. | -| `api-version` in `[package.metadata.shopify_api]` | Kept in `graphql/admin.schema.json`, downloaded when the file is missing or holds another version. The bundled version needs no file. | -| `graphql/admin.schema.json` | Used as it is when `Cargo.toml` declares no version. | -| The bundled schema | [`ApiVersion::DEFAULT`]. | +| `api-version` in `[package.metadata.shopify_api]` | Kept in `graphql/admin.schema.json`, downloaded when the file is missing or holds another version. | +| The latest stable version | Kept there too, the same way. | An operation goes to the version of the schema it was checked against: a crate whose schema is 2026-07 calls the 2026-07 endpoint, with nothing to diff --git a/crates/shopify_api_graphql/schema/admin.schema.json b/crates/shopify_api/graphql/admin.schema.json similarity index 100% rename from crates/shopify_api_graphql/schema/admin.schema.json rename to crates/shopify_api/graphql/admin.schema.json diff --git a/crates/shopify_api/graphql/internal.schema.json b/crates/shopify_api/graphql/internal.schema.json new file mode 100644 index 0000000..75adc91 --- /dev/null +++ b/crates/shopify_api/graphql/internal.schema.json @@ -0,0 +1,44 @@ +{"format":1,"apiVersion":"2026-10","query":"QueryRoot","mutation":"Mutation", +"directives":{"idempotent":{"l":["FIELD"],"a":{"key":"String!"}},"include":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}},"skip":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}}},"types":{ +"ApiVersion":{"o":{"f":{"handle":"String!"}}}, +"Boolean":"s", +"BulkMutationErrorCode":{"e":["OPERATION_IN_PROGRESS","INVALID_MUTATION","INVALID_STAGED_UPLOAD_FILE","NO_SUCH_FILE","INTERNAL_FILE_SERVER_ERROR","LIMIT_REACHED"]}, +"BulkMutationUserError":{"o":{"f":{"code":"BulkMutationErrorCode","field":"[String!]","message":"String!"}}}, +"BulkOperation":{"o":{"f":{"completedAt":"DateTime","createdAt":"DateTime!","errorCode":"BulkOperationErrorCode","fileSize":"UnsignedInt64","id":"ID!","objectCount":"UnsignedInt64!","partialDataUrl":"URL","query":"String!","rootObjectCount":"UnsignedInt64!","status":"BulkOperationStatus!","type":"BulkOperationType!","url":"URL"}}}, +"BulkOperationCancelPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[UserError!]!"}}}, +"BulkOperationConnection":{"o":{"f":{"nodes":"[BulkOperation!]!","pageInfo":"PageInfo!"}}}, +"BulkOperationErrorCode":{"e":["ACCESS_DENIED","INTERNAL_SERVER_ERROR","TIMEOUT"]}, +"BulkOperationRunMutationPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[BulkMutationUserError!]!"}}}, +"BulkOperationRunQueryPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[BulkOperationUserError!]!"}}}, +"BulkOperationStatus":{"e":["CANCELED","CANCELING","COMPLETED","CREATED","EXPIRED","FAILED","RUNNING"]}, +"BulkOperationType":{"e":["QUERY","MUTATION"]}, +"BulkOperationUserError":{"o":{"f":{"code":"BulkOperationUserErrorCode","field":"[String!]","message":"String!"}}}, +"BulkOperationUserErrorCode":{"e":["OPERATION_IN_PROGRESS","INVALID","LIMIT_REACHED"]}, +"BulkOperationsSortKeys":{"e":["COMPLETED_AT","CREATED_AT"]}, +"DateTime":"s", +"HasMetafieldsMetafieldIdentifierInput":{"i":{"key":"String!","namespace":"String"}}, +"ID":"s", +"Int":"s", +"Mutation":{"o":{"f":{"bulkOperationCancel":["BulkOperationCancelPayload",{"id":"ID!"}],"bulkOperationRunMutation":["BulkOperationRunMutationPayload",{"clientIdentifier":"String","groupObjects":"Boolean=","mutation":"String!","stagedUploadPath":"String!"}],"bulkOperationRunQuery":["BulkOperationRunQueryPayload",{"groupObjects":"Boolean!=","query":"String!"}],"stagedUploadsCreate":["StagedUploadsCreatePayload",{"input":"[StagedUploadInput!]!"}],"webhookSubscriptionCreate":["WebhookSubscriptionCreatePayload",{"topic":"WebhookSubscriptionTopic!","webhookSubscription":"WebhookSubscriptionInput!"}],"webhookSubscriptionDelete":["WebhookSubscriptionDeletePayload",{"id":"ID!"}],"webhookSubscriptionUpdate":["WebhookSubscriptionUpdatePayload",{"id":"ID!","webhookSubscription":"WebhookSubscriptionInput!"}]},"d":{"bulkOperationRunMutation(groupObjects)":"This argument has no effect on output order."}}}, +"PageInfo":{"o":{"f":{"endCursor":"String","hasNextPage":"Boolean!"}}}, +"QueryRoot":{"o":{"f":{"bulkOperation":["BulkOperation",{"id":"ID!"}],"bulkOperations":["BulkOperationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"BulkOperationsSortKeys="}],"webhookSubscriptions":["WebhookSubscriptionConnection!",{"after":"String","before":"String","callbackUrl":"URL","first":"Int","format":"WebhookSubscriptionFormat","last":"Int","query":"String","reverse":"Boolean=","sortKey":"WebhookSubscriptionSortKeys=","topics":"[WebhookSubscriptionTopic!]","uri":"String"}]},"d":{"webhookSubscriptions(callbackUrl)":"Use `uri` instead."}}}, +"StagedMediaUploadTarget":{"o":{"f":{"parameters":"[StagedUploadParameter!]!","resourceUrl":"URL","url":"URL"}}}, +"StagedUploadHttpMethodType":{"e":["POST","PUT"]}, +"StagedUploadInput":{"i":{"fileSize":"UnsignedInt64","filename":"String!","httpMethod":"StagedUploadHttpMethodType=","mimeType":"String!","resource":"StagedUploadTargetGenerateUploadResource!"}}, +"StagedUploadParameter":{"o":{"f":{"name":"String!","value":"String!"}}}, +"StagedUploadTargetGenerateUploadResource":{"e":{"v":["COLLECTION_IMAGE","FILE","IMAGE","MODEL_3D","PRODUCT_IMAGE","SHOP_IMAGE","VIDEO","BULK_MUTATION_VARIABLES","RETURN_LABEL","URL_REDIRECT_IMPORT","DISPUTE_FILE_UPLOAD"],"d":{"PRODUCT_IMAGE":"Use IMAGE instead. This resource type will be removed in a future version."}}}, +"StagedUploadsCreatePayload":{"o":{"f":{"stagedTargets":"[StagedMediaUploadTarget!]","userErrors":"[UserError!]!"}}}, +"String":"s", +"URL":"s", +"UnsignedInt64":"s", +"UserError":{"o":{"f":{"field":"[String!]","message":"String!"}}}, +"WebhookSubscription":{"o":{"f":{"apiVersion":"ApiVersion!","createdAt":"DateTime!","filter":"String","format":"WebhookSubscriptionFormat!","id":"ID!","includeFields":"[String!]!","metafieldNamespaces":"[String!]!","name":"String","topic":"WebhookSubscriptionTopic!","updatedAt":"DateTime!","uri":"String!"}}}, +"WebhookSubscriptionConnection":{"o":{"f":{"nodes":"[WebhookSubscription!]!","pageInfo":"PageInfo!"}}}, +"WebhookSubscriptionCreatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"WebhookSubscriptionDeletePayload":{"o":{"f":{"deletedWebhookSubscriptionId":"ID","userErrors":"[UserError!]!"}}}, +"WebhookSubscriptionFormat":{"e":["JSON","XML"]}, +"WebhookSubscriptionInput":{"i":{"f":{"callbackUrl":"URL","filter":"String","format":"WebhookSubscriptionFormat","includeFields":"[String!]","metafieldNamespaces":"[String!]","metafields":"[HasMetafieldsMetafieldIdentifierInput!]","name":"String","uri":"String"},"d":{"callbackUrl":"Use `uri` instead."}}}, +"WebhookSubscriptionSortKeys":{"e":["CREATED_AT","ID"]}, +"WebhookSubscriptionTopic":{"e":["TAX_SUMMARIES_CREATE","APP_UNINSTALLED","APP_SCOPES_UPDATE","CARTS_CREATE","CARTS_UPDATE","CHANNELS_DELETE","CHECKOUTS_CREATE","CHECKOUTS_DELETE","CHECKOUTS_UPDATE","CUSTOMER_PAYMENT_METHODS_CREATE","CUSTOMER_PAYMENT_METHODS_UPDATE","CUSTOMER_PAYMENT_METHODS_REVOKE","COLLECTION_LISTINGS_ADD","COLLECTION_LISTINGS_REMOVE","COLLECTION_LISTINGS_UPDATE","COLLECTION_PUBLICATIONS_CREATE","COLLECTION_PUBLICATIONS_DELETE","COLLECTION_PUBLICATIONS_UPDATE","COLLECTIONS_CREATE","COLLECTIONS_DELETE","COLLECTIONS_UPDATE","CUSTOMER_GROUPS_CREATE","CUSTOMER_GROUPS_DELETE","CUSTOMER_GROUPS_UPDATE","CUSTOMERS_CREATE","CUSTOMERS_DELETE","CUSTOMERS_DISABLE","CUSTOMERS_ENABLE","CUSTOMERS_UPDATE","CUSTOMERS_PURCHASING_SUMMARY","CUSTOMERS_MARKETING_CONSENT_UPDATE","CUSTOMERS_WHATS_APP_MARKETING_CONSENT_UPDATE","CUSTOMER_TAGS_ADDED","CUSTOMER_TAGS_REMOVED","CUSTOMERS_EMAIL_MARKETING_CONSENT_UPDATE","DISPUTES_CREATE","DISPUTES_UPDATE","DRAFT_ORDERS_CREATE","DRAFT_ORDERS_DELETE","DRAFT_ORDERS_UPDATE","FULFILLMENT_EVENTS_CREATE","FULFILLMENT_EVENTS_DELETE","FULFILLMENTS_CREATE","FULFILLMENTS_UPDATE","ATTRIBUTED_SESSIONS_FIRST","ATTRIBUTED_SESSIONS_LAST","ORDER_TRANSACTIONS_CREATE","ORDERS_CANCELLED","ORDERS_CREATE","ORDERS_DELETE","ORDERS_EDITED","ORDERS_FULFILLED","ORDERS_PAID","ORDERS_PARTIALLY_FULFILLED","ORDERS_UPDATED","ORDERS_LINK_REQUESTED","FULFILLMENT_ORDERS_MOVED","FULFILLMENT_ORDERS_HOLD_RELEASED","FULFILLMENT_ORDERS_SCHEDULED_FULFILLMENT_ORDER_READY","FULFILLMENT_HOLDS_RELEASED","FULFILLMENT_ORDERS_ORDER_ROUTING_COMPLETE","FULFILLMENT_ORDERS_CANCELLED","FULFILLMENT_ORDERS_FULFILLMENT_SERVICE_FAILED_TO_COMPLETE","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_REJECTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_SUBMITTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_ACCEPTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_REJECTED","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_SUBMITTED","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_ACCEPTED","FULFILLMENT_HOLDS_ADDED","FULFILLMENT_ORDERS_LINE_ITEMS_PREPARED_FOR_LOCAL_DELIVERY","FULFILLMENT_ORDERS_PLACED_ON_HOLD","FULFILLMENT_ORDERS_MERGED","FULFILLMENT_ORDERS_SPLIT","FULFILLMENT_ORDERS_PROGRESS_REPORTED","FULFILLMENT_ORDERS_MANUALLY_REPORTED_PROGRESS_STOPPED","PRODUCT_LISTINGS_ADD","PRODUCT_LISTINGS_REMOVE","PRODUCT_LISTINGS_UPDATE","SCHEDULED_PRODUCT_LISTINGS_ADD","SCHEDULED_PRODUCT_LISTINGS_UPDATE","SCHEDULED_PRODUCT_LISTINGS_REMOVE","PRODUCT_PUBLICATIONS_CREATE","PRODUCT_PUBLICATIONS_DELETE","PRODUCT_PUBLICATIONS_UPDATE","PRODUCTS_CREATE","PRODUCTS_DELETE","PRODUCTS_UPDATE","REFUNDS_CREATE","SEGMENTS_CREATE","SEGMENTS_DELETE","SEGMENTS_UPDATE","SHIPPING_ADDRESSES_CREATE","SHIPPING_ADDRESSES_UPDATE","SHOP_UPDATE","TAX_PARTNERS_UPDATE","TAX_SERVICES_CREATE","TAX_SERVICES_UPDATE","THEMES_CREATE","THEMES_DELETE","THEMES_PUBLISH","THEMES_UPDATE","VARIANTS_IN_STOCK","VARIANTS_OUT_OF_STOCK","INVENTORY_LEVELS_CONNECT","INVENTORY_LEVELS_UPDATE","INVENTORY_LEVELS_DISCONNECT","INVENTORY_ITEMS_CREATE","INVENTORY_ITEMS_UPDATE","INVENTORY_ITEMS_DELETE","LOCATIONS_ACTIVATE","LOCATIONS_DEACTIVATE","LOCATIONS_CREATE","LOCATIONS_UPDATE","LOCATIONS_DELETE","TENDER_TRANSACTIONS_CREATE","APP_PURCHASES_ONE_TIME_UPDATE","APP_SUBSCRIPTIONS_APPROACHING_CAPPED_AMOUNT","APP_SUBSCRIPTIONS_UPDATE","LOCALES_CREATE","LOCALES_UPDATE","LOCALES_DESTROY","MACHINE_TRANSLATION_BATCH_COMPLETED","DOMAINS_CREATE","DOMAINS_UPDATE","DOMAINS_DESTROY","SUBSCRIPTION_CONTRACTS_CREATE","SUBSCRIPTION_CONTRACTS_UPDATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_CREATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_UPDATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_DELETE","PROFILES_CREATE","PROFILES_UPDATE","PROFILES_DELETE","SUBSCRIPTION_BILLING_ATTEMPTS_SUCCESS","SUBSCRIPTION_BILLING_ATTEMPTS_FAILURE","SUBSCRIPTION_BILLING_ATTEMPTS_CHALLENGED","RETURNS_CANCEL","RETURNS_CLOSE","RETURNS_REOPEN","RETURNS_REQUEST","RETURNS_APPROVE","RETURNS_UPDATE","RETURNS_PROCESS","RETURNS_DECLINE","REVERSE_DELIVERIES_ATTACH_DELIVERABLE","REVERSE_FULFILLMENT_ORDERS_DISPOSE","PAYMENT_TERMS_CREATE","PAYMENT_TERMS_DELETE","PAYMENT_TERMS_UPDATE","PAYMENT_SCHEDULES_DUE","SELLING_PLAN_GROUPS_CREATE","SELLING_PLAN_GROUPS_UPDATE","SELLING_PLAN_GROUPS_DELETE","BULK_OPERATIONS_FINISH","PRODUCT_FEEDS_CREATE","PRODUCT_FEEDS_UPDATE","PRODUCT_FEEDS_INCREMENTAL_SYNC","PRODUCT_FEEDS_FULL_SYNC","PRODUCT_FEEDS_FULL_SYNC_FINISH","MARKETS_CREATE","MARKETS_UPDATE","MARKETS_DELETE","ORDERS_RISK_ASSESSMENT_CHANGED","ORDERS_SHOPIFY_PROTECT_ELIGIBILITY_CHANGED","FINANCE_KYC_INFORMATION_UPDATE","FULFILLMENT_ORDERS_RESCHEDULED","PUBLICATIONS_DELETE","AUDIT_EVENTS_ADMIN_API_ACTIVITY","FULFILLMENT_ORDERS_LINE_ITEMS_PREPARED_FOR_PICKUP","COMPANIES_CREATE","COMPANIES_UPDATE","COMPANIES_DELETE","COMPANY_LOCATIONS_CREATE","COMPANY_LOCATIONS_UPDATE","COMPANY_LOCATIONS_DELETE","COMPANY_CONTACTS_CREATE","COMPANY_CONTACTS_UPDATE","COMPANY_CONTACTS_DELETE","CUSTOMERS_MERGE","INVENTORY_TRANSFERS_ADD_ITEMS","INVENTORY_TRANSFERS_UPDATE_ITEM_QUANTITIES","INVENTORY_TRANSFERS_REMOVE_ITEMS","INVENTORY_TRANSFERS_READY_TO_SHIP","INVENTORY_TRANSFERS_CANCEL","INVENTORY_TRANSFERS_COMPLETE","INVENTORY_TRANSFERS_UPDATED","INVENTORY_SHIPMENTS_DELETE","INVENTORY_SHIPMENTS_CREATE","INVENTORY_SHIPMENTS_MARK_IN_TRANSIT","INVENTORY_SHIPMENTS_UPDATE_TRACKING","INVENTORY_SHIPMENTS_ADD_ITEMS","INVENTORY_SHIPMENTS_UPDATE_ITEM_QUANTITIES","INVENTORY_SHIPMENTS_REMOVE_ITEMS","INVENTORY_SHIPMENTS_RECEIVE_ITEMS","CUSTOMER_ACCOUNT_SETTINGS_UPDATE","CUSTOMER_JOINED_SEGMENT","CUSTOMER_LEFT_SEGMENT","COMPANY_CONTACT_ROLES_ASSIGN","COMPANY_CONTACT_ROLES_REVOKE","SUBSCRIPTION_CONTRACTS_ACTIVATE","SUBSCRIPTION_CONTRACTS_PAUSE","SUBSCRIPTION_CONTRACTS_CANCEL","SUBSCRIPTION_CONTRACTS_FAIL","SUBSCRIPTION_CONTRACTS_EXPIRE","SUBSCRIPTION_CONTRACT_CALCULATIONS_SUCCEED","SUBSCRIPTION_CONTRACT_CALCULATIONS_FAIL","SUBSCRIPTION_BILLING_CYCLES_SKIP","SUBSCRIPTION_BILLING_CYCLES_UNSKIP","METAOBJECTS_CREATE","METAOBJECTS_UPDATE","METAOBJECTS_DELETE","FINANCE_APP_STAFF_MEMBER_GRANT","FINANCE_APP_STAFF_MEMBER_REVOKE","FINANCE_APP_STAFF_MEMBER_DELETE","FINANCE_APP_STAFF_MEMBER_UPDATE","ROLLOUTS_CREATE","ROLLOUTS_DELETE","ROLLOUTS_RESOURCE_CHANGE_ADDED","ROLLOUTS_RESOURCE_CHANGE_REMOVED","ROLLOUTS_RESOURCE_CHANGE_UPDATED","ROLLOUTS_UPDATE","DISCOUNTS_CREATE","DISCOUNTS_UPDATE","DISCOUNTS_DELETE","DISCOUNTS_REDEEMCODE_ADDED","DISCOUNTS_REDEEMCODE_REMOVED","METAFIELD_DEFINITIONS_CREATE","METAFIELD_DEFINITIONS_UPDATE","METAFIELD_DEFINITIONS_DELETE","DELIVERY_PROMISE_SETTINGS_UPDATE","MARKETS_BACKUP_REGION_UPDATE","CHECKOUT_AND_ACCOUNTS_CONFIGURATIONS_UPDATE","REQUESTED_ORDER_EDIT_CREATED","REQUESTED_ORDER_EDIT_RESOLVED","REQUESTED_ORDER_EDIT_DECLINED"]}, +"WebhookSubscriptionUpdatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}} +}} diff --git a/crates/shopify_api/graphql/operations/bulk_cancel.graphql b/crates/shopify_api/graphql/operations/bulk_cancel.graphql new file mode 100644 index 0000000..9d55bbe --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_cancel.graphql @@ -0,0 +1,9 @@ +mutation BulkOperationCancel($id: ID!) { + bulkOperationCancel(id: $id) { + bulkOperation { ...BulkOperationFields } + userErrors { field message } + } +} +fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query +} diff --git a/crates/shopify_api/graphql/operations/bulk_get.graphql b/crates/shopify_api/graphql/operations/bulk_get.graphql new file mode 100644 index 0000000..6df9b6c --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_get.graphql @@ -0,0 +1,6 @@ +query BulkOperation($id: ID!) { + bulkOperation(id: $id) { ...BulkOperationFields } +} +fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query +} diff --git a/crates/shopify_api/graphql/operations/bulk_list.graphql b/crates/shopify_api/graphql/operations/bulk_list.graphql new file mode 100644 index 0000000..8bf1439 --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_list.graphql @@ -0,0 +1,9 @@ +query BulkOperations($first: Int!, $after: String, $query: String, $reverse: Boolean) { + bulkOperations(first: $first, after: $after, query: $query, reverse: $reverse, sortKey: CREATED_AT) { + nodes { ...BulkOperationFields } + pageInfo { hasNextPage endCursor } + } +} +fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query +} diff --git a/crates/shopify_api/graphql/operations/bulk_run_mutation.graphql b/crates/shopify_api/graphql/operations/bulk_run_mutation.graphql new file mode 100644 index 0000000..af329d2 --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_run_mutation.graphql @@ -0,0 +1,9 @@ +mutation BulkOperationRunMutation($mutation: String!, $stagedUploadPath: String!, $clientIdentifier: String) { + bulkOperationRunMutation(mutation: $mutation, stagedUploadPath: $stagedUploadPath, clientIdentifier: $clientIdentifier) { + bulkOperation { ...BulkOperationFields } + userErrors { field message code } + } +} +fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query +} diff --git a/crates/shopify_api/graphql/operations/bulk_run_query.graphql b/crates/shopify_api/graphql/operations/bulk_run_query.graphql new file mode 100644 index 0000000..e613d45 --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_run_query.graphql @@ -0,0 +1,9 @@ +mutation BulkOperationRunQuery($query: String!, $groupObjects: Boolean!) { + bulkOperationRunQuery(query: $query, groupObjects: $groupObjects) { + bulkOperation { ...BulkOperationFields } + userErrors { field message code } + } +} +fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query +} diff --git a/crates/shopify_api/graphql/operations/bulk_staged_uploads.graphql b/crates/shopify_api/graphql/operations/bulk_staged_uploads.graphql new file mode 100644 index 0000000..ef6394d --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_staged_uploads.graphql @@ -0,0 +1,6 @@ +mutation StagedUploadsCreate($input: [StagedUploadInput!]!) { + stagedUploadsCreate(input: $input) { + stagedTargets { url resourceUrl parameters { name value } } + userErrors { field message } + } +} diff --git a/crates/shopify_api/graphql/operations/webhooks_create.graphql b/crates/shopify_api/graphql/operations/webhooks_create.graphql new file mode 100644 index 0000000..bbbbdf2 --- /dev/null +++ b/crates/shopify_api/graphql/operations/webhooks_create.graphql @@ -0,0 +1,10 @@ +mutation WebhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) { + webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) { + webhookSubscription { ...WebhookSubscriptionFields } + userErrors { field message } + } +} +fragment WebhookSubscriptionFields on WebhookSubscription { + id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt + apiVersion { handle } +} diff --git a/crates/shopify_api/graphql/operations/webhooks_delete.graphql b/crates/shopify_api/graphql/operations/webhooks_delete.graphql new file mode 100644 index 0000000..f7824f7 --- /dev/null +++ b/crates/shopify_api/graphql/operations/webhooks_delete.graphql @@ -0,0 +1,6 @@ +mutation WebhookSubscriptionDelete($id: ID!) { + webhookSubscriptionDelete(id: $id) { + deletedWebhookSubscriptionId + userErrors { field message } + } +} diff --git a/crates/shopify_api/graphql/operations/webhooks_list.graphql b/crates/shopify_api/graphql/operations/webhooks_list.graphql new file mode 100644 index 0000000..ec51e0f --- /dev/null +++ b/crates/shopify_api/graphql/operations/webhooks_list.graphql @@ -0,0 +1,10 @@ +query WebhookSubscriptions($after: String) { + webhookSubscriptions(first: 250, after: $after) { + nodes { ...WebhookSubscriptionFields } + pageInfo { hasNextPage endCursor } + } +} +fragment WebhookSubscriptionFields on WebhookSubscription { + id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt + apiVersion { handle } +} diff --git a/crates/shopify_api/graphql/operations/webhooks_update.graphql b/crates/shopify_api/graphql/operations/webhooks_update.graphql new file mode 100644 index 0000000..6e9c579 --- /dev/null +++ b/crates/shopify_api/graphql/operations/webhooks_update.graphql @@ -0,0 +1,10 @@ +mutation WebhookSubscriptionUpdate($id: ID!, $webhookSubscription: WebhookSubscriptionInput!) { + webhookSubscriptionUpdate(id: $id, webhookSubscription: $webhookSubscription) { + webhookSubscription { ...WebhookSubscriptionFields } + userErrors { field message } + } +} +fragment WebhookSubscriptionFields on WebhookSubscription { + id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt + apiVersion { handle } +} diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index 4662d88..d2e9368 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -1,16 +1,20 @@ -//! `shopify-api`: downloads the Shopify Admin schema of the version a crate -//! declares in its `Cargo.toml`, and checks `.graphql` files against it. +//! `shopify-api`: downloads the Shopify Admin schema of a crate's API version +//! (the one its `Cargo.toml` declares, else the latest), and checks +//! `.graphql` files against it. use std::path::{Path, PathBuf}; use std::process::ExitCode; use clap::{Args, Parser, Subcommand}; use shopify_api::{ApiVersion, Auth, Shopify}; +use std::sync::Arc; +use std::time::SystemTime; + use shopify_api_graphql::project::{ - configured_api_version, download_schema_file, metadata_snippet, write_atomically, + configured_api_version, previous_api_version, up_to_date_schema, write_atomically, }; use shopify_api_graphql::{ - BUNDLED_API_VERSION, PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, SchemaSource, analyze, + PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, SchemaSource, analyze, latest_api_version, schema_source, }; @@ -38,13 +42,13 @@ enum Command { #[derive(Debug, Subcommand)] enum SchemaCommand { - /// Downloads the Admin schema of the version in `Cargo.toml` again, where + /// Downloads the Admin schema of the crate's version again, where /// `graphql!` reads it. /// /// The version is `api-version` in `[package.metadata.shopify_api]` of the - /// nearest package. `graphql!` downloads it by itself when the file is - /// missing or holds another version: this command refreshes it, or - /// downloads it through a shop with --shop. + /// nearest package, else the latest stable one. `graphql!` downloads it by + /// itself when the file is missing or holds another version: this command + /// refreshes it, or downloads it through a shop with --shop. Download(DownloadArgs), } @@ -59,6 +63,10 @@ struct DownloadArgs { /// of the compact form `graphql!` reads. #[arg(long)] introspection: bool, + /// Keeps only what these `.graphql` files use: the types they reach, and + /// the fields they select. For a small schema to commit with a library. + #[arg(long, num_args = 1.., value_name = "FILES", conflicts_with = "introspection")] + only: Vec, /// Downloads through this shop, with its token: the schema the token sees. #[arg(long, env = "SHOPIFY_SHOP")] shop: Option, @@ -105,46 +113,28 @@ async fn download(args: DownloadArgs) -> Result { let root = package_root().ok_or( "no Cargo.toml of a package in this directory or above: run it in the crate's directory", )?; - let declared = configured_api_version(&root)?.ok_or_else(|| { - format!( - "{} declares no Admin API version. Add:\n\n{}", - root.join("Cargo.toml").display(), - metadata_snippet(BUNDLED_API_VERSION) - ) - })?; - let version = ApiVersion::new(&declared).map_err(|error| error.to_string())?; - let introspection = match &args.shop { - None => { - eprintln!("Downloading the Admin schema {version} from Shopify's public endpoint…"); - shopify_api::schema::download_public_admin_schema(version) - .await - .map_err(|error| error.to_string())? - } - Some(shop) => { - let auth = match (&args.access_token, &args.client_id, &args.client_secret) { - (Some(token), _, _) => Auth::access_token(token), - (None, Some(id), Some(secret)) => Auth::client_credentials(id, secret), - _ => { - return Err( - "--shop needs --access-token, or --client-id and --client-secret" - .to_string(), - ); - } + let declared = configured_api_version(&root)?; + let latest = declared.is_none(); + let wanted = declared.unwrap_or_else(|| latest_api_version(SystemTime::now())); + if latest { + eprintln!( + "{} declares no Admin API version: the latest is {wanted}.", + root.join("Cargo.toml").display() + ); + } + let mut version = ApiVersion::new(&wanted).map_err(|error| error.to_string())?; + let introspection = match fetch(&args, version).await { + Ok(introspection) => introspection, + // A new version may not be out on its first day. + Err(error) if latest && args.shop.is_none() => { + let Some(previous) = previous_api_version(&wanted) else { + return Err(error); }; - let shopify = Shopify::builder(shop) - .auth(auth) - .api_version(version) - .build() - .map_err(|error| error.to_string())?; - eprintln!( - "Downloading the Admin schema {version} through {}…", - shopify.shop() - ); - shopify - .download_admin_schema() - .await - .map_err(|error| error.to_string())? + eprintln!("{error}\nTrying the version before, {previous}."); + version = ApiVersion::new(&previous).map_err(|error| error.to_string())?; + fetch(&args, version).await? } + Err(error) => return Err(error), }; let (out, project) = match &args.out { @@ -168,8 +158,22 @@ async fn download(args: DownloadArgs) -> Result { serde_json::to_string_pretty(&introspection).map_err(|error| error.to_string())?; (format!("{pretty}\n"), types) } else { - let schema = Schema::from_introspection(&introspection, &version.to_string()) + let mut schema = Schema::from_introspection(&introspection, &version.to_string()) .map_err(|error| error.to_string())?; + if !args.only.is_empty() { + let texts = args + .only + .iter() + .map(|file| { + std::fs::read_to_string(file) + .map_err(|error| format!("cannot read {}: {error}", file.display())) + }) + .collect::, _>>()?; + let texts: Vec<&str> = texts.iter().map(String::as_str).collect(); + schema = schema + .restricted_to(&texts) + .map_err(|error| error.to_string())?; + } (schema.to_json(), schema.types.len()) }; write_atomically(&out, &contents)?; @@ -192,6 +196,39 @@ async fn download(args: DownloadArgs) -> Result { Ok(ExitCode::SUCCESS) } +/// The introspection result for `version`, from Shopify's public endpoint or +/// through the shop of `args`. +async fn fetch(args: &DownloadArgs, version: ApiVersion) -> Result { + let Some(shop) = &args.shop else { + eprintln!("Downloading the Admin schema {version} from Shopify's public endpoint…"); + return shopify_api::schema::download_public_admin_schema(version) + .await + .map_err(|error| error.to_string()); + }; + let auth = match (&args.access_token, &args.client_id, &args.client_secret) { + (Some(token), _, _) => Auth::access_token(token), + (None, Some(id), Some(secret)) => Auth::client_credentials(id, secret), + _ => { + return Err( + "--shop needs --access-token, or --client-id and --client-secret".to_string(), + ); + } + }; + let shopify = Shopify::builder(shop) + .auth(auth) + .api_version(version) + .build() + .map_err(|error| error.to_string())?; + eprintln!( + "Downloading the Admin schema {version} through {}…", + shopify.shop() + ); + shopify + .download_admin_schema() + .await + .map_err(|error| error.to_string()) +} + /// Cargo follows a schema file once `graphql!` read it, not before it /// exists: touching the sources makes the next build read the new file. fn touch_sources(package: &Path) { @@ -222,32 +259,44 @@ fn package_root() -> Option { /// The schema `graphql!` would use for the nearest package, as it looks for it. fn load_schema(path: Option<&Path>) -> Result<(Schema, String), String> { - let read = |path: &Path| -> Result { + let read = |path: &Path| -> Result, String> { let json = std::fs::read_to_string(path) .map_err(|error| format!("cannot read {}: {error}", path.display()))?; - Schema::from_json(&json).map_err(|error| format!("{}: {error}", path.display())) + Schema::from_json(&json) + .map(Arc::new) + .map_err(|error| format!("{}: {error}", path.display())) }; - if let Some(path) = path { - return Ok((read(path)?, path.display().to_string())); - } - let named = std::env::var_os(SCHEMA_ENV); - match schema_source(package_root().as_deref(), named.as_deref())? { - SchemaSource::Bundled => Ok((Schema::bundled().clone(), "the bundled schema".to_string())), - SchemaSource::File(path) => Ok((read(&path)?, path.display().to_string())), - SchemaSource::Declared { path, version } => { - let schema = match read(&path) { - Ok(schema) if schema.api_version == version => schema, - _ => { - eprintln!( - "Downloading the Admin schema {version} into {}…", - path.display() - ); - download_schema_file(&path, &version)? + let path = match path { + Some(path) => path.to_path_buf(), + None => { + let named = std::env::var_os(SCHEMA_ENV); + match schema_source( + package_root().as_deref(), + named.as_deref(), + SystemTime::now(), + )? { + SchemaSource::File(path) => path, + SchemaSource::Version { + path, + version, + latest, + } => { + let schema = up_to_date_schema(&path, &version, latest, |file| { + if !file.is_file() || read(file).is_ok_and(|s| s.api_version != version) { + eprintln!( + "Downloading the Admin schema {version} into {}…", + file.display() + ); + } + read(file) + })?; + return Ok((Arc::unwrap_or_clone(schema), path.display().to_string())); } - }; - Ok((schema, path.display().to_string())) + } } - } + }; + let schema = read(&path)?; + Ok((Arc::unwrap_or_clone(schema), path.display().to_string())) } fn check(args: CheckArgs) -> Result { diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 693bd23..fee054b 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -42,81 +42,34 @@ use serde::{Deserialize, Serialize}; use tokio::time::Instant; use crate::transport::{HttpRequest, Method}; -use crate::{Error, Page, Result, Shopify, UserError, graphql}; +use crate::{Error, Page, Result, Shopify, UserError}; +use shopify_api_macros::__graphql_internal as graphql; /// How long a download of results may take. const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60); graphql! { - mod run_query = "#graphql - mutation BulkOperationRunQuery($query: String!, $groupObjects: Boolean!) { - bulkOperationRunQuery(query: $query, groupObjects: $groupObjects) { - bulkOperation { ...BulkOperationFields } - userErrors { field message code } - } - } - fragment BulkOperationFields on BulkOperation { - id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query - }"; + mod run_query = file("graphql/operations/bulk_run_query.graphql"); } graphql! { - mod run_mutation = "#graphql - mutation BulkOperationRunMutation($mutation: String!, $stagedUploadPath: String!, $clientIdentifier: String) { - bulkOperationRunMutation(mutation: $mutation, stagedUploadPath: $stagedUploadPath, clientIdentifier: $clientIdentifier) { - bulkOperation { ...BulkOperationFields } - userErrors { field message code } - } - } - fragment BulkOperationFields on BulkOperation { - id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query - }"; + mod run_mutation = file("graphql/operations/bulk_run_mutation.graphql"); } graphql! { - mod get = "#graphql - query BulkOperation($id: ID!) { - bulkOperation(id: $id) { ...BulkOperationFields } - } - fragment BulkOperationFields on BulkOperation { - id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query - }"; + mod get = file("graphql/operations/bulk_get.graphql"); } graphql! { - mod list = "#graphql - query BulkOperations($first: Int!, $after: String, $query: String, $reverse: Boolean) { - bulkOperations(first: $first, after: $after, query: $query, reverse: $reverse, sortKey: CREATED_AT) { - nodes { ...BulkOperationFields } - pageInfo { hasNextPage endCursor } - } - } - fragment BulkOperationFields on BulkOperation { - id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query - }"; + mod list = file("graphql/operations/bulk_list.graphql"); } graphql! { - mod cancel = "#graphql - mutation BulkOperationCancel($id: ID!) { - bulkOperationCancel(id: $id) { - bulkOperation { ...BulkOperationFields } - userErrors { field message } - } - } - fragment BulkOperationFields on BulkOperation { - id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query - }"; + mod cancel = file("graphql/operations/bulk_cancel.graphql"); } graphql! { - mod staged_uploads = "#graphql - mutation StagedUploadsCreate($input: [StagedUploadInput!]!) { - stagedUploadsCreate(input: $input) { - stagedTargets { url resourceUrl parameters { name value } } - userErrors { field message } - } - }"; + mod staged_uploads = file("graphql/operations/bulk_staged_uploads.graphql"); } /// A bulk operation, as Shopify last reported it. diff --git a/crates/shopify_api/src/schema.rs b/crates/shopify_api/src/schema.rs index 3988848..6747346 100644 --- a/crates/shopify_api/src/schema.rs +++ b/crates/shopify_api/src/schema.rs @@ -1,9 +1,9 @@ //! Downloading Shopify's Admin GraphQL schema, as an introspection result. //! //! [`graphql!`](crate::graphql!) checks operations against the schema of -//! [`ApiVersion::DEFAULT`], bundled with this crate, or against the version -//! a crate declares in its `Cargo.toml`, which it downloads by itself. These -//! functions return the raw introspection result, for other tools. +//! the version a crate declares in its `Cargo.toml`, else of the latest +//! version, and downloads it by itself. These functions return the raw +//! introspection result, for other tools. use serde_json::{Value, json}; diff --git a/crates/shopify_api/src/version.rs b/crates/shopify_api/src/version.rs index 98e900b..efa3a1a 100644 --- a/crates/shopify_api/src/version.rs +++ b/crates/shopify_api/src/version.rs @@ -33,8 +33,10 @@ impl ApiVersion { pub const V2027_01: Self = Self::dated(2027, 1); pub const UNSTABLE: Self = Self(Repr::Unstable); - /// The version this crate calls when none is chosen: the one of the - /// schema bundled with it, which `graphql!` checks operations against. + /// The version untyped requests ([`Shopify::graphql`](crate::Shopify::graphql)) + /// go to when none is chosen: the newest stable version this release of + /// the crate knows. A `graphql!` operation goes to the version of the + /// schema it was checked against. pub const DEFAULT: Self = Self::V2026_10; /// The oldest version this crate accepts: the first whose bulk operation diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs index c7b8fa9..b05487e 100644 --- a/crates/shopify_api/src/webhooks.rs +++ b/crates/shopify_api/src/webhooks.rs @@ -33,7 +33,8 @@ use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use sha2::Sha256; -use crate::{Error, Result, ShopDomain, Shopify, UserError, graphql}; +use crate::{Error, Result, ShopDomain, Shopify, UserError}; +use shopify_api_macros::__graphql_internal as graphql; /// Whether `hmac_header` (`X-Shopify-Hmac-Sha256`) is the signature of /// `body` with `secret`, the client secret of the app. Compares in constant time. @@ -225,45 +226,15 @@ pub fn topic_enum(topic: &str) -> String { // ─── Subscriptions ─────────────────────────────────────────────────── graphql! { - mod list = "#graphql - query WebhookSubscriptions($after: String) { - webhookSubscriptions(first: 250, after: $after) { - nodes { ...WebhookSubscriptionFields } - pageInfo { hasNextPage endCursor } - } - } - fragment WebhookSubscriptionFields on WebhookSubscription { - id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt - apiVersion { handle } - }"; + mod list = file("graphql/operations/webhooks_list.graphql"); } graphql! { - mod create = "#graphql - mutation WebhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) { - webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) { - webhookSubscription { ...WebhookSubscriptionFields } - userErrors { field message } - } - } - fragment WebhookSubscriptionFields on WebhookSubscription { - id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt - apiVersion { handle } - }"; + mod create = file("graphql/operations/webhooks_create.graphql"); } graphql! { - mod update = "#graphql - mutation WebhookSubscriptionUpdate($id: ID!, $webhookSubscription: WebhookSubscriptionInput!) { - webhookSubscriptionUpdate(id: $id, webhookSubscription: $webhookSubscription) { - webhookSubscription { ...WebhookSubscriptionFields } - userErrors { field message } - } - } - fragment WebhookSubscriptionFields on WebhookSubscription { - id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt - apiVersion { handle } - }"; + mod update = file("graphql/operations/webhooks_update.graphql"); } /// The input of `create` or `update` for a spec. An update sends every @@ -286,13 +257,7 @@ macro_rules! input { } graphql! { - mod delete = "#graphql - mutation WebhookSubscriptionDelete($id: ID!) { - webhookSubscriptionDelete(id: $id) { - deletedWebhookSubscriptionId - userErrors { field message } - } - }"; + mod delete = file("graphql/operations/webhooks_delete.graphql"); } /// A webhook subscription of a shop. diff --git a/crates/shopify_api_graphql/Cargo.toml b/crates/shopify_api_graphql/Cargo.toml index fc86f64..050d412 100644 --- a/crates/shopify_api_graphql/Cargo.toml +++ b/crates/shopify_api_graphql/Cargo.toml @@ -11,7 +11,7 @@ rust-version.workspace = true license.workspace = true repository.workspace = true authors.workspace = true -include = ["src/**", "schema/**", "Cargo.toml", "README.md"] +include = ["src/**", "Cargo.toml", "README.md"] [dependencies] graphql-parser.workspace = true @@ -23,14 +23,9 @@ toml.workspace = true ureq = { workspace = true, optional = true } [features] -## `project::download_public_schema` and `project::download_schema_file`. +## `project::download_public_schema`, `project::download_schema_file` and `project::up_to_date_schema`. download = ["dep:ureq"] -# The version of the bundled schema, `schema/admin.schema.json`: change it -# with `BUNDLED_API_VERSION`, then `mise run schema:bundle`. -[package.metadata.shopify_api] -api-version = "2026-10" - [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] diff --git a/crates/shopify_api_graphql/README.md b/crates/shopify_api_graphql/README.md index dc76ffe..dd06124 100644 --- a/crates/shopify_api_graphql/README.md +++ b/crates/shopify_api_graphql/README.md @@ -7,7 +7,7 @@ against it, and generates the Rust types of its variables and of its result. You do not need to depend on it directly: use `shopify_api::graphql!`. It is a separate crate so that the macro and the `shopify-api` command line share it. -It also bundles the Admin schema of the API version `shopify_api` calls by -default, in a compact form (one line per type, no descriptions), reads the -version a crate declares in `[package.metadata.shopify_api]` of its -`Cargo.toml`, and downloads that version's schema (`download` feature). +It bundles no schema: it reads the version a crate declares in +`[package.metadata.shopify_api]` of its `Cargo.toml` (else takes the latest +stable one), downloads that version's schema (`download` feature), and stores +it in a compact form (one line per type, no descriptions). diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs index 79c1c44..ebedd6d 100644 --- a/crates/shopify_api_graphql/src/lib.rs +++ b/crates/shopify_api_graphql/src/lib.rs @@ -4,26 +4,26 @@ //! [`analyze`](fn@analyze) checks an operation against a [`Schema`] and describes the //! shape of its variables and of its result; [`codegen`] turns that //! description into Rust types. The `graphql!` macro is a thin layer over -//! both. [`project`] finds the API version a crate declares in its -//! `Cargo.toml`, and downloads that version's schema (with the `download` -//! feature). +//! both. [`project`] finds the API version of a crate (the one its +//! `Cargo.toml` declares, else the latest), and downloads that version's +//! schema (with the `download` feature). No schema is bundled. #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] pub mod analyze; pub mod codegen; pub mod project; +mod restrict; pub mod schema; pub use analyze::{ Deprecation, Error, FieldBase, Operation, OperationKind, Scalar, SelectedField, Selection, Variable, VariableBase, analyze, }; -pub use project::{PROJECT_SCHEMA_PATH, SCHEMA_ENV, SchemaSource, schema_source}; -pub use schema::{ - BUNDLED_API_VERSION, Field, INTROSPECTION_QUERY, InputValue, Schema, SchemaError, TypeDef, - TypeRef, +pub use project::{ + PROJECT_SCHEMA_PATH, SCHEMA_ENV, SchemaSource, latest_api_version, schema_source, }; +pub use schema::{Field, INTROSPECTION_QUERY, InputValue, Schema, SchemaError, TypeDef, TypeRef}; /// The oldest Admin API version `shopify_api` calls. pub const MINIMUM_API_VERSION: &str = "2026-04"; diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index c10d653..5145e68 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -1,20 +1,22 @@ -//! The Admin API version a crate declares, and the schema file that goes with it. +//! The Admin API version of a crate, and the schema file that goes with it. //! -//! A crate picks its version in its `Cargo.toml`: +//! A crate may pin its version in its `Cargo.toml`: //! //! ```toml //! [package.metadata.shopify_api] //! api-version = "2026-07" //! ``` //! -//! `graphql!` then checks the crate's operations against that version's -//! schema, kept in [`PROJECT_SCHEMA_PATH`]: downloaded on the first build, -//! and again when the version changes. +//! Without it, the crate follows the latest stable version. Either way, +//! `graphql!` checks the crate's operations against that version's schema, +//! kept in [`PROJECT_SCHEMA_PATH`]: downloaded on the first build, and again +//! when the version changes. use std::ffi::OsStr; use std::path::{Path, PathBuf}; +use std::time::SystemTime; -use crate::{BUNDLED_API_VERSION, MINIMUM_API_VERSION, is_supported_api_version}; +use crate::{MINIMUM_API_VERSION, is_supported_api_version}; /// Where a crate keeps the schema of its API version, relative to its `Cargo.toml`. pub const PROJECT_SCHEMA_PATH: &str = "graphql/admin.schema.json"; @@ -34,6 +36,47 @@ pub fn metadata_snippet(version: &str) -> String { format!("[package.metadata.{METADATA_TABLE}]\n{API_VERSION_KEY} = \"{version}\"") } +/// The newest stable Admin API version at `now`: Shopify releases one on the +/// first day of each quarter, named after it (`2026-10` on October 1st). +pub fn latest_api_version(now: SystemTime) -> String { + let seconds = now + .duration_since(SystemTime::UNIX_EPOCH) + .map_or(0, |since| since.as_secs()); + let (year, month) = year_and_month(seconds / 86_400); + format!("{year}-{:02}", (month - 1) / 3 * 3 + 1) +} + +/// The quarterly release before `version`: `2026-01` before `2026-04`. +pub fn previous_api_version(version: &str) -> Option { + let (year, month) = version.split_once('-')?; + let (year, month): (u32, u32) = (year.parse().ok()?, month.parse().ok()?); + let previous = match month { + 1 => format!("{}-10", year.checked_sub(1)?), + 4 | 7 | 10 => format!("{year}-{:02}", month - 3), + _ => return None, + }; + Some(previous) +} + +/// The year and month (1 to 12) of a day counted from 1970-01-01, in UTC. +fn year_and_month(days: u64) -> (u64, u64) { + // Howard Hinnant's `civil_from_days`, for days after the epoch. + let z = days + 719_468; + let era = z / 146_097; + let day_of_era = z - era * 146_097; + let year_of_era = + (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let shifted_month = (5 * day_of_year + 2) / 153; + let month = if shifted_month < 10 { + shifted_month + 3 + } else { + shifted_month - 9 + }; + let year = year_of_era + era * 400 + u64::from(month <= 2); + (year, month) +} + /// The Admin API version the `Cargo.toml` in `manifest_dir` declares, if any. pub fn configured_api_version(manifest_dir: &Path) -> Result, String> { let manifest = manifest_dir.join("Cargo.toml"); @@ -58,13 +101,13 @@ fn api_version_in(manifest: &str) -> Result, String> { }; let Some(version) = value.as_str() else { return Err(format!( - "`{API_VERSION_KEY}` in [package.metadata.{METADATA_TABLE}] must be a string, such as \"{BUNDLED_API_VERSION}\"" + "`{API_VERSION_KEY}` in [package.metadata.{METADATA_TABLE}] must be a string, such as \"2026-10\"" )); }; if !is_supported_api_version(version) { return Err(format!( "`{API_VERSION_KEY} = \"{version}\"` in [package.metadata.{METADATA_TABLE}] is not a version shopify_api calls: \ - a quarterly release from {MINIMUM_API_VERSION} on, such as \"{BUNDLED_API_VERSION}\", or \"unstable\"" + a quarterly release from {MINIMUM_API_VERSION} on, such as \"2026-10\", or \"unstable\"" )); } Ok(Some(version.to_string())) @@ -73,30 +116,29 @@ fn api_version_in(manifest: &str) -> Result, String> { /// Where the schema of a crate comes from. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SchemaSource { - /// The schema bundled with this crate. - Bundled, /// A schema file, used as it is. File(PathBuf), - /// The schema of the version the crate declares, in `path`: to download - /// when the file is missing or holds another version. - Declared { + /// The schema of `version`, kept in `path`: to download when the file is + /// missing or holds another version. + Version { /// The crate's [`PROJECT_SCHEMA_PATH`]. path: PathBuf, - /// The version its `Cargo.toml` declares. + /// The version its `Cargo.toml` declares, else the latest one. version: String, + /// No version is declared: `version` is the latest one. + latest: bool, }, } -/// The schema `graphql!` uses for the crate in `manifest_dir`, in order: +/// The schema `graphql!` uses for the crate in `manifest_dir`, at `now`: /// /// 1. the file `named` by [`SCHEMA_ENV`]; -/// 2. the version declared in `Cargo.toml`, kept in [`PROJECT_SCHEMA_PATH`] -/// (the bundled schema serves the bundled version until a file exists); -/// 3. [`PROJECT_SCHEMA_PATH`] as it is, when nothing is declared; -/// 4. the bundled schema. +/// 2. the version declared in `Cargo.toml`, kept in [`PROJECT_SCHEMA_PATH`]; +/// 3. else the latest version, kept there too. pub fn schema_source( manifest_dir: Option<&Path>, named: Option<&OsStr>, + now: SystemTime, ) -> Result { if let Some(named) = named.filter(|value| !value.is_empty()) { let path = match manifest_dir { @@ -111,15 +153,13 @@ pub fn schema_source( } return Ok(SchemaSource::File(path)); } - let Some(dir) = manifest_dir else { - return Ok(SchemaSource::Bundled); - }; - let path = dir.join(PROJECT_SCHEMA_PATH); - Ok(match configured_api_version(dir)? { - Some(version) if version == BUNDLED_API_VERSION && !path.is_file() => SchemaSource::Bundled, - Some(version) => SchemaSource::Declared { path, version }, - None if path.is_file() => SchemaSource::File(path), - None => SchemaSource::Bundled, + let dir = manifest_dir + .ok_or("no Cargo.toml of a package: the schema of a crate is kept next to it")?; + let declared = configured_api_version(dir)?; + Ok(SchemaSource::Version { + path: dir.join(PROJECT_SCHEMA_PATH), + latest: declared.is_none(), + version: declared.unwrap_or_else(|| latest_api_version(now)), }) } @@ -139,6 +179,7 @@ pub fn download_public_schema(version: &str) -> Result { }; let agent: ureq::Agent = ureq::Agent::config_builder() .timeout_global(Some(Duration::from_secs(120))) + .http_status_as_error(false) .build() .into(); let body = serde_json::json!({ "query": crate::INTROSPECTION_QUERY }).to_string(); @@ -158,10 +199,19 @@ pub fn download_public_schema(version: &str) -> Result { .limit(256 * 1024 * 1024) .read_to_string() .map_err(|error| failed(&error))?; - let value: serde_json::Value = serde_json::from_str(&text).map_err(|error| failed(&error))?; - if let Some(message) = value.get("error").and_then(serde_json::Value::as_str) { - return Err(failed(&message)); + let value: Option = serde_json::from_str(&text).ok(); + let message = value + .as_ref() + .and_then(|value| value.get("error")) + .and_then(serde_json::Value::as_str); + let status = response.status(); + if let Some(message) = message { + return Err(failed(&format!("{message} (HTTP {})", status.as_u16()))); } + if !status.is_success() { + return Err(failed(&format!("HTTP {}", status.as_u16()))); + } + let value = value.ok_or_else(|| failed(&"the answer is not JSON"))?; crate::Schema::from_introspection(&value, version).map_err(|error| failed(&error)) } @@ -197,8 +247,45 @@ pub fn write_atomically(path: &Path, contents: &str) -> Result<(), String> { }) } +/// The schema of `version` in `path`, read with `read`: the file when it +/// holds that version, else downloaded into it. +/// +/// For the `latest` version, a failed download falls back on the file as it +/// is, else on the previous version: a new version may not be out yet on its +/// first day, and a build without network keeps the schema it has. +#[cfg(feature = "download")] +#[cfg_attr(docsrs, doc(cfg(feature = "download")))] +pub fn up_to_date_schema>( + path: &Path, + version: &str, + latest: bool, + read: impl Fn(&Path) -> Result, +) -> Result { + let current = path.is_file().then(|| read(path).ok()).flatten(); + if let Some(current) = current { + if current.as_ref().api_version == version { + return Ok(current); + } + return match download_schema_file(path, version) { + Ok(_) => read(path), + Err(_) if latest => Ok(current), + Err(error) => Err(error), + }; + } + match download_schema_file(path, version) { + Ok(_) => read(path), + Err(error) if latest => match previous_api_version(version) { + Some(previous) if download_schema_file(path, &previous).is_ok() => read(path), + _ => Err(error), + }, + Err(error) => Err(error), + } +} + #[cfg(test)] mod tests { + use std::time::Duration; + use super::*; /// An empty directory removed when the test ends. @@ -235,12 +322,54 @@ mod tests { } } + fn leap(year: u64) -> bool { + (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) + } + + /// Midnight UTC of a day. + fn day(year: u64, month: u64, day: u64) -> SystemTime { + let mut days = 0; + for y in 1970..year { + days += if leap(y) { 366 } else { 365 }; + } + let leap = leap(year); + let lengths = [ + 31, + if leap { 29 } else { 28 }, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31, + ]; + days += lengths[..(month - 1) as usize].iter().sum::() + day - 1; + SystemTime::UNIX_EPOCH + Duration::from_secs(days * 86_400) + } + #[test] - fn the_bundled_schema_is_the_version_its_crate_declares() { - let dir = Path::new(env!("CARGO_MANIFEST_DIR")); - let declared = configured_api_version(dir).unwrap(); - assert_eq!(declared.as_deref(), Some(BUNDLED_API_VERSION)); - assert_eq!(crate::Schema::bundled().api_version, BUNDLED_API_VERSION); + fn the_latest_version_is_the_one_of_the_quarter() { + assert_eq!(latest_api_version(day(2026, 10, 1)), "2026-10"); + assert_eq!(latest_api_version(day(2026, 10, 22)), "2026-10"); + assert_eq!(latest_api_version(day(2026, 12, 31)), "2026-10"); + assert_eq!(latest_api_version(day(2027, 1, 1)), "2027-01"); + assert_eq!(latest_api_version(day(2027, 3, 31)), "2027-01"); + assert_eq!(latest_api_version(day(2028, 2, 29)), "2028-01"); + assert_eq!(latest_api_version(day(2028, 4, 1)), "2028-04"); + assert_eq!(latest_api_version(day(2030, 9, 30)), "2030-07"); + } + + #[test] + fn the_previous_version_is_the_quarter_before() { + assert_eq!(previous_api_version("2027-01").as_deref(), Some("2026-10")); + assert_eq!(previous_api_version("2026-10").as_deref(), Some("2026-07")); + assert_eq!(previous_api_version("2026-04").as_deref(), Some("2026-01")); + assert_eq!(previous_api_version("unstable"), None); + assert_eq!(previous_api_version("2026-05"), None); } #[test] @@ -264,75 +393,62 @@ mod tests { } #[test] - fn without_a_declared_version_the_file_or_the_bundled_schema_is_used() { - let project = Project::new("undeclared"); + fn without_a_declared_version_the_latest_is_used() { + let project = Project::new("latest"); project.manifest(None); assert_eq!( - schema_source(Some(&project.0), None), - Ok(SchemaSource::Bundled) - ); - let file = project.write(PROJECT_SCHEMA_PATH, "{}"); - assert_eq!( - schema_source(Some(&project.0), None), - Ok(SchemaSource::File(file)) + schema_source(Some(&project.0), None, day(2027, 2, 3)), + Ok(SchemaSource::Version { + path: project.0.join(PROJECT_SCHEMA_PATH), + version: "2027-01".to_string(), + latest: true, + }) ); - assert_eq!(schema_source(None, None), Ok(SchemaSource::Bundled)); + assert!(schema_source(None, None, day(2027, 2, 3)).is_err()); } #[test] - fn a_declared_version_selects_the_project_file() { + fn a_declared_version_is_used() { let project = Project::new("declared"); project.manifest(Some("2026-07")); assert_eq!( - schema_source(Some(&project.0), None), - Ok(SchemaSource::Declared { + schema_source(Some(&project.0), None, day(2027, 2, 3)), + Ok(SchemaSource::Version { path: project.0.join(PROJECT_SCHEMA_PATH), version: "2026-07".to_string(), - }) - ); - } - - #[test] - fn the_bundled_version_needs_no_download() { - let project = Project::new("declared-bundled"); - project.manifest(Some(BUNDLED_API_VERSION)); - assert_eq!( - schema_source(Some(&project.0), None), - Ok(SchemaSource::Bundled) - ); - // A file already there is kept up to date like any other version. - let path = project.write(PROJECT_SCHEMA_PATH, "{}"); - assert_eq!( - schema_source(Some(&project.0), None), - Ok(SchemaSource::Declared { - path, - version: BUNDLED_API_VERSION.to_string(), + latest: false, }) ); } #[test] fn the_environment_names_another_file() { + let now = day(2026, 10, 22); let project = Project::new("named"); project.manifest(Some("2026-07")); let other = project.write("schemas/unstable.json", "{}"); assert_eq!( - schema_source(Some(&project.0), Some(OsStr::new("schemas/unstable.json"))), + schema_source( + Some(&project.0), + Some(OsStr::new("schemas/unstable.json")), + now + ), Ok(SchemaSource::File(other.clone())) ); assert_eq!( - schema_source(None, Some(other.as_os_str())), + schema_source(None, Some(other.as_os_str()), now), Ok(SchemaSource::File(other)) ); assert_eq!( - schema_source(Some(&project.0), Some(OsStr::new(""))), - Ok(SchemaSource::Declared { + schema_source(Some(&project.0), Some(OsStr::new("")), now), + Ok(SchemaSource::Version { path: project.0.join(PROJECT_SCHEMA_PATH), version: "2026-07".to_string(), + latest: false, }) ); assert_eq!( - schema_source(Some(&project.0), Some(OsStr::new("missing.json"))), + schema_source(Some(&project.0), Some(OsStr::new("missing.json")), now), Err(format!( "SHOPIFY_GRAPHQL_SCHEMA names `{}`, which is not a file", project.0.join("missing.json").display() diff --git a/crates/shopify_api_graphql/src/restrict.rs b/crates/shopify_api_graphql/src/restrict.rs new file mode 100644 index 0000000..59d3289 --- /dev/null +++ b/crates/shopify_api_graphql/src/restrict.rs @@ -0,0 +1,226 @@ +//! A schema cut down to what some operations use: the types they reach, and +//! of objects and interfaces, the fields they select. +//! +//! `shopify_api` checks its own operations against such a schema, a few +//! kilobytes instead of the whole Admin API. + +use std::collections::{BTreeMap, BTreeSet}; + +use graphql_parser::query as ast; + +use crate::schema::{Field, InputValue, Schema, TypeDef}; +use crate::{Error, analyze}; + +type Document<'a> = ast::Document<'a, String>; +type SelectionSet<'a> = ast::SelectionSet<'a, String>; + +impl Schema { + /// The part of the schema `operations` use. Each operation is checked + /// first, and is accepted by the result as by `self`, with the same shape. + pub fn restricted_to(&self, operations: &[&str]) -> Result { + let mut used = Used::default(); + for source in operations { + analyze(self, source)?; + let document: Document = + graphql_parser::parse_query(source).expect("an operation analyze accepted parses"); + used.document(self, &document); + } + Ok(used.schema(self)) + } +} + +/// What the operations reach, before the closure over types. +#[derive(Default)] +struct Used { + /// Selected fields, by object or interface. + fields: BTreeMap>, + /// Types named by variables and type conditions. + types: BTreeSet, +} + +impl Used { + fn document<'a>(&mut self, schema: &Schema, document: &'a Document<'a>) { + let fragments: BTreeMap<&str, &'a ast::FragmentDefinition<'a, String>> = document + .definitions + .iter() + .filter_map(|definition| match definition { + ast::Definition::Fragment(fragment) => Some((fragment.name.as_str(), fragment)), + ast::Definition::Operation(_) => None, + }) + .collect(); + for definition in &document.definitions { + let ast::Definition::Operation(operation) = definition else { + continue; + }; + let (root, variables, set) = match operation { + ast::OperationDefinition::SelectionSet(set) => (&schema.query, &[][..], set), + ast::OperationDefinition::Query(query) => ( + &schema.query, + &query.variable_definitions[..], + &query.selection_set, + ), + ast::OperationDefinition::Mutation(mutation) => ( + schema.mutation.as_ref().unwrap_or(&schema.query), + &mutation.variable_definitions[..], + &mutation.selection_set, + ), + ast::OperationDefinition::Subscription(_) => continue, + }; + for variable in variables { + self.types.insert(named(&variable.var_type).to_string()); + } + self.selection(schema, root, set, &fragments, &mut BTreeSet::new()); + } + } + + fn selection<'a>( + &mut self, + schema: &Schema, + parent: &str, + set: &'a SelectionSet<'a>, + fragments: &BTreeMap<&str, &'a ast::FragmentDefinition<'a, String>>, + spread: &mut BTreeSet<&'a str>, + ) { + self.types.insert(parent.to_string()); + for item in &set.items { + match item { + ast::Selection::Field(field) => { + if field.name.starts_with("__") { + continue; + } + let fields = match schema.get(parent) { + Some( + TypeDef::Object { fields, .. } | TypeDef::Interface { fields, .. }, + ) => fields, + _ => continue, + }; + let Some(definition) = fields.get(&field.name) else { + continue; + }; + self.fields + .entry(parent.to_string()) + .or_default() + .insert(field.name.clone()); + let inner = definition.ty.name(); + if schema.get(inner).is_some_and(TypeDef::is_composite) { + self.selection(schema, inner, &field.selection_set, fragments, spread); + } + } + ast::Selection::InlineFragment(fragment) => { + let condition = match &fragment.type_condition { + Some(ast::TypeCondition::On(condition)) => condition.as_str(), + None => parent, + }; + self.selection( + schema, + condition, + &fragment.selection_set, + fragments, + spread, + ); + } + ast::Selection::FragmentSpread(item) => { + let Some(fragment) = fragments.get(item.fragment_name.as_str()) else { + continue; + }; + if !spread.insert(fragment.name.as_str()) { + continue; + } + let ast::TypeCondition::On(condition) = &fragment.type_condition; + self.selection( + schema, + condition, + &fragment.selection_set, + fragments, + spread, + ); + spread.remove(fragment.name.as_str()); + } + } + } + } + + /// The schema of the used types, closed over the types they refer to. + fn schema(self, schema: &Schema) -> Schema { + let mut pending: Vec = self.types.iter().cloned().collect(); + pending.push(schema.query.clone()); + pending.extend(schema.mutation.clone()); + for directive in schema.directives.values() { + pending.extend(directive.args.values().map(|arg| arg.ty.name().to_string())); + } + let mut types = BTreeMap::new(); + while let Some(name) = pending.pop() { + if types.contains_key(&name) { + continue; + } + let Some(definition) = schema.get(&name) else { + continue; + }; + let selected = self.fields.get(&name); + let kept = |fields: &BTreeMap, pending: &mut Vec| { + let fields: BTreeMap = fields + .iter() + .filter(|(field, _)| selected.is_some_and(|selected| selected.contains(*field))) + .map(|(field, definition)| (field.clone(), definition.clone())) + .collect(); + for field in fields.values() { + pending.push(field.ty.name().to_string()); + pending.extend(field.args.values().map(|arg| arg.ty.name().to_string())); + } + fields + }; + let restricted = match definition { + TypeDef::Object { fields, interfaces } => TypeDef::Object { + fields: kept(fields, &mut pending), + interfaces: interfaces.clone(), + }, + TypeDef::Interface { + fields, + possible_types, + } => TypeDef::Interface { + fields: kept(fields, &mut pending), + possible_types: possible_types.clone(), + }, + TypeDef::Input { fields } => { + pending.extend( + fields + .values() + .map(|field: &InputValue| field.ty.name().to_string()), + ); + definition.clone() + } + TypeDef::Scalar | TypeDef::Enum { .. } | TypeDef::Union { .. } => { + definition.clone() + } + }; + types.insert(name, restricted); + } + // Interfaces and possible types only among the types kept. + let names: BTreeSet = types.keys().cloned().collect(); + let keep = |list: &mut Vec| list.retain(|name| names.contains(name)); + for definition in types.values_mut() { + match definition { + TypeDef::Object { interfaces, .. } => keep(interfaces), + TypeDef::Interface { possible_types, .. } | TypeDef::Union { possible_types } => { + keep(possible_types) + } + _ => {} + } + } + Schema { + api_version: schema.api_version.clone(), + query: schema.query.clone(), + mutation: schema.mutation.clone(), + types, + directives: schema.directives.clone(), + } + } +} + +/// The type a variable type names, without lists and non-null. +fn named<'a>(ty: &'a ast::Type<'a, String>) -> &'a str { + match ty { + ast::Type::NamedType(name) => name, + ast::Type::ListType(inner) | ast::Type::NonNullType(inner) => named(inner), + } +} diff --git a/crates/shopify_api_graphql/src/schema.rs b/crates/shopify_api_graphql/src/schema.rs index c9cf6cd..81cd5d2 100644 --- a/crates/shopify_api_graphql/src/schema.rs +++ b/crates/shopify_api_graphql/src/schema.rs @@ -4,7 +4,6 @@ use std::collections::BTreeMap; use std::fmt; -use std::sync::OnceLock; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -54,12 +53,6 @@ fragment TypeRef on __Type { } "; -/// The Admin API version of the schema bundled with this crate. -pub const BUNDLED_API_VERSION: &str = "2026-10"; - -/// Shopify's Admin GraphQL schema for [`BUNDLED_API_VERSION`]. -const BUNDLED_SCHEMA: &str = include_str!("../schema/admin.schema.json"); - /// The version of the stored form written by [`Schema::to_json`]. const FORMAT: u32 = 1; @@ -481,13 +474,6 @@ fn load_inputs( } impl Schema { - /// The Shopify Admin schema bundled with this crate, for [`BUNDLED_API_VERSION`]. - pub fn bundled() -> &'static Schema { - static BUNDLED: OnceLock = OnceLock::new(); - BUNDLED - .get_or_init(|| Schema::from_json(BUNDLED_SCHEMA).expect("the bundled schema is valid")) - } - /// Reads the form written by [`Schema::to_json`]. pub fn from_json(json: &str) -> Result { let format = serde_json::from_str::(json) @@ -1076,7 +1062,7 @@ mod tests { bare.directives.keys().collect::>(), ["include", "skip"] ); - assert!(Schema::bundled().directive("idempotent").is_some()); + assert!(admin().directive("idempotent").is_some()); } #[test] @@ -1129,10 +1115,15 @@ mod tests { ); } + /// The Admin schema 2026-10 the tests of the workspace use. + fn admin() -> Schema { + Schema::from_json(include_str!("../../shopify_api/graphql/admin.schema.json")).unwrap() + } + #[test] - fn the_bundled_schema_is_the_admin_api() { - let schema = Schema::bundled(); - assert_eq!(schema.api_version, BUNDLED_API_VERSION); + fn the_test_schema_is_the_admin_api() { + let schema = admin(); + assert_eq!(schema.api_version, "2026-10"); assert_eq!(schema.query, "QueryRoot"); assert_eq!(schema.mutation.as_deref(), Some("Mutation")); assert!(schema.types.len() > 1000); diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs index 931050c..099f8c0 100644 --- a/crates/shopify_api_graphql/tests/analyze.rs +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -1,16 +1,26 @@ -//! Operations checked against the bundled Shopify Admin schema: what is +//! Operations checked against the Shopify Admin schema 2026-10: what is //! refused, with which message, and the shape of what is accepted. +use std::sync::OnceLock; + use shopify_api_graphql::{ FieldBase, Operation, OperationKind, Scalar, Schema, Selection, VariableBase, analyze, }; +/// The Admin schema 2026-10 the tests of the workspace use. +fn admin() -> &'static Schema { + static ADMIN: OnceLock = OnceLock::new(); + ADMIN.get_or_init(|| { + Schema::from_json(include_str!("../../shopify_api/graphql/admin.schema.json")).unwrap() + }) +} + fn check(source: &str) -> Operation { - analyze(Schema::bundled(), source).unwrap_or_else(|error| panic!("{error}\n{source}")) + analyze(admin(), source).unwrap_or_else(|error| panic!("{error}\n{source}")) } fn refusal(source: &str) -> String { - match analyze(Schema::bundled(), source) { + match analyze(admin(), source) { Ok(_) => panic!("accepted: {source}"), Err(error) => error.to_string(), } @@ -584,7 +594,7 @@ fn reports_deprecated_enum_values_written_in_the_operation() { let operation = check("{ shop { name } discountNodes(first: 1, query: \"x\") { nodes { id } } }"); assert!(operation.deprecations.is_empty()); - let deprecated = Schema::bundled() + let deprecated = admin() .types .iter() .find_map(|(name, definition)| match definition { diff --git a/crates/shopify_api_graphql/tests/internal_schema.rs b/crates/shopify_api_graphql/tests/internal_schema.rs new file mode 100644 index 0000000..f81d1a9 --- /dev/null +++ b/crates/shopify_api_graphql/tests/internal_schema.rs @@ -0,0 +1,71 @@ +//! `shopify_api` checks its own operations, `graphql/operations/*.graphql`, +//! against `graphql/internal.schema.json`: the test schema cut down to them. +//! `SHOPIFY_API_BLESS=1` (`mise run schema:internal`) writes it again. + +use std::path::{Path, PathBuf}; + +use shopify_api_graphql::{Schema, analyze}; + +fn runtime_crate() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../shopify_api/graphql") +} + +#[test] +fn the_internal_schema_is_cut_down_to_the_operations_of_shopify_api() { + let dir = runtime_crate(); + let full = Schema::from_json(&std::fs::read_to_string(dir.join("admin.schema.json")).unwrap()) + .unwrap(); + let mut files: Vec = std::fs::read_dir(dir.join("operations")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| { + path.extension() + .is_some_and(|extension| extension == "graphql") + }) + .collect(); + files.sort(); + let operations: Vec = files + .iter() + .map(|file| std::fs::read_to_string(file).unwrap()) + .collect(); + let operations: Vec<&str> = operations.iter().map(String::as_str).collect(); + assert!(operations.len() >= 10); + + let internal = full.restricted_to(&operations).unwrap(); + for (file, operation) in files.iter().zip(&operations) { + assert_eq!( + analyze(&internal, operation).unwrap(), + analyze(&full, operation).unwrap(), + "{}", + file.display() + ); + } + assert!(internal.types.len() < full.types.len() / 10); + + let path = dir.join("internal.schema.json"); + let json = internal.to_json(); + if std::env::var_os("SHOPIFY_API_BLESS").is_some() { + std::fs::write(&path, &json).unwrap(); + } + let written = std::fs::read_to_string(&path).unwrap_or_default(); + assert!( + written == json, + "{} is not the schema of the operations: run `mise run schema:internal`", + path.display() + ); +} + +#[test] +fn a_restricted_schema_refuses_what_it_left_out() { + let dir = runtime_crate(); + let full = Schema::from_json(&std::fs::read_to_string(dir.join("admin.schema.json")).unwrap()) + .unwrap(); + let internal = full.restricted_to(&["{ shop { name } }"]).unwrap(); + assert!(analyze(&internal, "{ shop { name } }").is_ok()); + let error = analyze(&internal, "{ shop { email } }").unwrap_err(); + assert!( + error.to_string().contains("has no field `email`"), + "{error}" + ); + assert!(full.restricted_to(&["{ shop { nam } }"]).is_err()); +} diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 5a23f69..3e7aef9 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -12,18 +12,19 @@ use quote::{format_ident, quote, quote_spanned}; use shopify_api_graphql::codegen::{ DATA_TYPE, VARIABLES_TYPE, data_types, variable_type, variables_types, }; -use shopify_api_graphql::project::{download_schema_file, metadata_snippet}; +use shopify_api_graphql::project::{metadata_snippet, up_to_date_schema}; use shopify_api_graphql::{ - BUNDLED_API_VERSION, MINIMUM_API_VERSION, Operation, OperationKind, PROJECT_SCHEMA_PATH, - SCHEMA_ENV, Schema, SchemaSource, Variable, analyze, is_supported_api_version, schema_source, + MINIMUM_API_VERSION, Operation, OperationKind, PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, + SchemaSource, Variable, analyze, is_supported_api_version, latest_api_version, schema_source, }; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{Attribute, Expr, Ident, LitStr, Token, Visibility}; -/// The package whose own operations are always checked against the bundled -/// schema: the schema a crate that depends on it selects is not its own. -const RUNTIME_PACKAGE: &str = "shopify_api"; +/// The schema of `shopify_api`'s own operations, relative to its `Cargo.toml`: +/// the Admin schema cut down to what they use. A crate that depends on +/// `shopify_api` selects a version for its operations, not for these. +const INTERNAL_SCHEMA_PATH: &str = "graphql/internal.schema.json"; /// Where the text of an operation comes from. enum Source { @@ -184,32 +185,35 @@ fn resolve(manifest_dir: Option<&Path>, path: &Path) -> PathBuf { /// Parsed schema files by path, with the modification time they were read at. type SchemaCache = HashMap, Arc)>; -/// The schema operations are checked against. -enum LoadedSchema { - /// The one bundled with `shopify_api_graphql`. - Bundled, - /// The one of the crate being compiled. - File { path: PathBuf, schema: Arc }, +/// The schema operations are checked against, and its file. +struct LoadedSchema { + path: PathBuf, + schema: Arc, } impl LoadedSchema { - /// The schema of the crate being compiled, else the bundled one. + /// The schema of the crate being compiled. fn load() -> Result { - if std::env::var("CARGO_PKG_NAME").is_ok_and(|name| name == RUNTIME_PACKAGE) { - return Ok(Self::Bundled); - } // The variable is for the crates being built, not for their // dependencies, which ship their own schema files. let primary = std::env::var_os("CARGO_PRIMARY_PACKAGE").is_some(); let named = std::env::var_os(SCHEMA_ENV).filter(|_| primary); - let (path, schema) = match schema_source(manifest_dir().as_deref(), named.as_deref())? { - SchemaSource::Bundled => return Ok(Self::Bundled), + let source = schema_source( + manifest_dir().as_deref(), + named.as_deref(), + SystemTime::now(), + )?; + let (path, schema) = match source { SchemaSource::File(path) => { let schema = read_schema(&path)?; (path, schema) } - SchemaSource::Declared { path, version } => { - let schema = declared_schema(&path, &version)?; + SchemaSource::Version { + path, + version, + latest, + } => { + let schema = version_schema(&path, &version, latest)?; (path, schema) } }; @@ -219,17 +223,21 @@ impl LoadedSchema { declare another one in Cargo.toml:\n\n{}", path.display(), schema.api_version, - metadata_snippet(BUNDLED_API_VERSION) + metadata_snippet(&latest_api_version(SystemTime::now())) )); } - Ok(Self::File { schema, path }) + Ok(Self { schema, path }) + } + + /// The schema of `shopify_api`'s own operations. + fn internal() -> Result { + let path = resolve(manifest_dir().as_deref(), Path::new(INTERNAL_SCHEMA_PATH)); + let schema = read_schema(&path)?; + Ok(Self { schema, path }) } fn schema(&self) -> &Schema { - match self { - Self::Bundled => Schema::bundled(), - Self::File { schema, .. } => schema, - } + &self.schema } /// Makes the compiler rebuild the crate when what the expansion depends on changes. @@ -241,11 +249,7 @@ impl LoadedSchema { .unwrap_or_else(|poisoned| poisoned.into_inner()); // The manifest declares the API version, the schema file holds it. let manifest = manifest_dir().map(|dir| dir.join("Cargo.toml")); - let schema = match self { - Self::File { path, .. } => Some(path.clone()), - Self::Bundled => None, - }; - let files = [manifest, schema] + let files = [manifest, Some(self.path.clone())] .into_iter() .flatten() .filter(|path| path.is_file()); @@ -287,27 +291,24 @@ impl LoadedSchema { } } -/// The schema of the version the crate declares: its file when it holds that -/// version, else downloaded into it, once for every operation of the build. -fn declared_schema(path: &Path, version: &str) -> Result, String> { +/// The schema of `version`: its file when it holds that version, else +/// downloaded into it, once for every operation of the build. +fn version_schema(path: &Path, version: &str, latest: bool) -> Result, String> { static DOWNLOAD: Mutex<()> = Mutex::new(()); let _one_at_a_time = DOWNLOAD .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - if path.is_file() - && let Ok(schema) = read_schema(path) - && schema.api_version == version - { - return Ok(schema); - } - download_schema_file(path, version).map_err(|error| { + up_to_date_schema(path, version, latest, read_schema).map_err(|error| { + let which = if latest { + format!("the latest Admin API version, {version} (Cargo.toml declares none)") + } else { + format!("the Admin API version in Cargo.toml, {version}") + }; format!( - "{error}\n`graphql!` downloads the schema of the version in Cargo.toml once, into `{}`: \ - build once with network access and commit the file", - PROJECT_SCHEMA_PATH + "{error}\n`graphql!` downloads the schema of {which} into `{PROJECT_SCHEMA_PATH}`: \ + build once with network access and commit the file" ) - })?; - read_schema(path) + }) } /// Reads a schema file. One compilation expands many operations: each file is @@ -548,9 +549,8 @@ fn expand_module( }) } -fn expand(input: Input) -> syn::Result { - let schema = - LoadedSchema::load().map_err(|message| syn::Error::new(Span::call_site(), message))?; +fn expand(input: Input, schema: Result) -> syn::Result { + let schema = schema.map_err(|message| syn::Error::new(Span::call_site(), message))?; match input { Input::Expression { source, variables } => expand_expression(&schema, &source, &variables), Input::Module { @@ -566,7 +566,18 @@ fn expand(input: Input) -> syn::Result { #[proc_macro] pub fn graphql(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as Input); - expand(input) + expand(input, LoadedSchema::load()) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +/// `graphql!` for the operations of `shopify_api` itself, checked against its +/// `graphql/internal.schema.json`. Not for other crates. +#[doc(hidden)] +#[proc_macro] +pub fn __graphql_internal(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as Input); + expand(input, LoadedSchema::internal()) .unwrap_or_else(syn::Error::into_compile_error) .into() } diff --git a/mise.toml b/mise.toml index df79051..4df8f0f 100644 --- a/mise.toml +++ b/mise.toml @@ -45,10 +45,15 @@ description = "Rewrite the expected compiler errors of the `graphql!` compile-fa env = { TRYBUILD = "overwrite" } run = "cargo test -p shopify_api --all-features --locked --test compile_fail" -[tasks."schema:bundle"] -description = "Download the bundled Admin schema again, for the version in crates/shopify_api_graphql/Cargo.toml" -dir = "crates/shopify_api_graphql" -run = "cargo run -p shopify_api --features cli --locked -- schema download --out schema/admin.schema.json" +[tasks."schema:test"] +description = "Download the Admin schema the tests use again, for the version in crates/shopify_api/Cargo.toml" +dir = "crates/shopify_api" +run = "cargo run -p shopify_api --features cli --locked -- schema download" + +[tasks."schema:internal"] +description = "Cut the test schema down to the operations of shopify_api, into crates/shopify_api/graphql/internal.schema.json" +env = { SHOPIFY_API_BLESS = "1" } +run = "cargo test -p shopify_api_graphql --locked --test internal_schema" [tasks."test:live"] description = "Run the tests against a real development store (needs SHOPIFY_TEST_SHOP and a token, see tests/live.rs)" From 288c6b7d0fc2b2feb0eef82a7b471f0bce8ecc1b Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:21:08 +0200 Subject: [PATCH 004/135] ci: build the docs without `--cfg docsrs` `--cfg docsrs` turns on `feature(doc_cfg)`, which stable Rust rejects, so the `doc` task failed in CI. docs.rs still sets the flag itself, on nightly. Co-Authored-By: Claude Opus 5.5 --- mise.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mise.toml b/mise.toml index 4df8f0f..6d679e8 100644 --- a/mise.toml +++ b/mise.toml @@ -29,7 +29,7 @@ run = "cargo test -p shopify_api --locked" [tasks.doc] description = "Build the documentation, warnings are errors" -env = { RUSTDOCFLAGS = "-D warnings --cfg docsrs" } +env = { RUSTDOCFLAGS = "-D warnings" } run = "cargo doc --workspace --all-features --no-deps --locked" [tasks.check] From ad1aca868c75eb33348b2733617f64d933d8701a Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:34:21 +0200 Subject: [PATCH 005/135] fix: say when Shopify has no Admin API version, not to build with network Pinning a version that is not out yet, or misspelt, failed with "build once with network access and commit the file", though the download had worked: Shopify answers such a version with a 400 "Invalid API version". - The downloads of `shopify_api_graphql::project` return a `DownloadError`, whose `UnknownVersion` is that answer. - `graphql!` then names the version and suggests a released one. Other failures keep the advice to build with network access. - When the latest version is not out and the one before fails too, the error is the one before's, the one to fix. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bin/shopify-api.rs | 3 +- crates/shopify_api_graphql/src/project.rs | 141 ++++++++++++++++++---- crates/shopify_api_macros/src/lib.rs | 75 ++++++++++-- 3 files changed, 182 insertions(+), 37 deletions(-) diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index d2e9368..50a42d1 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -289,7 +289,8 @@ fn load_schema(path: Option<&Path>) -> Result<(Schema, String), String> { ); } read(file) - })?; + }) + .map_err(|error| error.to_string())?; return Ok((Arc::unwrap_or_clone(schema), path.display().to_string())); } } diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index 5145e68..23fce67 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -167,15 +167,84 @@ pub fn schema_source( /// that answers introspection without a token. pub const PUBLIC_ADMIN_SCHEMA_ENDPOINT: &str = "https://shopify.dev/admin-graphql-direct-proxy"; +/// Why the schema of a version could not be had. +#[cfg(feature = "download")] +#[cfg_attr(docsrs, doc(cfg(feature = "download")))] +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DownloadError { + /// Shopify has no Admin API of this version: it is not out yet, or its + /// name is wrong. Downloading it again will not help. + UnknownVersion { + /// The version asked for. + version: String, + /// What Shopify answered. + answer: String, + }, + /// Anything else: no network, an answer that is not a schema, a file + /// that cannot be written or read. + Failed(String), +} + +#[cfg(feature = "download")] +impl std::fmt::Display for DownloadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UnknownVersion { version, answer } => { + write!(f, "Shopify has no Admin API version {version} ({answer})") + } + Self::Failed(message) => f.write_str(message), + } + } +} + +#[cfg(feature = "download")] +impl std::error::Error for DownloadError {} + +/// The introspection result in Shopify's answer to `url`, or why there is none. +#[cfg(feature = "download")] +fn introspection_in( + version: &str, + url: &str, + status: u16, + text: &str, +) -> Result { + let failed = |error: &dyn std::fmt::Display| { + DownloadError::Failed(format!( + "cannot download the Admin schema {version} from {url}: {error}" + )) + }; + let value: Option = serde_json::from_str(text).ok(); + let message = value + .as_ref() + .and_then(|value| value.get("error")) + .and_then(serde_json::Value::as_str); + if let Some(message) = message { + // Shopify answers a version it does not have with a 400 that says so. + if status == 400 && message.to_ascii_lowercase().contains("api version") { + return Err(DownloadError::UnknownVersion { + version: version.to_string(), + answer: format!("{url} answered \"{message}\", HTTP 400"), + }); + } + return Err(failed(&format!("{message} (HTTP {status})"))); + } + if !(200..300).contains(&status) { + return Err(failed(&format!("HTTP {status}"))); + } + value.ok_or_else(|| failed(&"the answer is not JSON")) +} + /// Downloads the Admin schema of `version` from Shopify's public endpoint. #[cfg(feature = "download")] #[cfg_attr(docsrs, doc(cfg(feature = "download")))] -pub fn download_public_schema(version: &str) -> Result { +pub fn download_public_schema(version: &str) -> Result { use std::time::Duration; let url = format!("{PUBLIC_ADMIN_SCHEMA_ENDPOINT}/{version}"); let failed = |error: &dyn std::fmt::Display| { - format!("cannot download the Admin schema {version} from {url}: {error}") + DownloadError::Failed(format!( + "cannot download the Admin schema {version} from {url}: {error}" + )) }; let agent: ureq::Agent = ureq::Agent::config_builder() .timeout_global(Some(Duration::from_secs(120))) @@ -199,19 +268,7 @@ pub fn download_public_schema(version: &str) -> Result { .limit(256 * 1024 * 1024) .read_to_string() .map_err(|error| failed(&error))?; - let value: Option = serde_json::from_str(&text).ok(); - let message = value - .as_ref() - .and_then(|value| value.get("error")) - .and_then(serde_json::Value::as_str); - let status = response.status(); - if let Some(message) = message { - return Err(failed(&format!("{message} (HTTP {})", status.as_u16()))); - } - if !status.is_success() { - return Err(failed(&format!("HTTP {}", status.as_u16()))); - } - let value = value.ok_or_else(|| failed(&"the answer is not JSON"))?; + let value = introspection_in(version, &url, response.status().as_u16(), &text)?; crate::Schema::from_introspection(&value, version).map_err(|error| failed(&error)) } @@ -221,9 +278,9 @@ pub fn download_public_schema(version: &str) -> Result { /// the old schema or the new one, never part of one. #[cfg(feature = "download")] #[cfg_attr(docsrs, doc(cfg(feature = "download")))] -pub fn download_schema_file(path: &Path, version: &str) -> Result { +pub fn download_schema_file(path: &Path, version: &str) -> Result { let schema = download_public_schema(version)?; - write_atomically(path, &schema.to_json())?; + write_atomically(path, &schema.to_json()).map_err(DownloadError::Failed)?; Ok(schema) } @@ -260,7 +317,8 @@ pub fn up_to_date_schema>( version: &str, latest: bool, read: impl Fn(&Path) -> Result, -) -> Result { +) -> Result { + let read = |path: &Path| read(path).map_err(DownloadError::Failed); let current = path.is_file().then(|| read(path).ok()).flatten(); if let Some(current) = current { if current.as_ref().api_version == version { @@ -272,13 +330,19 @@ pub fn up_to_date_schema>( Err(error) => Err(error), }; } - match download_schema_file(path, version) { + let error = match download_schema_file(path, version) { + Ok(_) => return read(path), + Err(error) => error, + }; + let Some(previous) = previous_api_version(version).filter(|_| latest) else { + return Err(error); + }; + match download_schema_file(path, &previous) { Ok(_) => read(path), - Err(error) if latest => match previous_api_version(version) { - Some(previous) if download_schema_file(path, &previous).is_ok() => read(path), - _ => Err(error), - }, - Err(error) => Err(error), + // The latest version not being out yet does not explain why the one + // before failed: that failure is the one to fix. + Err(fallback) if matches!(error, DownloadError::UnknownVersion { .. }) => Err(fallback), + Err(_) => Err(error), } } @@ -468,4 +532,33 @@ mod tests { 1 ); } + + #[cfg(feature = "download")] + #[test] + fn a_version_shopify_does_not_have_is_told_apart() { + let url = "https://shopify.dev/admin-graphql-direct-proxy/2027-04"; + let answer = |status, text| introspection_in("2027-04", url, status, text); + let failed = |reason: &str| { + Err(DownloadError::Failed(format!( + "cannot download the Admin schema 2027-04 from {url}: {reason}" + ))) + }; + assert_eq!( + answer(400, r#"{"error":"Invalid API version"}"#), + Err(DownloadError::UnknownVersion { + version: "2027-04".to_string(), + answer: format!("{url} answered \"Invalid API version\", HTTP 400"), + }) + ); + assert_eq!( + answer(401, r#"{"error":"Unauthorized"}"#), + failed("Unauthorized (HTTP 401)") + ); + assert_eq!(answer(503, "Service Unavailable"), failed("HTTP 503")); + assert_eq!(answer(200, ""), failed("the answer is not JSON")); + assert_eq!( + answer(200, r#"{"data":{}}"#), + Ok(serde_json::json!({ "data": {} })) + ); + } } diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 3e7aef9..dc8ec3b 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -12,7 +12,9 @@ use quote::{format_ident, quote, quote_spanned}; use shopify_api_graphql::codegen::{ DATA_TYPE, VARIABLES_TYPE, data_types, variable_type, variables_types, }; -use shopify_api_graphql::project::{metadata_snippet, up_to_date_schema}; +use shopify_api_graphql::project::{ + DownloadError, metadata_snippet, previous_api_version, up_to_date_schema, +}; use shopify_api_graphql::{ MINIMUM_API_VERSION, Operation, OperationKind, PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, SchemaSource, Variable, analyze, is_supported_api_version, latest_api_version, schema_source, @@ -298,17 +300,38 @@ fn version_schema(path: &Path, version: &str, latest: bool) -> Result String { + match error { + DownloadError::UnknownVersion { .. } => { + // On the first day of a quarter, its version may not be out yet. + let released = latest_api_version(now); + let suggested = match previous_api_version(version) { + Some(previous) if released.as_str() >= version => previous, + _ => released, + }; + format!( + "{error}: it is not out yet, or its name is wrong. \ + Declare a released version in Cargo.toml:\n\n{}", + metadata_snippet(&suggested) + ) + } + DownloadError::Failed(_) => { + let which = if latest { + format!("the latest Admin API version, {version} (Cargo.toml declares none)") + } else { + format!("the Admin API version in Cargo.toml, {version}") + }; + format!( + "{error}\n`graphql!` downloads the schema of {which} into `{PROJECT_SCHEMA_PATH}`: \ + build once with network access and commit the file" + ) + } + } } /// Reads a schema file. One compilation expands many operations: each file is @@ -737,4 +760,32 @@ mod tests { assert_eq!(error, message, "{source}"); } } + + #[test] + fn a_version_shopify_does_not_have_is_named_and_a_released_one_suggested() { + let day = + |days: u64| SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(days * 86_400); + let (october_22_2026, january_1_2027) = (day(20_748), day(20_819)); + let unknown = |version: &str| DownloadError::UnknownVersion { + version: version.to_string(), + answer: "HTTP 400".to_string(), + }; + + assert_eq!( + download_failure(&unknown("2027-04"), "2027-04", false, october_22_2026), + "Shopify has no Admin API version 2027-04 (HTTP 400): it is not out yet, \ + or its name is wrong. Declare a released version in Cargo.toml:\n\n\ + [package.metadata.shopify_api]\napi-version = \"2026-10\"" + ); + // On the first day of a quarter, before Shopify releases its version. + let error = download_failure(&unknown("2027-01"), "2027-01", false, january_1_2027); + assert!(error.ends_with("api-version = \"2026-10\""), "{error}"); + + let offline = DownloadError::Failed("cannot download".to_string()); + let error = download_failure(&offline, "2026-07", false, october_22_2026); + assert!( + error.ends_with("build once with network access and commit the file"), + "{error}" + ); + } } From 069c507feb5ca42059df41a30c2d9c740e01ec54 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:00:12 +0200 Subject: [PATCH 006/135] ci: bump actions/checkout to v7 and jdx/mise-action to v5 (Node 24) Both v4/v2 ran on the deprecated Node 20 runtime. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 6 +++--- .github/workflows/publish.yml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 97f8fc0..cef848e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,8 +28,8 @@ jobs: name: fmt, clippy, tests, docs runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: jdx/mise-action@v2 + - uses: actions/checkout@v7 + - uses: jdx/mise-action@v5 - uses: Swatinem/rust-cache@v2 - run: mise run check @@ -37,7 +37,7 @@ jobs: name: Rust 1.88 runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - uses: dtolnay/rust-toolchain@1.88 - uses: Swatinem/rust-cache@v2 - run: cargo check --workspace --all-features --locked diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e0dcd48..1d65227 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -20,8 +20,8 @@ jobs: needs: - call-ci steps: - - uses: actions/checkout@v4 - - uses: jdx/mise-action@v2 + - uses: actions/checkout@v7 + - uses: jdx/mise-action@v5 # In dependency order: the schema and checker, the macro, then the client. - run: cargo publish --locked -p shopify_api_graphql env: From 6964e488c7191e3b0e3d56af73d21ee5ac26c925 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:09:47 +0200 Subject: [PATCH 007/135] fix: never retry a mutation hidden behind a comment ended by a bare \r MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OperationKind::of ended comments at \n only, so "# c\rmutation { … }" read as a query and was sent again after a 5xx or a network failure. It now lexes the document: comments end at \r, \n or \r\n (the spec's LineTerminator), strings and block strings are skipped, and a document it cannot read to the end (subscription, typo, unbalanced braces) counts as a mutation, so it is never retried. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/graphql/operation.rs | 256 ++++++++++++++++---- crates/shopify_api/tests/retry.rs | 15 ++ 2 files changed, 220 insertions(+), 51 deletions(-) diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs index be067b4..c8294a9 100644 --- a/crates/shopify_api/src/graphql/operation.rs +++ b/crates/shopify_api/src/graphql/operation.rs @@ -19,25 +19,15 @@ impl OperationKind { /// Reads the kind of a document: a mutation as soon as one of its /// operations is one, so that a document that holds a mutation is never /// sent twice by a retry. + /// + /// It fails safe: a document it can't read to the end (a subscription, a + /// typo, an unclosed string or block…) is a [`Mutation`](Self::Mutation) + /// too, so it is never retried either. Only a document made of queries, + /// fragments and `{ … }` shorthands is a [`Query`](Self::Query). pub fn of(document: &str) -> Self { - let mut rest = document; - loop { - rest = skip_ignored(rest); - if rest.is_empty() { - return Self::Query; - } - let word: String = rest - .chars() - .take_while(|character| character.is_ascii_alphanumeric() || *character == '_') - .collect(); - if word == "mutation" { - return Self::Mutation; - } - // A query, a fragment or a shorthand `{ … }`: on to the next definition. - match skip_block(&rest[word.len()..]) { - Some(after) => rest = after, - None => return Self::Query, - } + match read_kind(document) { + Some(kind) => kind, + None => Self::Mutation, } } @@ -46,54 +36,168 @@ impl OperationKind { } } -/// Skips white space, commas, comments and a byte order mark. -fn skip_ignored(mut text: &str) -> &str { +/// The kind of the document, `None` when it can't be read. +fn read_kind(document: &str) -> Option { + let mut lexer = Lexer { + text: document, + position: 0, + }; loop { - let trimmed = text.trim_start_matches(|character: char| { - character.is_whitespace() || character == ',' || character == '\u{feff}' - }); - match trimmed.strip_prefix('#') { - Some(comment) => text = comment.split_once('\n').map_or("", |(_, after)| after), - None => return trimmed, + match lexer.next()? { + None => return Some(OperationKind::Query), + Some(Token::Punctuator(b'{')) => lexer.skip_selection_set()?, + Some(Token::Name("query" | "fragment")) => { + lexer.skip_to_selection_set()?; + lexer.skip_selection_set()?; + } + Some(Token::Name("mutation")) => return Some(OperationKind::Mutation), + Some(_) => return None, } } } -/// What follows the next `{ … }` block, strings and comments taken into account. -fn skip_block(text: &str) -> Option<&str> { - let start = text.find('{')?; - let mut depth = 0usize; - let mut chars = text[start..].char_indices().peekable(); - while let Some((index, character)) = chars.next() { - match character { - '{' => depth += 1, - '}' => { - depth -= 1; - if depth == 0 { - return Some(&text[start + index + 1..]); +/// The tokens that tell where a definition starts and ends. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Token<'a> { + Name(&'a str), + /// `{`, `}`, `(`, `)`, `[` or `]`. + Punctuator(u8), + /// Strings, numbers and every other punctuator. + Other, +} + +/// Just enough of a GraphQL lexer to find the definitions of a document. +struct Lexer<'a> { + text: &'a str, + position: usize, +} + +impl<'a> Lexer<'a> { + fn rest(&self) -> &'a [u8] { + &self.text.as_bytes()[self.position..] + } + + /// Skips white space, line terminators, commas, comments and byte order marks. + fn skip_ignored(&mut self) { + loop { + let rest = self.rest(); + match rest.first() { + Some(b' ' | b'\t' | b'\n' | b'\r' | b',') => self.position += 1, + Some(0xEF) if rest.starts_with("\u{feff}".as_bytes()) => self.position += 3, + // A comment runs to the next line terminator: `\n`, `\r` or `\r\n`. + Some(b'#') => { + self.position += rest + .iter() + .position(|byte| matches!(byte, b'\n' | b'\r')) + .unwrap_or(rest.len()); } + _ => return, } - '#' => { - for (_, character) in chars.by_ref() { - if character == '\n' { + } + } + + /// The next token: `None` when the text can't be read, `Some(None)` at its end. + fn next(&mut self) -> Option>> { + self.skip_ignored(); + let rest = self.rest(); + let Some(&first) = rest.first() else { + return Some(None); + }; + let start = self.position; + let token = match first { + b'A'..=b'Z' | b'a'..=b'z' | b'_' => { + let length = rest + .iter() + .position(|byte| !(byte.is_ascii_alphanumeric() || *byte == b'_')) + .unwrap_or(rest.len()); + self.position += length; + Token::Name(&self.text[start..self.position]) + } + b'"' if rest.starts_with(b"\"\"\"") => { + // A block string: its only escape is `\"""`. + let mut index = 3; + loop { + let tail = rest.get(index..)?; + if tail.is_empty() { + return None; + } else if tail.starts_with(b"\\\"\"\"") { + index += 4; + } else if tail.starts_with(b"\"\"\"") { break; + } else { + index += 1; } } + self.position += index + 3; + Token::Other } - '"' => { - let mut escaped = false; - for (_, character) in chars.by_ref() { - match character { - '\\' if !escaped => escaped = true, - '"' if !escaped => break, - _ => escaped = false, + b'"' => { + let mut index = 1; + loop { + match rest.get(index)? { + b'\\' => index += 2, + b'"' => break, + b'\n' | b'\r' => return None, + _ => index += 1, } } + self.position += index + 1; + Token::Other + } + b'{' | b'}' | b'(' | b')' | b'[' | b']' => { + self.position += 1; + Token::Punctuator(first) + } + b'0'..=b'9' | b'-' => { + let length = rest + .iter() + .position(|byte| { + !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'+' | b'-')) + }) + .unwrap_or(rest.len()); + self.position += length; + Token::Other + } + _ => { + // Any other punctuator, or a character GraphQL doesn't allow here. + let length = self.text[start..].chars().next().map_or(1, char::len_utf8); + self.position += length; + Token::Other + } + }; + Some(Some(token)) + } + + /// Skips the header of a definition (name, variables and their default + /// values, directives), up to and with the `{` of its selection set. + fn skip_to_selection_set(&mut self) -> Option<()> { + let mut depth = 0usize; + loop { + match self.next()?? { + Token::Punctuator(b'{') if depth == 0 => return Some(()), + Token::Punctuator(b'{' | b'(' | b'[') => depth += 1, + Token::Punctuator(_) => depth = depth.checked_sub(1)?, + _ => {} + } + } + } + + /// Skips a selection set, its `{` already read. + fn skip_selection_set(&mut self) -> Option<()> { + let mut depth = 1usize; + loop { + match self.next()?? { + Token::Punctuator(b'{') => depth += 1, + Token::Punctuator(b'}') => { + depth -= 1; + if depth == 0 { + return Some(()); + } + } + _ => {} } - _ => {} } } - None } /// An operation, its variables, and the type `D` of its `data`. @@ -407,13 +511,63 @@ mod tests { "fragment F on Shop { name } query { shop { ...F } }", OperationKind::Query, ), - ("mutations", OperationKind::Query), ("", OperationKind::Query), ] { assert_eq!(OperationKind::of(document), kind, "{document}"); } } + /// A comment ends at `\r`, `\n` or `\r\n` (the spec's LineTerminator). + #[test] + fn a_comment_ends_at_any_line_terminator() { + for document in [ + "# comment\rmutation { tagsAdd(id: \"1\", tags: [\"a\"]) { userErrors { message } } }", + "# comment\r\nmutation { a }", + "# comment\nmutation { a }", + "query { a # }\r } mutation { b }", + "query { a } # x\rmutation { b }", + ] { + assert_eq!( + OperationKind::of(document), + OperationKind::Mutation, + "{document:?}" + ); + } + } + + /// When the document can't be read, it's treated as a mutation: never retried. + #[test] + fn a_document_it_cannot_read_is_a_mutation() { + for document in [ + "mutations", + "subscription { a }", + "query { a", + "query { a(x: \"}) } mutation { b }", + "query { a(x: \"\"\" } \" \"\"\") } mutation { b }", + "query { a } }", + "query @d(x: \"{\") { a } mutation { b }", + "query ($x: In = {a: 1}) { a } mutation { b }", + ] { + assert_eq!( + OperationKind::of(document), + OperationKind::Mutation, + "{document:?}" + ); + } + for document in [ + "query ($x: In = {a: 1}) { a(x: $x) }", + "query { a(x: \"\"\" } \\\"\"\" \"\"\") }", + "query @d(x: \"{\") { a }", + "query { a } # mutation { b }\r\n", + ] { + assert_eq!( + OperationKind::of(document), + OperationKind::Query, + "{document:?}" + ); + } + } + #[test] fn converts_the_usual_spellings_of_a_value() { let operation = Operation::<()>::new("query { shop { id } }") diff --git a/crates/shopify_api/tests/retry.rs b/crates/shopify_api/tests/retry.rs index 9c6917e..0616355 100644 --- a/crates/shopify_api/tests/retry.rs +++ b/crates/shopify_api/tests/retry.rs @@ -147,3 +147,18 @@ async fn waits_shopify_cannot_mean_do_not_panic() { shopify.graphql("{ shop { name } }", ()).await.unwrap(); assert_eq!(mock.requests().len(), 4); } + +/// A comment that ends with a bare `\r` still hides nothing: the mutation +/// after it is sent once. +#[tokio::test] +async fn a_mutation_after_a_comment_ended_by_a_carriage_return_is_not_sent_again() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(502, "Bad Gateway")) + .push_data(json!({ "tagsAdd": { "userErrors": [] } })); + let shopify = client(&mock); + + let mutation = "# comment\rmutation { tagsAdd(id: \"gid://shopify/Order/1\", tags: [\"a\"]) { userErrors { message } } }"; + let error = shopify.graphql(mutation, ()).await.unwrap_err(); + assert_eq!(error.status(), Some(502)); + assert_eq!(mock.requests().len(), 1); +} From 4293dc4f96101d9b732d08cae16d92a0996deccd Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:09:48 +0200 Subject: [PATCH 008/135] fix: honor a Retry-After longer than max_delay A 429's Retry-After was clamped to max_delay (30 s by default), so a 120-300 s cooldown burned every retry early. max_delay now caps only the computed backoff. A Retry-After longer than the new RetryPolicy::max_retry_after (5 min by default) is not waited for: the request ends in Error::Throttled, which now carries that wait in retry_after (the variant is #[non_exhaustive], so this is additive). Co-Authored-By: Claude Opus 5.5 --- MIGRATION.md | 2 +- README.md | 5 ++- crates/shopify_api/src/client.rs | 30 ++++++++++++-- crates/shopify_api/src/error.rs | 7 +++- crates/shopify_api/src/graphql.rs | 43 ++++++++++++++------ crates/shopify_api/tests/retry.rs | 66 +++++++++++++++++++++++++++++-- 6 files changed, 131 insertions(+), 22 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index b51fbf9..baf2644 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -51,7 +51,7 @@ to keep that. | --- | --- | | `ConnectionFailed(reqwest::Error)` | `Transport { url, source }` | | An `error_for_status` failure | `Http { status, url, body }`; `error.status()`, `error.is_unauthorized()` | -| `Throttled` | `Throttled { retries, cost }`, once the retries are spent | +| `Throttled` | `Throttled { retries, cost, retry_after }`, once the retries are spent or when `Retry-After` exceeds `max_retry_after` | | `GraphqlErrors(Vec)` | `Graphql(GraphqlErrors { errors, data })` | | `JsonParseError` | `Json`, or `Decode { path, message }` when `data` does not fit its type | | `NotWantedJsonFormat`, `NotJson`, `ResponseBroken` | `Decode` | diff --git a/README.md b/README.md index 738af1b..b5da5ee 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,10 @@ requests wait for it. ## Rate limits and retries A request Shopify throttles is sent again when the bucket holds its cost again, -computed from `extensions.cost`. A `429` waits for its `Retry-After`. A query +computed from `extensions.cost`. A `429` waits for its `Retry-After`, even past +`max_delay` (which caps only the backoff the client computes); a `Retry-After` +longer than `max_retry_after` (five minutes by default) is not waited for, and +ends in `Error::Throttled` with that wait in `retry_after`. A query is also retried after a `5xx` or a network failure, with exponential backoff; a mutation is not, since it may have run. diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index 56f27dd..5830770 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -171,20 +171,30 @@ fn warn_mismatch(pinned: ApiVersion, checked: &'static str) { /// the time its cost says the bucket needs. A query is also sent again after /// a `5xx` or a network failure, with exponential backoff; a mutation is not, /// since it may have run. +/// +/// A `429` waits for its `Retry-After`, however longer than +/// [`max_delay`](Self::max_delay) it is: that cap is for the backoff the client +/// computes. A `Retry-After` longer than +/// [`max_retry_after`](Self::max_retry_after) (five minutes by default) is not +/// waited for: the request ends in [`Error::Throttled`](crate::Error::Throttled), +/// with the wait Shopify asked for in its `retry_after`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RetryPolicy { max_retries: u32, base_delay: Duration, max_delay: Duration, + max_retry_after: Duration, } impl RetryPolicy { - /// At most `max_retries` retries, from one second up to thirty seconds apart. + /// At most `max_retries` retries, from one second up to thirty seconds + /// apart, or as long as a `Retry-After` of up to five minutes asks. pub const fn new(max_retries: u32) -> Self { Self { max_retries, base_delay: Duration::from_secs(1), max_delay: Duration::from_secs(30), + max_retry_after: Duration::from_secs(300), } } @@ -199,21 +209,35 @@ impl RetryPolicy { self } - /// The longest wait between two attempts. + /// The longest backoff between two attempts. A `Retry-After` from + /// Shopify is not capped by it: see [`with_max_retry_after`](Self::with_max_retry_after). pub const fn with_max_delay(mut self, delay: Duration) -> Self { self.max_delay = delay; self } + /// The longest `Retry-After` the client waits for before sending a `429` + /// again. A longer one ends the request in + /// [`Error::Throttled`](crate::Error::Throttled) at once. + pub const fn with_max_retry_after(mut self, wait: Duration) -> Self { + self.max_retry_after = wait; + self + } + pub const fn max_retries(&self) -> u32 { self.max_retries } - /// The longest wait between two attempts. + /// The longest backoff between two attempts. pub const fn max_delay(&self) -> Duration { self.max_delay } + /// The longest `Retry-After` the client waits for. + pub const fn max_retry_after(&self) -> Duration { + self.max_retry_after + } + /// The wait before retry number `retry` (from 0): exponential, with up /// to a quarter of jitter, capped at the longest wait. pub(crate) fn backoff(&self, retry: u32) -> Duration { diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index 161064e..743950d 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -55,7 +55,12 @@ pub enum Error { /// [`RetryPolicy`](crate::RetryPolicy). #[error("throttled by Shopify after {retries} retries")] #[non_exhaustive] - Throttled { retries: u32, cost: Option }, + Throttled { + retries: u32, + cost: Option, + /// The wait the `Retry-After` of the last `429` asked for, if any. + retry_after: Option, + }, /// The `data` of the answer does not fit the type it is read as: the /// shop runs another API version than the schema the operation was diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index b7ccd50..008077a 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -159,21 +159,31 @@ impl Shopify { None => return Err(Error::http(&url, &response)), } } - 429 if may_retry => { - let wait = retry_after(&response) - .unwrap_or_else(|| self.retry.backoff(retries)) - .min(self.retry.max_delay()); + 429 => { + let asked = retry_after(&response); + let throttled = Error::Throttled { + retries, + cost: None, + retry_after: asked, + }; + if !may_retry { + return Err(throttled); + } + // `max_delay` caps the backoff, not the wait Shopify asks for; + // a wait longer than `max_retry_after` goes back to the caller. + let wait = match asked { + Some(wait) if wait > self.retry.max_retry_after() => { + tracing::debug!("Shopify answered 429 with a Retry-After of {wait:?}"); + return Err(throttled); + } + Some(wait) => wait, + None => self.retry.backoff(retries), + }; tracing::debug!("Shopify answered 429: retrying in {wait:?}"); tokio::time::sleep(wait).await; retries += 1; continue; } - 429 => { - return Err(Error::Throttled { - retries, - cost: None, - }); - } 500..=599 if may_retry && !kind.is_mutation() => { tracing::debug!("Shopify answered {}: retrying the query", response.status); tokio::time::sleep(self.retry.backoff(retries)).await; @@ -187,7 +197,11 @@ impl Shopify { if raw.is_throttled() { let cost = raw.cost(); if !may_retry { - return Err(Error::Throttled { retries, cost }); + return Err(Error::Throttled { + retries, + cost, + retry_after: None, + }); } let wait = self.retry.throttled(retries, cost); tracing::debug!("throttled by Shopify: retrying in {wait:?}"); @@ -201,10 +215,13 @@ impl Shopify { } /// The wait a `Retry-After` header asks for, in seconds; `None` for a -/// value that is not a wait. +/// value that is not a wait. A wait too long for a `Duration` is the longest one. fn retry_after(response: &crate::transport::HttpResponse) -> Option { let seconds: f64 = response.header("Retry-After")?.trim().parse().ok()?; - std::time::Duration::try_from_secs_f64(seconds).ok() + if seconds.is_nan() || seconds < 0.0 { + return None; + } + Some(std::time::Duration::try_from_secs_f64(seconds).unwrap_or(std::time::Duration::MAX)) } /// The `data` and `extensions` of an answer without errors. diff --git a/crates/shopify_api/tests/retry.rs b/crates/shopify_api/tests/retry.rs index 0616355..0256c71 100644 --- a/crates/shopify_api/tests/retry.rs +++ b/crates/shopify_api/tests/retry.rs @@ -132,8 +132,7 @@ async fn no_retry_policy_sends_once() { #[tokio::test] async fn waits_shopify_cannot_mean_do_not_panic() { let mock = MockTransport::new(); - mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "1e300")) - .push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "-5")) + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "-5")) .push_json(json!({ "errors": [{ "message": "Throttled", "extensions": { "code": "THROTTLED" } }], "extensions": { "cost": { @@ -145,7 +144,68 @@ async fn waits_shopify_cannot_mean_do_not_panic() { let shopify = client(&mock); shopify.graphql("{ shop { name } }", ()).await.unwrap(); - assert_eq!(mock.requests().len(), 4); + assert_eq!(mock.requests().len(), 3); + + // Too long to wait for: the caller gets it. + mock.clear(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "1e300")); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!( + matches!( + error, + Error::Throttled { + retry_after: Some(Duration::MAX), + .. + } + ), + "{error:?}" + ); +} + +/// `max_delay` caps the backoff the client computes, not the wait Shopify asks for. +#[tokio::test(start_paused = true)] +async fn a_429_waits_for_a_retry_after_longer_than_the_longest_backoff() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "120")) + .push_data(shop()); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(mock.clone()) + .build() + .unwrap(); + + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(started.elapsed(), Duration::from_secs(120)); + assert_eq!(mock.requests().len(), 2); +} + +/// A wait longer than `max_retry_after` is not slept through: the caller gets it. +#[tokio::test(start_paused = true)] +async fn a_retry_after_beyond_the_limit_is_returned_as_a_throttle_error() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "600")); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(mock.clone()) + .retry(RetryPolicy::new(4).with_max_retry_after(Duration::from_secs(300))) + .build() + .unwrap(); + + let started = tokio::time::Instant::now(); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert_eq!(started.elapsed(), Duration::ZERO); + let Error::Throttled { + retries, + retry_after, + .. + } = error + else { + panic!("throttled: {error:?}"); + }; + assert_eq!(retries, 0); + assert_eq!(retry_after, Some(Duration::from_secs(600))); + assert_eq!(mock.requests().len(), 1); } /// A comment that ends with a bare `\r` still hides nothing: the mutation From 102ea52bcfe7ac9775126df471898169e8dfc679 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:10:25 +0200 Subject: [PATCH 009/135] fix: reject out-of-range timestamps instead of panicking timestamp=-9223372036854775808 overflowed `now - timestamp` in verify_query and verify_app_proxy before the signature was checked. The distance is now an abs_diff, and the timestamp is only read once the HMAC (constant-time verify_slice) holds. Session token exp/nbf checks use saturating arithmetic for the same reason. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/oauth.rs | 60 ++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/shopify_api/src/oauth.rs b/crates/shopify_api/src/oauth.rs index f0c3670..13904c3 100644 --- a/crates/shopify_api/src/oauth.rs +++ b/crates/shopify_api/src/oauth.rs @@ -393,13 +393,14 @@ impl ShopifyApp { let params = parse_query(query)?; let signature = single(¶ms, "hmac")?.ok_or_else(|| invalid("the query has no `hmac`"))?; - check_timestamp(¶ms, now)?; let expected = hex::decode(signature) .map_err(|_| invalid("the `hmac` of the query is not hexadecimal"))?; let mut mac = mac(self.secret()?); mac.update(admin_message(¶ms).as_bytes()); mac.verify_slice(&expected) .map_err(|_| invalid("the signature of the query does not match"))?; + // Only once the signature holds: nothing unsigned reaches the clock. + check_timestamp(¶ms, now)?; Ok(signed(params)) } @@ -424,13 +425,14 @@ impl ShopifyApp { } let signature = single(¶ms, "signature")?.ok_or_else(|| invalid("the query has no `signature`"))?; - check_timestamp(¶ms, now)?; let expected = hex::decode(signature) .map_err(|_| invalid("the `signature` of the query is not hexadecimal"))?; let mut mac = mac(self.secret()?); mac.update(proxy_message(¶ms).as_bytes()); mac.verify_slice(&expected) .map_err(|_| invalid("the signature of the app proxy request does not match"))?; + // Only once the signature holds: nothing unsigned reaches the clock. + check_timestamp(¶ms, now)?; Ok(signed(params)) } @@ -481,10 +483,12 @@ impl ShopifyApp { let time = |name: &str| claims.get(name).and_then(Value::as_i64); let now = now.timestamp(); let expires = time("exp").ok_or_else(|| invalid("the session token has no `exp`"))?; - if now > expires + JWT_TOLERANCE_SECONDS { + if now > expires.saturating_add(JWT_TOLERANCE_SECONDS) { return Err(invalid("the session token has expired")); } - if time("nbf").is_some_and(|not_before| now < not_before - JWT_TOLERANCE_SECONDS) { + if time("nbf") + .is_some_and(|not_before| now < not_before.saturating_sub(JWT_TOLERANCE_SECONDS)) + { return Err(invalid("the session token is not valid yet")); } let audience_matches = match claims.get("aud") { @@ -602,7 +606,8 @@ fn check_timestamp(params: &[(String, String)], now: DateTime) -> Result<() let timestamp: i64 = single(params, "timestamp")? .and_then(|timestamp| timestamp.parse().ok()) .ok_or_else(|| invalid("the query has no valid `timestamp`"))?; - if (now.timestamp() - timestamp).abs() > QUERY_TOLERANCE_SECONDS { + // `abs_diff`: any `i64` timestamp, however far, is a distance, not an overflow. + if now.timestamp().abs_diff(timestamp) > QUERY_TOLERANCE_SECONDS.unsigned_abs() { return Err(invalid( "the `timestamp` of the query is more than 90 seconds away", )); @@ -695,6 +700,51 @@ mod tests { ); } + /// A timestamp at the edge of `i64` is rejected, never a panic, in both checks. + #[test] + fn extreme_timestamps_are_rejected_without_panicking() { + for timestamp in [i64::MIN, i64::MAX] { + let query = format!("timestamp={timestamp}&hmac=00&signature=00"); + for result in [ + app().verify_query_at(&query, at(1_700_000_000)), + app().verify_app_proxy_at(&query, at(1_700_000_000)), + ] { + assert!(matches!(result, Err(Error::Verification(_))), "{result:?}"); + } + // Signed, so only the timestamp fails. + let unsigned = format!("shop=a.myshopify.com×tamp={timestamp}"); + let hmac = app().sign_query(&unsigned).unwrap(); + let error = app() + .verify_query_at(&format!("{unsigned}&hmac={hmac}"), at(1_700_000_000)) + .unwrap_err(); + assert!(error.to_string().contains("90 seconds"), "{error}"); + let signature = app().sign_app_proxy(&unsigned).unwrap(); + let error = app() + .verify_app_proxy_at( + &format!("{unsigned}&signature={signature}"), + at(1_700_000_000), + ) + .unwrap_err(); + assert!(error.to_string().contains("90 seconds"), "{error}"); + } + } + + /// Extreme `exp` and `nbf` claims are rejected, never a panic. + #[test] + fn extreme_session_token_times_do_not_panic() { + let now = 1_700_000_000; + for (exp, nbf) in [(i64::MAX, now), (now + 60, i64::MIN), (i64::MIN, now)] { + let token = app().sign_session_token(&json!({ + "iss": "https://a.myshopify.com/admin", + "dest": "https://a.myshopify.com", + "aud": "client-id", + "exp": exp, + "nbf": nbf, + })); + let _ = app().verify_session_token_at(&token, at(now)); + } + } + #[test] fn signs_queries_as_shopify_admin_does() { // Spaces as %20, repeated values joined, names sorted, the signature left out. From 48852c2c63466a6fd72fc2e279d22d50fabd5fec Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:11:47 +0200 Subject: [PATCH 010/135] fix: keep tokens and signed URLs out of Debug output - testing::GraphqlRequest: manual Debug, access_token shown as [redacted]. - transport::HttpRequest: the URL is shown without its query string, so a signed bulk-download address no longer leaks its signature. - transport::HttpResponse: secret headers (now also Set-Cookie and Proxy-Authorization) redacted; a Location header loses its query string. - bulk::BulkOperation: url and partial_data_url shown without their query string. - CLI DownloadArgs: access token and client secret redacted. The fields themselves are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bin/shopify-api.rs | 19 +++++- crates/shopify_api/src/bulk.rs | 56 +++++++++++++++- crates/shopify_api/src/testing.rs | 44 ++++++++++++- crates/shopify_api/src/transport.rs | 79 +++++++++++++++++------ 4 files changed, 174 insertions(+), 24 deletions(-) diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index 50a42d1..0f94b6a 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -52,7 +52,8 @@ enum SchemaCommand { Download(DownloadArgs), } -#[derive(Debug, Args)] +/// `Debug` hides the access token and the client secret. +#[derive(Args)] struct DownloadArgs { /// Where to write it. By default, `graphql/admin.schema.json` next to the /// nearest `Cargo.toml` of a package, where `graphql!` reads it @@ -78,6 +79,22 @@ struct DownloadArgs { client_secret: Option, } +impl std::fmt::Debug for DownloadArgs { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let hidden = |secret: &Option| secret.as_ref().map(|_| "[redacted]"); + formatter + .debug_struct("DownloadArgs") + .field("out", &self.out) + .field("introspection", &self.introspection) + .field("only", &self.only) + .field("shop", &self.shop) + .field("access_token", &hidden(&self.access_token)) + .field("client_id", &self.client_id) + .field("client_secret", &hidden(&self.client_secret)) + .finish() + } +} + #[derive(Debug, Args)] struct CheckArgs { /// The `.graphql` files, one operation each. diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index fee054b..d279204 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -72,8 +72,9 @@ graphql! { mod staged_uploads = file("graphql/operations/bulk_staged_uploads.graphql"); } -/// A bulk operation, as Shopify last reported it. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +/// A bulk operation, as Shopify last reported it. `Debug` leaves out the +/// query string of `url` and `partial_data_url`: their signature. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] #[non_exhaustive] pub struct BulkOperation { pub id: String, @@ -96,6 +97,27 @@ pub struct BulkOperation { pub query: String, } +impl std::fmt::Debug for BulkOperation { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let unsigned = |url: &Option| url.as_deref().map(crate::error::without_query); + formatter + .debug_struct("BulkOperation") + .field("id", &self.id) + .field("kind", &self.kind) + .field("status", &self.status) + .field("error_code", &self.error_code) + .field("created_at", &self.created_at) + .field("completed_at", &self.completed_at) + .field("object_count", &self.object_count) + .field("root_object_count", &self.root_object_count) + .field("file_size", &self.file_size) + .field("url", &unsigned(&self.url)) + .field("partial_data_url", &unsigned(&self.partial_data_url)) + .field("query", &self.query) + .finish() + } +} + /// The status of a bulk operation. A status Shopify adds later is `Other`. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[non_exhaustive] @@ -665,6 +687,36 @@ fn multipart( mod tests { use super::*; + #[test] + fn debug_hides_the_signature_of_the_download_addresses() { + let operation = BulkOperation { + id: "gid://shopify/BulkOperation/1".to_string(), + kind: BulkOperationType::Query, + status: BulkOperationStatus::Completed, + error_code: None, + created_at: "2026-10-22T10:00:00Z".to_string(), + completed_at: None, + object_count: 0, + root_object_count: 0, + file_size: None, + url: Some("https://storage.googleapis.com/a.jsonl?X-Goog-Signature=SECRET".to_string()), + partial_data_url: Some( + "https://storage.googleapis.com/b.jsonl?X-Goog-Signature=SECRET".to_string(), + ), + query: "{ shop { name } }".to_string(), + }; + let shown = format!("{operation:?}"); + assert!(!shown.contains("SECRET"), "{shown}"); + assert!( + shown.contains("https://storage.googleapis.com/a.jsonl"), + "{shown}" + ); + assert!( + shown.contains("https://storage.googleapis.com/b.jsonl"), + "{shown}" + ); + } + #[test] fn parses_jsonl_and_names_the_line_at_fault() { let rows: Vec = parse_jsonl(b"{\"id\":1}\n\n{\"id\":2}\n").unwrap(); diff --git a/crates/shopify_api/src/testing.rs b/crates/shopify_api/src/testing.rs index cecd0ca..a7d0d23 100644 --- a/crates/shopify_api/src/testing.rs +++ b/crates/shopify_api/src/testing.rs @@ -160,8 +160,9 @@ impl Transport for MockTransport { } } -/// A GraphQL request, as a [`MockTransport`] received it. -#[derive(Debug, Clone, PartialEq)] +/// A GraphQL request, as a [`MockTransport`] received it. `Debug` hides +/// the access token. +#[derive(Clone, PartialEq)] #[non_exhaustive] pub struct GraphqlRequest { pub url: String, @@ -174,6 +175,23 @@ pub struct GraphqlRequest { pub access_token: Option, } +impl std::fmt::Debug for GraphqlRequest { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("GraphqlRequest") + .field("url", &self.url) + .field("api_version", &self.api_version) + .field("query", &self.query) + .field("variables", &self.variables) + .field("operation_name", &self.operation_name) + .field( + "access_token", + &self.access_token.as_ref().map(|_| "[redacted]"), + ) + .finish() + } +} + impl GraphqlRequest { fn read(request: &HttpRequest) -> Option { let (_, path) = request.url.split_once("/admin/api/")?; @@ -210,3 +228,25 @@ pub fn client(mock: &MockTransport) -> Shopify { .build() .expect("a valid test client") } + +#[cfg(test)] +mod tests { + use super::*; + use crate::transport::Method; + + #[test] + fn a_graphql_request_debug_hides_the_access_token() { + let request = HttpRequest::new( + Method::Post, + "https://shop.myshopify.com/admin/api/2026-10/graphql.json", + ) + .with_header("X-Shopify-Access-Token", "shpat_SECRET") + .with_body(r#"{"query":"{ shop { name } }"}"#); + let request = GraphqlRequest::read(&request).unwrap(); + assert_eq!(request.access_token.as_deref(), Some("shpat_SECRET")); + let shown = format!("{request:?}"); + assert!(!shown.contains("shpat_SECRET"), "{shown}"); + assert!(shown.contains("[redacted]"), "{shown}"); + assert!(shown.contains("{ shop { name } }"), "{shown}"); + } +} diff --git a/crates/shopify_api/src/transport.rs b/crates/shopify_api/src/transport.rs index 39b8f46..e67b869 100644 --- a/crates/shopify_api/src/transport.rs +++ b/crates/shopify_api/src/transport.rs @@ -10,7 +10,34 @@ use std::time::Duration; pub type BoxFuture<'a, T> = Pin + Send + 'a>>; /// Header names whose value is a secret, hidden by `Debug`. -const SECRET_HEADERS: [&str; 3] = ["x-shopify-access-token", "authorization", "cookie"]; +const SECRET_HEADERS: [&str; 5] = [ + "x-shopify-access-token", + "authorization", + "proxy-authorization", + "cookie", + "set-cookie", +]; + +/// Headers as `Debug` shows them: secret values hidden, and the query +/// string of a `Location`, which may be a signed address, left out. +fn shown_headers(headers: &[(String, String)]) -> Vec<(&str, String)> { + headers + .iter() + .map(|(name, value)| { + let shown = if SECRET_HEADERS + .iter() + .any(|secret| name.eq_ignore_ascii_case(secret)) + { + "[redacted]".to_string() + } else if name.eq_ignore_ascii_case("location") { + crate::error::without_query(value) + } else { + value.clone() + }; + (name.as_str(), shown) + }) + .collect() +} #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] @@ -21,8 +48,9 @@ pub enum Method { /// A request this crate sends. /// -/// `Debug` hides the value of secret headers and the body, which may hold a -/// client secret or a refresh token. +/// `Debug` hides the value of secret headers, the query string of the +/// address, which may sign it, and the body, which may hold a client secret +/// or a refresh token. #[derive(Clone, PartialEq, Eq)] #[non_exhaustive] pub struct HttpRequest { @@ -90,24 +118,12 @@ impl HttpRequest { impl fmt::Debug for HttpRequest { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - let headers: Vec<(&str, &str)> = self - .headers - .iter() - .map(|(name, value)| { - let secret = SECRET_HEADERS - .iter() - .any(|secret| name.eq_ignore_ascii_case(secret)); - ( - name.as_str(), - if secret { "[redacted]" } else { value.as_str() }, - ) - }) - .collect(); formatter .debug_struct("HttpRequest") .field("method", &self.method) - .field("url", &self.url) - .field("headers", &headers) + // A signed address (a bulk download) carries its credential in its query string. + .field("url", &crate::error::without_query(&self.url)) + .field("headers", &shown_headers(&self.headers)) .field("body", &format_args!("[{} bytes]", self.body.len())) .field("timeout", &self.timeout) .finish() @@ -130,7 +146,7 @@ impl fmt::Debug for HttpResponse { formatter .debug_struct("HttpResponse") .field("status", &self.status) - .field("headers", &self.headers) + .field("headers", &shown_headers(&self.headers)) .field("body", &format_args!("[{} bytes]", self.body.len())) .finish() } @@ -360,6 +376,31 @@ mod tests { ); } + /// A signed download address carries its credential in its query string. + #[test] + fn debug_hides_the_query_string_of_the_url() { + let request = HttpRequest::new( + Method::Get, + "https://storage.googleapis.com/export.jsonl?X-Goog-Signature=SECRET#frag", + ); + let shown = format!("{request:?}"); + assert!(!shown.contains("SECRET"), "{shown}"); + assert!( + shown.contains("https://storage.googleapis.com/export.jsonl"), + "{shown}" + ); + assert_eq!( + request.url, + "https://storage.googleapis.com/export.jsonl?X-Goog-Signature=SECRET#frag" + ); + + let response = HttpResponse::new(302, "") + .with_header("Set-Cookie", "session=SECRET") + .with_header("Location", "https://storage.googleapis.com/x?sig=SECRET"); + let shown = format!("{response:?}"); + assert!(!shown.contains("SECRET"), "{shown}"); + } + #[test] fn responses_read_headers_whatever_their_case() { let response = HttpResponse::json(429, &serde_json::json!({ "errors": "Throttled" })) From e4fd8d164b14d634c828d52d09403a3392f1c3fa Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:12:51 +0200 Subject: [PATCH 011/135] fix: build without default features; check it in CI auth.rs spawns the token renewal with tokio::spawn, which needs tokio's `rt` feature; only `sync` and `time` were declared, so `cargo check -p shopify_api --no-default-features --lib` failed with E0425 while reqwest's tokio features hid it in the default build. The crate now declares `rt`. A new `check:features` mise task builds the library with no default features and with each feature alone; CI runs it in its own `features` job, required by "CI is green". Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 13 +++++++++++++ crates/shopify_api/Cargo.toml | 3 ++- mise.toml | 13 +++++++++++-- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cef848e..dc2f565 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,7 @@ jobs: runs-on: ubuntu-latest needs: - check + - features - msrv steps: - run: exit 0 @@ -33,6 +34,18 @@ jobs: - uses: Swatinem/rust-cache@v2 - run: mise run check + # In its own job, so the build of nothing else can lend the client a + # feature it does not declare (`mise run check` runs it too). + features: + name: no default features, each feature alone + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: jdx/mise-action@v5 + - uses: Swatinem/rust-cache@v2 + # `cargo check -p shopify_api --no-default-features --lib --locked`, then each feature alone. + - run: mise run check:features + msrv: name: Rust 1.88 runs-on: ubuntu-latest diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index d76831e..fa80be7 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -43,7 +43,8 @@ serde_json.workspace = true serde_path_to_error.workspace = true serde_urlencoded.workspace = true thiserror.workspace = true -tokio = { workspace = true, features = ["sync", "time"] } +# `rt`: a token renewal runs in its own task, so a caller that gives up does not cancel it. +tokio = { workspace = true, features = ["rt", "sync", "time"] } tracing.workspace = true base64 = { workspace = true, optional = true } diff --git a/mise.toml b/mise.toml index 6d679e8..3fbbc47 100644 --- a/mise.toml +++ b/mise.toml @@ -27,14 +27,23 @@ run = "cargo test --workspace --all-features --locked" description = "Build and test the client with its default features only" run = "cargo test -p shopify_api --locked" +[tasks."check:features"] +description = "Build the client without its default features, then with each feature alone: what feature unification in the workspace hides" +run = [ + "cargo check -p shopify_api --no-default-features --lib --locked", + "cargo check -p shopify_api --no-default-features --features webhooks --lib --locked", + "cargo check -p shopify_api --no-default-features --features oauth --lib --locked", + "cargo check -p shopify_api --no-default-features --features testing --lib --locked", +] + [tasks.doc] description = "Build the documentation, warnings are errors" env = { RUSTDOCFLAGS = "-D warnings" } run = "cargo doc --workspace --all-features --no-deps --locked" [tasks.check] -description = "What CI runs: fmt check, clippy, tests, docs" -depends = ["fmt:check", "lint", "test", "test:min", "doc"] +description = "What CI runs: fmt check, clippy, tests, docs, features alone" +depends = ["fmt:check", "lint", "test", "test:min", "check:features", "doc"] [tasks.msrv] description = "Build the workspace with the minimum supported Rust version (1.88)" From 8017d639a45846886ebe45b7f06652a0d6ac8f80 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:13:40 +0200 Subject: [PATCH 012/135] fix: keep every possible type when cutting a schema restricted_to dropped the possible types of interfaces and unions that no operation selected, so in a cut schema `node { ... on Product { title } }` made Product the only Node: the fragment always applied and `title` became `String` instead of `Option`. Decoding an Order then failed with "missing field title". Interfaces and unions now keep their whole list of possible types (the names only; the types stay out). Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api_graphql/src/restrict.rs | 14 ++++---- .../tests/internal_schema.rs | 32 ++++++++++++++++++- 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/crates/shopify_api_graphql/src/restrict.rs b/crates/shopify_api_graphql/src/restrict.rs index 59d3289..5c55af1 100644 --- a/crates/shopify_api_graphql/src/restrict.rs +++ b/crates/shopify_api_graphql/src/restrict.rs @@ -195,16 +195,14 @@ impl Used { }; types.insert(name, restricted); } - // Interfaces and possible types only among the types kept. + // Interfaces only among the types kept. The possible types of an + // interface or a union all stay, kept or not: they tell whether a + // fragment always applies, and so whether its fields are optional. + // Left out, `... on Product` in a `Node` would always apply. let names: BTreeSet = types.keys().cloned().collect(); - let keep = |list: &mut Vec| list.retain(|name| names.contains(name)); for definition in types.values_mut() { - match definition { - TypeDef::Object { interfaces, .. } => keep(interfaces), - TypeDef::Interface { possible_types, .. } | TypeDef::Union { possible_types } => { - keep(possible_types) - } - _ => {} + if let TypeDef::Object { interfaces, .. } = definition { + interfaces.retain(|name| names.contains(name)); } } Schema { diff --git a/crates/shopify_api_graphql/tests/internal_schema.rs b/crates/shopify_api_graphql/tests/internal_schema.rs index f81d1a9..c327b38 100644 --- a/crates/shopify_api_graphql/tests/internal_schema.rs +++ b/crates/shopify_api_graphql/tests/internal_schema.rs @@ -4,7 +4,7 @@ use std::path::{Path, PathBuf}; -use shopify_api_graphql::{Schema, analyze}; +use shopify_api_graphql::{FieldBase, Schema, analyze}; fn runtime_crate() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../shopify_api/graphql") @@ -69,3 +69,33 @@ fn a_restricted_schema_refuses_what_it_left_out() { ); assert!(full.restricted_to(&["{ shop { nam } }"]).is_err()); } + +/// Cutting the schema keeps every possible type of an interface or a union: +/// a fragment on one of them stays conditional, and its fields optional. +#[test] +fn a_restricted_schema_keeps_fragments_on_abstract_types_conditional() { + let dir = runtime_crate(); + let full = Schema::from_json(&std::fs::read_to_string(dir.join("admin.schema.json")).unwrap()) + .unwrap(); + for query in [ + "query($id: ID!) { node(id: $id) { id ... on Product { title } } }", + "query($id: ID!) { node(id: $id) { id ...P } } fragment P on Product { title }", + ] { + let cut = full.restricted_to(&[query]).unwrap(); + let shape = analyze(&cut, query).unwrap(); + assert_eq!(shape, analyze(&full, query).unwrap(), "{query}"); + let FieldBase::Object(node) = &shape.data.fields[0].base else { + panic!("node is an object"); + }; + let title = node + .fields + .iter() + .find(|field| field.key == "title") + .unwrap(); + assert!(title.conditional, "{query}: {title:?}"); + + // Through JSON too, as `graphql!` reads it. + let reloaded = Schema::from_json(&cut.to_json()).unwrap(); + assert_eq!(analyze(&reloaded, query).unwrap(), shape, "{query}"); + } +} From 47573932f919531a7177257a32335a08bdb15195 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:14:51 +0200 Subject: [PATCH 013/135] fix: let one response key name different fields on exclusive object types The analyzer required every selection of a response key to be the same field with the same arguments, so `node { ... on Product { label: title } ... on Order { label: name } }` was refused. Per the spec's FieldsInSetCanMerge, when the two parents are different object types (never both present), only the shape of the answer must agree; the field names and arguments may differ. On the same type or an interface they still must match. The shape check stays strict: the two types must be the same (same nullability, lists and named type), so the merged key keeps a single Rust type. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api_graphql/src/analyze.rs | 67 +++++++++++++++++---- crates/shopify_api_graphql/tests/analyze.rs | 39 ++++++++++++ 2 files changed, 94 insertions(+), 12 deletions(-) diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index 29681e1..0b7444c 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -369,8 +369,10 @@ struct Pending<'a> { key: String, field: String, ty: TypeRef, - /// The arguments, written the same way for every place that gives the same ones. - arguments: String, + /// Where the key was selected: on which parent type, which field, with + /// which arguments (written the same way for every place that gives the + /// same ones). + origins: Vec, /// The field may be absent from a value of the parent. conditional: bool, /// The subfields selected at each place, with whether that place may @@ -382,6 +384,13 @@ struct Pending<'a> { position: Pos, } +/// One place a response key is selected at. +struct Origin { + parent: String, + field: String, + arguments: String, +} + /// Which of the sets merged into one selection a field comes from. #[derive(Clone, Copy)] struct Place { @@ -534,7 +543,8 @@ impl<'a> Analyzer<'a> { match pending.iter_mut().find(|existing| existing.key == key) { Some(existing) => { - if existing.field != field.name || existing.ty != ty { + // The answer holds one value under the key: one type. + if existing.ty != ty { return error_at( field.position, format!( @@ -543,15 +553,39 @@ impl<'a> Analyzer<'a> { ), ); } - if existing.arguments != arguments { - return error_at( - field.position, - format!( - "`{key}` is selected twice with different arguments (`({})` and `({arguments})`); give one of them an alias", - existing.arguments - ), - ); + // FieldsInSetCanMerge: on two different object + // types, never both there, the fields and their + // arguments may differ; elsewhere they may not. + for origin in &existing.origins { + let exclusive = origin.parent != parent + && self.is_object(parent) + && self.is_object(&origin.parent); + if !exclusive { + if origin.field != field.name { + return error_at( + field.position, + format!( + "`{key}` is selected twice with different fields or types (`{}: {}` and `{}: {ty}`); give one of them an alias", + origin.field, existing.ty, field.name + ), + ); + } + if origin.arguments != arguments { + return error_at( + field.position, + format!( + "`{key}` is selected twice with different arguments (`({})` and `({arguments})`); give one of them an alias", + origin.arguments + ), + ); + } + } } + existing.origins.push(Origin { + parent: parent.to_string(), + field: field.name.clone(), + arguments, + }); existing.conditional &= conditional; existing.sets.extend(sets); if !conditional { @@ -562,7 +596,11 @@ impl<'a> Analyzer<'a> { key, field: field.name.clone(), ty, - arguments, + origins: vec![Origin { + parent: parent.to_string(), + field: field.name.clone(), + arguments, + }], conditional, sets: sets.into_iter().collect(), unconditional_in: (!conditional) @@ -634,6 +672,11 @@ impl<'a> Analyzer<'a> { /// Whether every value of type `parent` matches a fragment on `condition`. /// Fails when none can. + /// An object type, as opposed to an interface or a union. + fn is_object(&self, name: &str) -> bool { + matches!(self.schema.get(name), Some(TypeDef::Object { .. })) + } + fn fragment_always_applies( &self, parent: &str, diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs index 099f8c0..5038dcf 100644 --- a/crates/shopify_api_graphql/tests/analyze.rs +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -703,3 +703,42 @@ fn directives_come_from_the_schema() { "Variable `$flag` of type `String!` cannot be used for argument `if` of `@include`, which expects `Boolean!` (line 1, column 37)" ); } + +/// FieldsInSetCanMerge: on two different object types, one key may name +/// different fields, or the same field with other arguments, as long as the +/// shapes of the answers agree. On the same type, or an interface, it may not. +#[test] +fn one_key_may_name_different_fields_on_different_object_types() { + let operation = check( + "query($id: ID!) { node(id: $id) { ... on Product { label: title } ... on Order { label: name } } }", + ); + assert_eq!(fields(child(&operation.data, "node")), ["label?: String!"]); + + // Same type of object below: their subfields merge. + let operation = check( + "query($id: ID!) { node(id: $id) { ...P ...O } } + fragment P on ProductVariant { owner: image { url } } + fragment O on Collection { owner: image { url } }", + ); + assert_eq!(fields(child(&operation.data, "node")), ["owner?: Image"]); + + let operation = check( + "query($id: ID!) { node(id: $id) { ... on Product { m: metafield(key: \"a\") { value } } ... on Order { m: metafield(key: \"b\") { value } } } }", + ); + assert_eq!(fields(child(&operation.data, "node")), ["m?: Metafield"]); + + // The same object type: the fields must be the same. + assert!( + refusal( + "query($id: ID!) { node(id: $id) { ... on Product { label: title } ... on Order { label: name } ... on Product { label: handle } } }" + ) + .contains("`label` is selected twice with different fields or types (`title: String!` and `handle: String!`)") + ); + // Shapes that differ, even on different types. + assert!( + refusal( + "query($id: ID!) { node(id: $id) { ... on Product { label: title } ... on Order { label: email } } }" + ) + .contains("`label` is selected twice with different fields or types") + ); +} From 05a4abb79fe1d7231150a813bc2bc5cf7d97405c Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:16:06 +0200 Subject: [PATCH 014/135] docs: changelog for Retry-After limit and fail-safe mutation detection Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad2d567..0ecb3aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - Add: `shopify-api check` checks `.graphql` files against the schema. -- Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`; queries are retried after a `5xx` or a network failure, mutations never. `RetryPolicy`. +- Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After` (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`. - Add: tokens are renewed once for all the clones of a client, before they expire and when Shopify refuses one with a `401`. `Auth::expiring_token` with a `TokenStore`. - Add: `Shopify::paginate`, `Page`. - Add: bulk operations: `bulk_query_rows`, `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, typed `BulkOperation` and statuses, adaptive polling. From d5d6170f75b960a10dfe1c85bec29b18d4258f32 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:43:39 +0200 Subject: [PATCH 015/135] fix: keep partial data values out of the Debug of GraphqlErrors A response that returns a bulk operation's signed url next to an errored field ended in Error::Graphql, whose derived Debug printed the url. Debug now lists the keys of the partial data, not their values. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api/src/error.rs | 67 ++++++++++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ecb3aa..d7627e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `oauth`: `ShopifyApp` with install links, callback and admin launch verification, code exchange, session tokens and token exchange, app proxies. - Add: `Transport` trait, `ReqwestTransport` (redirections always off, `from_builder` for your own settings), and `testing::MockTransport`. - Add: token renewals run in a task of their own: a cancelled request does not lose a rotated refresh token. A failed renewal answers the requests waiting for it. -- Add: errors never hold a query string (signed bulk result addresses stay out of logs); `Error::Http` carries Shopify's `X-Request-Id`. +- Add: errors never hold a query string (signed bulk result addresses stay out of logs), and the `Debug` of `GraphqlErrors` names the fields of partial `data` without their values; `Error::Http` carries Shopify's `X-Request-Id`. - Add: `ShopDomain` refuses anything but `` or `.myshopify.com`. - Breaking: `Shopify::new(shop, auth)` and `Shopify::builder`; `ShopifyAuth` is `Auth`; `ShopifyConfig` is gone; `ShopifyAPIError` is `Error`. - Breaking: `graphql` returns `data` as a `Value` and `graphql_as` reads it as a type; `post_graphql` and the `graphql-client` feature are gone. diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index 743950d..f1c1c26 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -192,7 +192,10 @@ pub(crate) fn without_query(url: &str) -> String { } /// The `errors` of a GraphQL answer, and its `data` when it had some. -#[derive(Debug, Clone)] +/// +/// Its `Debug` shows the names of the fields of `data`, not their values, +/// which may be secret: the signed address of a bulk operation's results. +#[derive(Clone)] #[non_exhaustive] pub struct GraphqlErrors { pub errors: Vec, @@ -200,6 +203,38 @@ pub struct GraphqlErrors { pub data: Option, } +impl fmt::Debug for GraphqlErrors { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("GraphqlErrors") + .field("errors", &self.errors) + .field("data", &self.data.as_ref().map(DataShape)) + .finish() + } +} + +/// The top-level keys of partial `data`, without their values. +struct DataShape<'a>(&'a serde_json::Value); + +impl fmt::Debug for DataShape<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + serde_json::Value::Object(fields) => { + write!(formatter, "{{")?; + for (index, key) in fields.keys().enumerate() { + if index > 0 { + write!(formatter, ", ")?; + } + write!(formatter, "{key:?}: ..")?; + } + write!(formatter, "}}") + } + serde_json::Value::Null => formatter.write_str("null"), + _ => formatter.write_str(".."), + } + } +} + impl fmt::Display for GraphqlErrors { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { for (index, error) in self.errors.iter().enumerate() { @@ -256,6 +291,36 @@ mod tests { assert!(!error.is_unauthorized()); } + #[test] + fn graphql_errors_debug_hides_partial_data() { + let errors: Vec = serde_json::from_value(serde_json::json!([{ + "message": "Access denied for orders field", + "path": ["orders"], + "extensions": { "code": "ACCESS_DENIED" }, + }])) + .unwrap(); + let error = Error::Graphql(GraphqlErrors { + errors, + data: Some(serde_json::json!({ + "bulkOperation": { + "id": "gid://shopify/BulkOperation/1", + "url": "https://storage.googleapis.com/r.jsonl?X-Goog-Signature=SIGNED_SECRET", + }, + "orders": null, + })), + }); + let shown = format!("{error:?} {error} {error:#?}"); + assert!(!shown.contains("SIGNED_SECRET"), "{shown}"); + assert!(!shown.contains("storage.googleapis.com"), "{shown}"); + assert!(shown.contains("\"bulkOperation\": .."), "{shown}"); + assert!(shown.contains("ACCESS_DENIED"), "{shown}"); + // The data itself stays available to the caller. + let Error::Graphql(errors) = &error else { + unreachable!() + }; + assert!(errors.data.as_ref().unwrap()["bulkOperation"]["url"].is_string()); + } + #[test] fn user_errors_name_their_field() { let error = Error::UserErrors { From c57d2001885903373968b262feb604ce4e59fc7b Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:44:08 +0200 Subject: [PATCH 016/135] fix: let testing::client retry a 429 without sleeping through its Retry-After Since Retry-After is honored past max_delay, a mocked 429 with Retry-After: 300 made the test client sleep five minutes. An internal RetryPolicy flag, set only by testing::client, retries at once; a wait beyond max_retry_after still ends in Error::Throttled. Production clients are unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api/src/client.rs | 21 +++++++++++++++++++++ crates/shopify_api/src/graphql.rs | 2 +- crates/shopify_api/src/testing.rs | 7 +++++-- crates/shopify_api/tests/retry.rs | 24 ++++++++++++++++++++++++ 5 files changed, 52 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d7627e0..40e0c67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: bulk operations: `bulk_query_rows`, `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, typed `BulkOperation` and statuses, adaptive polling. - Add: `webhooks`: `Webhook::verify` (headers, signature with secret rotation, payload), subscriptions with `sync_webhook_subscriptions`, which updates in place and creates before it deletes. - Add: `oauth`: `ShopifyApp` with install links, callback and admin launch verification, code exchange, session tokens and token exchange, app proxies. -- Add: `Transport` trait, `ReqwestTransport` (redirections always off, `from_builder` for your own settings), and `testing::MockTransport`. +- Add: `Transport` trait, `ReqwestTransport` (redirections always off, `from_builder` for your own settings), and `testing::MockTransport`, with `testing::client`, which retries without waiting, even for a scripted `Retry-After`. - Add: token renewals run in a task of their own: a cancelled request does not lose a rotated refresh token. A failed renewal answers the requests waiting for it. - Add: errors never hold a query string (signed bulk result addresses stay out of logs), and the `Debug` of `GraphqlErrors` names the fields of partial `data` without their values; `Error::Http` carries Shopify's `X-Request-Id`. - Add: `ShopDomain` refuses anything but `` or `.myshopify.com`. diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index 5830770..b6297ce 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -184,6 +184,8 @@ pub struct RetryPolicy { base_delay: Duration, max_delay: Duration, max_retry_after: Duration, + /// `false` only for `testing::client`: a `Retry-After` is not slept through. + wait_for_retry_after: bool, } impl RetryPolicy { @@ -195,6 +197,7 @@ impl RetryPolicy { base_delay: Duration::from_secs(1), max_delay: Duration::from_secs(30), max_retry_after: Duration::from_secs(300), + wait_for_retry_after: true, } } @@ -224,6 +227,24 @@ impl RetryPolicy { self } + /// Retries a `429` at once instead of waiting for its `Retry-After`, for + /// tests with a mocked Shopify. A `Retry-After` beyond `max_retry_after` + /// still ends in [`Error::Throttled`](crate::Error::Throttled). + #[cfg_attr(not(feature = "testing"), allow(dead_code))] + pub(crate) const fn without_retry_after_waits(mut self) -> Self { + self.wait_for_retry_after = false; + self + } + + /// The wait before retrying a `429` whose `Retry-After` asked for `wait`. + pub(crate) const fn retry_after_wait(&self, wait: Duration) -> Duration { + if self.wait_for_retry_after { + wait + } else { + Duration::ZERO + } + } + pub const fn max_retries(&self) -> u32 { self.max_retries } diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index 008077a..995727e 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -176,7 +176,7 @@ impl Shopify { tracing::debug!("Shopify answered 429 with a Retry-After of {wait:?}"); return Err(throttled); } - Some(wait) => wait, + Some(wait) => self.retry.retry_after_wait(wait), None => self.retry.backoff(retries), }; tracing::debug!("Shopify answered 429: retrying in {wait:?}"); diff --git a/crates/shopify_api/src/testing.rs b/crates/shopify_api/src/testing.rs index a7d0d23..30ac6df 100644 --- a/crates/shopify_api/src/testing.rs +++ b/crates/shopify_api/src/testing.rs @@ -215,7 +215,9 @@ impl GraphqlRequest { } /// A client of `test-shop.myshopify.com` with the token `test-token`, -/// sending through `mock`, retrying without waiting. +/// sending through `mock`, retrying without waiting: neither backoff nor a +/// scripted `Retry-After` is slept through. A `Retry-After` beyond +/// [`RetryPolicy::max_retry_after`] still ends in [`Error::Throttled`](crate::Error::Throttled). pub fn client(mock: &MockTransport) -> Shopify { Shopify::builder("test-shop") .access_token("test-token") @@ -223,7 +225,8 @@ pub fn client(mock: &MockTransport) -> Shopify { .retry( RetryPolicy::new(4) .with_base_delay(Duration::ZERO) - .with_max_delay(Duration::ZERO), + .with_max_delay(Duration::ZERO) + .without_retry_after_waits(), ) .build() .expect("a valid test client") diff --git a/crates/shopify_api/tests/retry.rs b/crates/shopify_api/tests/retry.rs index 0256c71..0115b48 100644 --- a/crates/shopify_api/tests/retry.rs +++ b/crates/shopify_api/tests/retry.rs @@ -222,3 +222,27 @@ async fn a_mutation_after_a_comment_ended_by_a_carriage_return_is_not_sent_again assert_eq!(error.status(), Some(502)); assert_eq!(mock.requests().len(), 1); } + +/// The test client retries a `429` at once, whatever its `Retry-After`; one +/// beyond the limit still ends in an error. +#[tokio::test(start_paused = true)] +async fn the_test_client_does_not_wait_for_a_retry_after() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "300")) + .push_data(shop()); + let shopify = client(&mock); + + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(started.elapsed(), Duration::ZERO); + assert_eq!(mock.requests().len(), 2); + + mock.clear(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "301")); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!( + matches!(error, Error::Throttled { retry_after: Some(wait), .. } if wait == Duration::from_secs(301)), + "{error:?}" + ); + assert_eq!(started.elapsed(), Duration::ZERO); +} From 64415ddceb270acf61be01c61f1c10b4a2d30d3f Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:44:53 +0200 Subject: [PATCH 017/135] fix: read a Retry-After given as an HTTP date RFC 9110 allows Retry-After as an HTTP date. Only seconds were read, so a dated 429 was retried after the 1s backoff. The three HTTP-date forms are now parsed with chrono (already a dependency), the wait is counted from now, a past date is no wait, and max_retry_after applies as before. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 2 +- crates/shopify_api/src/client.rs | 6 +-- crates/shopify_api/src/graphql.rs | 74 ++++++++++++++++++++++++++++--- crates/shopify_api/tests/retry.rs | 51 +++++++++++++++++++++ 5 files changed, 124 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40e0c67..c991713 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - Add: `shopify-api check` checks `.graphql` files against the schema. -- Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After` (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`. +- Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`. - Add: tokens are renewed once for all the clones of a client, before they expire and when Shopify refuses one with a `401`. `Auth::expiring_token` with a `TokenStore`. - Add: `Shopify::paginate`, `Page`. - Add: bulk operations: `bulk_query_rows`, `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, typed `BulkOperation` and statuses, adaptive polling. diff --git a/README.md b/README.md index b5da5ee..420419b 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ requests wait for it. ## Rate limits and retries A request Shopify throttles is sent again when the bucket holds its cost again, -computed from `extensions.cost`. A `429` waits for its `Retry-After`, even past +computed from `extensions.cost`. A `429` waits for its `Retry-After` (seconds or an HTTP date), even past `max_delay` (which caps only the backoff the client computes); a `Retry-After` longer than `max_retry_after` (five minutes by default) is not waited for, and ends in `Error::Throttled` with that wait in `retry_after`. A query diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index b6297ce..db3a623 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -172,9 +172,9 @@ fn warn_mismatch(pinned: ApiVersion, checked: &'static str) { /// a `5xx` or a network failure, with exponential backoff; a mutation is not, /// since it may have run. /// -/// A `429` waits for its `Retry-After`, however longer than -/// [`max_delay`](Self::max_delay) it is: that cap is for the backoff the client -/// computes. A `Retry-After` longer than +/// A `429` waits for its `Retry-After`, in seconds or until an HTTP date, +/// however longer than [`max_delay`](Self::max_delay) it is: that cap is for +/// the backoff the client computes. A `Retry-After` longer than /// [`max_retry_after`](Self::max_retry_after) (five minutes by default) is not /// waited for: the request ends in [`Error::Throttled`](crate::Error::Throttled), /// with the wait Shopify asked for in its `retry_after`. diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index 995727e..350ce59 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -214,14 +214,42 @@ impl Shopify { } } -/// The wait a `Retry-After` header asks for, in seconds; `None` for a -/// value that is not a wait. A wait too long for a `Duration` is the longest one. +/// The wait a `Retry-After` header asks for: a number of seconds, or an +/// HTTP date (RFC 9110), counted from now. `None` for a value that is +/// neither. A date already past is no wait; a wait too long for a `Duration` +/// is the longest one. fn retry_after(response: &crate::transport::HttpResponse) -> Option { - let seconds: f64 = response.header("Retry-After")?.trim().parse().ok()?; - if seconds.is_nan() || seconds < 0.0 { - return None; + retry_after_from(response.header("Retry-After")?, chrono::Utc::now()) +} + +fn retry_after_from( + value: &str, + now: chrono::DateTime, +) -> Option { + let value = value.trim(); + if let Ok(seconds) = value.parse::() { + if seconds.is_nan() || seconds < 0.0 { + return None; + } + return Some( + std::time::Duration::try_from_secs_f64(seconds).unwrap_or(std::time::Duration::MAX), + ); + } + let date = http_date(value)?; + Some((date - now).to_std().unwrap_or_default()) +} + +/// An HTTP date in any of its three forms: `Sun, 06 Nov 1994 08:49:37 GMT`, +/// the obsolete `Sunday, 06-Nov-94 08:49:37 GMT` and `Sun Nov 6 08:49:37 1994`. +fn http_date(value: &str) -> Option> { + use chrono::{DateTime, NaiveDateTime, Utc}; + if let Ok(date) = DateTime::parse_from_rfc2822(value) { + return Some(date.with_timezone(&Utc)); } - Some(std::time::Duration::try_from_secs_f64(seconds).unwrap_or(std::time::Duration::MAX)) + ["%A, %d-%b-%y %H:%M:%S GMT", "%a %b %e %H:%M:%S %Y"] + .iter() + .find_map(|format| NaiveDateTime::parse_from_str(value, format).ok()) + .map(|date| date.and_utc()) } /// The `data` and `extensions` of an answer without errors. @@ -234,3 +262,37 @@ fn into_data(raw: RawResponse) -> Result<(Value, Option)> { } Ok((raw.data.unwrap_or(Value::Null), raw.extensions)) } + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::retry_after_from; + + #[test] + fn retry_after_reads_seconds_and_http_dates() { + let now = chrono::DateTime::parse_from_rfc3339("1994-11-06T08:47:37Z") + .unwrap() + .to_utc(); + let read = |value| retry_after_from(value, now); + assert_eq!(read("120"), Some(Duration::from_secs(120))); + assert_eq!(read(" 2.5 "), Some(Duration::from_millis(2500))); + assert_eq!(read("-5"), None); + // The three forms of RFC 9110, two minutes after `now`. + assert_eq!( + read("Sun, 06 Nov 1994 08:49:37 GMT"), + Some(Duration::from_secs(120)) + ); + assert_eq!( + read("Sunday, 06-Nov-94 08:49:37 GMT"), + Some(Duration::from_secs(120)) + ); + assert_eq!( + read("Sun Nov 6 08:49:37 1994"), + Some(Duration::from_secs(120)) + ); + // A date already past is no wait. + assert_eq!(read("Sun, 06 Nov 1994 08:00:00 GMT"), Some(Duration::ZERO)); + assert_eq!(read("soon"), None); + } +} diff --git a/crates/shopify_api/tests/retry.rs b/crates/shopify_api/tests/retry.rs index 0115b48..e10f70c 100644 --- a/crates/shopify_api/tests/retry.rs +++ b/crates/shopify_api/tests/retry.rs @@ -246,3 +246,54 @@ async fn the_test_client_does_not_wait_for_a_retry_after() { ); assert_eq!(started.elapsed(), Duration::ZERO); } + +fn http_date_in(seconds: i64) -> String { + (chrono::Utc::now() + chrono::Duration::seconds(seconds)) + .format("%a, %d %b %Y %H:%M:%S GMT") + .to_string() +} + +/// A `Retry-After` may be an HTTP date: the client waits until then. +#[tokio::test(start_paused = true)] +async fn a_429_waits_until_its_retry_after_date() { + let mock = MockTransport::new(); + mock.push( + HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", http_date_in(120)), + ) + .push_data(shop()); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(mock.clone()) + .build() + .unwrap(); + + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + // The date has whole seconds: up to one less than asked. + let elapsed = started.elapsed(); + assert!( + elapsed > Duration::from_secs(118) && elapsed <= Duration::from_secs(120), + "{elapsed:?}" + ); + + // Past: sent again at once. Beyond `max_retry_after`: the caller gets it. + mock.clear(); + mock.push( + HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", http_date_in(-60)), + ) + .push_data(shop()); + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(started.elapsed(), Duration::ZERO); + + mock.clear(); + mock.push( + HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", http_date_in(600)), + ); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!( + matches!(error, Error::Throttled { retry_after: Some(wait), .. } if wait > Duration::from_secs(590)), + "{error:?}" + ); + assert_eq!(started.elapsed(), Duration::ZERO); +} From c635e8324f55e7398d7390f89befd3ad9a961051 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:46:29 +0200 Subject: [PATCH 018/135] fix: refuse a null default for a variable used where null is not allowed The spec (All Variable Usages Are Allowed) lets a nullable variable fill a non-null location only with a non-null default. `$id: ID = null` was taken as a default and passed. A "gid://..." default is still accepted. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + crates/shopify_api_graphql/src/analyze.rs | 21 ++++++++++++++++----- crates/shopify_api_graphql/tests/analyze.rs | 17 +++++++++++++++++ 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c991713..7a00429 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`, with typed input objects) or read from a file (`file("…graphql")`). - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. +- Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - Add: `shopify-api check` checks `.graphql` files against the schema. - Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`. diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index 0b7444c..ec9acd0 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -247,6 +247,7 @@ pub fn analyze(schema: &Schema, source: &str) -> Result { fragments, variables: Vec::new(), used_variables: BTreeSet::new(), + null_defaults: BTreeSet::new(), used_fragments: BTreeSet::new(), fragment_stack: Vec::new(), deprecations: Vec::new(), @@ -298,6 +299,9 @@ pub fn analyze(schema: &Schema, source: &str) -> Result { base, }); if let Some(default) = &definition.default_value { + if matches!(default, ast::Value::Null) { + analyzer.null_defaults.insert(definition.name.clone()); + } // The parser refuses a variable here. let expected = InputValue::of(ty); let place = format!("the default value of `${}`", definition.name); @@ -416,6 +420,9 @@ struct Analyzer<'a> { /// The declared variables, in the order of the operation. variables: Vec, used_variables: BTreeSet, + /// The variables whose default value is `null`: it does not stand in for + /// a value where `null` is not allowed. + null_defaults: BTreeSet, used_fragments: BTreeSet<&'a str>, fragment_stack: Vec<&'a str>, deprecations: Vec, @@ -963,8 +970,9 @@ impl<'a> Analyzer<'a> { } match value { ast::Value::Variable(name) => { + let null_default = self.null_defaults.contains(name); let variable = self.variable(name, position)?; - if !variable_fits(variable, expected) { + if !variable_fits(variable, null_default, expected) { return error_at( position, format!( @@ -1121,8 +1129,10 @@ fn fits_int(number: &ast::Number) -> bool { .is_some_and(|number| i32::try_from(number).is_ok()) } -/// The rule of the GraphQL specification for using a variable at a location. -fn variable_fits(variable: &Variable, location: &InputValue) -> bool { +/// The rule of the GraphQL specification for using a variable at a location +/// ("All Variable Usages Are Allowed"). `null_default`: the default value of +/// the variable is `null`. +fn variable_fits(variable: &Variable, null_default: bool, location: &InputValue) -> bool { fn compatible(variable: &TypeRef, location: &TypeRef) -> bool { match (variable, location) { (TypeRef::NonNull(variable), TypeRef::NonNull(location)) => { @@ -1136,8 +1146,9 @@ fn variable_fits(variable: &Variable, location: &InputValue) -> bool { } } if location.ty.is_non_null() && !variable.ty.is_non_null() { - // A nullable variable is accepted when a default value fills the gap. - return (variable.has_default || location.has_default) + // A nullable variable is accepted when a default value other than + // `null` fills the gap. + return ((variable.has_default && !null_default) || location.has_default) && compatible(&variable.ty, location.ty.nullable()); } compatible(&variable.ty, &location.ty) diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs index 5038dcf..8f016f8 100644 --- a/crates/shopify_api_graphql/tests/analyze.rs +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -232,12 +232,29 @@ fn accepts_literals_of_every_kind() { ); // An integer where an ID is expected, and a variable with a default for a non-null argument. check("query($id: ID = 1) { product(id: $id) { id } node(id: 2) { id } }"); + check(r#"query($id: ID = "gid://shopify/Product/1") { product(id: $id) { id } }"#); + check(r#"query($ids: [ID!] = ["gid://shopify/Product/1"]) { nodes(ids: $ids) { id } }"#); // A single value where a list is expected. check("{ nodes(ids: \"gid://shopify/Product/1\") { id } }"); } // ─── Refused ───────────────────────────────────────────────────────── +/// Only a default other than `null` lets a nullable variable fill a non-null place. +#[test] +fn refuses_a_null_default_for_a_non_null_place() { + assert_eq!( + refusal("query($id: ID = null) { product(id: $id) { id } }"), + "Variable `$id` of type `ID` cannot be used for argument `id` of `QueryRoot.product`, which expects `ID!` (line 1, column 25)" + ); + assert!( + refusal("query($ids: [ID!] = null) { nodes(ids: $ids) { id } }") + .starts_with("Variable `$ids` of type `[ID!]` cannot be used"), + ); + // Where `null` is allowed, a `null` default is fine. + check("query($after: String = null) { products(first: 1, after: $after) { nodes { id } } }"); +} + #[test] fn refuses_unknown_fields_and_arguments_with_a_suggestion() { assert_eq!( From 2a2ca323dec5db9bb5c79e5235db01c7d19a02bf Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:47:17 +0200 Subject: [PATCH 019/135] fix: refuse an input field given twice in one input object graphql-parser keeps input objects in a map, so in {id: "1", title: "old", title: "new"} the first title vanished before validation while the text sent to Shopify kept both. A small scan of the text applies Input Object Field Uniqueness before analysis. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api_graphql/src/analyze.rs | 10 + .../src/analyze/input_objects.rs | 213 ++++++++++++++++++ crates/shopify_api_graphql/tests/analyze.rs | 14 ++ 4 files changed, 238 insertions(+), 1 deletion(-) create mode 100644 crates/shopify_api_graphql/src/analyze/input_objects.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a00429..f724227 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`, with typed input objects) or read from a file (`file("…graphql")`). - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. -- Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected. +- Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, and an input field given twice in one input object. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - Add: `shopify-api check` checks `.graphql` files against the schema. - Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`. diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index ec9acd0..926ea06 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -1,6 +1,8 @@ //! Checks a GraphQL operation against a schema and describes the shape of //! its variables and of its result. +mod input_objects; + use std::collections::{BTreeMap, BTreeSet}; use std::fmt; @@ -179,6 +181,14 @@ pub fn analyze(schema: &Schema, source: &str) -> Result { } }; + // Checked on the text: the parser keeps only the last of the two. + if let Some((field, position)) = input_objects::duplicate_field(source) { + return error_at( + position, + format!("The input field `{field}` is given twice in the same input object"), + ); + } + let mut operations = Vec::new(); let mut fragments = BTreeMap::new(); for definition in &document.definitions { diff --git a/crates/shopify_api_graphql/src/analyze/input_objects.rs b/crates/shopify_api_graphql/src/analyze/input_objects.rs new file mode 100644 index 0000000..3c69999 --- /dev/null +++ b/crates/shopify_api_graphql/src/analyze/input_objects.rs @@ -0,0 +1,213 @@ +//! Input Object Field Uniqueness: `{ title: "a", title: "b" }` is invalid. +//! +//! The parser keeps input objects in a map, so the second `title` overwrites +//! the first and the analyzer never sees it, while the text Shopify receives +//! still holds both. The check reads the text itself. + +use graphql_parser::Pos; + +/// The first input field given twice in one input object of `source`, with +/// its position. `source` already parsed: anything unexpected ends the scan. +pub(super) fn duplicate_field(source: &str) -> Option<(&str, Pos)> { + let mut lexer = Lexer { + text: source, + position: 0, + }; + let mut frames: Vec> = Vec::new(); + let mut previous: Option> = None; + while let Some((token, start)) = lexer.next() { + match token { + Token::Punctuator(b'{') => { + // A value follows `:` (an argument or a field of an input + // object) or `=` (a default value), or stands in a list. + let object = matches!(previous, Some(Token::Punctuator(b':' | b'='))) + || matches!(frames.last(), Some(Frame::List)); + frames.push(if object { + Frame::Object(Vec::new()) + } else { + Frame::Other + }); + } + Token::Punctuator(b'[') => frames.push(Frame::List), + Token::Punctuator(b'(') => frames.push(Frame::Other), + Token::Punctuator(b'}' | b']' | b')') => { + frames.pop()?; + } + Token::Name(name) => { + // In an input object, a name is a field unless it is the value + // of one (an enum value, `true`, `null`) or of a variable. + if let Some(Frame::Object(fields)) = frames.last_mut() + && !matches!(previous, Some(Token::Punctuator(b':' | b'$'))) + { + if fields.contains(&name) { + return Some((name, position_of(source, start))); + } + fields.push(name); + } + } + _ => {} + } + previous = Some(token); + } + None +} + +enum Frame<'a> { + /// An input object, with the fields given so far. + Object(Vec<&'a str>), + List, + /// A selection set or arguments. + Other, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Token<'a> { + Name(&'a str), + Punctuator(u8), + /// A string, a number, or a punctuator of no use here. + Other, +} + +struct Lexer<'a> { + text: &'a str, + position: usize, +} + +impl<'a> Lexer<'a> { + /// The next token and where it starts, `None` at the end. + fn next(&mut self) -> Option<(Token<'a>, usize)> { + self.skip_ignored(); + let rest = &self.text.as_bytes()[self.position..]; + let &first = rest.first()?; + let start = self.position; + let (token, length) = match first { + b'A'..=b'Z' | b'a'..=b'z' | b'_' => { + let length = rest + .iter() + .position(|byte| !(byte.is_ascii_alphanumeric() || *byte == b'_')) + .unwrap_or(rest.len()); + (Token::Name(&self.text[start..start + length]), length) + } + b'"' if rest.starts_with(b"\"\"\"") => { + // A block string: its only escape is `\"""`. + let mut index = 3; + loop { + let tail = rest.get(index..).filter(|tail| !tail.is_empty())?; + if tail.starts_with(b"\\\"\"\"") { + index += 4; + } else if tail.starts_with(b"\"\"\"") { + break; + } else { + index += 1; + } + } + (Token::Other, index + 3) + } + b'"' => { + let mut index = 1; + loop { + match rest.get(index)? { + b'\\' => index += 2, + b'"' => break, + _ => index += 1, + } + } + (Token::Other, index + 1) + } + b'{' | b'}' | b'(' | b')' | b'[' | b']' | b':' | b'=' | b'$' => { + (Token::Punctuator(first), 1) + } + b'0'..=b'9' | b'-' => { + let length = rest + .iter() + .position(|byte| { + !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'+' | b'-')) + }) + .unwrap_or(rest.len()); + (Token::Other, length) + } + _ => { + let length = self.text[start..].chars().next().map_or(1, char::len_utf8); + (Token::Other, length) + } + }; + self.position += length; + Some((token, start)) + } + + /// Skips white space, line terminators, commas, comments and byte order marks. + fn skip_ignored(&mut self) { + loop { + let rest = &self.text.as_bytes()[self.position..]; + match rest.first() { + Some(b' ' | b'\t' | b'\n' | b'\r' | b',') => self.position += 1, + Some(0xEF) if rest.starts_with("\u{feff}".as_bytes()) => self.position += 3, + Some(b'#') => { + self.position += rest + .iter() + .position(|byte| matches!(byte, b'\n' | b'\r')) + .unwrap_or(rest.len()); + } + _ => return, + } + } + } +} + +/// The line and column of the byte `offset` of `source`, both from 1. +fn position_of(source: &str, offset: usize) -> Pos { + let before = &source[..offset]; + let line_start = before.rfind(['\n', '\r']).map_or(0, |index| index + 1); + Pos { + line: before.matches('\n').count() + before.matches('\r').count() + - before.matches("\r\n").count() + + 1, + column: before[line_start..].chars().count() + 1, + } +} + +#[cfg(test)] +mod tests { + use super::duplicate_field; + + fn duplicate(source: &str) -> Option<(&str, usize, usize)> { + duplicate_field(source).map(|(name, position)| (name, position.line, position.column)) + } + + #[test] + fn finds_a_field_given_twice_in_one_input_object() { + assert_eq!( + duplicate(r#"mutation { a(x: {id: "1", title: "old", title: "new"}) { id } }"#), + Some(("title", 1, 41)) + ); + // In a list, nested, in a default value, in a directive, on a later line. + assert_eq!( + duplicate("{ a(x: [{b: 1}, {b: 1, b: 2}]) { id } }"), + Some(("b", 1, 24)) + ); + assert_eq!(duplicate("{ a(x: {b: {c: 1, c: 2}}) }"), Some(("c", 1, 19))); + assert_eq!( + duplicate("query($x: In = {a: 1\n a: 2}) { a }"), + Some(("a", 2, 2)) + ); + assert_eq!(duplicate("{ a @d(x: {k: 1, k: 1}) }"), Some(("k", 1, 18))); + } + + #[test] + fn leaves_distinct_fields_and_selections_alone() { + for source in [ + // The same name in sibling objects, in a nested one, or as a value. + "{ a(x: [{b: 1}, {b: 2}]) { b b } }", + "{ a(x: {b: {b: 1}, c: B}) { id } }", + "{ a(x: {b: B, B: b, c: $b, d: null, null: true}) { id } }", + // Selection sets repeat fields legally. + "{ a { id id } b: a { id } }", + "query($x: [In!] = [{a: 1}]) { a(x: $x) { a a } }", + // Names in strings, block strings and comments are not fields. + r#"{ a(x: {b: "b: 1, b: 2", c: """ b: \""" b: """}) { id } }"#, + "{ a(x: {b: 1 # b: 2\n}) { id } }", + ] { + assert_eq!(duplicate(source), None, "{source}"); + } + } +} diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs index 8f016f8..7ee6100 100644 --- a/crates/shopify_api_graphql/tests/analyze.rs +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -240,6 +240,20 @@ fn accepts_literals_of_every_kind() { // ─── Refused ───────────────────────────────────────────────────────── +/// Input Object Field Uniqueness: the parser would keep one, Shopify gets both. +#[test] +fn refuses_an_input_field_given_twice() { + assert_eq!( + refusal( + r#"mutation { productUpdate(product: {id: "1", title: "old", title: "new"}) { product { id } } }"# + ), + "The input field `title` is given twice in the same input object (line 1, column 59)" + ); + check( + r#"mutation { productUpdate(product: {id: "1", title: "new"}) { product { id title } } }"#, + ); +} + /// Only a default other than `null` lets a nullable variable fill a non-null place. #[test] fn refuses_a_null_default_for_a_non_null_place() { From 148c4be6d5d8bfcb17e3ac496c9437986f193b33 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:49:36 +0200 Subject: [PATCH 020/135] fix: let keys below exclusive object types name different fields `... on ProductVariant { x: image { a: url } } ... on Collection { x: image { a: originalSrc } }` was refused: the subselections of `x` merged on Image and lost the fact that their parents can never both be present. Each place now carries the parent types above it; two places whose chains differ by two object types at some depth only need the same shape (FieldsInSetCanMerge / SameResponseShape). Same type or an interface still needs the same field and arguments. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api_graphql/src/analyze.rs | 71 ++++++++++++++------- crates/shopify_api_graphql/tests/analyze.rs | 40 ++++++++++++ 3 files changed, 89 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f724227..dd17d77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`, with typed input objects) or read from a file (`file("…graphql")`). - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. -- Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, and an input field given twice in one input object. +- Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, and an input field given twice in one input object. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - Add: `shopify-api check` checks `.graphql` files against the schema. - Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`. diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index 926ea06..3f6ebc1 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -324,7 +324,7 @@ pub fn analyze(schema: &Schema, source: &str) -> Result { OperationKind::Mutation => "MUTATION", }; analyzer.check_directives(directives, location)?; - let data = analyzer.selection(root, &[(selection_set, false)], position)?; + let data = analyzer.selection(root, &[(selection_set, false, Vec::new())], position)?; if let Some(unused) = analyzer .variables @@ -390,17 +390,27 @@ struct Pending<'a> { /// The field may be absent from a value of the parent. conditional: bool, /// The subfields selected at each place, with whether that place may - /// be absent when the field is present. - sets: Vec<(&'a SelectionSet<'a>, bool)>, + /// be absent when the field is present, and the place's [`Lineage`]. + sets: Vec>, /// The selections of the parent (see [`Analyzer::selection`]) that select /// the field unconditionally. unconditional_in: BTreeSet, position: Pos, } +/// A selection set, whether the place that selected it may be absent while +/// the value is present, and the [`Lineage`] of that place. +type SubSet<'a> = (&'a SelectionSet<'a>, bool, Lineage); + +/// The parent type of a place and of each field above it, from the root: +/// two places whose lineages differ by two object types at some depth are +/// never both in one answer. +type Lineage = Vec; + /// One place a response key is selected at. struct Origin { - parent: String, + /// Its parent type last. + lineage: Lineage, field: String, arguments: String, } @@ -456,15 +466,10 @@ impl<'a> Analyzer<'a> { /// others select is conditional. When none is, any of them may be the /// one that is there: a subfield is then certain only if every place /// selects it. - fn selection( - &mut self, - parent: &str, - sets: &[(&'a SelectionSet<'a>, bool)], - position: Pos, - ) -> Result { - let any_certain = sets.iter().any(|(_, conditional)| !conditional); + fn selection(&mut self, parent: &str, sets: &[SubSet<'a>], position: Pos) -> Result { + let any_certain = sets.iter().any(|(_, conditional, _)| !conditional); let mut pending = Vec::new(); - for (index, (set, conditional)) in sets.iter().enumerate() { + for (index, (set, conditional, lineage)) in sets.iter().enumerate() { let place = Place { index, // Several places that may each be the one there: what each @@ -476,6 +481,7 @@ impl<'a> Analyzer<'a> { set, any_certain && *conditional, place, + lineage, &mut pending, )?; } @@ -545,6 +551,7 @@ impl<'a> Analyzer<'a> { set: &'a SelectionSet<'a>, conditional: bool, place: Place, + lineage: &[String], pending: &mut Vec>, ) -> Result<()> { for item in &set.items { @@ -555,8 +562,18 @@ impl<'a> Analyzer<'a> { let ty = self.field_type(parent, field)?; let key = field.alias.as_ref().unwrap_or(&field.name).clone(); let arguments = arguments_key(&field.arguments); - let sets = (!field.selection_set.items.is_empty()) - .then_some((&field.selection_set, conditional || place.uncertain)); + let origin_lineage: Lineage = lineage + .iter() + .cloned() + .chain([parent.to_string()]) + .collect(); + let sets = (!field.selection_set.items.is_empty()).then(|| { + ( + &field.selection_set, + conditional || place.uncertain, + origin_lineage.clone(), + ) + }); match pending.iter_mut().find(|existing| existing.key == key) { Some(existing) => { @@ -572,12 +589,10 @@ impl<'a> Analyzer<'a> { } // FieldsInSetCanMerge: on two different object // types, never both there, the fields and their - // arguments may differ; elsewhere they may not. + // arguments may differ, and so may those below + // them; elsewhere they may not. for origin in &existing.origins { - let exclusive = origin.parent != parent - && self.is_object(parent) - && self.is_object(&origin.parent); - if !exclusive { + if !self.exclusive(&origin.lineage, &origin_lineage) { if origin.field != field.name { return error_at( field.position, @@ -599,7 +614,7 @@ impl<'a> Analyzer<'a> { } } existing.origins.push(Origin { - parent: parent.to_string(), + lineage: origin_lineage, field: field.name.clone(), arguments, }); @@ -614,7 +629,7 @@ impl<'a> Analyzer<'a> { field: field.name.clone(), ty, origins: vec![Origin { - parent: parent.to_string(), + lineage: origin_lineage, field: field.name.clone(), arguments, }], @@ -643,6 +658,7 @@ impl<'a> Analyzer<'a> { &fragment.selection_set, conditional | !always, place, + lineage, pending, )?; } @@ -677,6 +693,7 @@ impl<'a> Analyzer<'a> { &fragment.selection_set, conditional | !always, place, + lineage, pending, ); self.fragment_stack.pop(); @@ -687,13 +704,21 @@ impl<'a> Analyzer<'a> { Ok(()) } - /// Whether every value of type `parent` matches a fragment on `condition`. - /// Fails when none can. /// An object type, as opposed to an interface or a union. fn is_object(&self, name: &str) -> bool { matches!(self.schema.get(name), Some(TypeDef::Object { .. })) } + /// Two places never both in one answer: at some depth, their parents are + /// two different object types. + fn exclusive(&self, left: &[String], right: &[String]) -> bool { + left.iter() + .zip(right) + .any(|(left, right)| left != right && self.is_object(left) && self.is_object(right)) + } + + /// Whether every value of type `parent` matches a fragment on `condition`. + /// Fails when none can. fn fragment_always_applies( &self, parent: &str, diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs index 7ee6100..30d6be4 100644 --- a/crates/shopify_api_graphql/tests/analyze.rs +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -773,3 +773,43 @@ fn one_key_may_name_different_fields_on_different_object_types() { .contains("`label` is selected twice with different fields or types") ); } + +/// Below two exclusive object types, only the shapes must agree, at every +/// depth: `a` may be `url` on one side and `originalSrc` on the other. +/// Where both sides can be in one answer, the fields must still match. +#[test] +fn keys_below_exclusive_object_types_may_name_different_fields() { + let operation = check( + "query($id: ID!) { node(id: $id) { ... on ProductVariant { x: image { a: url } } ... on Collection { x: image { a: originalSrc } } } }", + ); + let node = child(&operation.data, "node"); + assert_eq!(fields(node), ["x?: Image"]); + assert_eq!(fields(child(node, "x")), ["a: URL!"]); + + // Two levels down, the same. + check( + "query($id: ID!) { node(id: $id) { ... on Product { m: metafield(key: \"a\") { d: definition { n: name } } } ... on Order { m: metafield(key: \"b\") { d: definition { n: namespace } } } } }", + ); + + // The same object type on both sides: the subfields must match. + assert!( + refusal( + "query($id: ID!) { node(id: $id) { ... on ProductVariant { x: image { a: url } } ... on ProductVariant { x: image { a: originalSrc } } } }" + ) + .contains("`a` is selected twice with different fields or types (`url: URL!` and `originalSrc: URL!`)") + ); + // An interface on one side: both may be there. + assert!( + refusal( + "query($id: ID!) { node(id: $id) { ... on Node { x: id } ... on Product { x: handle } } }" + ) + .contains("`x` is selected twice") + ); + // Shapes still must agree below exclusive types. + assert!( + refusal( + "query($id: ID!) { node(id: $id) { ... on ProductVariant { x: image { a: url } } ... on Collection { x: image { a: altText } } } }" + ) + .contains("`a` is selected twice with different fields or types") + ); +} From a4cf55a8054ff413c0a4b7ccf35ff429d590ae61 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:40:57 +0200 Subject: [PATCH 021/135] fix: keep GraphQL error extensions out of Debug GraphQL Ruby answers a variable that does not validate with its whole value under extensions.value, so a signed originalSource reached logs through {:?} of Error::Graphql. GraphqlError's Debug now shows the message, locations, path, extensions.code and only the names of the other extensions. errors that are neither a list nor a string keep their value in extensions.value instead of the message. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api/src/graphql/response.rs | 62 ++++++++++++++++++++-- crates/shopify_api/tests/graphql.rs | 48 +++++++++++++++++ 3 files changed, 107 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dd17d77..0663175 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `oauth`: `ShopifyApp` with install links, callback and admin launch verification, code exchange, session tokens and token exchange, app proxies. - Add: `Transport` trait, `ReqwestTransport` (redirections always off, `from_builder` for your own settings), and `testing::MockTransport`, with `testing::client`, which retries without waiting, even for a scripted `Retry-After`. - Add: token renewals run in a task of their own: a cancelled request does not lose a rotated refresh token. A failed renewal answers the requests waiting for it. -- Add: errors never hold a query string (signed bulk result addresses stay out of logs), and the `Debug` of `GraphqlErrors` names the fields of partial `data` without their values; `Error::Http` carries Shopify's `X-Request-Id`. +- Add: errors never hold a query string (signed bulk result addresses stay out of logs), the `Debug` of `GraphqlErrors` names the fields of partial `data` without their values, and that of `GraphqlError` shows `extensions.code` and only the names of the other extensions (Shopify echoes an invalid variable's whole value in `extensions.value`); `Error::Http` carries Shopify's `X-Request-Id`. - Add: `ShopDomain` refuses anything but `` or `.myshopify.com`. - Breaking: `Shopify::new(shop, auth)` and `Shopify::builder`; `ShopifyAuth` is `Auth`; `ShopifyConfig` is gone; `ShopifyAPIError` is `Error`. - Breaking: `graphql` returns `data` as a `Value` and `graphql_as` reads it as a type; `post_graphql` and the `graphql-client` feature are gone. diff --git a/crates/shopify_api/src/graphql/response.rs b/crates/shopify_api/src/graphql/response.rs index 5f59823..0f87e22 100644 --- a/crates/shopify_api/src/graphql/response.rs +++ b/crates/shopify_api/src/graphql/response.rs @@ -1,11 +1,18 @@ //! What a GraphQL answer holds besides `data`: errors, user errors, cost. +use std::fmt; + use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json::Value; /// An entry of the `errors` of an answer. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +/// +/// Its `Debug` shows `extensions.code` and the names of the other entries of +/// `extensions`, not their values: Shopify puts the whole value of a variable +/// that does not validate in `extensions.value`, a signed address included. +/// The fields themselves stay available. +#[derive(Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct GraphqlError { pub message: String, @@ -18,6 +25,37 @@ pub struct GraphqlError { pub extensions: Option, } +impl fmt::Debug for GraphqlError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("GraphqlError") + .field("message", &self.message) + .field("locations", &self.locations) + .field("path", &self.path) + .field("extensions", &self.extensions.as_ref().map(ExtensionsShape)) + .finish() + } +} + +/// `extensions.code`, and the names of the other entries without their values. +struct ExtensionsShape<'a>(&'a Value); + +impl fmt::Debug for ExtensionsShape<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let Value::Object(entries) = self.0 else { + return formatter.write_str(".."); + }; + let mut shown = formatter.debug_map(); + for (key, value) in entries { + match value { + Value::String(code) if key == "code" => shown.entry(key, code), + _ => shown.entry(key, &format_args!("..")), + }; + } + shown.finish() + } +} + impl GraphqlError { /// `extensions.code`, such as `THROTTLED`, `ACCESS_DENIED` or `MAX_COST_EXCEEDED`. pub fn code(&self) -> Option<&str> { @@ -112,7 +150,8 @@ pub struct RawResponse { } /// `errors` is a list of errors; Shopify answers a few refusals with a -/// string instead (`"errors": "Not Found"`). +/// string instead (`"errors": "Not Found"`). Anything else is one error whose +/// `extensions.value` holds it. fn errors<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { @@ -132,11 +171,12 @@ fn errors<'de, D: serde::Deserializer<'de>>( path: None, extensions: None, }], + // Kept in `extensions.value`, out of the message an error displays. Some(Errors::Other(value)) => vec![GraphqlError { - message: value.to_string(), + message: "Shopify answered `errors` that are neither a list nor a string".to_string(), locations: None, path: None, - extensions: None, + extensions: Some(serde_json::json!({ "value": value })), }], }) } @@ -200,6 +240,20 @@ mod tests { assert!(raw.errors.is_empty()); } + #[test] + fn errors_of_another_shape_keep_their_value_out_of_the_message() { + let raw: RawResponse = + serde_json::from_str(r#"{"errors":{"token":"shpat_SECRET"}}"#).unwrap(); + assert_eq!(raw.errors.len(), 1); + let error = &raw.errors[0]; + assert!(!error.message.contains("SECRET"), "{}", error.message); + assert!(!format!("{error:?}").contains("SECRET"), "{error:?}"); + assert_eq!( + error.extensions.as_ref().unwrap()["value"]["token"], + "shpat_SECRET" + ); + } + #[test] fn decoding_names_the_path_of_the_mismatch() { #[derive(Debug, Deserialize)] diff --git a/crates/shopify_api/tests/graphql.rs b/crates/shopify_api/tests/graphql.rs index a5b84f1..d6509d1 100644 --- a/crates/shopify_api/tests/graphql.rs +++ b/crates/shopify_api/tests/graphql.rs @@ -238,6 +238,54 @@ async fn graphql_errors_fail_the_operation_and_keep_partial_data() { assert_eq!(raw.data, Some(json!({ "shop": null }))); } +#[tokio::test] +async fn an_error_shows_no_value_shopify_echoes_in_its_extensions() { + // What GraphQL Ruby answers to a variable that does not validate: the + // whole value, a signed address included, under `extensions.value`. + let mock = MockTransport::new(); + mock.push_json(json!({ "errors": [{ + "message": "Variable $media of type [CreateMediaInput!] was provided invalid value for 0.mediaContentType (Expected \"INVALID\" to be one of: IMAGE, VIDEO)", + "locations": [{ "line": 1, "column": 10 }], + "extensions": { + "value": [{ + "originalSource": "https://storage.test/image.jpg?X-Goog-Signature=SIGNED_SECRET", + "mediaContentType": "INVALID", + }], + "problems": [{ "path": [0, "mediaContentType"], "explanation": "Expected \"INVALID\" to be one of: IMAGE, VIDEO" }], + "code": "INVALID_VARIABLE", + }, + }] })); + let shopify = client(&mock); + + let error = shopify + .graphql( + "mutation($media: [CreateMediaInput!]) { productCreate(media: $media) { product { id } } }", + json!({ "media": [{ + "originalSource": "https://storage.test/image.jpg?X-Goog-Signature=SIGNED_SECRET", + "mediaContentType": "INVALID", + }] }), + ) + .await + .unwrap_err(); + for shown in [ + format!("{error}"), + format!("{error:?}"), + format!("{error:#?}"), + format!("{:?}", error.graphql_errors()), + ] { + assert!(!shown.contains("SIGNED_SECRET"), "{shown}"); + assert!(!shown.contains("storage.test"), "{shown}"); + } + let debug = format!("{error:?}"); + assert!(debug.contains(r#""code": "INVALID_VARIABLE""#), "{debug}"); + assert!(debug.contains(r#""value": .."#), "{debug}"); + assert!(debug.contains(r#""problems": .."#), "{debug}"); + assert!(debug.contains("Variable $media"), "{debug}"); + // The values stay available to the caller. + let extensions = error.graphql_errors()[0].extensions.as_ref().unwrap(); + assert!(extensions["value"][0]["originalSource"].is_string()); +} + #[tokio::test] async fn an_answer_that_does_not_fit_names_the_path() { let mock = MockTransport::new(); From 2cd392a0ba103e6fb31eeedf3b427e11aa559d19 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:44:46 +0200 Subject: [PATCH 022/135] fix: keep secrets out of what an error displays MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Error documented that secrets never appear in it; decode and HTTP errors did not hold to it. - Error::Decode (and the token endpoint and variables errors) keep the path and the kinds of value, not the values serde quotes: 'invalid type: string "…"' becomes 'invalid type: string'. - Error::Http shows at most 1 KiB of the body, with address query strings, token-like words (shp…_ prefixes, JWTs, long mixed letters and digits) and the values of secret-named entries replaced by [redacted], in Display and Debug. The whole body stays available through Error::raw_http_body and the new raw_body: RawBody field, whose Debug shows its length only. - The doc of Error states what is guaranteed and what is shown as is. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- MIGRATION.md | 4 +- crates/shopify_api/src/auth.rs | 12 +- crates/shopify_api/src/bulk.rs | 13 +- crates/shopify_api/src/error.rs | 170 ++++++- crates/shopify_api/src/graphql.rs | 2 +- crates/shopify_api/src/graphql/response.rs | 6 +- crates/shopify_api/src/lib.rs | 3 +- crates/shopify_api/src/redact.rs | 500 +++++++++++++++++++++ crates/shopify_api/src/schema.rs | 12 +- crates/shopify_api/src/webhooks.rs | 8 +- crates/shopify_api/tests/auth.rs | 34 ++ 12 files changed, 714 insertions(+), 52 deletions(-) create mode 100644 crates/shopify_api/src/redact.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 0663175..35ecdaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `oauth`: `ShopifyApp` with install links, callback and admin launch verification, code exchange, session tokens and token exchange, app proxies. - Add: `Transport` trait, `ReqwestTransport` (redirections always off, `from_builder` for your own settings), and `testing::MockTransport`, with `testing::client`, which retries without waiting, even for a scripted `Retry-After`. - Add: token renewals run in a task of their own: a cancelled request does not lose a rotated refresh token. A failed renewal answers the requests waiting for it. -- Add: errors never hold a query string (signed bulk result addresses stay out of logs), the `Debug` of `GraphqlErrors` names the fields of partial `data` without their values, and that of `GraphqlError` shows `extensions.code` and only the names of the other extensions (Shopify echoes an invalid variable's whole value in `extensions.value`); `Error::Http` carries Shopify's `X-Request-Id`. +- Add: what an error displays holds no secret the crate knows of (`Error` documents what is and is not shown): no query string (signed bulk result addresses stay out of logs); `Error::Decode` keeps the path and the kinds of value, not the value; `Error::Http` shows at most 1 KiB of the body, with query strings, token-like words and the values of secret-named entries redacted, and `Error::raw_http_body` (or the `raw_body: RawBody` field) gives the whole body; the `Debug` of `GraphqlErrors` names the fields of partial `data` without their values, and that of `GraphqlError` shows `extensions.code` and only the names of the other extensions (Shopify echoes an invalid variable's whole value in `extensions.value`); `Error::Http` carries Shopify's `X-Request-Id`. - Add: `ShopDomain` refuses anything but `` or `.myshopify.com`. - Breaking: `Shopify::new(shop, auth)` and `Shopify::builder`; `ShopifyAuth` is `Auth`; `ShopifyConfig` is gone; `ShopifyAPIError` is `Error`. - Breaking: `graphql` returns `data` as a `Value` and `graphql_as` reads it as a type; `post_graphql` and the `graphql-client` feature are gone. diff --git a/MIGRATION.md b/MIGRATION.md index baf2644..41846c1 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -50,10 +50,10 @@ to keep that. | 0.10 | 1.0 | | --- | --- | | `ConnectionFailed(reqwest::Error)` | `Transport { url, source }` | -| An `error_for_status` failure | `Http { status, url, body }`; `error.status()`, `error.is_unauthorized()` | +| An `error_for_status` failure | `Http { status, url, body, .. }`: `body` is cut at 1 KiB and redacted; `error.raw_http_body()` gives the whole body, secrets included; `error.status()`, `error.is_unauthorized()` | | `Throttled` | `Throttled { retries, cost, retry_after }`, once the retries are spent or when `Retry-After` exceeds `max_retry_after` | | `GraphqlErrors(Vec)` | `Graphql(GraphqlErrors { errors, data })` | -| `JsonParseError` | `Json`, or `Decode { path, message }` when `data` does not fit its type | +| `JsonParseError` | `Json`, or `Decode { path, message }` when `data` does not fit its type: the path and the kinds of value, not the value | | `NotWantedJsonFormat`, `NotJson`, `ResponseBroken` | `Decode` | | `Authentication(text)` | `Auth(text)` | | `MissingGraphqlData`, `InvalidHeaderValue`, `Other` | Gone | diff --git a/crates/shopify_api/src/auth.rs b/crates/shopify_api/src/auth.rs index bd0a5a1..a554c96 100644 --- a/crates/shopify_api/src/auth.rs +++ b/crates/shopify_api/src/auth.rs @@ -359,12 +359,11 @@ pub(crate) async fn request_token( .get("error_description") .and_then(serde_json::Value::as_str); let detail = match (code, description) { - (Some(code), Some(description)) => format!("{code}: {description}"), - (Some(code), None) => code.to_string(), - _ => { - let text = response.text(); - text.chars().take(300).collect() + (Some(code), Some(description)) => { + crate::redact::http_body(format!("{code}: {description}").as_bytes()) } + (Some(code), None) => crate::redact::http_body(code.as_bytes()), + _ => crate::redact::http_body(&response.body), }; return Err(Error::Auth(format!( "the token endpoint of {shop} answered {}: {detail}", @@ -373,7 +372,8 @@ pub(crate) async fn request_token( } let parsed: TokenResponse = serde_json::from_slice(&response.body).map_err(|error| { Error::Auth(format!( - "the token endpoint of {shop} answered an invalid token: {error}" + "the token endpoint of {shop} answered an invalid token: {}", + crate::redact::serde_message(&error.to_string()) )) })?; Ok(parsed.into_token()) diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index d279204..7355216 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -635,13 +635,10 @@ pub fn parse_jsonl(body: &[u8]) -> Result> { let inner = error.inner(); let position = format!(" at line {} column {}", inner.line(), inner.column()); let message = inner.to_string(); - Error::Decode { - path: format!("line {}: {}", index + 1, error.path()), - message: message - .strip_suffix(&position) - .unwrap_or(&message) - .to_string(), - } + Error::decode( + format!("line {}: {}", index + 1, error.path()), + message.strip_suffix(&position).unwrap_or(&message), + ) }) }) .collect() @@ -731,7 +728,7 @@ mod tests { let error = parse_jsonl::(b"{\"id\":\"a\"}\n{\"id\":2}\n").unwrap_err(); assert_eq!( error.to_string(), - "Shopify's answer does not match the operation at `line 2: id`: invalid type: integer `2`, expected a string" + "Shopify's answer does not match the operation at `line 2: id`: invalid type: integer, expected a string" ); } diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index f1c1c26..125626c 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -10,9 +10,31 @@ pub type Result = std::result::Result; /// What went wrong, with what Shopify said about it. /// -/// Secrets never appear in an error: no access token, client secret or -/// refresh token, and no query string of an address, which may be signed -/// (the results of a bulk operation). +/// What an error displays (`Display`, `Debug`, `{:#?}`) and what its +/// [`source`](std::error::Error::source) chain displays holds no secret the +/// crate knows of: +/// +/// - no access token, refresh token or client secret; +/// - no query string or fragment of an address, which may be signed (the +/// results of a bulk operation, a staged upload); +/// - no value of the answer: [`Error::Decode`] names the path and the kinds +/// of value, without the value; the `data` and the `extensions` of a +/// GraphQL error show the names of their entries, not their values; +/// - of a body that is not a success, [`Error::Http`] shows at most 1 KiB, +/// with query strings, words that look like a token (Shopify's `shp…_` +/// prefixes, JWTs, 32 letters and digits or more) and the values of entries +/// named like a secret (`access_token`, `X-Goog-Signature`, +/// `Authorization`, …) replaced by `[redacted]`. +/// +/// What is shown as is: the messages Shopify writes (in `errors` and +/// `userErrors`), which may quote a part of a variable that does not +/// validate; the messages of your [`Transport`](crate::transport::Transport) +/// and of your [`TokenStore`](crate::TokenStore); and what a type's own +/// `Deserialize` implementation writes outside quotes. +/// +/// The values themselves stay available where you ask for them: +/// [`GraphqlErrors::data`], [`GraphqlError::extensions`] and +/// [`Error::raw_http_body`]. #[derive(Debug, thiserror::Error)] #[non_exhaustive] pub enum Error { @@ -41,10 +63,14 @@ pub enum Error { status: u16, /// The address, without its query string. url: String, - /// The body of the answer, cut at 2 KiB. + /// The body of the answer, cut at 1 KiB, with what looks like a + /// secret replaced by `[redacted]` (see [`Error`]). body: String, /// Shopify's `X-Request-Id`, which its support asks for. request_id: Option, + /// The whole body, as it was received. It may hold secrets: read it + /// with [`Error::raw_http_body`]. Its `Debug` shows its length only. + raw_body: RawBody, }, /// The answer has a non-empty `errors` list. @@ -140,6 +166,18 @@ impl Error { } } + /// The whole body of the answer, for [`Error::Http`], exactly as it was + /// received: unlike `body`, nothing is cut or redacted. + /// + /// **It may contain secrets** (a token, a signed address): do not log it + /// or show it to a user. + pub fn raw_http_body(&self) -> Option<&[u8]> { + match self { + Self::Http { raw_body, .. } => Some(raw_body.as_bytes()), + _ => None, + } + } + /// The errors Shopify returned, for [`Error::Graphql`]. pub fn graphql_errors(&self) -> &[GraphqlError] { match self { @@ -165,27 +203,50 @@ impl Error { ) } - fn http_parts(status: u16, url: &str, body: &[u8], request_id: Option) -> Self { - const LIMIT: usize = 2048; - let text = String::from_utf8_lossy(body); - let body = if text.len() > LIMIT { - let mut end = LIMIT; - while !text.is_char_boundary(end) { - end -= 1; - } - format!("{}…", &text[..end]) - } else { - text.into_owned() - }; + pub(crate) fn http_parts( + status: u16, + url: &str, + body: &[u8], + request_id: Option, + ) -> Self { Self::Http { status, url: without_query(url), - body, + body: crate::redact::http_body(body), request_id, + raw_body: RawBody(body.to_vec()), + } + } + + /// An answer that does not fit its type: serde's message without the + /// values it quotes. + pub(crate) fn decode(path: impl Into, message: &str) -> Self { + Self::Decode { + path: path.into(), + message: crate::redact::serde_message(message), } } } +/// The body of an answer exactly as it was received, in [`Error::Http`]. +/// +/// **It may contain secrets.** Its `Debug` shows its length, not its content. +#[derive(Clone, PartialEq, Eq, Default)] +pub struct RawBody(Vec); + +impl RawBody { + /// The bytes of the body. They may contain secrets: do not log them. + pub fn as_bytes(&self) -> &[u8] { + &self.0 + } +} + +impl fmt::Debug for RawBody { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "RawBody([{} bytes])", self.0.len()) + } +} + /// `url` without its query string and fragment, which may hold a signature. pub(crate) fn without_query(url: &str) -> String { url.split(['?', '#']).next().unwrap_or_default().to_string() @@ -283,12 +344,85 @@ mod tests { panic!("an HTTP error"); }; assert!(body.ends_with('…')); - assert!(body.len() <= 2048 + '…'.len_utf8()); + assert!(body.len() <= 1024 + '…'.len_utf8()); assert_eq!(url, "https://storage.example.com/results.jsonl"); assert!(!error.to_string().contains("secret")); assert_eq!(error.status(), Some(500)); assert_eq!(error.request_id(), Some("a1b2")); assert!(!error.is_unauthorized()); + assert_eq!(error.raw_http_body().unwrap().len(), 4000); + } + + #[test] + fn http_errors_show_no_secret_of_their_body() { + // A storage error that echoes the signed request, a token endpoint + // that echoes the token. + let raw = concat!( + "SignatureDoesNotMatch
GET /b/r.jsonl?X-Goog-Credential=CRED_SECRET", + "&X-Goog-Signature=SIG_SECRET https://storage.googleapis.com/b/r.jsonl?X-Goog-Signature=URL_SECRET
", + r#" {"access_token":"shpat_TOKEN_SECRET","scope":"read_orders"}"#, + ); + let error = Error::http_parts( + 403, + "https://storage.googleapis.com/b/r.jsonl", + raw.as_bytes(), + None, + ); + for shown in [ + format!("{error}"), + format!("{error:?}"), + format!("{error:#?}"), + ] { + for secret in ["CRED_SECRET", "SIG_SECRET", "URL_SECRET", "TOKEN_SECRET"] { + assert!(!shown.contains(secret), "{secret} in {shown}"); + } + assert!(shown.contains("SignatureDoesNotMatch"), "{shown}"); + assert!(shown.contains("read_orders"), "{shown}"); + } + assert!(format!("{error:?}").contains("RawBody(["), "{error:?}"); + // Asked for explicitly, the body is whole. + assert_eq!(error.raw_http_body(), Some(raw.as_bytes())); + assert_eq!(Error::Variables(String::new()).raw_http_body(), None); + } + + #[test] + fn json_errors_say_where_not_what() { + let source = + br#"{"data": {"url": "https://x.test/r?sig=SIGNED_SECRET"}, shpat_TOKEN_SECRET}"#; + let error: Error = serde_json::from_slice::(source) + .unwrap_err() + .into(); + let mut shown = format!("{error} {error:?} {error:#?}"); + let mut source = std::error::Error::source(&error); + while let Some(cause) = source { + shown.push_str(&format!(" {cause} {cause:?}")); + source = cause.source(); + } + assert!(!shown.contains("SECRET"), "{shown}"); + assert!(shown.contains("line 1 column"), "{shown}"); + } + + #[test] + fn decode_errors_keep_kinds_not_values() { + #[derive(Debug, serde::Deserialize)] + #[allow(dead_code)] + struct Data { + count: u64, + } + let value = serde_json::json!({ "count": "https://x.test/r.jsonl?sig=SIGNED_SECRET" }); + let error = crate::graphql::decode::(value).unwrap_err(); + for shown in [ + format!("{error}"), + format!("{error:?}"), + format!("{error:#?}"), + ] { + assert!(!shown.contains("SIGNED_SECRET"), "{shown}"); + assert!(!shown.contains("x.test"), "{shown}"); + } + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `count`: invalid type: string, expected u64" + ); } #[test] diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index 350ce59..066ae5b 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -94,7 +94,7 @@ impl Shopify { /// A throttled request is still retried. pub async fn graphql_raw(&self, query: &str, variables: impl Serialize) -> Result { let variables = match serde_json::to_value(variables) - .map_err(|error| Error::Variables(error.to_string()))? + .map_err(|error| Error::Variables(crate::redact::serde_message(&error.to_string())))? { Value::Null => Map::new(), Value::Object(variables) => variables, diff --git a/crates/shopify_api/src/graphql/response.rs b/crates/shopify_api/src/graphql/response.rs index 0f87e22..f214372 100644 --- a/crates/shopify_api/src/graphql/response.rs +++ b/crates/shopify_api/src/graphql/response.rs @@ -201,10 +201,8 @@ impl RawResponse { /// Reads `value` as `T`, naming the path of the first field that does not fit. pub(crate) fn decode(value: Value) -> crate::Result { - serde_path_to_error::deserialize(value).map_err(|error| crate::Error::Decode { - path: error.path().to_string(), - message: error.inner().to_string(), - }) + serde_path_to_error::deserialize(value) + .map_err(|error| crate::Error::decode(error.path().to_string(), &error.inner().to_string())) } #[cfg(test)] diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index 476085f..81bdf8c 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -62,6 +62,7 @@ mod client; mod error; mod graphql; mod pagination; +mod redact; pub mod schema; mod shop; pub mod transport; @@ -79,7 +80,7 @@ pub mod webhooks; pub use auth::{AssociatedUser, Auth, TokenData, TokenStore}; pub use client::{RetryPolicy, Shopify, ShopifyBuilder, USER_AGENT}; -pub use error::{Error, GraphqlErrors, Result}; +pub use error::{Error, GraphqlErrors, RawBody, Result}; pub use graphql::{ Cost, GraphqlError, IntoVariable, Location, Operation, OperationKind, RawResponse, Response, ThrottleStatus, UserError, diff --git a/crates/shopify_api/src/redact.rs b/crates/shopify_api/src/redact.rs new file mode 100644 index 0000000..4710b5a --- /dev/null +++ b/crates/shopify_api/src/redact.rs @@ -0,0 +1,500 @@ +//! What an error keeps of a text that may hold a secret: a serde message +//! without the values it quotes, a body without addresses' query strings, +//! tokens or signatures. + +/// The longest body an [`Error::Http`](crate::Error::Http) shows, in bytes. +pub(crate) const BODY_LIMIT: usize = 1024; + +/// What is read of a body before it is redacted, then cut at [`BODY_LIMIT`]. +const BODY_SCAN: usize = 16 * 1024; + +const REDACTED: &str = "[redacted]"; + +/// A serde or serde_json message without the values it quotes: +/// `invalid type: string "…", expected u64` becomes +/// `invalid type: string, expected u64`. What the type expects, the names of +/// its fields and the position in the text stay. +/// +/// A message of another shape, which a type's own `Deserialize` wrote, loses +/// whatever it quotes between `"` or backticks. +pub(crate) fn serde_message(message: &str) -> String { + for prefix in ["invalid type: ", "invalid value: "] { + if let Some(rest) = message.strip_prefix(prefix) { + let (kind, rest) = unexpected(rest); + return format!("{prefix}{kind}{rest}"); + } + } + for (prefix, separators) in [ + ( + "unknown variant `", + ["`, expected ", "`, there are no variants"], + ), + ( + "unknown field `", + ["`, expected ", "`, there are no fields"], + ), + ] { + if let Some(rest) = message.strip_prefix(prefix) { + // The name is the input's, and may hold the separator: the last + // one is serde's. + if let Some(end) = separators + .iter() + .filter_map(|separator| rest.rfind(separator)) + .max() + { + let what = prefix.trim_end_matches(" `"); + return format!("{what}{}", &rest[end + 1..]); + } + return prefix.trim_end_matches(" `").to_string(); + } + } + // `missing field `name``, `duplicate field `name``, `invalid length 3, + // expected …`: names of the type, counts. serde_json's syntax errors + // quote one punctuator at most. + if message.starts_with("missing field `") + || message.starts_with("duplicate field `") + || message.starts_with("invalid length ") + { + return message.to_string(); + } + without_quoted(message) +} + +/// The kind of an `Unexpected` value without the value, and what follows it. +fn unexpected(text: &str) -> (&'static str, &str) { + // `string "…"`: the string as `Debug` writes it, quotes escaped. + if let Some(rest) = text.strip_prefix("string \"") { + let mut escaped = false; + for (index, character) in rest.char_indices() { + match character { + '\\' if !escaped => escaped = true, + '"' if !escaped => return ("string", &rest[index + 1..]), + _ => escaped = false, + } + } + return ("string", ""); + } + for kind in ["boolean", "integer", "floating point", "character"] { + if let Some(rest) = text + .strip_prefix(kind) + .and_then(|rest| rest.strip_prefix(" `")) + { + // A character may be a backtick itself: skip one before looking. + let skip = if kind == "character" { + rest.chars().next().map_or(0, char::len_utf8) + } else { + 0 + }; + return match rest[skip..].find('`') { + Some(end) => (kind, &rest[skip + end + 1..]), + None => (kind, ""), + }; + } + } + for kind in [ + "byte array", + "unit value", + "Option value", + "newtype struct", + "sequence", + "map", + "enum", + "unit variant", + "newtype variant", + "tuple variant", + "struct variant", + "null", + ] { + if let Some(rest) = text.strip_prefix(kind) + && (rest.is_empty() || rest.starts_with(',')) + { + return (kind, rest); + } + } + // `Unexpected::Other`, written by the type: its text up to serde's + // separator is left out. + match text.rfind(", expected ") { + Some(end) => ("a value", &text[end..]), + None => ("a value", ""), + } +} + +/// `text` without what it quotes between `"` or backticks, except a single +/// character (serde_json's ``expected `,` or `}` ``). +fn without_quoted(text: &str) -> String { + let mut kept = String::with_capacity(text.len()); + let mut rest = text; + while let Some(start) = rest.find(['"', '`']) { + let quote = rest[start..].chars().next().unwrap_or('"'); + kept.push_str(&rest[..=start]); + let inside = &rest[start + 1..]; + let Some(end) = inside.find(quote) else { + kept.push('…'); + kept.push(quote); + return kept; + }; + if inside[..end].chars().count() <= 1 { + kept.push_str(&inside[..end]); + } else { + kept.push('…'); + } + kept.push(quote); + rest = &inside[end + 1..]; + } + kept.push_str(rest); + kept +} + +/// The body of an answer as an error shows it: at most [`BODY_LIMIT`] bytes, +/// with the query string of each address, anything that looks like a token, +/// and the value of each entry whose name holds `token`, `secret`, +/// `signature`, `password`, `credential`, `authorization` or `api_key` +/// replaced by `[redacted]`. +pub(crate) fn http_body(body: &[u8]) -> String { + let scanned = &body[..body.len().min(BODY_SCAN)]; + let mut text = String::from_utf8_lossy(scanned).into_owned(); + if scanned.len() < body.len() { + // Do not show the start of a word cut in two: it may be a token + // whose end would no longer look like one. + let end = text + .rfind(|character: char| !is_word(character)) + .unwrap_or(0); + text.truncate(end); + } + let text = redact(&text); + if text.len() <= BODY_LIMIT && scanned.len() == body.len() { + return text; + } + let mut end = text.len().min(BODY_LIMIT); + while !text.is_char_boundary(end) { + end -= 1; + } + format!("{}…", &text[..end]) +} + +/// Characters of a token, a key or an encoded value. +fn is_word(character: char) -> bool { + character.is_ascii_alphanumeric() + || matches!(character, '_' | '-' | '.' | '~' | '+' | '/' | '=' | '%') +} + +/// Names of entries whose value is a secret, lower case. +const SECRET_NAMES: [&str; 9] = [ + "token", + "secret", + "signature", + "password", + "credential", + "authorization", + "apikey", + "api_key", + "api-key", +]; + +fn redact(text: &str) -> String { + let text = redact_query_strings(text); + let text = redact_entries(&text); + redact_tokens(&text) +} + +/// Each `http://` or `https://` address keeps its path, not its query string +/// or fragment. +fn redact_query_strings(text: &str) -> String { + let mut kept = String::with_capacity(text.len()); + let mut rest = text; + while let Some(start) = find_ignoring_case(rest, "http://") + .into_iter() + .chain(find_ignoring_case(rest, "https://")) + .min() + { + let end = rest[start..] + .find(|character: char| { + character.is_whitespace() + || matches!(character, '"' | '\'' | '<' | '>' | '\\' | '`') + }) + .map_or(rest.len(), |end| start + end); + let address = &rest[start..end]; + kept.push_str(&rest[..start]); + match address.find(['?', '#']) { + Some(query) => { + kept.push_str(&address[..=query]); + kept.push_str(REDACTED); + } + None => kept.push_str(address), + } + rest = &rest[end..]; + } + kept.push_str(rest); + kept +} + +/// The value after a secret's name and `:` or `=`, quoted or not +/// (`"access_token": "…"`, `X-Goog-Signature=…`, `Authorization: Bearer …`). +fn redact_entries(text: &str) -> String { + let lower = text.to_ascii_lowercase(); + let mut kept = String::with_capacity(text.len()); + let mut copied = 0; + let mut search = 0; + while let Some((name_end, value_start, value_end)) = next_entry(text, &lower, search) { + if value_start < copied { + search = name_end; + continue; + } + kept.push_str(&text[copied..value_start]); + kept.push_str(REDACTED); + copied = value_end; + search = value_end.max(name_end); + } + kept.push_str(&text[copied..]); + kept +} + +/// The next secret entry from `from`: where its name ends, and where its +/// value starts and ends. +fn next_entry(text: &str, lower: &str, from: usize) -> Option<(usize, usize, usize)> { + let bytes = text.as_bytes(); + let mut position = from; + loop { + let (start, name) = SECRET_NAMES + .iter() + .filter_map(|name| Some((lower[position..].find(name)? + position, *name))) + .min()?; + let mut cursor = start + name.len(); + // The rest of the name: `access_token`, `X-Goog-Signature`, `tokens`. + while cursor < bytes.len() + && (bytes[cursor].is_ascii_alphanumeric() || matches!(bytes[cursor], b'_' | b'-')) + { + cursor += 1; + } + let name_end = cursor; + // A closing quote, spaces, then `:` or `=`. + if cursor < bytes.len() && matches!(bytes[cursor], b'"' | b'\'') { + cursor += 1; + } + while cursor < bytes.len() && bytes[cursor] == b' ' { + cursor += 1; + } + if cursor >= bytes.len() || !matches!(bytes[cursor], b':' | b'=') { + position = name_end; + continue; + } + cursor += 1; + while cursor < bytes.len() && bytes[cursor] == b' ' { + cursor += 1; + } + // `Bearer abc`: the scheme stays, the credential goes. + for scheme in ["bearer ", "basic "] { + if lower[cursor..].starts_with(scheme) { + cursor += scheme.len(); + while cursor < bytes.len() && bytes[cursor] == b' ' { + cursor += 1; + } + } + } + let value_start = cursor; + let value_end = match bytes.get(cursor) { + Some("e @ (b'"' | b'\'')) => { + let mut end = cursor + 1; + while end < bytes.len() && bytes[end] != quote { + end += if bytes[end] == b'\\' { 2 } else { 1 }; + } + // The quotes stay; what is between them goes. + return Some((name_end, value_start + 1, end.min(bytes.len()))); + } + _ => { + let mut end = cursor; + while end < bytes.len() + && !bytes[end].is_ascii_whitespace() + && !matches!( + bytes[end], + b'&' | b',' | b';' | b'"' | b'\'' | b'<' | b'}' | b']' | b')' + ) + { + end += 1; + } + end + } + }; + if value_end == value_start { + position = name_end; + continue; + } + return Some((name_end, value_start, value_end)); + } +} + +/// Words that look like a credential: Shopify's tokens and secrets +/// (`shpat_…`, `shpss_…`), a JWT, or 32 characters or more of letters and +/// digits mixed. +fn redact_tokens(text: &str) -> String { + let mut kept = String::with_capacity(text.len()); + let mut rest = text; + while !rest.is_empty() { + let start = rest.find(is_word).unwrap_or(rest.len()); + kept.push_str(&rest[..start]); + rest = &rest[start..]; + let end = rest + .find(|character| !is_word(character)) + .unwrap_or(rest.len()); + let word = &rest[..end]; + if looks_like_a_credential(word) { + kept.push_str(REDACTED); + } else { + kept.push_str(word); + } + rest = &rest[end..]; + } + kept +} + +fn looks_like_a_credential(word: &str) -> bool { + let bytes = word.as_bytes(); + let shopify = bytes.len() > 6 + && bytes.starts_with(b"shp") + && bytes[3..5].iter().all(u8::is_ascii_lowercase) + && bytes[5] == b'_'; + let jwt = word.starts_with("eyJ") && word.matches('.').count() >= 2; + let mixed = word.len() >= 32 + && word.bytes().any(|byte| byte.is_ascii_alphabetic()) + && word.bytes().any(|byte| byte.is_ascii_digit()) + && word != REDACTED; + shopify || jwt || mixed +} + +fn find_ignoring_case(text: &str, needle: &str) -> Option { + text.as_bytes() + .windows(needle.len()) + .position(|window| window.eq_ignore_ascii_case(needle.as_bytes())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn serde_messages_keep_kinds_and_lose_values() { + for (message, expected) in [ + ( + r#"invalid type: string "https://x.test/r?sig=SECRET", expected u64"#, + "invalid type: string, expected u64", + ), + ( + r#"invalid type: string "a \"quoted\", expected x", expected u64 at line 1 column 9"#, + "invalid type: string, expected u64 at line 1 column 9", + ), + ( + "invalid type: integer `4242`, expected a string", + "invalid type: integer, expected a string", + ), + ( + "invalid type: floating point `1.5`, expected u32", + "invalid type: floating point, expected u32", + ), + ( + "invalid type: boolean `true`, expected a string", + "invalid type: boolean, expected a string", + ), + ( + "invalid type: character ```, expected a string", + "invalid type: character, expected a string", + ), + ( + "invalid type: map, expected a sequence", + "invalid type: map, expected a sequence", + ), + ( + "invalid type: null, expected a string", + "invalid type: null, expected a string", + ), + ( + r#"invalid value: string "SECRET", expected a date"#, + "invalid value: string, expected a date", + ), + ( + "invalid value: SECRET thing, expected a date", + "invalid value: a value, expected a date", + ), + ( + "unknown variant `SECRET`, expected one of `ACTIVE`, `DRAFT`", + "unknown variant, expected one of `ACTIVE`, `DRAFT`", + ), + ( + "unknown variant `SE`, expected `CRET`, expected `A` or `B`", + "unknown variant, expected `A` or `B`", + ), + ( + "unknown field `SECRET`, there are no fields", + "unknown field, there are no fields", + ), + ("missing field `name`", "missing field `name`"), + ( + "invalid length 3, expected a tuple of size 2", + "invalid length 3, expected a tuple of size 2", + ), + ( + "expected `,` or `}` at line 1 column 9", + "expected `,` or `}` at line 1 column 9", + ), + ( + "invalid shop `SECRET`: expected ``", + "invalid shop `…`: expected `…`", + ), + (r#"bad "SECRET"#, r#"bad "…""#), + ] { + assert_eq!(serde_message(message), expected, "{message}"); + } + } + + #[test] + fn bodies_lose_query_strings_tokens_and_signatures() { + let body = concat!( + r#"{"errors":"Invalid token","url":"https://storage.googleapis.com/b/r.jsonl?X-Goog-Signature=AAA111&X-Goog-Credential=BBB","#, + r#""access_token": "shpat_0123456789abcdef", "refresh_token":'shprt_x1', "#, + "plain shpss_00112233 jwt eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl ", + "random 4f9a8c7e6d5b4a39281706f5e4d3c2b1a0 ", + "Authorization: Bearer abc.DEF-123 next ", + "GOOG4-RSA-SHA256 X-Goog-Signature=CCC&b=1 ", + "id gid://shopify/Product/1 request a1b2c3d4-e5f6", + ); + let shown = http_body(body.as_bytes()); + for secret in [ + "AAA111", + "BBB", + "shpat_", + "shprt_", + "shpss_", + "eyJ", + "4f9a8c7e6d5b4a39281706f5e4d3c2b1a0", + "abc.DEF-123", + "CCC", + ] { + assert!(!shown.contains(secret), "{secret} in {shown}"); + } + for kept in [ + "Invalid token", + "https://storage.googleapis.com/b/r.jsonl?[redacted]", + r#""access_token": "[redacted]""#, + "Bearer [redacted] next", + "gid://shopify/Product/1", + "a1b2c3d4-e5f6", + "next", + ] { + assert!(shown.contains(kept), "{kept} not in {shown}"); + } + } + + #[test] + fn bodies_are_cut_at_one_kibibyte() { + let shown = http_body("é".repeat(2000).as_bytes()); + assert!(shown.ends_with('…')); + assert!(shown.len() <= BODY_LIMIT + '…'.len_utf8()); + // Tokens shrink to `[redacted]`: one cut at the end of what is read + // would show its start, which no longer looks like a token. + let token = format!("{} ", "a1".repeat(150)); + let body = token.repeat(BODY_SCAN / token.len() + 2); + let shown = http_body(body.as_bytes()); + assert!(shown.starts_with("[redacted] [redacted]"), "{shown}"); + assert!(!shown.contains("a1"), "{shown}"); + assert_eq!(http_body(b"short"), "short"); + } +} diff --git a/crates/shopify_api/src/schema.rs b/crates/shopify_api/src/schema.rs index 6747346..bdca799 100644 --- a/crates/shopify_api/src/schema.rs +++ b/crates/shopify_api/src/schema.rs @@ -105,12 +105,12 @@ impl Shopify { /// An introspection result, or why it is not one. fn check(value: Value) -> Result { if let Some(message) = value.get("error").and_then(Value::as_str) { - return Err(Error::Http { - status: 200, - url: PUBLIC_ADMIN_SCHEMA_ENDPOINT.to_string(), - body: message.to_string(), - request_id: None, - }); + return Err(Error::http_parts( + 200, + PUBLIC_ADMIN_SCHEMA_ENDPOINT, + message.as_bytes(), + None, + )); } if value.pointer("/data/__schema/types").is_none() { return Err(Error::Decode { diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs index b05487e..30b773d 100644 --- a/crates/shopify_api/src/webhooks.rs +++ b/crates/shopify_api/src/webhooks.rs @@ -208,10 +208,8 @@ impl Webhook { /// The body read as `T`, the path of the first mismatch in the error. pub fn payload(&self) -> Result { let mut deserializer = serde_json::Deserializer::from_slice(&self.body); - serde_path_to_error::deserialize(&mut deserializer).map_err(|error| Error::Decode { - path: error.path().to_string(), - message: error.inner().to_string(), - }) + serde_path_to_error::deserialize(&mut deserializer) + .map_err(|error| Error::decode(error.path().to_string(), &error.inner().to_string())) } } @@ -631,7 +629,7 @@ mod tests { } assert_eq!( webhook.payload::().unwrap_err().to_string(), - "Shopify's answer does not match the operation at `name`: invalid type: string \"#1001\", expected u32 at line 1 column 22" + "Shopify's answer does not match the operation at `name`: invalid type: string, expected u32 at line 1 column 22" ); } diff --git a/crates/shopify_api/tests/auth.rs b/crates/shopify_api/tests/auth.rs index 417e942..41f874e 100644 --- a/crates/shopify_api/tests/auth.rs +++ b/crates/shopify_api/tests/auth.rs @@ -282,6 +282,40 @@ async fn a_refused_grant_says_what_shopify_answered_and_never_the_secret() { assert!(!format!("{error:?}").contains("top-secret")); } +#[tokio::test] +async fn a_token_answer_that_does_not_parse_shows_no_token() { + for answer in [ + // A token, with a field of the wrong type next to it. + HttpResponse::json( + 200, + &json!({ "access_token": "shpat_TOKEN_SECRET", "scope": 1, "refresh_token": "shprt_REFRESH_SECRET", "expires_in": "shpat_TOKEN_SECRET" }), + ), + // A refusal that echoes what was sent. + HttpResponse::new( + 400, + "invalid request: client_secret=CLIENT_SECRET&refresh_token=shprt_REFRESH_SECRET", + ), + ] { + let mock = MockTransport::new(); + mock.push(answer); + let shopify = builder(&mock) + .client_credentials("id", "CLIENT_SECRET") + .build() + .unwrap(); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + for shown in [ + format!("{error}"), + format!("{error:?}"), + format!("{error:#?}"), + ] { + for secret in ["TOKEN_SECRET", "REFRESH_SECRET", "CLIENT_SECRET"] { + assert!(!shown.contains(secret), "{secret} in {shown}"); + } + assert!(shown.contains("token endpoint"), "{shown}"); + } + } +} + #[tokio::test] async fn a_failed_renewal_ahead_of_expiry_keeps_the_token_that_still_works() { let mock = MockTransport::new(); From e6cfd2775bd5a99c4dc1df3ab1ef9cc94f582f7b Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:45:32 +0200 Subject: [PATCH 023/135] fix: read RFC 850 two-digit years as RFC 9110 says MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit chrono's %y pivots at a fixed year, so in 2069 a Retry-After of 'Wednesday, 06-Nov-69 …' did not parse, and later two-digit years would be read a century off. The century is now chosen from the current date: the latest year with those two digits that is not more than 50 years ahead (RFC 9110 §5.6.7). The weekday must still match. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/graphql.rs | 85 +++++++++++++++++++++++++++++-- 1 file changed, 80 insertions(+), 5 deletions(-) diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index 066ae5b..169c70d 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -235,23 +235,61 @@ fn retry_after_from( std::time::Duration::try_from_secs_f64(seconds).unwrap_or(std::time::Duration::MAX), ); } - let date = http_date(value)?; + let date = http_date(value, now)?; Some((date - now).to_std().unwrap_or_default()) } /// An HTTP date in any of its three forms: `Sun, 06 Nov 1994 08:49:37 GMT`, /// the obsolete `Sunday, 06-Nov-94 08:49:37 GMT` and `Sun Nov 6 08:49:37 1994`. -fn http_date(value: &str) -> Option> { +/// +/// The two-digit year of the second form is read as RFC 9110 (§5.6.7) says: +/// a date more than 50 years after `now` is the most recent past year with +/// the same last two digits. +fn http_date( + value: &str, + now: chrono::DateTime, +) -> Option> { use chrono::{DateTime, NaiveDateTime, Utc}; if let Ok(date) = DateTime::parse_from_rfc2822(value) { return Some(date.with_timezone(&Utc)); } - ["%A, %d-%b-%y %H:%M:%S GMT", "%a %b %e %H:%M:%S %Y"] - .iter() - .find_map(|format| NaiveDateTime::parse_from_str(value, format).ok()) + if let Some(date) = rfc850_date(value, now) { + return Some(date); + } + NaiveDateTime::parse_from_str(value, "%a %b %e %H:%M:%S %Y") + .ok() .map(|date| date.and_utc()) } +/// `Sunday, 06-Nov-94 08:49:37 GMT`, its century chosen from `now`. +fn rfc850_date( + value: &str, + now: chrono::DateTime, +) -> Option> { + use chrono::{Datelike, Months, NaiveDateTime}; + let (weekday, rest) = value.split_once(", ")?; + let (day, rest) = rest.split_once('-')?; + let (month, rest) = rest.split_once('-')?; + let (year, time) = rest.split_once(' ')?; + if year.len() != 2 || !year.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let two_digits: i32 = year.parse().ok()?; + let latest = now.checked_add_months(Months::new(50 * 12))?; + // The latest year ending in these digits that is not more than 50 years ahead. + let mut full_year = now.year() - now.year().rem_euclid(100) + 100 + two_digits; + loop { + let text = format!("{day}-{month}-{full_year} {time}"); + let date = NaiveDateTime::parse_from_str(&text, "%d-%b-%Y %H:%M:%S GMT") + .ok()? + .and_utc(); + if date <= latest { + let named = date.format("%A").to_string(); + return (named == weekday).then_some(date); + } + full_year -= 100; + } +} /// The `data` and `extensions` of an answer without errors. fn into_data(raw: RawResponse) -> Result<(Value, Option)> { if !raw.errors.is_empty() { @@ -291,6 +329,43 @@ mod tests { read("Sun Nov 6 08:49:37 1994"), Some(Duration::from_secs(120)) ); + // RFC 850's two-digit years: never more than 50 years ahead (RFC + // 9110 §5.6.7). + let in_2026 = chrono::DateTime::parse_from_rfc3339("2026-10-22T12:00:00Z") + .unwrap() + .to_utc(); + let year = |value| { + use chrono::Datelike; + super::http_date(value, in_2026).map(|date| date.year()) + }; + assert_eq!(year("Friday, 06-Nov-26 08:49:37 GMT"), Some(2026)); + assert_eq!(year("Wednesday, 06-Nov-69 08:49:37 GMT"), Some(2069)); + assert_eq!(year("Wednesday, 21-Oct-76 08:49:37 GMT"), Some(2076)); + // A day after `now` plus 50 years is in the past century. + assert_eq!(year("Saturday, 23-Oct-76 08:49:37 GMT"), Some(1976)); + assert_eq!(year("Saturday, 06-Nov-99 08:49:37 GMT"), Some(1999)); + assert_eq!(year("Thursday, 06-Nov-70 08:49:37 GMT"), Some(2070)); + assert_eq!(year("Monday, 06-Nov-00 08:49:37 GMT"), Some(2000)); + // A weekday that does not match its date is no date. + assert_eq!(year("Monday, 06-Nov-69 08:49:37 GMT"), None); + assert_eq!(year("Sunday, 06-Nov-1994 08:49:37 GMT"), None); + // In 2069, `69` is this year, not a century ahead: an hour from now. + let in_2069 = chrono::DateTime::parse_from_rfc3339("2069-11-06T07:49:37Z") + .unwrap() + .to_utc(); + assert_eq!( + retry_after_from("Wednesday, 06-Nov-69 08:49:37 GMT", in_2069), + Some(Duration::from_secs(3600)) + ); + // In 2099, `01` is two years ahead, not 98 years ago. + let in_2099 = chrono::DateTime::parse_from_rfc3339("2099-01-01T00:00:00Z") + .unwrap() + .to_utc(); + assert_eq!( + super::http_date("Saturday, 01-Jan-01 00:00:00 GMT", in_2099) + .map(|date| date.to_rfc3339()), + Some("2101-01-01T00:00:00+00:00".to_string()) + ); // A date already past is no wait. assert_eq!(read("Sun, 06 Nov 1994 08:00:00 GMT"), Some(Duration::ZERO)); assert_eq!(read("soon"), None); From c8646580e1a1c91dbe9f9dabe6ee8862e4cfd351 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:46:48 +0200 Subject: [PATCH 024/135] perf: look up the fields of an input object in a set The duplicate input field scan searched a Vec of the fields given so far, quadratic in the size of one object: 100,000 fields took about 50 s in a debug build, 0.2 s with a HashSet per object. Same results. Co-Authored-By: Claude Opus 5.5 --- .../src/analyze/input_objects.rs | 34 +++++++++++++++---- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/crates/shopify_api_graphql/src/analyze/input_objects.rs b/crates/shopify_api_graphql/src/analyze/input_objects.rs index 3c69999..43020e3 100644 --- a/crates/shopify_api_graphql/src/analyze/input_objects.rs +++ b/crates/shopify_api_graphql/src/analyze/input_objects.rs @@ -4,6 +4,8 @@ //! the first and the analyzer never sees it, while the text Shopify receives //! still holds both. The check reads the text itself. +use std::collections::HashSet; + use graphql_parser::Pos; /// The first input field given twice in one input object of `source`, with @@ -23,7 +25,7 @@ pub(super) fn duplicate_field(source: &str) -> Option<(&str, Pos)> { let object = matches!(previous, Some(Token::Punctuator(b':' | b'='))) || matches!(frames.last(), Some(Frame::List)); frames.push(if object { - Frame::Object(Vec::new()) + Frame::Object(HashSet::new()) } else { Frame::Other }); @@ -38,11 +40,9 @@ pub(super) fn duplicate_field(source: &str) -> Option<(&str, Pos)> { // of one (an enum value, `true`, `null`) or of a variable. if let Some(Frame::Object(fields)) = frames.last_mut() && !matches!(previous, Some(Token::Punctuator(b':' | b'$'))) + && !fields.insert(name) { - if fields.contains(&name) { - return Some((name, position_of(source, start))); - } - fields.push(name); + return Some((name, position_of(source, start))); } } _ => {} @@ -54,7 +54,7 @@ pub(super) fn duplicate_field(source: &str) -> Option<(&str, Pos)> { enum Frame<'a> { /// An input object, with the fields given so far. - Object(Vec<&'a str>), + Object(HashSet<&'a str>), List, /// A selection set or arguments. Other, @@ -210,4 +210,26 @@ mod tests { assert_eq!(duplicate(source), None, "{source}"); } } + + #[test] + fn a_large_input_object_is_scanned_in_linear_time() { + // Looking each field up among the previous ones took about 50 s for this + // object in a debug build; a set takes well under one. + let fields: Vec = (0..100_000) + .map(|index| format!("f{index}: {index}")) + .collect(); + let source = format!("{{ a(x: {{{}}}) {{ id }} }}", fields.join(", ")); + let started = std::time::Instant::now(); + assert_eq!(duplicate(&source), None); + let duplicated = format!("{{ a(x: {{{}, f99999: 0}}) {{ id }} }}", fields.join(", ")); + assert_eq!( + duplicate(&duplicated).map(|(name, ..)| name), + Some("f99999") + ); + assert!( + started.elapsed() < std::time::Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + } } From 513ac22bc82f3682c7264e9ffdd6923bdb9b4b19 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:50:20 +0200 Subject: [PATCH 025/135] fix: compare field arguments by kind, value and order Arguments were compared as text, and graphql-parser writes 1.0 as 1 and keeps input objects in a map, so x: f(a: 1) and x: f(a: 1.0), or {a: 1, b: 2} and {b: 2, a: 1}, were merged while Shopify's GraphQL Ruby refuses both with fieldConflict. Values are now compared structurally, by kind (Int, Float, String, Enum, Boolean, null, variable, list, object): -0.0 is not 0.0, 1.0 is 1.00, a block string is the string it holds. The order of an input object's fields, which the parser drops, is read back from the text at the position the parser gives; when it cannot be, the selection is refused rather than sent. Messages write each value with its kind. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api_graphql/src/analyze.rs | 199 +++++++++++++++--- .../src/analyze/input_objects.rs | 159 ++++++++++++-- crates/shopify_api_graphql/tests/analyze.rs | 103 +++++++++ 4 files changed, 416 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35ecdaf..bfc8df2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`, with typed input objects) or read from a file (`file("…graphql")`). - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. -- Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, and an input field given twice in one input object. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree. +- Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - Add: `shopify-api check` checks `.graphql` files against the schema. - Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`. diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index 3f6ebc1..3544433 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -3,7 +3,7 @@ mod input_objects; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt; use graphql_parser::Pos; @@ -254,6 +254,8 @@ pub fn analyze(schema: &Schema, source: &str) -> Result { let mut analyzer = Analyzer { schema, + source, + argument_orders: HashMap::new(), fragments, variables: Vec::new(), used_variables: BTreeSet::new(), @@ -384,9 +386,8 @@ struct Pending<'a> { field: String, ty: TypeRef, /// Where the key was selected: on which parent type, which field, with - /// which arguments (written the same way for every place that gives the - /// same ones). - origins: Vec, + /// which arguments. + origins: Vec>, /// The field may be absent from a value of the parent. conditional: bool, /// The subfields selected at each place, with whether that place may @@ -408,11 +409,20 @@ type SubSet<'a> = (&'a SelectionSet<'a>, bool, Lineage); type Lineage = Vec; /// One place a response key is selected at. -struct Origin { +struct Origin<'a> { /// Its parent type last. lineage: Lineage, field: String, - arguments: String, + arguments: &'a [(String, Value<'a>)], + position: Pos, +} + +/// How the arguments of two places that select one response key compare. +enum Arguments { + Same, + Different, + /// Equal, but the fields of an input object come in another order. + Reordered, } /// Which of the sets merged into one selection a field comes from. @@ -423,19 +433,90 @@ struct Place { uncertain: bool, } -/// The arguments of a field in one canonical text, to compare two places -/// that select the same response key. -fn arguments_key(arguments: &[(String, Value<'_>)]) -> String { - let mut written: Vec = arguments +/// Two values written alike, as Shopify compares the arguments of two fields +/// (GraphQL Ruby's `fieldConflict`): of the same kind (`1` is not `1.0`, `"A"` +/// is not `A`), equal, with lists in the same order. Input objects are +/// compared field by field here; the order of their fields, which the parser +/// does not keep, is compared on the text (see [`Analyzer::same_arguments`]). +fn same_value(left: &Value<'_>, right: &Value<'_>) -> bool { + use ast::Value as V; + match (left, right) { + (V::Variable(left), V::Variable(right)) + | (V::String(left), V::String(right)) + | (V::Enum(left), V::Enum(right)) => left == right, + (V::Int(left), V::Int(right)) => left.as_i64() == right.as_i64(), + // `-0.0` is not `0.0`; `1.0` is `1.00`. + (V::Float(left), V::Float(right)) => left.to_bits() == right.to_bits(), + (V::Boolean(left), V::Boolean(right)) => left == right, + (V::Null, V::Null) => true, + (V::List(left), V::List(right)) => { + left.len() == right.len() + && left + .iter() + .zip(right) + .all(|(left, right)| same_value(left, right)) + } + (V::Object(left), V::Object(right)) => { + left.len() == right.len() + && left.iter().all(|(name, left)| { + right.get(name).is_some_and(|right| same_value(left, right)) + }) + } + _ => false, + } +} + +/// Holds an input object of two fields or more, whose order matters. +fn has_ordered_object(value: &Value<'_>) -> bool { + match value { + ast::Value::Object(fields) => fields.len() > 1 || fields.values().any(has_ordered_object), + ast::Value::List(items) => items.iter().any(has_ordered_object), + _ => false, + } +} + +/// The arguments of a field for a message, each value written with its kind. +fn arguments_text(arguments: &[(String, Value<'_>)]) -> String { + let written: Vec = arguments .iter() - .map(|(name, value)| format!("{name}: {value}")) + .map(|(name, value)| format!("{name}: {}", value_text(value))) .collect(); - written.sort(); written.join(", ") } +fn value_text(value: &Value<'_>) -> String { + match value { + ast::Value::Variable(name) => format!("${name}"), + ast::Value::Int(number) => number.as_i64().unwrap_or_default().to_string(), + ast::Value::Float(number) => format!("{number:?}"), + ast::Value::String(text) => format!("{text:?}"), + ast::Value::Boolean(value) => value.to_string(), + ast::Value::Null => "null".to_string(), + ast::Value::Enum(name) => name.clone(), + ast::Value::List(items) => { + let items: Vec = items.iter().map(value_text).collect(); + format!("[{}]", items.join(", ")) + } + ast::Value::Object(fields) => { + let fields: Vec = fields + .iter() + .map(|(name, value)| format!("{name}: {}", value_text(value))) + .collect(); + format!("{{{}}}", fields.join(", ")) + } + } +} + +/// The arguments of a field and the order of their input fields, by name. +type ArgumentOrders<'a> = Option)>>; + struct Analyzer<'a> { schema: &'a Schema, + /// The text of the operation. + source: &'a str, + /// [`input_objects::argument_orders`] of the fields compared so far, by + /// position. + argument_orders: HashMap<(usize, usize), ArgumentOrders<'a>>, fragments: BTreeMap<&'a str, &'a ast::FragmentDefinition<'a, String>>, /// The declared variables, in the order of the operation. variables: Vec, @@ -561,7 +642,12 @@ impl<'a> Analyzer<'a> { conditional | self.check_directives(&field.directives, "FIELD")?; let ty = self.field_type(parent, field)?; let key = field.alias.as_ref().unwrap_or(&field.name).clone(); - let arguments = arguments_key(&field.arguments); + let origin = |lineage| Origin { + lineage, + field: field.name.clone(), + arguments: &field.arguments, + position: field.position, + }; let origin_lineage: Lineage = lineage .iter() .cloned() @@ -602,22 +688,31 @@ impl<'a> Analyzer<'a> { ), ); } - if origin.arguments != arguments { - return error_at( - field.position, - format!( - "`{key}` is selected twice with different arguments (`({})` and `({arguments})`); give one of them an alias", - origin.arguments - ), - ); + match self.same_arguments(origin, field) { + Arguments::Same => {} + Arguments::Different => { + return error_at( + field.position, + format!( + "`{key}` is selected twice with different arguments (`({})` and `({})`); give one of them an alias", + arguments_text(origin.arguments), + arguments_text(&field.arguments) + ), + ); + } + Arguments::Reordered => { + return error_at( + field.position, + format!( + "`{key}` is selected twice with the fields of an input object in another order (`({})`), which Shopify refuses; write them in the same order, or give one of them an alias", + arguments_text(&field.arguments) + ), + ); + } } } } - existing.origins.push(Origin { - lineage: origin_lineage, - field: field.name.clone(), - arguments, - }); + existing.origins.push(origin(origin_lineage)); existing.conditional &= conditional; existing.sets.extend(sets); if !conditional { @@ -628,11 +723,7 @@ impl<'a> Analyzer<'a> { key, field: field.name.clone(), ty, - origins: vec![Origin { - lineage: origin_lineage, - field: field.name.clone(), - arguments, - }], + origins: vec![origin(origin_lineage)], conditional, sets: sets.into_iter().collect(), unconditional_in: (!conditional) @@ -704,6 +795,52 @@ impl<'a> Analyzer<'a> { Ok(()) } + /// Whether `field` gives the arguments `origin` gave. + fn same_arguments( + &mut self, + origin: &Origin<'a>, + field: &'a ast::Field<'a, String>, + ) -> Arguments { + let (left, right) = (origin.arguments, &field.arguments); + let same = left.len() == right.len() + && left.iter().all(|(name, left)| { + right + .iter() + .find(|(given, _)| given == name) + .is_some_and(|(_, right)| same_value(left, right)) + }); + if !same { + return Arguments::Different; + } + if !left.iter().any(|(_, value)| has_ordered_object(value)) { + return Arguments::Same; + } + let left = self.argument_orders(origin.position, &origin.field); + let right = self.argument_orders(field.position, &field.name); + match (left, right) { + (Some(left), Some(right)) + if left.iter().all(|(name, order)| { + right + .iter() + .any(|(given, other)| given == name && order == other) + }) => + { + Arguments::Same + } + // The text cannot be read back: refuse rather than send what + // Shopify may refuse. + _ => Arguments::Reordered, + } + } + + fn argument_orders(&mut self, position: Pos, name: &str) -> ArgumentOrders<'a> { + let source = self.source; + self.argument_orders + .entry((position.line, position.column)) + .or_insert_with(|| input_objects::argument_orders(source, position, name)) + .clone() + } + /// An object type, as opposed to an interface or a union. fn is_object(&self, name: &str) -> bool { matches!(self.schema.get(name), Some(TypeDef::Object { .. })) diff --git a/crates/shopify_api_graphql/src/analyze/input_objects.rs b/crates/shopify_api_graphql/src/analyze/input_objects.rs index 43020e3..a907682 100644 --- a/crates/shopify_api_graphql/src/analyze/input_objects.rs +++ b/crates/shopify_api_graphql/src/analyze/input_objects.rs @@ -1,8 +1,9 @@ -//! Input Object Field Uniqueness: `{ title: "a", title: "b" }` is invalid. +//! What the parser loses of input objects, read from the text itself. //! -//! The parser keeps input objects in a map, so the second `title` overwrites -//! the first and the analyzer never sees it, while the text Shopify receives -//! still holds both. The check reads the text itself. +//! The parser keeps input objects in a map, so of `{ title: "a", title: "b" }` +//! (invalid: Input Object Field Uniqueness) the analyzer only sees the second +//! `title`, and `{ a: 1, b: 2 }` looks like `{ b: 2, a: 1 }`, which Shopify +//! tells apart when it compares the arguments of two fields. use std::collections::HashSet; @@ -11,10 +12,7 @@ use graphql_parser::Pos; /// The first input field given twice in one input object of `source`, with /// its position. `source` already parsed: anything unexpected ends the scan. pub(super) fn duplicate_field(source: &str) -> Option<(&str, Pos)> { - let mut lexer = Lexer { - text: source, - position: 0, - }; + let mut lexer = Lexer::new(source); let mut frames: Vec> = Vec::new(); let mut previous: Option> = None; while let Some((token, start)) = lexer.next() { @@ -52,6 +50,89 @@ pub(super) fn duplicate_field(source: &str) -> Option<(&str, Pos)> { None } +/// The order of the input fields of each argument of the field at `field` +/// (its position as the parser gives it): for each argument, by name, the +/// brackets of its value and the names of the input fields in the order of +/// the text. Two values the parser holds equal have their fields in the same +/// order when these are equal. +/// +/// `None` when the text at `field` is not the field `name`. +pub(super) fn argument_orders<'a>( + source: &'a str, + field: Pos, + name: &str, +) -> Option)>> { + let mut lexer = Lexer::new(source); + // The field starts with its alias or its name. + let first = loop { + let at = lexer.pos; + let (token, _) = lexer.next()?; + if at == field { + break token; + } + if (at.line, at.column) > (field.line, field.column) { + return None; + } + }; + let Token::Name(first) = first else { + return None; + }; + let mut after = lexer.next(); + if first != name { + // `alias: name` + if after.map(|(token, _)| token) != Some(Token::Punctuator(b':')) { + return None; + } + if lexer.next().map(|(token, _)| token) != Some(Token::Name(name)) { + return None; + } + after = lexer.next(); + } + let mut arguments = Vec::new(); + if after.map(|(token, _)| token) != Some(Token::Punctuator(b'(')) { + return Some(arguments); + } + // The arguments: `Other`; in their values, objects and lists. + let mut frames: Vec> = vec![Frame::Other]; + let mut previous: Option> = None; + while let Some((token, _)) = lexer.next() { + let order = match token { + Token::Punctuator(b'{') => { + frames.push(Frame::Object(HashSet::new())); + Some("{") + } + Token::Punctuator(b'[') => { + frames.push(Frame::List); + Some("[") + } + Token::Punctuator(close @ (b'}' | b']' | b')')) => { + frames.pop()?; + if frames.is_empty() { + return Some(arguments); + } + Some(if close == b'}' { "}" } else { "]" }) + } + // A name is an argument or an input field unless it is a value. + Token::Name(name) if !matches!(previous, Some(Token::Punctuator(b':' | b'$'))) => { + match frames.last() { + Some(Frame::Other) => { + arguments.push((name, Vec::new())); + None + } + Some(Frame::Object(_)) => Some(name), + _ => None, + } + } + _ => None, + }; + if let Some(order) = order { + arguments.last_mut()?.1.push(order); + } + previous = Some(token); + } + None +} + enum Frame<'a> { /// An input object, with the fields given so far. Object(HashSet<&'a str>), @@ -71,12 +152,25 @@ enum Token<'a> { struct Lexer<'a> { text: &'a str, position: usize, + /// The position of the next token as the parser counts it: a tab is 8 + /// columns, `\r` none, a name or a number one per byte, a string one per + /// character. + pos: Pos, } impl<'a> Lexer<'a> { + fn new(text: &'a str) -> Self { + let mut lexer = Self { + text, + position: 0, + pos: Pos { line: 1, column: 1 }, + }; + lexer.skip_ignored(); + lexer + } + /// The next token and where it starts, `None` at the end. fn next(&mut self) -> Option<(Token<'a>, usize)> { - self.skip_ignored(); let rest = &self.text.as_bytes()[self.position..]; let &first = rest.first()?; let start = self.position; @@ -131,22 +225,57 @@ impl<'a> Lexer<'a> { (Token::Other, length) } }; + let text = &self.text[start..start + length]; + if first == b'"' && length >= 6 && text.starts_with("\"\"\"") { + let lines = text.matches('\n').count(); + if lines > 0 { + let last = text.rfind('\n').map_or(0, |index| index + 1); + self.pos.line += lines; + self.pos.column = text[last..].chars().count() + 1; + } else { + self.pos.column += text.chars().count(); + } + } else if first == b'"' { + self.pos.column += text.chars().count(); + } else { + self.pos.column += length; + } self.position += length; + self.skip_ignored(); Some((token, start)) } - /// Skips white space, line terminators, commas, comments and byte order marks. + /// Skips white space, line terminators, commas, comments and byte order + /// marks, counting lines and columns as the parser does. fn skip_ignored(&mut self) { loop { let rest = &self.text.as_bytes()[self.position..]; match rest.first() { - Some(b' ' | b'\t' | b'\n' | b'\r' | b',') => self.position += 1, + Some(b' ' | b',') => { + self.position += 1; + self.pos.column += 1; + } + Some(b'\t') => { + self.position += 1; + self.pos.column += 8; + } + Some(b'\n') => { + self.position += 1; + self.pos.line += 1; + self.pos.column = 1; + } + Some(b'\r') => self.position += 1, Some(0xEF) if rest.starts_with("\u{feff}".as_bytes()) => self.position += 3, Some(b'#') => { - self.position += rest - .iter() - .position(|byte| matches!(byte, b'\n' | b'\r')) - .unwrap_or(rest.len()); + // The parser ends a comment with its line terminator. + match rest.iter().position(|byte| matches!(byte, b'\n' | b'\r')) { + Some(end) => { + self.position += end + 1; + self.pos.line += 1; + self.pos.column = 1; + } + None => self.position += rest.len(), + } } _ => return, } diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs index 30d6be4..4c4276a 100644 --- a/crates/shopify_api_graphql/tests/analyze.rs +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -699,6 +699,109 @@ fn the_same_key_with_other_arguments_needs_an_alias() { ); } +/// Arguments compare as Shopify (GraphQL Ruby) compares them: by kind and +/// value, input fields in the order of the text. +#[test] +fn arguments_compare_by_kind_value_and_order() { + let twice = |left: &str, right: &str| { + format!( + "mutation {{ x: flowTriggerReceive(handle: \"h\", payload: {left}) {{ userErrors {{ message }} }} x: flowTriggerReceive(handle: \"h\", payload: {right}) {{ userErrors {{ field }} }} }}" + ) + }; + for (left, right) in [ + ("1", "1.0"), + ("1.0", "-0.0"), + ("0.0", "-0.0"), + ("\"A\"", "A"), + ("\"1\"", "1"), + ("true", "\"true\""), + ("null", "\"null\""), + ("[1]", "1"), + ("[1, 2]", "[2, 1]"), + ("{a: 1}", "{a: 1.0}"), + ("{a: 1}", "{a: 1, b: 2}"), + ("{a: [1]}", "{a: 1}"), + ("{a: \"x\"}", "{a: x}"), + ] { + let refused = refusal(&twice(left, right)); + assert!( + refused.contains("`x` is selected twice with different arguments"), + "{left} / {right}: {refused}" + ); + } + // Written alike: the same value. + for (left, right) in [ + ("1.0", "1.00"), + ("1.0", "10e-1"), + ("\"abc\"", "\"\"\"abc\"\"\""), + ("\"\\u0041\"", "\"A\""), + ("{a: 1, b: [{c: 2, d: 3}]}", "{a: 1, b: [{c: 2, d: 3}]}"), + ] { + check(&twice(left, right)); + } + // The fields of an input object in another order: Shopify refuses it. + for (left, right) in [ + ("{a: 1, b: 2}", "{b: 2, a: 1}"), + ("{n: {a: 1, b: 2}}", "{n: {b: 2, a: 1}}"), + ("[{a: 1, b: 2}]", "[{b: 2, a: 1}]"), + ] { + let refused = refusal(&twice(left, right)); + assert!( + refused.contains( + "`x` is selected twice with the fields of an input object in another order" + ), + "{left} / {right}: {refused}" + ); + } + // An argument given or left out, as `null`. + assert!( + refusal( + "mutation { x: flowTriggerReceive(handle: \"h\", payload: null) { userErrors { message } } x: flowTriggerReceive(handle: \"h\") { userErrors { field } } }" + ) + .contains("different arguments (`(handle: \"h\", payload: null)` and `(handle: \"h\")`)") + ); + // The messages write each value with its kind. + assert!( + refusal(&twice("{a: 1}", "{a: 1.0}")).contains( + "(`(handle: \"h\", payload: {a: 1})` and `(handle: \"h\", payload: {a: 1.0})`)" + ) + ); +} + +/// The order of input fields is read on the text at the position the parser +/// gives: tabs, `\r\n`, comments, block strings and other characters before +/// the fields do not throw it off. +#[test] +fn the_order_of_input_fields_is_found_after_any_text() { + let field = |payload: &str| { + format!( + "x: flowTriggerReceive(handle: \"h\", payload: {payload}) {{ userErrors {{ message }} }}" + ) + }; + let same = field("{a: 1, b: \"é\"}"); + let other = field("{b: \"é\", a: 1}"); + for before in [ + "\t\t", + "\r\n\t# a comment ending in CRLF\r\n ", + "# é\n\u{feff}", + "y: flowTriggerReceive(handle: \"\"\"line\nanother é\r\n\"\"\", payload: \"é\\\"\") { userErrors { message } }\n\t", + "z: flowTriggerReceive(handle: \"ü\", payload: [\"\\u00e9\", {c: 1}]) { userErrors { message } } ", + ] { + check(&format!( + "mutation {{ {before}{same}\r\n\t{before}{same} }}" + )); + let refused = refusal(&format!("mutation {{ {before}{same}\n\t{before}{other} }}")); + assert!( + refused.contains("in another order"), + "{before:?}: {refused}" + ); + } + // Through an alias and a fragment. + check(&format!( + "mutation {{ ...F {same} }} fragment F on Mutation {{\t{same} }}" + )); +} + #[test] fn directives_come_from_the_schema() { // Shopify's `@idempotent`, on a mutation field. From f830b42e411f14d88be698eb3a265cce6dd319a8 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:54:41 +0200 Subject: [PATCH 026/135] fix: merge one key on fields of different types per SameResponseShape MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A key selected on two exclusive object types had to name fields of the same type, so nodes { ... on Product { price: priceRangeV2 { … } } ... on Order { price: totalPriceSet { … } } } was refused although its answers have one shape. Two places of a key now need the same lists, nullability and scalar or enum, or two types with subfields; the subfields of every place are merged, each collected on the type of its own place, and checked the same way at every depth. Where both places can be in one answer the field and its arguments must still match. The merged selection becomes one struct whose fields are those of every place, optional unless every place selects them; Selection::types lists the types it is selected on. Also refuse a field of an object type that has subfields at one place and none at another ({ shop { name } shop } was accepted). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api/tests/graphql.rs | 52 ++++++++ crates/shopify_api_graphql/src/analyze.rs | 121 +++++++++++++----- crates/shopify_api_graphql/src/codegen.rs | 8 +- crates/shopify_api_graphql/tests/analyze.rs | 134 ++++++++++++++++++++ 5 files changed, 280 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfc8df2..d7fe268 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`, with typed input objects) or read from a file (`file("…graphql")`). - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. -- Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree. +- Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - Add: `shopify-api check` checks `.graphql` files against the schema. - Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`. diff --git a/crates/shopify_api/tests/graphql.rs b/crates/shopify_api/tests/graphql.rs index d6509d1..525921c 100644 --- a/crates/shopify_api/tests/graphql.rs +++ b/crates/shopify_api/tests/graphql.rs @@ -238,6 +238,58 @@ async fn graphql_errors_fail_the_operation_and_keep_partial_data() { assert_eq!(raw.data, Some(json!({ "shop": null }))); } +graphql! { + /// One key, `price`, on fields of two types below exclusive object types. + mod prices = "query Prices($ids: [ID!]!) { + nodes(ids: $ids) { + ... on Product { price: priceRangeV2 { value: minVariantPrice { amount currencyCode } } } + ... on Order { price: totalPriceSet { value: shopMoney { amount currencyCode } } } + } + }"; +} + +#[tokio::test] +async fn one_key_on_fields_of_different_types_reads_both() { + let mock = MockTransport::new(); + let money = json!({ "value": { "amount": "10.0", "currencyCode": "EUR" } }); + mock.push_data(json!({ "nodes": [ + { "price": money }, + { "price": { "value": { "amount": "25.5", "currencyCode": "USD" } } }, + {}, + null, + ] })); + let shopify = client(&mock); + + let data = shopify + .execute(prices::operation(prices::Variables { + ids: vec![ + "gid://shopify/Product/1".into(), + "gid://shopify/Order/2".into(), + ], + })) + .await + .unwrap(); + let price = |index: usize| { + let node: &Option = &data.nodes[index]; + node.as_ref() + .and_then(|node| node.price.as_ref()) + .map(|price| { + let prices::DataNodesPrice { + value: + prices::DataNodesPriceValue { + amount, + currency_code, + }, + } = price; + (amount.as_str(), currency_code.as_str()) + }) + }; + assert_eq!(price(0), Some(("10.0", "EUR"))); + assert_eq!(price(1), Some(("25.5", "USD"))); + assert_eq!(price(2), None); + assert!(data.nodes[3].is_none()); +} + #[tokio::test] async fn an_error_shows_no_value_shopify_echoes_in_its_extensions() { // What GraphQL Ruby answers to a variable that does not validate: the diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index 3544433..645542a 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -117,8 +117,16 @@ impl Variable { #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub struct Selection { + /// The type the fields are selected on: of the first place, when one + /// response key names fields of different types (see `types`). pub type_name: String, pub fields: Vec, + /// Every type the fields are selected on, `type_name` first. More than + /// one when a response key names fields of different object, interface or + /// union types below two exclusive object types (`price` is + /// `Product.priceRangeV2` and `Order.totalPriceSet`): the fields are then + /// those of every place, each conditional unless every place selects it. + pub types: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -326,7 +334,15 @@ pub fn analyze(schema: &Schema, source: &str) -> Result { OperationKind::Mutation => "MUTATION", }; analyzer.check_directives(directives, location)?; - let data = analyzer.selection(root, &[(selection_set, false, Vec::new())], position)?; + let data = analyzer.selection( + &[SubSet { + set: selection_set, + conditional: false, + lineage: Vec::new(), + parent: root.to_string(), + }], + position, + )?; if let Some(unused) = analyzer .variables @@ -390,8 +406,7 @@ struct Pending<'a> { origins: Vec>, /// The field may be absent from a value of the parent. conditional: bool, - /// The subfields selected at each place, with whether that place may - /// be absent when the field is present, and the place's [`Lineage`]. + /// The subfields selected at each place that selects some. sets: Vec>, /// The selections of the parent (see [`Analyzer::selection`]) that select /// the field unconditionally. @@ -399,9 +414,17 @@ struct Pending<'a> { position: Pos, } -/// A selection set, whether the place that selected it may be absent while -/// the value is present, and the [`Lineage`] of that place. -type SubSet<'a> = (&'a SelectionSet<'a>, bool, Lineage); +/// The selection set of a field at one place. +struct SubSet<'a> { + set: &'a SelectionSet<'a>, + /// The place may be absent while the value is present. + conditional: bool, + /// The [`Lineage`] of the place. + lineage: Lineage, + /// The type the set is selected on: the field's type at that place, which + /// may differ from one place to another (see [`Selection::types`]). + parent: String, +} /// The parent type of a place and of each field above it, from the root: /// two places whose lineages differ by two object types at some depth are @@ -413,8 +436,12 @@ struct Origin<'a> { /// Its parent type last. lineage: Lineage, field: String, + /// The type of the field there. + ty: TypeRef, arguments: &'a [(String, Value<'a>)], position: Pos, + /// The field has a selection set there. + selects: bool, } /// How the arguments of two places that select one response key compare. @@ -547,10 +574,16 @@ impl<'a> Analyzer<'a> { /// others select is conditional. When none is, any of them may be the /// one that is there: a subfield is then certain only if every place /// selects it. - fn selection(&mut self, parent: &str, sets: &[SubSet<'a>], position: Pos) -> Result { - let any_certain = sets.iter().any(|(_, conditional, _)| !conditional); + fn selection(&mut self, sets: &[SubSet<'a>], position: Pos) -> Result { + let mut types: Vec = Vec::new(); + for sub in sets { + if !types.contains(&sub.parent) { + types.push(sub.parent.clone()); + } + } + let any_certain = sets.iter().any(|sub| !sub.conditional); let mut pending = Vec::new(); - for (index, (set, conditional, lineage)) in sets.iter().enumerate() { + for (index, sub) in sets.iter().enumerate() { let place = Place { index, // Several places that may each be the one there: what each @@ -558,11 +591,11 @@ impl<'a> Analyzer<'a> { uncertain: !any_certain && sets.len() > 1, }; self.collect( - parent, - set, - any_certain && *conditional, + &sub.parent, + sub.set, + any_certain && sub.conditional, place, - lineage, + &sub.lineage, &mut pending, )?; } @@ -572,7 +605,10 @@ impl<'a> Analyzer<'a> { } } if pending.is_empty() { - return error_at(position, format!("The selection on `{parent}` is empty")); + return error_at( + position, + format!("The selection on `{}` is empty", types.join("` and `")), + ); } let mut fields = Vec::new(); @@ -580,24 +616,25 @@ impl<'a> Analyzer<'a> { let named = field.ty.name(); let base = match self.schema.get(named) { Some(definition) if definition.is_composite() => { - if field.sets.is_empty() { + // Every place selects subfields, not only one of them. + if let Some(bare) = field.origins.iter().find(|origin| !origin.selects) { return error_at( - field.position, + bare.position, format!( "Field `{}` has the type `{}`: select the subfields you need, `{} {{ … }}`", - field.field, field.ty, field.field + bare.field, bare.ty, bare.field ), ); } - FieldBase::Object(self.selection(named, &field.sets, field.position)?) + FieldBase::Object(self.selection(&field.sets, field.position)?) } Some(_) => { - if !field.sets.is_empty() { + if let Some(selecting) = field.origins.iter().find(|origin| origin.selects) { return error_at( - field.position, + selecting.position, format!( "Field `{}` has the type `{}`, which has no subfields", - field.field, field.ty + selecting.field, selecting.ty ), ); } @@ -619,8 +656,9 @@ impl<'a> Analyzer<'a> { } Ok(Selection { - type_name: parent.to_string(), + type_name: types[0].clone(), fields, + types, }) } @@ -642,29 +680,34 @@ impl<'a> Analyzer<'a> { conditional | self.check_directives(&field.directives, "FIELD")?; let ty = self.field_type(parent, field)?; let key = field.alias.as_ref().unwrap_or(&field.name).clone(); + let selects = !field.selection_set.items.is_empty(); let origin = |lineage| Origin { lineage, field: field.name.clone(), + ty: ty.clone(), arguments: &field.arguments, position: field.position, + selects, }; let origin_lineage: Lineage = lineage .iter() .cloned() .chain([parent.to_string()]) .collect(); - let sets = (!field.selection_set.items.is_empty()).then(|| { - ( - &field.selection_set, - conditional || place.uncertain, - origin_lineage.clone(), - ) + let sets = selects.then(|| SubSet { + set: &field.selection_set, + conditional: conditional || place.uncertain, + lineage: origin_lineage.clone(), + parent: ty.name().to_string(), }); match pending.iter_mut().find(|existing| existing.key == key) { Some(existing) => { - // The answer holds one value under the key: one type. - if existing.ty != ty { + // SameResponseShape: the answer holds one value + // under the key, of one shape. Below, the + // subfields of every place merge and are checked + // the same way. + if !self.same_shape(&existing.ty, &ty) { return error_at( field.position, format!( @@ -722,7 +765,7 @@ impl<'a> Analyzer<'a> { None => pending.push(Pending { key, field: field.name.clone(), - ty, + ty: ty.clone(), origins: vec![origin(origin_lineage)], conditional, sets: sets.into_iter().collect(), @@ -841,6 +884,22 @@ impl<'a> Analyzer<'a> { .clone() } + /// SameResponseShape, for the types of two fields: the same lists and + /// nullability, the same scalar or enum, or two types with subfields, + /// whose selections [`Analyzer::selection`] then merges. + fn same_shape(&self, left: &TypeRef, right: &TypeRef) -> bool { + match (left, right) { + (TypeRef::NonNull(left), TypeRef::NonNull(right)) + | (TypeRef::List(left), TypeRef::List(right)) => self.same_shape(left, right), + (TypeRef::Named(left), TypeRef::Named(right)) => { + let composite = + |name: &str| self.schema.get(name).is_some_and(TypeDef::is_composite); + left == right || (composite(left) && composite(right)) + } + _ => false, + } + } + /// An object type, as opposed to an interface or a union. fn is_object(&self, name: &str) -> bool { matches!(self.schema.get(name), Some(TypeDef::Object { .. })) diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs index 236bf27..4e82b59 100644 --- a/crates/shopify_api_graphql/src/codegen.rs +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -150,13 +150,11 @@ impl DataTypes<'_> { let krate = self.krate; let serde = serde_path(krate); + let on = selection.types.join("` or `"); let doc = if name == DATA_TYPE { - format!( - " The `data` of the operation, selected on `{}`.", - selection.type_name - ) + format!(" The `data` of the operation, selected on `{on}`.") } else { - format!(" Selection on `{}`.", selection.type_name) + format!(" Selection on `{on}`.") }; self.items.push(quote! { #[doc = #doc] diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs index 4c4276a..6633759 100644 --- a/crates/shopify_api_graphql/tests/analyze.rs +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -916,3 +916,137 @@ fn keys_below_exclusive_object_types_may_name_different_fields() { .contains("`a` is selected twice with different fields or types") ); } + +/// SameResponseShape: below two exclusive object types, one key may name +/// fields of different object types when what is selected below has the +/// same shape. The subfields of both merge, each conditional unless both +/// select it. +#[test] +fn keys_below_exclusive_object_types_may_name_fields_of_different_types() { + let operation = check( + "{ nodes(ids: []) { + ... on Product { price: priceRangeV2 { value: minVariantPrice { amount currencyCode } } } + ... on Order { price: totalPriceSet { value: shopMoney { amount currencyCode } } } + } }", + ); + let nodes = child(&operation.data, "nodes"); + assert_eq!(fields(nodes), ["price?: ProductPriceRangeV2!"]); + let price = child(nodes, "price"); + assert_eq!(price.types, ["ProductPriceRangeV2", "MoneyBag"]); + assert_eq!(fields(price), ["value: MoneyV2!"]); + assert_eq!( + fields(child(price, "value")), + ["amount: Decimal!", "currencyCode: CurrencyCode!"] + ); + + // A subfield one side selects alone is conditional. + let operation = check( + "{ nodes(ids: []) { + ... on Product { price: priceRangeV2 { value: minVariantPrice { amount } min: minVariantPrice { amount } } } + ... on Order { price: totalPriceSet { value: shopMoney { amount currencyCode } } } + } }", + ); + let price = child(child(&operation.data, "nodes"), "price"); + assert_eq!(fields(price), ["value: MoneyV2!", "min?: MoneyV2!"]); + assert_eq!( + fields(child(price, "value")), + ["amount: Decimal!", "currencyCode?: CurrencyCode!"] + ); + + // Both nullable. + check( + "query($id: ID!) { node(id: $id) { + ... on Product { p: compareAtPriceRange { v: maxVariantCompareAtPrice { amount } } } + ... on Order { p: totalDiscountsSet { v: shopMoney { amount } } } + } }", + ); +} + +/// What does not have the same shape stays refused, at any depth: false +/// accepts are worse than false refusals. +#[test] +fn keys_of_different_types_need_the_same_shape() { + let refused = |source: &str, expected: &str| { + let refused = refusal(source); + assert!(refused.contains(expected), "{source}\n{refused}"); + }; + let node = |product: &str, order: &str| { + format!( + "query($id: ID!) {{ node(id: $id) {{ ... on Product {{ {product} }} ... on Order {{ {order} }} }} }}" + ) + }; + // A leaf of another scalar, or of another enum, below. + refused( + &node( + "p: priceRangeV2 { v: minVariantPrice { amount } }", + "p: totalPriceSet { v: shopMoney { amount: currencyCode } }", + ), + "`amount` is selected twice with different fields or types (`amount: Decimal!` and `currencyCode: CurrencyCode!`)", + ); + // A leaf on one side, subfields on the other. + refused( + &node( + "p: seo { t: title }", + "p: totalPriceSet { t: shopMoney { amount } }", + ), + "`t` is selected twice with different fields or types (`title: String` and `shopMoney: MoneyV2!`)", + ); + refused( + &node("p: title", "p: totalPriceSet { shopMoney { amount } }"), + "`p` is selected twice with different fields or types (`title: String!` and `totalPriceSet: MoneyBag!`)", + ); + // Non-null on one side only. + refused( + &node( + "p: priceRangeV2 { v: minVariantPrice { amount } }", + "p: totalDiscountsSet { v: shopMoney { amount } }", + ), + "`p` is selected twice with different fields or types (`priceRangeV2: ProductPriceRangeV2!` and `totalDiscountsSet: MoneyBag`)", + ); + // A list on one side only. + refused( + &node( + "p: options { name }", + "p: totalPriceSet { name: shopMoney { amount } }", + ), + "`p` is selected twice with different fields or types (`options: [ProductOption!]!` and `totalPriceSet: MoneyBag!`)", + ); + // The same parent type: the same field, whatever the types. + refused( + "query($id: ID!) { node(id: $id) { ... on Product { p: priceRangeV2 { v: maxVariantPrice { amount } } } ... on Product { p: compareAtPriceRange { v: maxVariantCompareAtPrice { amount } } } } }", + "`p` is selected twice with different fields or types", + ); + // An interface on one side: both may be there. + refused( + "query($id: ID!) { node(id: $id) { ... on HasMetafields { p: metafield(key: \"a\") { id } } ... on Product { p: featuredMedia { id } } } }", + "`p` is selected twice with different fields or types", + ); + // The same field named on two places must be selected the same way below. + refused( + &node( + "p: priceRangeV2 { v: minVariantPrice { amount } }", + "p: totalPriceSet { v: shopMoney { amount } v: presentmentMoney { amount } }", + ), + "`v` is selected twice with different fields or types (`shopMoney: MoneyV2!` and `presentmentMoney: MoneyV2!`)", + ); +} + +/// A field of an object type needs subfields at every place it is selected, +/// a leaf at none. +#[test] +fn every_place_of_a_field_selects_subfields_or_none() { + assert_eq!( + refusal("{ shop { name } shop }"), + "Field `shop` has the type `Shop!`: select the subfields you need, `shop { … }` (line 1, column 17)" + ); + assert_eq!( + refusal("{ shop { name name { x } } }"), + "Field `name` has the type `String!`, which has no subfields (line 1, column 15)" + ); + assert_eq!( + refusal( + "query($id: ID!) { node(id: $id) { ... on Product { p: seo { title } } ... on Order { p: totalPriceSet } } }" + ), + "Field `totalPriceSet` has the type `MoneyBag!`: select the subfields you need, `totalPriceSet { … }` (line 1, column 86)" + ); +} From 7bb5af49bf12a3c5d899ad0eaf0de4e58a3296c8 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:58:19 +0200 Subject: [PATCH 027/135] fix: redact a token glued after a separator in an error body MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit is_word keeps '=' and '/' in a word, so 'x=shpat_…' or '/eyJ…' were one word that did not start like a token. Shopify token prefixes and JWTs are now found after any non-alphanumeric character of a word. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/redact.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/crates/shopify_api/src/redact.rs b/crates/shopify_api/src/redact.rs index 4710b5a..34801b6 100644 --- a/crates/shopify_api/src/redact.rs +++ b/crates/shopify_api/src/redact.rs @@ -349,11 +349,20 @@ fn redact_tokens(text: &str) -> String { fn looks_like_a_credential(word: &str) -> bool { let bytes = word.as_bytes(); - let shopify = bytes.len() > 6 - && bytes.starts_with(b"shp") - && bytes[3..5].iter().all(u8::is_ascii_lowercase) - && bytes[5] == b'_'; - let jwt = word.starts_with("eyJ") && word.matches('.').count() >= 2; + // Anywhere in the word after a separator: `key=shpat_…`, `/eyJ….….…`. + let starts = + (0..bytes.len()).filter(|&index| index == 0 || !bytes[index - 1].is_ascii_alphanumeric()); + let shopify = starts.clone().any(|index| { + let rest = &bytes[index..]; + rest.len() > 6 + && rest.starts_with(b"shp") + && rest[3..5].iter().all(u8::is_ascii_lowercase) + && rest[5] == b'_' + }); + let jwt = starts.into_iter().any(|index| { + bytes[index..].starts_with(b"eyJ") + && bytes[index..].iter().filter(|byte| **byte == b'.').count() >= 2 + }); let mixed = word.len() >= 32 && word.bytes().any(|byte| byte.is_ascii_alphabetic()) && word.bytes().any(|byte| byte.is_ascii_digit()) @@ -454,7 +463,8 @@ mod tests { "random 4f9a8c7e6d5b4a39281706f5e4d3c2b1a0 ", "Authorization: Bearer abc.DEF-123 next ", "GOOG4-RSA-SHA256 X-Goog-Signature=CCC&b=1 ", - "id gid://shopify/Product/1 request a1b2c3d4-e5f6", + "id gid://shopify/Product/1 request a1b2c3d4-e5f6 ", + "glued x=shpat_GLUED1 /eyJhbGciOiJIUzI1NiJ9.eyJzdWIi.GLUED2 ", ); let shown = http_body(body.as_bytes()); for secret in [ @@ -467,6 +477,8 @@ mod tests { "4f9a8c7e6d5b4a39281706f5e4d3c2b1a0", "abc.DEF-123", "CCC", + "GLUED1", + "GLUED2", ] { assert!(!shown.contains(secret), "{secret} in {shown}"); } From ea9ad0fa6aabdc7460e4a475e6279380b9d7706e Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:40:30 +0200 Subject: [PATCH 028/135] fix: build error messages from the crate's own words, never from the input Text scrubbing kept missing secrets (escaped quotes, JSON \u escapes, tabs, escaped slashes, map keys, bulk counts, variables errors). Errors now never put text they did not write in Display, Debug or source(): - Error::Http shows the status, address, content type and body length; the body stays in raw_http_body(). The redacted `body` preview is gone. - Error::Decode: a new path-tracking deserializer (decode.rs) names only the fields and variants the Rust type declares (&'static str), writes `[key]` for map keys, and describes the mismatch in its own words with the line and column. serde's message is in sensitive_detail(). - Error::Variables: one path for Operation::variables, json_variable and graphql_raw; the Serialize message is in sensitive_detail(). - Error::Auth: the token endpoint's status and a known OAuth code; its answer is in sensitive_detail(). - Bulk counts, ids, statuses and error codes are not echoed. - InvalidShop/InvalidApiVersion do not show the text given; addresses lose their user and password too; GraphQL data/extensions Debug counts entries instead of naming them. - Error::Json and From are gone; redact.rs, serde_path_to_error and thiserror are dropped. A test builds every variant from secret-bearing input and checks Display, Debug, {:#?} and the source chain. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- Cargo.lock | 13 - Cargo.toml | 2 - MIGRATION.md | 8 +- crates/shopify_api/Cargo.toml | 2 - crates/shopify_api/src/auth.rs | 78 +- crates/shopify_api/src/bulk.rs | 109 +- crates/shopify_api/src/client.rs | 6 +- crates/shopify_api/src/decode.rs | 1113 +++++++++++++++++++ crates/shopify_api/src/error.rs | 1041 ++++++++++++++--- crates/shopify_api/src/graphql.rs | 19 +- crates/shopify_api/src/graphql/operation.rs | 56 +- crates/shopify_api/src/graphql/response.rs | 29 +- crates/shopify_api/src/lib.rs | 4 +- crates/shopify_api/src/pagination.rs | 5 +- crates/shopify_api/src/redact.rs | 512 --------- crates/shopify_api/src/schema.rs | 13 +- crates/shopify_api/src/transport.rs | 6 +- crates/shopify_api/src/webhooks.rs | 65 +- crates/shopify_api/tests/auth.rs | 11 +- crates/shopify_api/tests/graphql.rs | 15 +- 21 files changed, 2244 insertions(+), 866 deletions(-) create mode 100644 crates/shopify_api/src/decode.rs delete mode 100644 crates/shopify_api/src/redact.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index d7fe268..8eb301b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,8 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: `oauth`: `ShopifyApp` with install links, callback and admin launch verification, code exchange, session tokens and token exchange, app proxies. - Add: `Transport` trait, `ReqwestTransport` (redirections always off, `from_builder` for your own settings), and `testing::MockTransport`, with `testing::client`, which retries without waiting, even for a scripted `Retry-After`. - Add: token renewals run in a task of their own: a cancelled request does not lose a rotated refresh token. A failed renewal answers the requests waiting for it. -- Add: what an error displays holds no secret the crate knows of (`Error` documents what is and is not shown): no query string (signed bulk result addresses stay out of logs); `Error::Decode` keeps the path and the kinds of value, not the value; `Error::Http` shows at most 1 KiB of the body, with query strings, token-like words and the values of secret-named entries redacted, and `Error::raw_http_body` (or the `raw_body: RawBody` field) gives the whole body; the `Debug` of `GraphqlErrors` names the fields of partial `data` without their values, and that of `GraphqlError` shows `extensions.code` and only the names of the other extensions (Shopify echoes an invalid variable's whole value in `extensions.value`); `Error::Http` carries Shopify's `X-Request-Id`. +- Add: an error shows nothing of what the crate did not write (`Error` documents the contract): no body, value or map key of an answer, no message of serde or of a `Serialize` implementation, no query string or user of an address. `Error::Http` displays the status, the address, the content type and the length of the body; `Error::raw_http_body` (or the `raw_body: RawBody` field) gives the body. `Error::Decode` displays the kind of mismatch, its line and column, and a path of the type's own field names and indexes, with `[key]` for a map key. `Error::Variables` names the variable that does not serialize. `Error::sensitive_detail` gives serde's message, the `Serialize` implementation's or the token endpoint's, all kept out of `Display` and `Debug` (`SensitiveDetail`). The `Debug` of `GraphqlErrors` counts the entries of partial `data`, and that of `GraphqlError` shows `extensions.code` and counts the other extensions (Shopify echoes an invalid variable's whole value in `extensions.value`). Shopify's own messages in `errors` and `userErrors` are shown as they are. `Error::Http` carries Shopify's `X-Request-Id`. +- Breaking (against the 1.0 previews): `Error::Http` displays no part of the body and has no `body` field any more (it was a redacted 1 KiB preview); it has `content_type`. `Error::Json` is gone: a body that is not JSON is `Error::Decode`. `Error::Decode` has a `detail` field and its path writes a map key `[key]`. `Error::Variables(String)` and `Error::Auth(String)` are `Variables { message, detail }` and `Auth { message, detail }`. `Error` no longer converts from `serde_json::Error`. `InvalidShop` and `InvalidApiVersion` do not display the text given, which may be a token given in the wrong place (`InvalidApiVersion` shows a version written `YYYY-MM`). - Add: `ShopDomain` refuses anything but `` or `.myshopify.com`. - Breaking: `Shopify::new(shop, auth)` and `Shopify::builder`; `ShopifyAuth` is `Auth`; `ShopifyConfig` is gone; `ShopifyAPIError` is `Error`. - Breaking: `graphql` returns `data` as a `Value` and `graphql_as` reads it as a type; `post_graphql` and the `graphql-client` feature are gone. diff --git a/Cargo.lock b/Cargo.lock index cb656ce..d73241a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1397,17 +1397,6 @@ dependencies = [ "zmij", ] -[[package]] -name = "serde_path_to_error" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" -dependencies = [ - "itoa", - "serde", - "serde_core", -] - [[package]] name = "serde_spanned" version = "1.1.2" @@ -1458,12 +1447,10 @@ dependencies = [ "reqwest", "serde", "serde_json", - "serde_path_to_error", "serde_urlencoded", "sha2", "shopify_api_graphql", "shopify_api_macros", - "thiserror 2.0.21", "tokio", "tracing", "trybuild", diff --git a/Cargo.toml b/Cargo.toml index 8a2d58e..45188ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,12 +32,10 @@ quote = "1" reqwest = { version = "0.13.5", default-features = false } serde = { version = "1", features = ["derive"] } serde_json = "1" -serde_path_to_error = "0.1" serde_urlencoded = "0.7" sha2 = "0.11" subtle = "2.6" syn = { version = "2", features = ["full"] } -thiserror = "2.0.21" tokio = { version = "1", default-features = false } tracing = { version = "0.1", default-features = false, features = ["std"] } toml = { version = "1", default-features = false, features = ["std", "parse", "serde"] } diff --git a/MIGRATION.md b/MIGRATION.md index 41846c1..86e76f1 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -50,12 +50,12 @@ to keep that. | 0.10 | 1.0 | | --- | --- | | `ConnectionFailed(reqwest::Error)` | `Transport { url, source }` | -| An `error_for_status` failure | `Http { status, url, body, .. }`: `body` is cut at 1 KiB and redacted; `error.raw_http_body()` gives the whole body, secrets included; `error.status()`, `error.is_unauthorized()` | +| An `error_for_status` failure | `Http { status, url, content_type, request_id, raw_body }`: it displays the status, the address, the content type and the length of the body, never the body; `error.raw_http_body()` gives the whole body, secrets included; `error.status()`, `error.is_unauthorized()` | | `Throttled` | `Throttled { retries, cost, retry_after }`, once the retries are spent or when `Retry-After` exceeds `max_retry_after` | | `GraphqlErrors(Vec)` | `Graphql(GraphqlErrors { errors, data })` | -| `JsonParseError` | `Json`, or `Decode { path, message }` when `data` does not fit its type: the path and the kinds of value, not the value | -| `NotWantedJsonFormat`, `NotJson`, `ResponseBroken` | `Decode` | -| `Authentication(text)` | `Auth(text)` | +| `JsonParseError`, `NotWantedJsonFormat`, `NotJson`, `ResponseBroken` | `Decode { path, message, detail }`: a body that is not JSON, or `data` that does not fit its type. `path` and `message` hold no text of the answer (a map key is `[key]`); serde's message is `error.sensitive_detail()` | +| Variables that do not serialize | `Variables { message, detail }`: what a `Serialize` implementation wrote is `error.sensitive_detail()`, not the message | +| `Authentication(text)` | `Auth { message, detail }`: what the token endpoint wrote is `error.sensitive_detail()` | | `MissingGraphqlData`, `InvalidHeaderValue`, `Other` | Gone | ## GraphQL calls diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index fa80be7..b9f277a 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -40,9 +40,7 @@ chrono.workspace = true reqwest = { workspace = true, optional = true } serde.workspace = true serde_json.workspace = true -serde_path_to_error.workspace = true serde_urlencoded.workspace = true -thiserror.workspace = true # `rt`: a token renewal runs in its own task, so a caller that gives up does not cancel it. tokio = { workspace = true, features = ["rt", "sync", "time"] } tracing.workspace = true diff --git a/crates/shopify_api/src/auth.rs b/crates/shopify_api/src/auth.rs index a554c96..6e9fe0d 100644 --- a/crates/shopify_api/src/auth.rs +++ b/crates/shopify_api/src/auth.rs @@ -353,28 +353,40 @@ pub(crate) async fn request_token( .await .map_err(|source| Error::transport(&url, source))?; if !response.is_success() { + // What the endpoint wrote is kept apart: it may echo what it was sent. let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap_or_default(); - let code = body.get("error").and_then(serde_json::Value::as_str); + let code = body + .get("error") + .and_then(serde_json::Value::as_str) + .map(oauth_error_code); let description = body .get("error_description") .and_then(serde_json::Value::as_str); - let detail = match (code, description) { - (Some(code), Some(description)) => { - crate::redact::http_body(format!("{code}: {description}").as_bytes()) - } - (Some(code), None) => crate::redact::http_body(code.as_bytes()), - _ => crate::redact::http_body(&response.body), + let detail = match ( + body.get("error").and_then(serde_json::Value::as_str), + description, + ) { + (Some(code), Some(description)) => format!("{code}: {description}"), + (Some(code), None) => code.to_string(), + _ => String::from_utf8_lossy(&response.body).into_owned(), + }; + let message = match code { + Some(code) => format!( + "the token endpoint of {shop} answered {} ({code})", + response.status + ), + None => format!("the token endpoint of {shop} answered {}", response.status), }; - return Err(Error::Auth(format!( - "the token endpoint of {shop} answered {}: {detail}", - response.status - ))); + return Err(Error::auth_with_detail(message, detail)); } - let parsed: TokenResponse = serde_json::from_slice(&response.body).map_err(|error| { - Error::Auth(format!( - "the token endpoint of {shop} answered an invalid token: {}", - crate::redact::serde_message(&error.to_string()) - )) + let parsed: TokenResponse = crate::decode::from_slice(&response.body).map_err(|failure| { + Error::auth_with_detail( + format!( + "the token endpoint of {shop} answered an invalid token: {} at `{}`", + failure.message, failure.path + ), + failure.detail, + ) })?; Ok(parsed.into_token()) } @@ -429,7 +441,7 @@ impl State { fn held_failure(&self) -> Option { let (at, message) = self.failure.as_ref()?; (at.elapsed() < FAILURE_HOLD) - .then(|| Error::Auth(format!("{message} (asked again in a few seconds)"))) + .then(|| Error::auth(format!("{message} (asked again in a few seconds)"))) } } @@ -526,7 +538,7 @@ impl Tokens { .token .as_ref() .map(|token| token.access_token.clone()) - .ok_or_else(|| Error::Auth("no access token".to_string())); + .ok_or_else(|| Error::auth("no access token")); } let kind = self.kind.clone(); let endpoint = endpoint.clone(); @@ -556,16 +568,40 @@ impl Tokens { saved.map(|()| access_token) }); renewal.await.map_err(|stopped| { - Error::Auth(format!("the renewal of the token stopped: {stopped}")) + // A panic's message is not this crate's to show. + Error::auth(if stopped.is_panic() { + "the renewal of the token panicked" + } else { + "the renewal of the token was cancelled" + }) })? } } +/// An OAuth error code (RFC 6749, 5.2, and Shopify's) as an error shows it. +fn oauth_error_code(code: &str) -> &'static str { + const CODES: [&str; 8] = [ + "shop_not_permitted", + "invalid_request", + "invalid_client", + "invalid_grant", + "unauthorized_client", + "unsupported_grant_type", + "invalid_scope", + "invalid_subject_token", + ]; + CODES + .iter() + .find(|known| **known == code) + .copied() + .unwrap_or("an error code this crate does not know") +} + /// Asks Shopify for a new token, as `kind` does. async fn obtain(kind: &Kind, state: &State, endpoint: &Endpoint) -> Result { let transport = endpoint.transport.as_ref(); match kind { - Kind::Static => Err(Error::Auth("a static token is not renewed".to_string())), + Kind::Static => Err(Error::auth("a static token is not renewed")), Kind::ClientCredentials { client_id, client_secret, @@ -594,7 +630,7 @@ async fn obtain(kind: &Kind, state: &State, endpoint: &Endpoint) -> Result &'static str { + match self { + Self::Created => "Created", + Self::Running => "Running", + Self::Completed => "Completed", + Self::Canceling => "Canceling", + Self::Canceled => "Canceled", + Self::Failed => "Failed", + Self::Expired => "Expired", + Self::Other(_) => "with a status this crate does not know", + } + } + fn parse(value: &str) -> Self { match value { "CREATED" => Self::Created, @@ -198,7 +212,8 @@ impl Wire { let number = |field: &str, value: &str| { value .parse::() - .map_err(|_| Error::Bulk(format!("`{field}` is not a number: {value}"))) + // The value is not shown: it is the answer's. + .map_err(|_| Error::Bulk(format!("`{field}` is not an unsigned integer"))) }; Ok(BulkOperation { object_count: number("objectCount", &self.object_count)?, @@ -221,15 +236,58 @@ impl Wire { } } +/// The ID of a bulk operation as an error shows it: a `gid://` of Shopify, +/// else nothing of the text. +fn shown_id(id: &str) -> &str { + let shown = id + .strip_prefix("gid://shopify/BulkOperation/") + .is_some_and(|number| { + !number.is_empty() && number.bytes().all(|byte| byte.is_ascii_digit()) + }); + if shown { id } else { "[id not shown]" } +} + +/// The error of an operation that ended without completing. +pub(crate) fn not_completed(operation: &BulkOperation) -> Error { + Error::Bulk(format!( + "the bulk operation {} ended {}{}", + shown_id(&operation.id), + operation.status.shown(), + operation + .error_code + .as_deref() + .map(|code| format!(" ({})", shown_error_code(code))) + .unwrap_or_default() + )) +} + +/// The error of a wait that ran out. +pub(crate) fn timed_out(id: &str, timeout: Duration) -> Error { + Error::Timeout(format!( + "the bulk operation {} did not end within {timeout:?}", + shown_id(id) + )) +} + +/// A `BulkOperationErrorCode` as an error shows it. +fn shown_error_code(code: &str) -> &'static str { + match code { + "ACCESS_DENIED" => "ACCESS_DENIED", + "INTERNAL_SERVER_ERROR" => "INTERNAL_SERVER_ERROR", + "TIMEOUT" => "TIMEOUT", + _ => "an error code this crate does not know", + } +} + /// Reads the `BulkOperationFields` of a generated type. -fn operation_of(selection: &impl Serialize) -> Result { - let wire: Wire = crate::graphql::decode(serde_json::to_value(selection)?)?; +pub(crate) fn operation_of(selection: &impl Serialize) -> Result { + let wire: Wire = crate::decode::reserialize(selection)?; wire.into_operation() } /// The user errors of a generated payload. fn user_errors(errors: &impl Serialize) -> Result> { - crate::graphql::decode(serde_json::to_value(errors)?) + crate::decode::reserialize(errors) } /// How [`Shopify::wait_for_bulk_operation`] polls. @@ -406,7 +464,8 @@ impl Shopify { pub async fn stage_bulk_variables(&self, variables: &[T]) -> Result { let mut jsonl = Vec::new(); for item in variables { - serde_json::to_writer(&mut jsonl, item)?; + serde_json::to_writer(&mut jsonl, item) + .map_err(|error| Error::variables(None, &error))?; jsonl.push(b'\n'); } @@ -533,17 +592,17 @@ impl Shopify { if let Some(timeout) = options.timeout { let elapsed = started.elapsed(); if elapsed >= timeout { - return Err(Error::Timeout(format!( - "the bulk operation {id} did not end within {timeout:?}" - ))); + return Err(timed_out(id, timeout)); } wait = wait.min(timeout - elapsed); } tokio::time::sleep(wait).await; - let operation = self - .bulk_operation(id) - .await? - .ok_or_else(|| Error::Bulk(format!("the bulk operation {id} does not exist")))?; + let operation = self.bulk_operation(id).await?.ok_or_else(|| { + Error::Bulk(format!( + "the bulk operation {} does not exist", + shown_id(id) + )) + })?; // A status this version does not know ends the wait too: it is // the caller's to read, rather than a loop that never ends. if operation.status.is_terminal() @@ -569,15 +628,7 @@ impl Shopify { let operation = self.run_bulk_query(query).await?; let operation = self.wait_for_bulk_operation(&operation.id, options).await?; if operation.status != BulkOperationStatus::Completed { - return Err(Error::Bulk(format!( - "the bulk operation {} ended {:?}{}", - operation.id, - operation.status, - operation - .error_code - .map(|code| format!(" ({code})")) - .unwrap_or_default() - ))); + return Err(not_completed(&operation)); } match &operation.url { Some(url) => self.download_bulk_results(url).await, @@ -628,19 +679,7 @@ pub fn parse_jsonl(body: &[u8]) -> Result> { body.split(|byte| *byte == b'\n') .enumerate() .filter(|(_, line)| !line.iter().all(u8::is_ascii_whitespace)) - .map(|(index, line)| { - let mut deserializer = serde_json::Deserializer::from_slice(line); - serde_path_to_error::deserialize(&mut deserializer).map_err(|error| { - // The position serde_json adds is within the line, not the file. - let inner = error.inner(); - let position = format!(" at line {} column {}", inner.line(), inner.column()); - let message = inner.to_string(); - Error::decode( - format!("line {}: {}", index + 1, error.path()), - message.strip_suffix(&position).unwrap_or(&message), - ) - }) - }) + .map(|(index, line)| crate::decode::from_jsonl_line(line, index + 1)) .collect() } @@ -728,7 +767,7 @@ mod tests { let error = parse_jsonl::(b"{\"id\":\"a\"}\n{\"id\":2}\n").unwrap_err(); assert_eq!( error.to_string(), - "Shopify's answer does not match the operation at `line 2: id`: invalid type: integer, expected a string" + "Shopify's answer does not match the operation at `id`: invalid type: integer, expected a string at line 2 column 7" ); } diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index db3a623..08b713c 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -400,9 +400,7 @@ impl ShopifyBuilder { pub fn build(self) -> Result { let shop = ShopDomain::new(&self.shop)?; let auth = self.auth.ok_or_else(|| { - Error::Auth( - "no credentials: call `access_token`, `client_credentials` or `auth`".to_string(), - ) + Error::auth("no credentials: call `access_token`, `client_credentials` or `auth`") })?; let transport = match self.transport { Some(transport) => transport, @@ -504,7 +502,7 @@ mod tests { )); assert!(matches!( Shopify::builder("shop").build(), - Err(Error::Auth(_)) + Err(Error::Auth { .. }) )); } } diff --git a/crates/shopify_api/src/decode.rs b/crates/shopify_api/src/decode.rs new file mode 100644 index 0000000..c05bd2b --- /dev/null +++ b/crates/shopify_api/src/decode.rs @@ -0,0 +1,1113 @@ +//! Reads JSON as a type, and builds an error that holds nothing of the input. +//! +//! An error of serde or serde_json may quote what it read: a value +//! (`invalid type: string "…"`), a map key in its path, the text a type's own +//! `Deserialize` writes. What [`Failure`] keeps to show is built from this +//! module's own words and from the `&'static str` names a type gives serde +//! (its fields, its variants, its name): a path segment or a quoted name is +//! shown only when it is one of those, never because of what it looks like. +//! serde's whole message is kept apart, in [`Failure::detail`]. + +use std::cell::RefCell; +use std::fmt; + +use serde::de::{ + self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, MapAccess, SeqAccess, + VariantAccess, Visitor, +}; +use serde_json::error::Category; + +/// A value that does not read as its type: what is safe to show, and serde's +/// own message, which is not. +pub(crate) struct Failure { + /// Field names of the type, indexes, and `[key]` for anything else. + pub(crate) path: String, + /// What went wrong, in this module's words. + pub(crate) message: String, + /// serde's message as it was: it may quote the input. + pub(crate) detail: String, +} + +impl Failure { + /// The [`Error::Decode`](crate::Error::Decode) of this failure. + pub(crate) fn into_error(self) -> crate::Error { + crate::Error::decode(self.path, self.message, Some(self.detail)) + } +} + +/// Reads `value` as `T`. +pub(crate) fn from_value(value: serde_json::Value) -> crate::Result { + read(value, None).map_err(Failure::into_error) +} + +/// Reads JSON text as `T`. +pub(crate) fn from_slice(bytes: &[u8]) -> Result { + let mut deserializer = serde_json::Deserializer::from_slice(bytes); + let value = read(&mut deserializer, None)?; + deserializer + .end() + .map_err(|error| failure(&error, &Track::default(), None))?; + Ok(value) +} + +/// Reads line `line` (from 1) of a JSONL file as `T`: the position the +/// error gives is in the file. +pub(crate) fn from_jsonl_line( + bytes: &[u8], + line: usize, +) -> crate::Result { + let mut deserializer = serde_json::Deserializer::from_slice(bytes); + let value = read(&mut deserializer, Some(line)).map_err(Failure::into_error)?; + deserializer + .end() + .map_err(|error| failure(&error, &Track::default(), Some(line)).into_error())?; + Ok(value) +} + +/// Writes `value` as JSON and reads it back as `T`: a generated type read as +/// one of this crate's. +pub(crate) fn reserialize( + value: &impl serde::Serialize, +) -> crate::Result { + let value = serde_json::to_value(value).map_err(|error| { + crate::Error::decode( + ".", + "the answer does not serialize".to_string(), + Some(error.to_string()), + ) + })?; + from_value(value) +} + +fn read<'de, D, T>(deserializer: D, line: Option) -> Result +where + D: Deserializer<'de, Error = serde_json::Error>, + T: Deserialize<'de>, +{ + let track = Track::default(); + T::deserialize(Wrap { + inner: deserializer, + chain: &Chain::Root, + track: &track, + }) + .map_err(|error| failure(&error, &track, line)) +} + +fn failure(error: &serde_json::Error, track: &Track, line: Option) -> Failure { + let path = track.path.borrow().clone().unwrap_or_default(); + let mut message = describe(error, track); + if error.line() > 0 { + let line = line.unwrap_or(error.line()); + message.push_str(&format!(" at line {line} column {}", error.column())); + } else if let Some(line) = line { + message.push_str(&format!(" at line {line}")); + } + Failure { + path: render(&path), + message, + detail: error.to_string(), + } +} + +/// What went wrong, without anything serde quoted from the input. +fn describe(error: &serde_json::Error, track: &Track) -> String { + let full = error.to_string(); + // serde_json adds the position to its message; it is shown on its own. + let position = format!(" at line {} column {}", error.line(), error.column()); + let message = full.strip_suffix(&position).unwrap_or(&full); + if let Some(known) = FIXED.iter().find(|known| **known == message) { + return (*known).to_string(); + } + match error.classify() { + Category::Io => "the input could not be read".to_string(), + Category::Eof => "the input ends too early".to_string(), + Category::Syntax => "invalid JSON".to_string(), + Category::Data => data_message(message, track), + } +} + +/// serde_json's own messages: none of them quotes the input. +const FIXED: &[&str] = &[ + "EOF while parsing a list", + "EOF while parsing an object", + "EOF while parsing a string", + "EOF while parsing a value", + "expected `:`", + "expected `,` or `]`", + "expected `,` or `}`", + "expected ident", + "expected value", + "expected `\"`", + "invalid escape", + "invalid number", + "number out of range", + "invalid unicode code point", + "control character (\\u0000-\\u001F) found while parsing a string", + "key must be a string", + "invalid value: expected key to be a number in quotes", + "float key must be finite (got NaN or +/-inf)", + "lone leading surrogate in hex escape", + "trailing comma", + "trailing characters", + "unexpected end of hex escape", + "recursion limit exceeded", +]; + +/// The kinds serde names an unexpected value by (`Unexpected`'s `Display`). +/// The longer first: `unit variant` before `unit value` is not an issue, but +/// `floating point` must not read as another kind. +const KINDS: &[&str] = &[ + "boolean", + "integer", + "floating point", + "character", + "string", + "byte array", + "unit value", + "Option value", + "newtype struct", + "sequence", + "map", + "enum", + "unit variant", + "newtype variant", + "tuple variant", + "struct variant", + "null", +]; + +/// What serde's primitive types and `Value` expect. +const EXPECTED: &[&str] = &[ + "a boolean", + "i8", + "i16", + "i32", + "i64", + "i128", + "u8", + "u16", + "u32", + "u64", + "u128", + "f32", + "f64", + "a character", + "a string", + "a borrowed string", + "a byte array", + "a borrowed byte array", + "option", + "unit", + "a sequence", + "a map", + "any valid JSON value", + "a JSON number", +]; + +fn data_message(message: &str, track: &Track) -> String { + for (prefix, what) in [ + ("invalid type: ", "invalid type"), + ("invalid value: ", "invalid value"), + ] { + if let Some(rest) = message.strip_prefix(prefix) { + let mut shown = what.to_string(); + if let Some(kind) = KINDS.iter().find(|kind| { + rest.strip_prefix(**kind) + .is_some_and(|after| after.is_empty() || after.starts_with([' ', ','])) + }) { + shown.push_str(": "); + shown.push_str(kind); + } + // What the type expects, when it is serde's or the type's name. + if let Some(expected) = rest.rfind(", expected ").map(|at| &rest[at + 11..]) + && let Some(expected) = expected_by_type(expected, track) + { + shown.push_str(", expected "); + shown.push_str(&expected); + } + return shown; + } + } + for (prefix, what) in [ + ("missing field `", "missing field"), + ("duplicate field `", "duplicate field"), + ] { + if let Some(rest) = message.strip_prefix(prefix) { + // The name a derived type gives serde, never one the input wrote. + return match rest + .strip_suffix('`') + .and_then(|name| track.static_name(name)) + { + Some(name) => format!("{what} `{name}`"), + None => what.to_string(), + }; + } + } + for (prefix, what) in [ + ("invalid length ", "invalid length"), + ("unknown variant `", "unknown variant"), + ("unknown field `", "unknown field"), + ( + "data did not match any variant of untagged enum ", + "no variant of an untagged enum matches", + ), + ] { + if message.starts_with(prefix) { + return what.to_string(); + } + } + "the type's `Deserialize` refused the value".to_string() +} + +/// `expected` as this crate writes it, from its tables and the names the +/// type gave serde. +fn expected_by_type(expected: &str, track: &Track) -> Option { + if let Some(known) = EXPECTED.iter().find(|known| **known == expected) { + return Some((*known).to_string()); + } + for kind in ["struct ", "tuple struct ", "unit struct ", "enum "] { + if let Some(name) = expected + .strip_prefix(kind) + .and_then(|name| track.static_name(name)) + { + return Some(format!("{kind}{name}")); + } + } + None +} + +/// One step of the path to a value. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Segment { + /// A field or a variant, by the name its type gives serde. + Name(&'static str), + /// An entry of a sequence. + Index(usize), + /// A map key, or a name the type does not know: never shown. + Key, +} + +fn render(path: &[Segment]) -> String { + if path.is_empty() { + return ".".to_string(); + } + let mut shown = String::new(); + for segment in path { + match segment { + Segment::Name(name) => { + if !shown.is_empty() { + shown.push('.'); + } + shown.push_str(name); + } + Segment::Index(index) => shown.push_str(&format!("[{index}]")), + Segment::Key => shown.push_str("[key]"), + } + } + shown +} + +/// The path to the value being read, on the stack. +enum Chain<'a> { + Root, + Step { + parent: &'a Chain<'a>, + segment: Segment, + }, +} + +impl Chain<'_> { + fn segments(&self) -> Vec { + let mut segments = Vec::new(); + let mut chain = self; + while let Chain::Step { parent, segment } = chain { + segments.push(*segment); + chain = parent; + } + segments.reverse(); + segments + } +} + +/// The path of the first error, and the names the types gave serde. +#[derive(Default)] +struct Track { + path: RefCell>>, + /// The lists of names seen, once each. + lists: RefCell>, + /// The names of the types seen. + types: RefCell>, +} + +impl Track { + /// Keeps the path of the innermost error: the first one to get here. + fn trigger(&self, chain: &Chain<'_>, error: E) -> E { + let mut path = self.path.borrow_mut(); + if path.is_none() { + *path = Some(chain.segments()); + } + error + } + + fn names(&self, names: &'static [&'static str]) { + let mut lists = self.lists.borrow_mut(); + if !lists.iter().any(|seen| std::ptr::eq(*seen, names)) { + lists.push(names); + } + } + + fn type_name(&self, name: &'static str) { + let mut types = self.types.borrow_mut(); + if !types.contains(&name) { + types.push(name); + } + } + + /// `text` as a name a type gave serde, when it is one. + fn static_name(&self, text: &str) -> Option<&'static str> { + let lists = self.lists.borrow(); + let types = self.types.borrow(); + lists + .iter() + .flat_map(|names| names.iter()) + .chain(types.iter()) + .find(|name| **name == text) + .copied() + } +} + +/// The name in `names` that `text` is, else [`Segment::Key`]. +fn segment_of(text: &str, names: Option<&'static [&'static str]>) -> Segment { + names + .and_then(|names| names.iter().find(|name| **name == text)) + .map_or(Segment::Key, |name| Segment::Name(name)) +} + +struct Wrap<'a, 'b, D> { + inner: D, + chain: &'a Chain<'a>, + track: &'b Track, +} + +macro_rules! forward { + ($($method:ident($($arg:ident: $type:ty),*);)*) => {$( + fn $method>(self, $($arg: $type,)* visitor: V) -> Result { + let (chain, track) = (self.chain, self.track); + self.inner + .$method($($arg,)* WrapVisitor { inner: visitor, chain, track, names: None }) + .map_err(|error| track.trigger(chain, error)) + } + )*}; +} + +impl<'de, D: Deserializer<'de>> Deserializer<'de> for Wrap<'_, '_, D> { + type Error = D::Error; + + forward! { + deserialize_any(); + deserialize_bool(); + deserialize_i8(); + deserialize_i16(); + deserialize_i32(); + deserialize_i64(); + deserialize_i128(); + deserialize_u8(); + deserialize_u16(); + deserialize_u32(); + deserialize_u64(); + deserialize_u128(); + deserialize_f32(); + deserialize_f64(); + deserialize_char(); + deserialize_str(); + deserialize_string(); + deserialize_bytes(); + deserialize_byte_buf(); + deserialize_option(); + deserialize_unit(); + deserialize_seq(); + deserialize_tuple(len: usize); + deserialize_map(); + deserialize_identifier(); + deserialize_ignored_any(); + } + + fn deserialize_unit_struct>( + self, + name: &'static str, + visitor: V, + ) -> Result { + self.track.type_name(name); + let (chain, track) = (self.chain, self.track); + self.inner + .deserialize_unit_struct(name, WrapVisitor::new(visitor, chain, track, None)) + .map_err(|error| track.trigger(chain, error)) + } + + fn deserialize_newtype_struct>( + self, + name: &'static str, + visitor: V, + ) -> Result { + self.track.type_name(name); + let (chain, track) = (self.chain, self.track); + self.inner + .deserialize_newtype_struct(name, WrapVisitor::new(visitor, chain, track, None)) + .map_err(|error| track.trigger(chain, error)) + } + + fn deserialize_tuple_struct>( + self, + name: &'static str, + len: usize, + visitor: V, + ) -> Result { + self.track.type_name(name); + let (chain, track) = (self.chain, self.track); + self.inner + .deserialize_tuple_struct(name, len, WrapVisitor::new(visitor, chain, track, None)) + .map_err(|error| track.trigger(chain, error)) + } + + fn deserialize_struct>( + self, + name: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result { + self.track.type_name(name); + self.track.names(fields); + let (chain, track) = (self.chain, self.track); + self.inner + .deserialize_struct( + name, + fields, + WrapVisitor::new(visitor, chain, track, Some(fields)), + ) + .map_err(|error| track.trigger(chain, error)) + } + + fn deserialize_enum>( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result { + self.track.type_name(name); + self.track.names(variants); + let (chain, track) = (self.chain, self.track); + self.inner + .deserialize_enum( + name, + variants, + WrapVisitor::new(visitor, chain, track, Some(variants)), + ) + .map_err(|error| track.trigger(chain, error)) + } + + fn is_human_readable(&self) -> bool { + self.inner.is_human_readable() + } +} + +struct WrapVisitor<'a, 'b, X> { + inner: X, + chain: &'a Chain<'a>, + track: &'b Track, + /// The fields of a struct, the variants of an enum. + names: Option<&'static [&'static str]>, +} + +impl<'a, 'b, X> WrapVisitor<'a, 'b, X> { + fn new( + inner: X, + chain: &'a Chain<'a>, + track: &'b Track, + names: Option<&'static [&'static str]>, + ) -> Self { + Self { + inner, + chain, + track, + names, + } + } +} + +macro_rules! forward_visit { + ($($method:ident($type:ty);)*) => {$( + fn $method(self, value: $type) -> Result { + self.inner.$method(value) + } + )*}; +} + +impl<'de, X: Visitor<'de>> Visitor<'de> for WrapVisitor<'_, '_, X> { + type Value = X::Value; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.inner.expecting(formatter) + } + + forward_visit! { + visit_bool(bool); + visit_i8(i8); + visit_i16(i16); + visit_i32(i32); + visit_i64(i64); + visit_i128(i128); + visit_u8(u8); + visit_u16(u16); + visit_u32(u32); + visit_u64(u64); + visit_u128(u128); + visit_f32(f32); + visit_f64(f64); + visit_char(char); + visit_str(&str); + visit_borrowed_str(&'de str); + visit_string(String); + visit_bytes(&[u8]); + visit_borrowed_bytes(&'de [u8]); + visit_byte_buf(Vec); + } + + fn visit_none(self) -> Result { + self.inner.visit_none() + } + + fn visit_unit(self) -> Result { + self.inner.visit_unit() + } + + fn visit_some>(self, deserializer: D) -> Result { + self.inner.visit_some(Wrap { + inner: deserializer, + chain: self.chain, + track: self.track, + }) + } + + fn visit_newtype_struct>( + self, + deserializer: D, + ) -> Result { + self.inner.visit_newtype_struct(Wrap { + inner: deserializer, + chain: self.chain, + track: self.track, + }) + } + + fn visit_seq>(self, seq: A) -> Result { + self.inner.visit_seq(WrapSeq { + inner: seq, + chain: self.chain, + track: self.track, + index: 0, + }) + } + + fn visit_map>(self, map: A) -> Result { + self.inner.visit_map(WrapMap { + inner: map, + chain: self.chain, + track: self.track, + names: self.names, + key: None, + }) + } + + fn visit_enum>(self, data: A) -> Result { + self.inner.visit_enum(WrapEnum { + inner: data, + chain: self.chain, + track: self.track, + names: self.names, + }) + } +} + +struct WrapSeed<'a, 'b, S> { + inner: S, + chain: &'a Chain<'a>, + track: &'b Track, +} + +impl<'de, S: DeserializeSeed<'de>> DeserializeSeed<'de> for WrapSeed<'_, '_, S> { + type Value = S::Value; + + fn deserialize>(self, deserializer: D) -> Result { + self.inner.deserialize(Wrap { + inner: deserializer, + chain: self.chain, + track: self.track, + }) + } +} + +struct WrapSeq<'a, 'b, A> { + inner: A, + chain: &'a Chain<'a>, + track: &'b Track, + index: usize, +} + +impl<'de, A: SeqAccess<'de>> SeqAccess<'de> for WrapSeq<'_, '_, A> { + type Error = A::Error; + + fn next_element_seed>( + &mut self, + seed: T, + ) -> Result, A::Error> { + let chain = Chain::Step { + parent: self.chain, + segment: Segment::Index(self.index), + }; + self.index += 1; + let track = self.track; + self.inner + .next_element_seed(WrapSeed { + inner: seed, + chain: &chain, + track, + }) + .map_err(|error| track.trigger(&chain, error)) + } + + fn size_hint(&self) -> Option { + self.inner.size_hint() + } +} + +struct WrapMap<'a, 'b, A> { + inner: A, + chain: &'a Chain<'a>, + track: &'b Track, + names: Option<&'static [&'static str]>, + /// The segment of the last key read. + key: Option, +} + +impl<'de, A: MapAccess<'de>> MapAccess<'de> for WrapMap<'_, '_, A> { + type Error = A::Error; + + fn next_key_seed>( + &mut self, + seed: K, + ) -> Result, A::Error> { + self.key = None; + let names = self.names; + let result = self.inner.next_key_seed(KeySeed { + inner: seed, + names, + key: &mut self.key, + }); + result.map_err(|error| { + let chain = Chain::Step { + parent: self.chain, + segment: self.key.unwrap_or(Segment::Key), + }; + self.track.trigger(&chain, error) + }) + } + + fn next_value_seed>(&mut self, seed: V) -> Result { + let chain = Chain::Step { + parent: self.chain, + segment: self.key.take().unwrap_or(Segment::Key), + }; + let track = self.track; + self.inner + .next_value_seed(WrapSeed { + inner: seed, + chain: &chain, + track, + }) + .map_err(|error| track.trigger(&chain, error)) + } + + fn size_hint(&self) -> Option { + self.inner.size_hint() + } +} + +struct WrapEnum<'a, 'b, A> { + inner: A, + chain: &'a Chain<'a>, + track: &'b Track, + names: Option<&'static [&'static str]>, +} + +impl<'a, 'b, 'de, A: EnumAccess<'de>> EnumAccess<'de> for WrapEnum<'a, 'b, A> { + type Error = A::Error; + type Variant = WrapVariant<'a, 'b, A::Variant>; + + fn variant_seed>( + self, + seed: V, + ) -> Result<(V::Value, Self::Variant), A::Error> { + let mut key = None; + let (chain, track) = (self.chain, self.track); + let (value, variant) = self + .inner + .variant_seed(KeySeed { + inner: seed, + names: self.names, + key: &mut key, + }) + .map_err(|error| track.trigger(chain, error))?; + Ok(( + value, + WrapVariant { + inner: variant, + parent: chain, + segment: key.unwrap_or(Segment::Key), + track, + }, + )) + } +} + +struct WrapVariant<'a, 'b, A> { + inner: A, + parent: &'a Chain<'a>, + segment: Segment, + track: &'b Track, +} + +impl<'de, A: VariantAccess<'de>> VariantAccess<'de> for WrapVariant<'_, '_, A> { + type Error = A::Error; + + fn unit_variant(self) -> Result<(), A::Error> { + let chain = Chain::Step { + parent: self.parent, + segment: self.segment, + }; + let track = self.track; + self.inner + .unit_variant() + .map_err(|error| track.trigger(&chain, error)) + } + + fn newtype_variant_seed>(self, seed: T) -> Result { + let chain = Chain::Step { + parent: self.parent, + segment: self.segment, + }; + let track = self.track; + self.inner + .newtype_variant_seed(WrapSeed { + inner: seed, + chain: &chain, + track, + }) + .map_err(|error| track.trigger(&chain, error)) + } + + fn tuple_variant>(self, len: usize, visitor: V) -> Result { + let chain = Chain::Step { + parent: self.parent, + segment: self.segment, + }; + let track = self.track; + self.inner + .tuple_variant(len, WrapVisitor::new(visitor, &chain, track, None)) + .map_err(|error| track.trigger(&chain, error)) + } + + fn struct_variant>( + self, + fields: &'static [&'static str], + visitor: V, + ) -> Result { + self.track.names(fields); + let chain = Chain::Step { + parent: self.parent, + segment: self.segment, + }; + let track = self.track; + self.inner + .struct_variant( + fields, + WrapVisitor::new(visitor, &chain, track, Some(fields)), + ) + .map_err(|error| track.trigger(&chain, error)) + } +} + +/// Reads a map key or a variant name, and notes which segment it is. +struct KeySeed<'k, S> { + inner: S, + names: Option<&'static [&'static str]>, + key: &'k mut Option, +} + +impl<'de, S: DeserializeSeed<'de>> DeserializeSeed<'de> for KeySeed<'_, S> { + type Value = S::Value; + + fn deserialize>(self, deserializer: D) -> Result { + self.inner.deserialize(KeyDeserializer { + inner: deserializer, + names: self.names, + key: self.key, + }) + } +} + +struct KeyDeserializer<'k, D> { + inner: D, + names: Option<&'static [&'static str]>, + key: &'k mut Option, +} + +macro_rules! forward_key { + ($($method:ident($($arg:ident: $type:ty),*);)*) => {$( + fn $method>(self, $($arg: $type,)* visitor: V) -> Result { + self.inner.$method($($arg,)* KeyVisitor { inner: visitor, names: self.names, key: self.key }) + } + )*}; +} + +impl<'de, D: Deserializer<'de>> Deserializer<'de> for KeyDeserializer<'_, D> { + type Error = D::Error; + + forward_key! { + deserialize_any(); + deserialize_bool(); + deserialize_i8(); + deserialize_i16(); + deserialize_i32(); + deserialize_i64(); + deserialize_i128(); + deserialize_u8(); + deserialize_u16(); + deserialize_u32(); + deserialize_u64(); + deserialize_u128(); + deserialize_f32(); + deserialize_f64(); + deserialize_char(); + deserialize_str(); + deserialize_string(); + deserialize_bytes(); + deserialize_byte_buf(); + deserialize_option(); + deserialize_unit(); + deserialize_unit_struct(name: &'static str); + deserialize_newtype_struct(name: &'static str); + deserialize_seq(); + deserialize_tuple(len: usize); + deserialize_tuple_struct(name: &'static str, len: usize); + deserialize_map(); + deserialize_struct(name: &'static str, fields: &'static [&'static str]); + deserialize_enum(name: &'static str, variants: &'static [&'static str]); + deserialize_identifier(); + deserialize_ignored_any(); + } + + fn is_human_readable(&self) -> bool { + self.inner.is_human_readable() + } +} + +struct KeyVisitor<'k, X> { + inner: X, + names: Option<&'static [&'static str]>, + key: &'k mut Option, +} + +macro_rules! capture_key { + ($($method:ident($type:ty);)*) => {$( + fn $method(self, value: $type) -> Result { + *self.key = Some(Segment::Key); + self.inner.$method(value) + } + )*}; +} + +impl<'de, X: Visitor<'de>> Visitor<'de> for KeyVisitor<'_, X> { + type Value = X::Value; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.inner.expecting(formatter) + } + + capture_key! { + visit_bool(bool); + visit_i8(i8); + visit_i16(i16); + visit_i32(i32); + visit_i64(i64); + visit_i128(i128); + visit_u8(u8); + visit_u16(u16); + visit_u32(u32); + visit_u64(u64); + visit_u128(u128); + visit_f32(f32); + visit_f64(f64); + visit_char(char); + visit_bytes(&[u8]); + visit_borrowed_bytes(&'de [u8]); + visit_byte_buf(Vec); + } + + fn visit_str(self, value: &str) -> Result { + *self.key = Some(segment_of(value, self.names)); + self.inner.visit_str(value) + } + + fn visit_borrowed_str(self, value: &'de str) -> Result { + *self.key = Some(segment_of(value, self.names)); + self.inner.visit_borrowed_str(value) + } + + fn visit_string(self, value: String) -> Result { + *self.key = Some(segment_of(&value, self.names)); + self.inner.visit_string(value) + } + + fn visit_none(self) -> Result { + self.inner.visit_none() + } + + fn visit_unit(self) -> Result { + self.inner.visit_unit() + } + + fn visit_some>(self, deserializer: D) -> Result { + self.inner.visit_some(deserializer) + } + + fn visit_newtype_struct>( + self, + deserializer: D, + ) -> Result { + self.inner.visit_newtype_struct(deserializer) + } + + fn visit_seq>(self, seq: A) -> Result { + self.inner.visit_seq(seq) + } + + fn visit_map>(self, map: A) -> Result { + self.inner.visit_map(map) + } + + fn visit_enum>(self, data: A) -> Result { + self.inner.visit_enum(data) + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use serde::Deserialize; + use serde_json::json; + + use super::*; + + fn error(value: serde_json::Value) -> Failure { + match read::<_, T>(value, None) { + Err(failure) => failure, + Ok(value) => panic!("read {value:?}"), + } + } + + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + struct Order { + name: String, + lines: Vec, + totals: BTreeMap, + } + + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + struct Line { + quantity: u64, + kind: Kind, + } + + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + enum Kind { + Physical, + Digital { url: String }, + } + + #[test] + fn paths_name_fields_and_hide_keys() { + let failure = error::(json!({ + "name": "#1", + "lines": [{ "quantity": 1, "kind": "Physical" }, { "quantity": "SECRET", "kind": "Physical" }], + "totals": {}, + })); + assert_eq!(failure.path, "lines[1].quantity"); + assert_eq!(failure.message, "invalid type: string, expected u64"); + assert!(failure.detail.contains("SECRET")); + + let failure = error::(json!({ + "name": "#1", + "lines": [], + "totals": { "https://x.test/k?sig=SECRET": "SECRET" }, + })); + assert_eq!(failure.path, "totals[key]"); + assert_eq!(failure.message, "invalid type: string, expected u64"); + + let failure = error::(json!({ + "name": "#1", + "lines": [{ "quantity": 1, "kind": { "Digital": { "url": 3 } } }], + "totals": {}, + })); + assert_eq!(failure.path, "lines[0].kind.Digital.url"); + assert_eq!(failure.message, "invalid type: integer, expected a string"); + } + + #[test] + fn messages_keep_only_names_the_types_give() { + let failure = error::(json!({ "name": "#1", "lines": [] })); + assert_eq!( + (failure.path.as_str(), failure.message.as_str()), + (".", "missing field `totals`") + ); + let failure = error::(json!("shpat_SECRET")); + assert_eq!(failure.message, "unknown variant"); + assert!(failure.detail.contains("shpat_SECRET")); + + #[derive(Debug)] + struct Custom; + impl<'de> Deserialize<'de> for Custom { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Err(de::Error::custom(format!( + "missing field `{text}` and invalid type: string {text:?}" + ))) + } + } + // Its message starts like serde's: the name it quotes is not a field's. + let failure = error::(json!("shpat_SECRET")); + assert_eq!(failure.message, "missing field"); + let failure = error::(json!("\"\\\"shpat_SECRET\\\"")); + assert!(!failure.message.contains("SECRET")); + } + + #[test] + fn text_errors_give_a_position_and_no_text() { + let failure = from_slice::(br#"{"name": "shpat_SECRET" "#) + .err() + .unwrap(); + assert_eq!( + failure.message, + "EOF while parsing an object at line 1 column 24" + ); + let failure = from_slice::(br#"{"name": shpat_SECRET}"#) + .err() + .unwrap(); + assert_eq!(failure.message, "expected value at line 1 column 10"); + let failure = from_slice::(b"1 shpat").err().unwrap(); + assert_eq!(failure.message, "trailing characters at line 1 column 3"); + } +} diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index 125626c..4f6247e 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -10,63 +10,89 @@ pub type Result = std::result::Result; /// What went wrong, with what Shopify said about it. /// +/// # What an error shows +/// /// What an error displays (`Display`, `Debug`, `{:#?}`) and what its -/// [`source`](std::error::Error::source) chain displays holds no secret the -/// crate knows of: +/// [`source`](std::error::Error::source) chain displays is written by this +/// crate. Text the crate does not control is not put in it, whatever it +/// looks like: +/// +/// - no body of an answer: [`Error::Http`] shows the status, the address, +/// the kind of content and the length of the body; +/// - no value of an answer, no map key, no message of serde: +/// [`Error::Decode`] says what kind of mismatch it is (`invalid type: +/// string, expected u64`, ``missing field `id` ``, `unknown variant`, a +/// JSON syntax error), where (the line and column of a text), and the path to +/// it, made of the names of the fields and variants the Rust type declares +/// and of indexes; a map key, or a name the type does not declare, is +/// `[key]`; +/// - nothing of what a `Serialize` implementation wrote: [`Error::Variables`] +/// says which variable does not serialize, and why in this crate's words; +/// - of an address, the scheme, the host and the path only: no user, no +/// password, no query string (a signature), no fragment; +/// - of the token endpoint's refusal, its status and its standard OAuth error +/// code; +/// - no shop domain or API version that does not validate: a token given in +/// their place is not shown. +/// +/// - of the partial `data` of a GraphQL error, and of its `extensions` but +/// `code`, how many entries there are: no name, no value; +/// - of a bulk operation, its ID when it is a `gid://` of Shopify, a status +/// or error code this crate knows, and which count does not read as a +/// number, not the count; +/// - the name of a variable when it is a GraphQL name, and the names of the +/// fields, variants and types your Rust types declare. /// -/// - no access token, refresh token or client secret; -/// - no query string or fragment of an address, which may be signed (the -/// results of a bulk operation, a staged upload); -/// - no value of the answer: [`Error::Decode`] names the path and the kinds -/// of value, without the value; the `data` and the `extensions` of a -/// GraphQL error show the names of their entries, not their values; -/// - of a body that is not a success, [`Error::Http`] shows at most 1 KiB, -/// with query strings, words that look like a token (Shopify's `shp…_` -/// prefixes, JWTs, 32 letters and digits or more) and the values of entries -/// named like a secret (`access_token`, `X-Goog-Signature`, -/// `Authorization`, …) replaced by `[redacted]`. +/// What is shown as is, because this crate does not write it: the +/// `message`, `path`, `locations` and `extensions.code` of Shopify's +/// `errors`, and the `field`, `message` and `code` of its `userErrors`, which +/// Shopify writes for people (a message may quote a part of a variable that +/// does not validate); the error of your +/// [`Transport`](crate::transport::Transport) (the default transport's leaves +/// the address out) and of your [`TokenStore`](crate::TokenStore), and the +/// `source` chain of either. /// -/// What is shown as is: the messages Shopify writes (in `errors` and -/// `userErrors`), which may quote a part of a variable that does not -/// validate; the messages of your [`Transport`](crate::transport::Transport) -/// and of your [`TokenStore`](crate::TokenStore); and what a type's own -/// `Deserialize` implementation writes outside quotes. +/// # What stays available /// -/// The values themselves stay available where you ask for them: -/// [`GraphqlErrors::data`], [`GraphqlError::extensions`] and -/// [`Error::raw_http_body`]. -#[derive(Debug, thiserror::Error)] +/// The text that is not shown stays available to code that asks for it, +/// through accessors that say so: [`Error::raw_http_body`], +/// [`Error::sensitive_detail`] (serde's message, a `Serialize` +/// implementation's, the token endpoint's answer), [`GraphqlErrors::data`], +/// [`GraphqlError::extensions`], and the fields of the variants. +/// They may hold secrets: do not log them. #[non_exhaustive] pub enum Error { - /// Not a shop's handle or `myshopify.com` domain. - #[error("invalid shop `{0}`: expected `` or `.myshopify.com`")] + /// Not a shop's handle or `myshopify.com` domain. The text is the one + /// given; it is not shown, in case it is a token given in its place. InvalidShop(String), - #[error("invalid API version `{version}`: {reason}")] + /// Not an API version this crate supports. `version` is shown only when + /// it is written `YYYY-MM`. #[non_exhaustive] - InvalidApiVersion { version: String, reason: String }, + InvalidApiVersion { + version: String, + reason: String, + }, /// The request did not reach Shopify, or its answer did not arrive. - #[error("request to {url} failed: {source}")] #[non_exhaustive] Transport { - /// The address, without its query string. + /// The address, without its user, query string and fragment. url: String, - #[source] source: TransportError, }, /// Shopify answered with a status other than 2xx. - #[error("Shopify answered {status} to {url}: {body}")] #[non_exhaustive] Http { status: u16, - /// The address, without its query string. + /// The address, without its user, query string and fragment. url: String, - /// The body of the answer, cut at 1 KiB, with what looks like a - /// secret replaced by `[redacted]` (see [`Error`]). - body: String, - /// Shopify's `X-Request-Id`, which its support asks for. + /// The `Content-Type` of the answer, as it was received. `Display` + /// and `Debug` show it only when it is a common type. + content_type: Option, + /// Shopify's `X-Request-Id`, which its support asks for. `Debug` + /// shows it when it is made of hexadecimal digits and dashes. request_id: Option, /// The whole body, as it was received. It may hold secrets: read it /// with [`Error::raw_http_body`]. Its `Debug` shows its length only. @@ -74,12 +100,10 @@ pub enum Error { }, /// The answer has a non-empty `errors` list. - #[error("GraphQL errors: {0}")] Graphql(GraphqlErrors), /// Shopify still throttled the request after the retries of the client's /// [`RetryPolicy`](crate::RetryPolicy). - #[error("throttled by Shopify after {retries} retries")] #[non_exhaustive] Throttled { retries: u32, @@ -88,27 +112,43 @@ pub enum Error { retry_after: Option, }, - /// The `data` of the answer does not fit the type it is read as: the - /// shop runs another API version than the schema the operation was - /// checked against, or a test scripts an answer without a non-null field. - #[error("Shopify's answer does not match the operation at `{path}`: {message}")] + /// A JSON text, or the `data` of an answer, that does not fit the type + /// it is read as: the shop runs another API version than the schema the + /// operation was checked against, a test scripts an answer without a + /// non-null field, a body is not JSON. + /// + /// `path` and `message` are written by this crate (see [`Error`]); + /// serde's own message is in `detail`. #[non_exhaustive] - Decode { path: String, message: String }, - - /// A body that is not the JSON it should be. - #[error("invalid JSON: {0}")] - Json(#[from] serde_json::Error), + Decode { + /// The fields and variants the type declares, indexes, and `[key]` + /// for anything else; `.` for the whole value. + path: String, + message: String, + /// serde's message: it may quote the value. See + /// [`Error::sensitive_detail`]. + detail: Option, + }, /// Variables that do not serialize, or not to an object. - #[error("invalid variables: {0}")] - Variables(String), + #[non_exhaustive] + Variables { + message: String, + /// The message of the `Serialize` implementation that failed: it may + /// quote the value. See [`Error::sensitive_detail`]. + detail: Option, + }, /// A token could not be obtained or renewed. - #[error("authentication failed: {0}")] - Auth(String), + #[non_exhaustive] + Auth { + message: String, + /// What the token endpoint said, or serde's message about its + /// answer. See [`Error::sensitive_detail`]. + detail: Option, + }, /// A mutation that this crate runs for you returned `userErrors`. - #[error("{mutation} refused: {}", UserErrors(errors))] #[non_exhaustive] UserErrors { mutation: &'static str, @@ -116,34 +156,224 @@ pub enum Error { }, /// A bulk operation failed, or its answer misses what was expected. - #[error("bulk operation: {0}")] Bulk(String), - #[error("timed out: {0}")] Timeout(String), /// The [`TokenStore`](crate::TokenStore) of the client failed to save a /// renewed token. The client holds the new token all the same. - #[error("the token store failed: {0}")] - TokenStore(#[source] Box), + TokenStore(Box), /// The client has no transport: enable the `rustls` or `native-tls` /// feature, or give one with [`ShopifyBuilder::transport`](crate::ShopifyBuilder::transport). - #[error( - "no HTTP transport: enable the `rustls` or `native-tls` feature, or set one with `ShopifyBuilder::transport`" - )] NoTransport, /// A webhook, an OAuth callback, an app proxy request or a session token /// that does not verify. - #[error("verification failed: {0}")] Verification(String), /// A client that cannot be set up, such as a transport that does not start. - #[error("configuration: {0}")] Config(String), } +impl fmt::Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidShop(_) => formatter + .write_str("invalid shop: expected `` or `.myshopify.com`"), + Self::InvalidApiVersion { version, reason } => match shown_version(version) { + Some(version) => write!(formatter, "invalid API version `{version}`: {reason}"), + None => write!(formatter, "invalid API version: {reason}"), + }, + Self::Transport { url, source } => write!(formatter, "request to {url} failed: {source}"), + Self::Http { + status, + url, + content_type, + raw_body, + .. + } => write!( + formatter, + "Shopify answered {status} to {url} ({}, {} bytes)", + shown_content_type(content_type.as_deref()), + raw_body.0.len() + ), + Self::Graphql(errors) => write!(formatter, "GraphQL errors: {errors}"), + Self::Throttled { retries, .. } => { + write!(formatter, "throttled by Shopify after {retries} retries") + } + Self::Decode { path, message, .. } => write!( + formatter, + "Shopify's answer does not match the operation at `{path}`: {message}" + ), + Self::Variables { message, .. } => write!(formatter, "invalid variables: {message}"), + Self::Auth { message, .. } => write!(formatter, "authentication failed: {message}"), + Self::UserErrors { mutation, errors } => { + write!(formatter, "{mutation} refused: {}", UserErrors(errors)) + } + Self::Bulk(message) => write!(formatter, "bulk operation: {message}"), + Self::Timeout(message) => write!(formatter, "timed out: {message}"), + Self::TokenStore(error) => write!(formatter, "the token store failed: {error}"), + Self::NoTransport => formatter.write_str( + "no HTTP transport: enable the `rustls` or `native-tls` feature, or set one with `ShopifyBuilder::transport`", + ), + Self::Verification(message) => write!(formatter, "verification failed: {message}"), + Self::Config(message) => write!(formatter, "configuration: {message}"), + } + } +} + +impl fmt::Debug for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidShop(shop) => formatter + .debug_tuple("InvalidShop") + .field(&format_args!("[{} bytes]", shop.len())) + .finish(), + Self::InvalidApiVersion { version, reason } => formatter + .debug_struct("InvalidApiVersion") + .field( + "version", + &shown_version(version).map_or_else( + || format!("[{} bytes]", version.len()), + |version| format!("{version:?}"), + ), + ) + .field("reason", reason) + .finish(), + Self::Transport { url, source } => formatter + .debug_struct("Transport") + .field("url", url) + .field("source", source) + .finish(), + Self::Http { + status, + url, + content_type, + request_id, + raw_body, + } => formatter + .debug_struct("Http") + .field("status", status) + .field("url", url) + .field( + "content_type", + &content_type + .as_deref() + .map(|content_type| shown_content_type(Some(content_type))), + ) + .field( + "request_id", + &request_id + .as_deref() + .map(|id| if is_request_id(id) { id } else { "[not shown]" }), + ) + .field("raw_body", raw_body) + .finish(), + Self::Graphql(errors) => formatter.debug_tuple("Graphql").field(errors).finish(), + Self::Throttled { + retries, + cost, + retry_after, + } => formatter + .debug_struct("Throttled") + .field("retries", retries) + .field("cost", cost) + .field("retry_after", retry_after) + .finish(), + Self::Decode { + path, + message, + detail, + } => formatter + .debug_struct("Decode") + .field("path", path) + .field("message", message) + .field("detail", detail) + .finish(), + Self::Variables { message, detail } => formatter + .debug_struct("Variables") + .field("message", message) + .field("detail", detail) + .finish(), + Self::Auth { message, detail } => formatter + .debug_struct("Auth") + .field("message", message) + .field("detail", detail) + .finish(), + Self::UserErrors { mutation, errors } => formatter + .debug_struct("UserErrors") + .field("mutation", mutation) + .field("errors", errors) + .finish(), + Self::Bulk(message) => formatter.debug_tuple("Bulk").field(message).finish(), + Self::Timeout(message) => formatter.debug_tuple("Timeout").field(message).finish(), + Self::TokenStore(error) => formatter.debug_tuple("TokenStore").field(error).finish(), + Self::NoTransport => formatter.write_str("NoTransport"), + Self::Verification(message) => formatter + .debug_tuple("Verification") + .field(message) + .finish(), + Self::Config(message) => formatter.debug_tuple("Config").field(message).finish(), + } + } +} + +impl std::error::Error for Error { + /// The transport's error, or the token store's: no other error is kept, + /// so that none shows what [`Error`] does not. + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Transport { source, .. } => Some(source), + Self::TokenStore(error) => Some(error.as_ref()), + _ => None, + } + } +} + +/// `version` when it is written `YYYY-MM`: digits cannot be a token. +fn shown_version(version: &str) -> Option<&str> { + let bytes = version.as_bytes(); + (bytes.len() == 7 + && bytes[4] == b'-' + && bytes[..4].iter().chain(&bytes[5..]).all(u8::is_ascii_digit)) + .then_some(version) +} + +/// The kind of content of an answer, from this crate's list. +fn shown_content_type(content_type: Option<&str>) -> &'static str { + const KNOWN: [&str; 11] = [ + "application/json", + "application/graphql-response+json", + "application/problem+json", + "application/jsonl", + "application/x-ndjson", + "application/xml", + "application/octet-stream", + "text/xml", + "text/html", + "text/plain", + "text/csv", + ]; + let Some(content_type) = content_type else { + return "no content type"; + }; + let essence = content_type.split(';').next().unwrap_or_default().trim(); + KNOWN + .iter() + .find(|known| known.eq_ignore_ascii_case(essence)) + .copied() + .unwrap_or("another content type") +} + +/// An `X-Request-Id` as Shopify writes them: hexadecimal digits and dashes. +fn is_request_id(id: &str) -> bool { + (1..=64).contains(&id.len()) + && id + .bytes() + .all(|byte| byte.is_ascii_hexdigit() || byte == b'-') +} + impl Error { /// The HTTP status Shopify answered with, for [`Error::Http`]. pub fn status(&self) -> Option { @@ -167,7 +397,7 @@ impl Error { } /// The whole body of the answer, for [`Error::Http`], exactly as it was - /// received: unlike `body`, nothing is cut or redacted. + /// received. /// /// **It may contain secrets** (a token, a signed address): do not log it /// or show it to a user. @@ -178,6 +408,23 @@ impl Error { } } + /// The text this crate does not show, for [`Error::Decode`] (serde's + /// message), [`Error::Variables`] (the message of the `Serialize` + /// implementation that failed) and [`Error::Auth`] (what the token + /// endpoint said). + /// + /// **It may contain secrets**: serde quotes the value that does not fit, + /// a map key, or what a type's own implementation wrote, and a token + /// endpoint may echo what it was sent. Do not log it or show it to a user. + pub fn sensitive_detail(&self) -> Option<&str> { + match self { + Self::Decode { detail, .. } + | Self::Variables { detail, .. } + | Self::Auth { detail, .. } => detail.as_ref().map(SensitiveDetail::as_str), + _ => None, + } + } + /// The errors Shopify returned, for [`Error::Graphql`]. pub fn graphql_errors(&self) -> &[GraphqlError] { match self { @@ -195,39 +442,89 @@ impl Error { /// The error of an answer that is not a success. pub(crate) fn http(url: &str, response: &HttpResponse) -> Self { - Self::http_parts( - response.status, - url, - &response.body, - response.header("X-Request-Id").map(str::to_string), - ) + Self::Http { + status: response.status, + url: without_query(url), + content_type: response.header("Content-Type").map(str::to_string), + request_id: response.header("X-Request-Id").map(str::to_string), + raw_body: RawBody(response.body.clone()), + } } - pub(crate) fn http_parts( - status: u16, - url: &str, - body: &[u8], - request_id: Option, - ) -> Self { + /// An error body that did not come with an [`HttpResponse`]. + pub(crate) fn http_parts(status: u16, url: &str, body: &[u8]) -> Self { Self::Http { status, url: without_query(url), - body: crate::redact::http_body(body), - request_id, + content_type: None, + request_id: None, raw_body: RawBody(body.to_vec()), } } - /// An answer that does not fit its type: serde's message without the - /// values it quotes. - pub(crate) fn decode(path: impl Into, message: &str) -> Self { + /// An answer that does not fit its type. `message` is this crate's; + /// `detail` is not shown. + pub(crate) fn decode(path: impl Into, message: String, detail: Option) -> Self { Self::Decode { path: path.into(), - message: crate::redact::serde_message(message), + message, + detail: detail.map(SensitiveDetail), + } + } + + /// Variables that do not serialize: `variable` is the name of the one + /// that failed, when the failure is one variable's. + pub(crate) fn variables(variable: Option<&str>, error: &serde_json::Error) -> Self { + let what = match variable { + Some(name) if is_graphql_name(name) => format!("variable `${name}` does"), + Some(_) => "a variable does".to_string(), + None => "the variables do".to_string(), + }; + // serde_json's own message about a map key does not quote it; any + // other is the `Serialize` implementation's, and may quote the value. + let why = if error.to_string().starts_with("key must be a string") { + "a map key is not a string" + } else { + "a value's `Serialize` implementation failed" + }; + Self::Variables { + message: format!("{what} not serialize: {why}"), + detail: Some(SensitiveDetail(error.to_string())), + } + } + + /// Variables that serialize to something else than an object. + pub(crate) fn variables_not_an_object() -> Self { + Self::Variables { + message: "the variables must serialize to an object".to_string(), + detail: None, + } + } + + pub(crate) fn auth(message: impl Into) -> Self { + Self::Auth { + message: message.into(), + detail: None, + } + } + + pub(crate) fn auth_with_detail(message: impl Into, detail: String) -> Self { + Self::Auth { + message: message.into(), + detail: Some(SensitiveDetail(detail)), } } } +/// A GraphQL name: what a variable is called in an operation. +fn is_graphql_name(name: &str) -> bool { + let mut bytes = name.bytes(); + bytes + .next() + .is_some_and(|first| first == b'_' || first.is_ascii_alphabetic()) + && bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric()) +} + /// The body of an answer exactly as it was received, in [`Error::Http`]. /// /// **It may contain secrets.** Its `Debug` shows its length, not its content. @@ -247,14 +544,44 @@ impl fmt::Debug for RawBody { } } -/// `url` without its query string and fragment, which may hold a signature. +/// A message this crate does not show: serde's, a `Serialize` +/// implementation's, a token endpoint's. See [`Error::sensitive_detail`]. +/// +/// **It may contain secrets.** Its `Debug` shows its length, not its content, +/// and it has no `Display`. +#[derive(Clone, PartialEq, Eq)] +pub struct SensitiveDetail(String); + +impl SensitiveDetail { + /// The message. It may contain secrets: do not log it. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Debug for SensitiveDetail { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "SensitiveDetail([{} bytes])", self.0.len()) + } +} + +/// `url` without its user, password, query string and fragment, which may +/// hold a credential. pub(crate) fn without_query(url: &str) -> String { - url.split(['?', '#']).next().unwrap_or_default().to_string() + let url = url.split(['?', '#']).next().unwrap_or_default(); + let Some((scheme, rest)) = url.split_once("://") else { + return url.to_string(); + }; + let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len())); + let host = authority + .rsplit_once('@') + .map_or(authority, |(_, host)| host); + format!("{scheme}://{host}{path}") } /// The `errors` of a GraphQL answer, and its `data` when it had some. /// -/// Its `Debug` shows the names of the fields of `data`, not their values, +/// Its `Debug` shows how many entries `data` has, not their names or values, /// which may be secret: the signed address of a bulk operation's results. #[derive(Clone)] #[non_exhaustive] @@ -274,22 +601,13 @@ impl fmt::Debug for GraphqlErrors { } } -/// The top-level keys of partial `data`, without their values. +/// How many entries partial `data` has: its keys are the answer's too. struct DataShape<'a>(&'a serde_json::Value); impl fmt::Debug for DataShape<'_> { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self.0 { - serde_json::Value::Object(fields) => { - write!(formatter, "{{")?; - for (index, key) in fields.keys().enumerate() { - if index > 0 { - write!(formatter, ", ")?; - } - write!(formatter, "{key:?}: ..")?; - } - write!(formatter, "}}") - } + serde_json::Value::Object(fields) => write!(formatter, "{{{} entries}}", fields.len()), serde_json::Value::Null => formatter.write_str("null"), _ => formatter.write_str(".."), } @@ -330,125 +648,482 @@ impl fmt::Display for UserErrors<'_> { #[cfg(test)] mod tests { + use std::collections::BTreeMap; + + use serde::{Deserialize, Serialize}; + use serde_json::{Value, json}; + use super::*; + use crate::transport::{BoxFuture, HttpRequest, Transport}; - #[test] - fn http_errors_cut_long_bodies_and_keep_no_signature() { - let error = Error::http_parts( - 500, - "https://storage.example.com/results.jsonl?X-Goog-Signature=secret#x", - "é".repeat(2000).as_bytes(), - Some("a1b2".to_string()), - ); - let Error::Http { body, url, .. } = &error else { - panic!("an HTTP error"); - }; - assert!(body.ends_with('…')); - assert!(body.len() <= 1024 + '…'.len_utf8()); - assert_eq!(url, "https://storage.example.com/results.jsonl"); - assert!(!error.to_string().contains("secret")); - assert_eq!(error.status(), Some(500)); - assert_eq!(error.request_id(), Some("a1b2")); - assert!(!error.is_unauthorized()); - assert_eq!(error.raw_http_body().unwrap().len(), 4000); + /// A token of Shopify's shape, written in two parts so that secret + /// scanners do not take this file for a leak. + const TOKEN: &str = concat!("shpat", "_0123456789abcdef0123456789abcdef"); + /// `TOKEN`, each character a JSON `\u` escape. + fn escaped_token() -> String { + TOKEN + .chars() + .map(|c| format!("\\u{:04x}", c as u32)) + .collect() + } + /// What no error may show: the token, the parts of a signed address, a + /// JSON-escaped token, a token in escaped quotes, a map key. + fn secrets() -> Vec { + vec![ + TOKEN.to_string(), + "SIGNED_SECRET".to_string(), + "USERINFO_SECRET".to_string(), + escaped_token(), + "\\u0073\\u0068".to_string(), + "QUOTED_SECRET".to_string(), + "MAPKEY_SECRET".to_string(), + "storage.test/k?".to_string(), + ] } + const SIGNED_URL: &str = + "https://me:USERINFO_SECRET@storage.test/k?sig=SIGNED_SECRET#SIGNED_SECRET"; - #[test] - fn http_errors_show_no_secret_of_their_body() { - // A storage error that echoes the signed request, a token endpoint - // that echoes the token. - let raw = concat!( - "SignatureDoesNotMatch
GET /b/r.jsonl?X-Goog-Credential=CRED_SECRET", - "&X-Goog-Signature=SIG_SECRET https://storage.googleapis.com/b/r.jsonl?X-Goog-Signature=URL_SECRET
", - r#" {"access_token":"shpat_TOKEN_SECRET","scope":"read_orders"}"#, - ); - let error = Error::http_parts( - 403, - "https://storage.googleapis.com/b/r.jsonl", - raw.as_bytes(), - None, - ); - for shown in [ - format!("{error}"), - format!("{error:?}"), - format!("{error:#?}"), - ] { - for secret in ["CRED_SECRET", "SIG_SECRET", "URL_SECRET", "TOKEN_SECRET"] { - assert!(!shown.contains(secret), "{secret} in {shown}"); - } - assert!(shown.contains("SignatureDoesNotMatch"), "{shown}"); - assert!(shown.contains("read_orders"), "{shown}"); - } - assert!(format!("{error:?}").contains("RawBody(["), "{error:?}"); - // Asked for explicitly, the body is whole. - assert_eq!(error.raw_http_body(), Some(raw.as_bytes())); - assert_eq!(Error::Variables(String::new()).raw_http_body(), None); + /// A body that holds every secret, the ways round 4 found. + fn secret_body() -> String { + format!( + "{{\"access_token\":\t\"{TOKEN}\",\n\"client_secret\":\n\"QUOTED_SECRET\",\ + \"url\":\"https:\\/\\/storage.test/k?a=1\\u0026sig=SIGNED_SECRET\",\ + \"echo\":\"{}\",\"q\":\"\\\"QUOTED_SECRET\\\"\",\ + \"https://storage.test/k?sig=MAPKEY_SECRET\":1}}\nX-Shopify-Access-Token:\t{TOKEN}", + escaped_token() + ) } - #[test] - fn json_errors_say_where_not_what() { - let source = - br#"{"data": {"url": "https://x.test/r?sig=SIGNED_SECRET"}, shpat_TOKEN_SECRET}"#; - let error: Error = serde_json::from_slice::(source) - .unwrap_err() - .into(); - let mut shown = format!("{error} {error:?} {error:#?}"); - let mut source = std::error::Error::source(&error); + /// Every way `error` is shown, its sources' included. + fn shown(error: &Error) -> String { + let mut shown = format!("{error}\n{error:?}\n{error:#?}"); + let mut source = std::error::Error::source(error); while let Some(cause) = source { - shown.push_str(&format!(" {cause} {cause:?}")); + shown.push_str(&format!("\n{cause}\n{cause:?}\n{cause:#?}")); source = cause.source(); } - assert!(!shown.contains("SECRET"), "{shown}"); - assert!(shown.contains("line 1 column"), "{shown}"); + shown } + fn assert_hides_secrets(name: &str, error: &Error) { + let shown = shown(error); + for secret in secrets() { + assert!(!shown.contains(&secret), "{name} shows {secret}:\n{shown}"); + } + // Not even decoded from JSON escapes. + assert!(!shown.contains("shpat_"), "{name}:\n{shown}"); + } + + /// A `Serialize` and a `Deserialize` whose own message quotes a token in + /// escaped quotes. + struct Leaky; + + impl Serialize for Leaky { + fn serialize(&self, _: S) -> Result { + Err(serde::ser::Error::custom(format!( + "cannot serialize {:?}", + format!("\"{TOKEN}\" QUOTED_SECRET") + ))) + } + } + + impl<'de> Deserialize<'de> for Leaky { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Err(serde::de::Error::custom(format!( + "cannot parse value {value:?}" + ))) + } + } + + /// A token endpoint that answers `body` with `status`. + struct Answer(u16, String); + + impl Transport for Answer { + fn send(&self, _: HttpRequest) -> BoxFuture<'_, Result> { + let response = HttpResponse::new(self.0, self.1.clone().into_bytes()); + Box::pin(async move { Ok(response) }) + } + } + + fn token_endpoint(status: u16, body: String) -> Error { + let shop = crate::ShopDomain::new("a-shop").unwrap(); + let transport = Answer(status, body); + let future = + crate::auth::request_token(&transport, &shop, "test", crate::auth::Encoding::Form, &[]); + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(future) + .unwrap_err() + } + + /// Every variant, built the way the crate builds it, from input that + /// holds secrets: none is shown by `Display`, `Debug`, `{:#?}` or the + /// `source` chain. #[test] - fn decode_errors_keep_kinds_not_values() { - #[derive(Debug, serde::Deserialize)] + fn no_variant_shows_a_secret() { + let body = secret_body(); + let mut errors: Vec<(&str, Error)> = Vec::new(); + + errors.push(("InvalidShop", crate::ShopDomain::new(TOKEN).unwrap_err())); + errors.push(( + "InvalidApiVersion", + crate::ApiVersion::new(TOKEN).unwrap_err(), + )); + errors.push(( + "Transport", + Error::transport(SIGNED_URL, TransportError::timeout("timed out")), + )); + errors.push(( + "Http", + Error::http( + SIGNED_URL, + &HttpResponse::new(400, body.clone()) + .with_header("Content-Type", format!("text/{TOKEN}")) + .with_header("X-Request-Id", TOKEN), + ), + )); + errors.push(( + "Graphql", + Error::Graphql(GraphqlErrors { + errors: serde_json::from_value(json!([{ + "message": "Variable $url is invalid", + "path": ["bulkOperation"], + "extensions": { + "code": "INVALID_VARIABLE", + "value": format!("https://storage.test/k?sig=SIGNED_SECRET {TOKEN}"), + "https://storage.test/k?sig=MAPKEY_SECRET": 1, + }, + }])) + .unwrap(), + data: Some(json!({ + "https://storage.test/k?sig=MAPKEY_SECRET": TOKEN, + "bulkOperation": { "url": "https://storage.test/k?sig=SIGNED_SECRET" }, + })), + }), + )); + errors.push(( + "Throttled", + Error::Throttled { + retries: 3, + cost: None, + retry_after: None, + }, + )); + // Decode: a map key, a value, a value in escaped quotes, JSON escapes, + // invalid JSON around a token, JSONL. + let raw = crate::RawResponse { + data: Some(json!({ "https://storage.test/k?sig=MAPKEY_SECRET": "SIGNED_SECRET" })), + ..Default::default() + }; + errors.push(( + "Decode map key", + raw.data_as::>().unwrap_err(), + )); + errors.push(( + "Decode escaped quotes", + crate::decode::from_value::(json!(format!("\"{TOKEN}\\\" QUOTED_SECRET"))) + .err() + .unwrap(), + )); + errors.push(( + "Decode JSON escapes", + crate::bulk::parse_jsonl::>( + format!( + "{{\"https://storage.test/k?sig=MAPKEY_SECRET\":\"{}\"}}", + escaped_token() + ) + .as_bytes(), + ) + .unwrap_err(), + )); + errors.push(( + "Decode invalid JSON", + crate::decode::from_slice::(body.as_bytes()) + .err() + .unwrap() + .into_error(), + )); + errors.push(( + "Bulk count", + crate::bulk::operation_of(&json!({ + "id": "gid://shopify/BulkOperation/1", + "type": "QUERY", + "status": "COMPLETED", + "errorCode": null, + "createdAt": "2026-01-01T00:00:00Z", + "completedAt": null, + "objectCount": format!("https://storage.test/k?sig=SIGNED_SECRET {TOKEN}"), + "rootObjectCount": "0", + "fileSize": null, + "url": null, + "partialDataUrl": null, + "query": "{ shop { id } }", + })) + .unwrap_err(), + )); + let mut operation = crate::bulk::operation_of(&json!({ + "id": TOKEN, + "type": "QUERY", + "status": TOKEN, + "errorCode": TOKEN, + "createdAt": "2026-01-01T00:00:00Z", + "completedAt": null, + "objectCount": "1", + "rootObjectCount": "1", + "fileSize": null, + "url": SIGNED_URL, + "partialDataUrl": null, + "query": "{ shop { id } }", + })) + .unwrap(); + errors.push(("Bulk ended", crate::bulk::not_completed(&operation))); + operation.id = format!("gid://shopify/BulkOperation/{TOKEN}"); + errors.push(("Bulk ended, odd id", crate::bulk::not_completed(&operation))); + errors.push(( + "Timeout", + crate::bulk::timed_out(TOKEN, std::time::Duration::from_secs(1)), + )); + // Variables: the three ways in, one path. + errors.push(( + "Variables of an operation", + crate::graphql::Operation::::new("query { shop { id } }") + .variables(BTreeMap::from([("x", Leaky)])) + .variables_json() + .unwrap_err(), + )); + errors.push(( + "Variables, one", + crate::graphql::Operation::::new("query { shop { id } }") + .json_variable("x", Leaky) + .variables_json() + .unwrap_err(), + )); + errors.push(( + "Variables, one with an odd name", + crate::graphql::Operation::::new("query { shop { id } }") + .json_variable(&format!("{TOKEN}\""), Leaky) + .variables_json() + .unwrap_err(), + )); + errors.push(( + "Variables of graphql_raw", + crate::graphql::operation::variables_of(BTreeMap::from([("x", Leaky)])).unwrap_err(), + )); + // Auth: a refusal that echoes the request, a token that does not read. + errors.push(( + "Auth refused", + token_endpoint( + 400, + json!({ "error": TOKEN, "error_description": body }).to_string(), + ), + )); + errors.push(("Auth refused, not JSON", token_endpoint(401, body.clone()))); + errors.push(( + "Auth invalid token", + token_endpoint( + 200, + json!({ "access_token": 1, "scope": [TOKEN] }).to_string(), + ), + )); + errors.push(( + "Auth invalid JSON", + token_endpoint(200, format!("{{\"access_token\": \"{TOKEN}\" ")), + )); + errors.push(( + "UserErrors", + Error::UserErrors { + mutation: "bulkOperationRunQuery", + errors: vec![UserError { + field: Some(vec!["query".to_string()]), + message: "Invalid query".to_string(), + code: None, + }], + }, + )); + errors.push(("NoTransport", Error::NoTransport)); + errors.push(("TokenStore", Error::TokenStore("the disk is full".into()))); + errors.push(( + "Config", + Error::Config("the HTTP client does not start".to_string()), + )); + #[cfg(feature = "webhooks")] + { + use base64::Engine; + use hmac::{KeyInit, Mac}; + let body = b"{}"; + let mut mac = hmac::Hmac::::new_from_slice(b"secret").unwrap(); + mac.update(body); + let signature = + base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes()); + let headers = [ + ("X-Shopify-Hmac-Sha256", signature.as_str()), + ("X-Shopify-Shop-Domain", TOKEN), + ("X-Shopify-Topic", "orders/create"), + ]; + errors.push(( + "Verification", + crate::webhooks::Webhook::verify(headers, body.to_vec(), "secret").unwrap_err(), + )); + } + + for (name, error) in &errors { + assert_hides_secrets(name, error); + } + // Each variant is there: a new one needs a case. + let mut variants: Vec<&str> = errors.iter().map(|(_, error)| variant(error)).collect(); + variants.sort_unstable(); + variants.dedup(); + let mut expected = vec![ + "Auth", + "Bulk", + "Config", + "Decode", + "Graphql", + "Http", + "InvalidApiVersion", + "InvalidShop", + "NoTransport", + "Throttled", + "Timeout", + "TokenStore", + "Transport", + "UserErrors", + "Variables", + ]; + if cfg!(feature = "webhooks") { + expected.push("Verification"); + expected.sort_unstable(); + } + assert_eq!(variants, expected); + } + + /// The name of `error`'s variant: a match with no wildcard, so that a new + /// variant does not compile until the test above covers it. + fn variant(error: &Error) -> &'static str { + match error { + Error::InvalidShop(_) => "InvalidShop", + Error::InvalidApiVersion { .. } => "InvalidApiVersion", + Error::Transport { .. } => "Transport", + Error::Http { .. } => "Http", + Error::Graphql(_) => "Graphql", + Error::Throttled { .. } => "Throttled", + Error::Decode { .. } => "Decode", + Error::Variables { .. } => "Variables", + Error::Auth { .. } => "Auth", + Error::UserErrors { .. } => "UserErrors", + Error::Bulk(_) => "Bulk", + Error::Timeout(_) => "Timeout", + Error::TokenStore(_) => "TokenStore", + Error::NoTransport => "NoTransport", + Error::Verification(_) => "Verification", + Error::Config(_) => "Config", + } + } + + #[test] + fn what_errors_show_instead() { + let error = Error::http( + "https://me:pw@a.myshopify.com/admin/api/2026-10/graphql.json?x=1", + &HttpResponse::new(500, "é".repeat(2000)) + .with_header("Content-Type", "application/json; charset=utf-8") + .with_header("X-Request-Id", "a1b2-c3"), + ); + assert_eq!( + error.to_string(), + "Shopify answered 500 to https://a.myshopify.com/admin/api/2026-10/graphql.json (application/json, 4000 bytes)" + ); + assert!(format!("{error:?}").contains("request_id: Some(\"a1b2-c3\")")); + assert_eq!(error.status(), Some(500)); + assert_eq!(error.request_id(), Some("a1b2-c3")); + assert_eq!(error.raw_http_body().unwrap().len(), 4000); + assert_eq!(error.sensitive_detail(), None); + + let raw = crate::RawResponse { + data: Some(json!({ "orders": [{ "count": "x" }] })), + ..Default::default() + }; + #[derive(Debug, Deserialize)] #[allow(dead_code)] struct Data { - count: u64, + orders: Vec, } - let value = serde_json::json!({ "count": "https://x.test/r.jsonl?sig=SIGNED_SECRET" }); - let error = crate::graphql::decode::(value).unwrap_err(); - for shown in [ - format!("{error}"), - format!("{error:?}"), - format!("{error:#?}"), - ] { - assert!(!shown.contains("SIGNED_SECRET"), "{shown}"); - assert!(!shown.contains("x.test"), "{shown}"); + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + struct Order { + count: u64, } + let error = raw.data_as::().unwrap_err(); + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `orders[0].count`: invalid type: string, expected u64" + ); + assert_eq!( + error.sensitive_detail(), + Some("invalid type: string \"x\", expected u64") + ); + let debug = format!("{error:?}"); + assert!(debug.contains("detail: Some(SensitiveDetail(["), "{debug}"); + assert!(!debug.contains("\"x\""), "{debug}"); + + let error = crate::ApiVersion::new("2026-02").unwrap_err(); + assert!( + error + .to_string() + .starts_with("invalid API version `2026-02`: "), + "{error}" + ); + + let error = crate::graphql::Operation::::new("query { shop { id } }") + .json_variable("input", Leaky) + .variables_json() + .unwrap_err(); assert_eq!( error.to_string(), - "Shopify's answer does not match the operation at `count`: invalid type: string, expected u64" + "invalid variables: variable `$input` does not serialize: a value's `Serialize` implementation failed" + ); + assert!(error.sensitive_detail().unwrap().contains(TOKEN)); + + let error = token_endpoint( + 400, + json!({ "error": "invalid_client", "error_description": "Client authentication failed" }) + .to_string(), + ); + assert_eq!( + error.to_string(), + "authentication failed: the token endpoint of a-shop.myshopify.com answered 400 (invalid_client)" + ); + assert_eq!( + error.sensitive_detail(), + Some("invalid_client: Client authentication failed") ); } #[test] - fn graphql_errors_debug_hides_partial_data() { - let errors: Vec = serde_json::from_value(serde_json::json!([{ + fn graphql_errors_keep_their_data() { + let errors: Vec = serde_json::from_value(json!([{ "message": "Access denied for orders field", "path": ["orders"], - "extensions": { "code": "ACCESS_DENIED" }, + "extensions": { "code": "ACCESS_DENIED", "documentation": "https://x" }, }])) .unwrap(); let error = Error::Graphql(GraphqlErrors { errors, - data: Some(serde_json::json!({ - "bulkOperation": { - "id": "gid://shopify/BulkOperation/1", - "url": "https://storage.googleapis.com/r.jsonl?X-Goog-Signature=SIGNED_SECRET", - }, - "orders": null, - })), + data: Some( + json!({ "bulkOperation": { "url": "https://x.test/r?sig=S" }, "orders": null }), + ), }); - let shown = format!("{error:?} {error} {error:#?}"); - assert!(!shown.contains("SIGNED_SECRET"), "{shown}"); - assert!(!shown.contains("storage.googleapis.com"), "{shown}"); - assert!(shown.contains("\"bulkOperation\": .."), "{shown}"); - assert!(shown.contains("ACCESS_DENIED"), "{shown}"); - // The data itself stays available to the caller. + let shown = format!("{error:?}"); + assert!(shown.contains("data: Some({2 entries})"), "{shown}"); + assert!( + shown.contains("code: \"ACCESS_DENIED\", others: 1 entries"), + "{shown}" + ); + assert_eq!( + error.to_string(), + "GraphQL errors: Access denied for orders field (ACCESS_DENIED)" + ); let Error::Graphql(errors) = &error else { unreachable!() }; diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index 169c70d..631b949 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -1,7 +1,7 @@ //! Running GraphQL operations: typed ones from [`graphql!`](crate::graphql!), //! untyped ones from any text. -mod operation; +pub(crate) mod operation; mod response; use serde::Serialize; @@ -93,17 +93,7 @@ impl Shopify { /// it, `errors` included: for an operation whose partial `data` matters. /// A throttled request is still retried. pub async fn graphql_raw(&self, query: &str, variables: impl Serialize) -> Result { - let variables = match serde_json::to_value(variables) - .map_err(|error| Error::Variables(crate::redact::serde_message(&error.to_string())))? - { - Value::Null => Map::new(), - Value::Object(variables) => variables, - _ => { - return Err(Error::Variables( - "the variables must serialize to an object".to_string(), - )); - } - }; + let variables = crate::graphql::operation::variables_of(variables)?; let mut body = Map::new(); body.insert("query".to_string(), Value::String(query.to_string())); if !variables.is_empty() { @@ -123,7 +113,7 @@ impl Shopify { kind: OperationKind, ) -> Result { let url = self.graphql_url(version); - let body = serde_json::to_vec(body)?; + let body = serde_json::to_vec(body).map_err(|error| Error::variables(None, &error))?; let endpoint = self.endpoint(); let mut token = self.shared.tokens.get(endpoint).await?; let mut retries = 0; @@ -193,7 +183,8 @@ impl Shopify { _ => return Err(Error::http(&url, &response)), } - let raw: RawResponse = serde_json::from_slice(&response.body)?; + let raw: RawResponse = crate::decode::from_slice(&response.body) + .map_err(|failure| failure.into_error())?; if raw.is_throttled() { let cost = raw.cost(); if !may_retry { diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs index c8294a9..8d77ed5 100644 --- a/crates/shopify_api/src/graphql/operation.rs +++ b/crates/shopify_api/src/graphql/operation.rs @@ -211,7 +211,7 @@ pub struct Operation { name: Option>, /// The Admin API version of the schema the operation was checked against. checked_against: Option<&'static str>, - variables: std::result::Result, String>, + variables: std::result::Result, VariablesFailure>, data: PhantomData D>, } @@ -288,7 +288,7 @@ impl Operation { variables.insert(name.to_string(), value); } (Ok(_), Err(error)) => { - self.variables = Err(format!("invalid value for variable `${name}`: {error}")) + self.variables = Err(VariablesFailure::of(Error::variables(Some(name), &error))) } (Err(_), _) => {} } @@ -308,12 +308,7 @@ impl Operation { /// Replaces the variables with the fields of a serializable struct or map. pub fn variables(mut self, variables: V) -> Self { - self.variables = match serde_json::to_value(variables) { - Ok(Value::Object(variables)) => Ok(variables), - Ok(Value::Null) => Ok(Map::new()), - Ok(_) => Err("the variables of an operation must serialize to an object".to_string()), - Err(error) => Err(format!("{error}")), - }; + self.variables = variables_of(variables).map_err(VariablesFailure::of); self } @@ -321,7 +316,7 @@ impl Operation { pub fn variables_json(&self) -> Result<&Map> { self.variables .as_ref() - .map_err(|message| Error::Variables(message.clone())) + .map_err(|failure| failure.to_error()) } /// The body Shopify receives: `query`, `variables` and `operationName`. @@ -339,6 +334,44 @@ impl Operation { } } +/// The variables of a [`Shopify::graphql_raw`](crate::Shopify::graphql_raw) +/// call or an [`Operation`]: one path, so that both fail the same way. +pub(crate) fn variables_of(variables: impl Serialize) -> Result> { + match serde_json::to_value(variables) { + Ok(Value::Object(variables)) => Ok(variables), + Ok(Value::Null) => Ok(Map::new()), + Ok(_) => Err(Error::variables_not_an_object()), + Err(error) => Err(Error::variables(None, &error)), + } +} + +/// An [`Error::Variables`] kept until the operation is sent. Its `Debug` is +/// the error's: the detail is not shown. +#[derive(Clone, Debug)] +struct VariablesFailure { + message: String, + detail: Option, +} + +impl VariablesFailure { + fn of(error: Error) -> Self { + match error { + Error::Variables { message, detail } => Self { message, detail }, + other => Self { + message: other.to_string(), + detail: None, + }, + } + } + + fn to_error(&self) -> Error { + Error::Variables { + message: self.message.clone(), + detail: self.detail.clone(), + } + } +} + impl Clone for Operation { fn clone(&self) -> Self { Self { @@ -638,7 +671,7 @@ mod tests { .unwrap_err(); assert_eq!( error.to_string(), - "invalid variables: the variables of an operation must serialize to an object" + "invalid variables: the variables must serialize to an object" ); } @@ -660,8 +693,9 @@ mod tests { .unwrap_err(); assert_eq!( error.to_string(), - "invalid variables: invalid value for variable `$input`: no" + "invalid variables: variable `$input` does not serialize: a value's `Serialize` implementation failed" ); + assert_eq!(error.sensitive_detail(), Some("no")); } #[test] diff --git a/crates/shopify_api/src/graphql/response.rs b/crates/shopify_api/src/graphql/response.rs index f214372..a043801 100644 --- a/crates/shopify_api/src/graphql/response.rs +++ b/crates/shopify_api/src/graphql/response.rs @@ -8,10 +8,11 @@ use serde_json::Value; /// An entry of the `errors` of an answer. /// -/// Its `Debug` shows `extensions.code` and the names of the other entries of -/// `extensions`, not their values: Shopify puts the whole value of a variable -/// that does not validate in `extensions.value`, a signed address included. -/// The fields themselves stay available. +/// Its `Debug` shows `message`, `locations`, `path` and `extensions.code`, +/// and how many other entries `extensions` has, not their names or values: +/// Shopify puts the whole value of a variable that does not validate in +/// `extensions.value`, a signed address included. The fields themselves stay +/// available. #[derive(Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct GraphqlError { @@ -37,7 +38,7 @@ impl fmt::Debug for GraphqlError { } } -/// `extensions.code`, and the names of the other entries without their values. +/// `extensions.code`, and how many other entries there are. struct ExtensionsShape<'a>(&'a Value); impl fmt::Debug for ExtensionsShape<'_> { @@ -45,14 +46,15 @@ impl fmt::Debug for ExtensionsShape<'_> { let Value::Object(entries) = self.0 else { return formatter.write_str(".."); }; - let mut shown = formatter.debug_map(); - for (key, value) in entries { - match value { - Value::String(code) if key == "code" => shown.entry(key, code), - _ => shown.entry(key, &format_args!("..")), - }; + let code = entries.get("code").and_then(Value::as_str); + let others = entries.len() - usize::from(entries.contains_key("code")); + let mut shown = formatter.debug_struct("Extensions"); + if let Some(code) = code { + shown.field("code", &code); } - shown.finish() + shown + .field("others", &format_args!("{others} entries")) + .finish() } } @@ -201,8 +203,7 @@ impl RawResponse { /// Reads `value` as `T`, naming the path of the first field that does not fit. pub(crate) fn decode(value: Value) -> crate::Result { - serde_path_to_error::deserialize(value) - .map_err(|error| crate::Error::decode(error.path().to_string(), &error.inner().to_string())) + crate::decode::from_value(value) } #[cfg(test)] diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index 81bdf8c..9dadc57 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -59,10 +59,10 @@ extern crate self as shopify_api; mod auth; pub mod bulk; mod client; +mod decode; mod error; mod graphql; mod pagination; -mod redact; pub mod schema; mod shop; pub mod transport; @@ -80,7 +80,7 @@ pub mod webhooks; pub use auth::{AssociatedUser, Auth, TokenData, TokenStore}; pub use client::{RetryPolicy, Shopify, ShopifyBuilder, USER_AGENT}; -pub use error::{Error, GraphqlErrors, RawBody, Result}; +pub use error::{Error, GraphqlErrors, RawBody, Result, SensitiveDetail}; pub use graphql::{ Cost, GraphqlError, IntoVariable, Location, Operation, OperationKind, RawResponse, Response, ThrottleStatus, UserError, diff --git a/crates/shopify_api/src/pagination.rs b/crates/shopify_api/src/pagination.rs index 46ed59a..814609c 100644 --- a/crates/shopify_api/src/pagination.rs +++ b/crates/shopify_api/src/pagination.rs @@ -86,10 +86,7 @@ impl Shopify { match current.end_cursor { Some(next) if cursor.as_ref() != Some(&next) => cursor = Some(next), _ => { - return Err(Error::Decode { - path: "pageInfo.endCursor".to_string(), - message: "`hasNextPage` is true but the cursor does not move: select `pageInfo { hasNextPage endCursor }` and pass the cursor as `after`".to_string(), - }); + return Err(Error::decode("pageInfo.endCursor".to_string(), "`hasNextPage` is true but the cursor does not move: select `pageInfo { hasNextPage endCursor }` and pass the cursor as `after`".to_string(), None)); } } } diff --git a/crates/shopify_api/src/redact.rs b/crates/shopify_api/src/redact.rs deleted file mode 100644 index 34801b6..0000000 --- a/crates/shopify_api/src/redact.rs +++ /dev/null @@ -1,512 +0,0 @@ -//! What an error keeps of a text that may hold a secret: a serde message -//! without the values it quotes, a body without addresses' query strings, -//! tokens or signatures. - -/// The longest body an [`Error::Http`](crate::Error::Http) shows, in bytes. -pub(crate) const BODY_LIMIT: usize = 1024; - -/// What is read of a body before it is redacted, then cut at [`BODY_LIMIT`]. -const BODY_SCAN: usize = 16 * 1024; - -const REDACTED: &str = "[redacted]"; - -/// A serde or serde_json message without the values it quotes: -/// `invalid type: string "…", expected u64` becomes -/// `invalid type: string, expected u64`. What the type expects, the names of -/// its fields and the position in the text stay. -/// -/// A message of another shape, which a type's own `Deserialize` wrote, loses -/// whatever it quotes between `"` or backticks. -pub(crate) fn serde_message(message: &str) -> String { - for prefix in ["invalid type: ", "invalid value: "] { - if let Some(rest) = message.strip_prefix(prefix) { - let (kind, rest) = unexpected(rest); - return format!("{prefix}{kind}{rest}"); - } - } - for (prefix, separators) in [ - ( - "unknown variant `", - ["`, expected ", "`, there are no variants"], - ), - ( - "unknown field `", - ["`, expected ", "`, there are no fields"], - ), - ] { - if let Some(rest) = message.strip_prefix(prefix) { - // The name is the input's, and may hold the separator: the last - // one is serde's. - if let Some(end) = separators - .iter() - .filter_map(|separator| rest.rfind(separator)) - .max() - { - let what = prefix.trim_end_matches(" `"); - return format!("{what}{}", &rest[end + 1..]); - } - return prefix.trim_end_matches(" `").to_string(); - } - } - // `missing field `name``, `duplicate field `name``, `invalid length 3, - // expected …`: names of the type, counts. serde_json's syntax errors - // quote one punctuator at most. - if message.starts_with("missing field `") - || message.starts_with("duplicate field `") - || message.starts_with("invalid length ") - { - return message.to_string(); - } - without_quoted(message) -} - -/// The kind of an `Unexpected` value without the value, and what follows it. -fn unexpected(text: &str) -> (&'static str, &str) { - // `string "…"`: the string as `Debug` writes it, quotes escaped. - if let Some(rest) = text.strip_prefix("string \"") { - let mut escaped = false; - for (index, character) in rest.char_indices() { - match character { - '\\' if !escaped => escaped = true, - '"' if !escaped => return ("string", &rest[index + 1..]), - _ => escaped = false, - } - } - return ("string", ""); - } - for kind in ["boolean", "integer", "floating point", "character"] { - if let Some(rest) = text - .strip_prefix(kind) - .and_then(|rest| rest.strip_prefix(" `")) - { - // A character may be a backtick itself: skip one before looking. - let skip = if kind == "character" { - rest.chars().next().map_or(0, char::len_utf8) - } else { - 0 - }; - return match rest[skip..].find('`') { - Some(end) => (kind, &rest[skip + end + 1..]), - None => (kind, ""), - }; - } - } - for kind in [ - "byte array", - "unit value", - "Option value", - "newtype struct", - "sequence", - "map", - "enum", - "unit variant", - "newtype variant", - "tuple variant", - "struct variant", - "null", - ] { - if let Some(rest) = text.strip_prefix(kind) - && (rest.is_empty() || rest.starts_with(',')) - { - return (kind, rest); - } - } - // `Unexpected::Other`, written by the type: its text up to serde's - // separator is left out. - match text.rfind(", expected ") { - Some(end) => ("a value", &text[end..]), - None => ("a value", ""), - } -} - -/// `text` without what it quotes between `"` or backticks, except a single -/// character (serde_json's ``expected `,` or `}` ``). -fn without_quoted(text: &str) -> String { - let mut kept = String::with_capacity(text.len()); - let mut rest = text; - while let Some(start) = rest.find(['"', '`']) { - let quote = rest[start..].chars().next().unwrap_or('"'); - kept.push_str(&rest[..=start]); - let inside = &rest[start + 1..]; - let Some(end) = inside.find(quote) else { - kept.push('…'); - kept.push(quote); - return kept; - }; - if inside[..end].chars().count() <= 1 { - kept.push_str(&inside[..end]); - } else { - kept.push('…'); - } - kept.push(quote); - rest = &inside[end + 1..]; - } - kept.push_str(rest); - kept -} - -/// The body of an answer as an error shows it: at most [`BODY_LIMIT`] bytes, -/// with the query string of each address, anything that looks like a token, -/// and the value of each entry whose name holds `token`, `secret`, -/// `signature`, `password`, `credential`, `authorization` or `api_key` -/// replaced by `[redacted]`. -pub(crate) fn http_body(body: &[u8]) -> String { - let scanned = &body[..body.len().min(BODY_SCAN)]; - let mut text = String::from_utf8_lossy(scanned).into_owned(); - if scanned.len() < body.len() { - // Do not show the start of a word cut in two: it may be a token - // whose end would no longer look like one. - let end = text - .rfind(|character: char| !is_word(character)) - .unwrap_or(0); - text.truncate(end); - } - let text = redact(&text); - if text.len() <= BODY_LIMIT && scanned.len() == body.len() { - return text; - } - let mut end = text.len().min(BODY_LIMIT); - while !text.is_char_boundary(end) { - end -= 1; - } - format!("{}…", &text[..end]) -} - -/// Characters of a token, a key or an encoded value. -fn is_word(character: char) -> bool { - character.is_ascii_alphanumeric() - || matches!(character, '_' | '-' | '.' | '~' | '+' | '/' | '=' | '%') -} - -/// Names of entries whose value is a secret, lower case. -const SECRET_NAMES: [&str; 9] = [ - "token", - "secret", - "signature", - "password", - "credential", - "authorization", - "apikey", - "api_key", - "api-key", -]; - -fn redact(text: &str) -> String { - let text = redact_query_strings(text); - let text = redact_entries(&text); - redact_tokens(&text) -} - -/// Each `http://` or `https://` address keeps its path, not its query string -/// or fragment. -fn redact_query_strings(text: &str) -> String { - let mut kept = String::with_capacity(text.len()); - let mut rest = text; - while let Some(start) = find_ignoring_case(rest, "http://") - .into_iter() - .chain(find_ignoring_case(rest, "https://")) - .min() - { - let end = rest[start..] - .find(|character: char| { - character.is_whitespace() - || matches!(character, '"' | '\'' | '<' | '>' | '\\' | '`') - }) - .map_or(rest.len(), |end| start + end); - let address = &rest[start..end]; - kept.push_str(&rest[..start]); - match address.find(['?', '#']) { - Some(query) => { - kept.push_str(&address[..=query]); - kept.push_str(REDACTED); - } - None => kept.push_str(address), - } - rest = &rest[end..]; - } - kept.push_str(rest); - kept -} - -/// The value after a secret's name and `:` or `=`, quoted or not -/// (`"access_token": "…"`, `X-Goog-Signature=…`, `Authorization: Bearer …`). -fn redact_entries(text: &str) -> String { - let lower = text.to_ascii_lowercase(); - let mut kept = String::with_capacity(text.len()); - let mut copied = 0; - let mut search = 0; - while let Some((name_end, value_start, value_end)) = next_entry(text, &lower, search) { - if value_start < copied { - search = name_end; - continue; - } - kept.push_str(&text[copied..value_start]); - kept.push_str(REDACTED); - copied = value_end; - search = value_end.max(name_end); - } - kept.push_str(&text[copied..]); - kept -} - -/// The next secret entry from `from`: where its name ends, and where its -/// value starts and ends. -fn next_entry(text: &str, lower: &str, from: usize) -> Option<(usize, usize, usize)> { - let bytes = text.as_bytes(); - let mut position = from; - loop { - let (start, name) = SECRET_NAMES - .iter() - .filter_map(|name| Some((lower[position..].find(name)? + position, *name))) - .min()?; - let mut cursor = start + name.len(); - // The rest of the name: `access_token`, `X-Goog-Signature`, `tokens`. - while cursor < bytes.len() - && (bytes[cursor].is_ascii_alphanumeric() || matches!(bytes[cursor], b'_' | b'-')) - { - cursor += 1; - } - let name_end = cursor; - // A closing quote, spaces, then `:` or `=`. - if cursor < bytes.len() && matches!(bytes[cursor], b'"' | b'\'') { - cursor += 1; - } - while cursor < bytes.len() && bytes[cursor] == b' ' { - cursor += 1; - } - if cursor >= bytes.len() || !matches!(bytes[cursor], b':' | b'=') { - position = name_end; - continue; - } - cursor += 1; - while cursor < bytes.len() && bytes[cursor] == b' ' { - cursor += 1; - } - // `Bearer abc`: the scheme stays, the credential goes. - for scheme in ["bearer ", "basic "] { - if lower[cursor..].starts_with(scheme) { - cursor += scheme.len(); - while cursor < bytes.len() && bytes[cursor] == b' ' { - cursor += 1; - } - } - } - let value_start = cursor; - let value_end = match bytes.get(cursor) { - Some("e @ (b'"' | b'\'')) => { - let mut end = cursor + 1; - while end < bytes.len() && bytes[end] != quote { - end += if bytes[end] == b'\\' { 2 } else { 1 }; - } - // The quotes stay; what is between them goes. - return Some((name_end, value_start + 1, end.min(bytes.len()))); - } - _ => { - let mut end = cursor; - while end < bytes.len() - && !bytes[end].is_ascii_whitespace() - && !matches!( - bytes[end], - b'&' | b',' | b';' | b'"' | b'\'' | b'<' | b'}' | b']' | b')' - ) - { - end += 1; - } - end - } - }; - if value_end == value_start { - position = name_end; - continue; - } - return Some((name_end, value_start, value_end)); - } -} - -/// Words that look like a credential: Shopify's tokens and secrets -/// (`shpat_…`, `shpss_…`), a JWT, or 32 characters or more of letters and -/// digits mixed. -fn redact_tokens(text: &str) -> String { - let mut kept = String::with_capacity(text.len()); - let mut rest = text; - while !rest.is_empty() { - let start = rest.find(is_word).unwrap_or(rest.len()); - kept.push_str(&rest[..start]); - rest = &rest[start..]; - let end = rest - .find(|character| !is_word(character)) - .unwrap_or(rest.len()); - let word = &rest[..end]; - if looks_like_a_credential(word) { - kept.push_str(REDACTED); - } else { - kept.push_str(word); - } - rest = &rest[end..]; - } - kept -} - -fn looks_like_a_credential(word: &str) -> bool { - let bytes = word.as_bytes(); - // Anywhere in the word after a separator: `key=shpat_…`, `/eyJ….….…`. - let starts = - (0..bytes.len()).filter(|&index| index == 0 || !bytes[index - 1].is_ascii_alphanumeric()); - let shopify = starts.clone().any(|index| { - let rest = &bytes[index..]; - rest.len() > 6 - && rest.starts_with(b"shp") - && rest[3..5].iter().all(u8::is_ascii_lowercase) - && rest[5] == b'_' - }); - let jwt = starts.into_iter().any(|index| { - bytes[index..].starts_with(b"eyJ") - && bytes[index..].iter().filter(|byte| **byte == b'.').count() >= 2 - }); - let mixed = word.len() >= 32 - && word.bytes().any(|byte| byte.is_ascii_alphabetic()) - && word.bytes().any(|byte| byte.is_ascii_digit()) - && word != REDACTED; - shopify || jwt || mixed -} - -fn find_ignoring_case(text: &str, needle: &str) -> Option { - text.as_bytes() - .windows(needle.len()) - .position(|window| window.eq_ignore_ascii_case(needle.as_bytes())) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn serde_messages_keep_kinds_and_lose_values() { - for (message, expected) in [ - ( - r#"invalid type: string "https://x.test/r?sig=SECRET", expected u64"#, - "invalid type: string, expected u64", - ), - ( - r#"invalid type: string "a \"quoted\", expected x", expected u64 at line 1 column 9"#, - "invalid type: string, expected u64 at line 1 column 9", - ), - ( - "invalid type: integer `4242`, expected a string", - "invalid type: integer, expected a string", - ), - ( - "invalid type: floating point `1.5`, expected u32", - "invalid type: floating point, expected u32", - ), - ( - "invalid type: boolean `true`, expected a string", - "invalid type: boolean, expected a string", - ), - ( - "invalid type: character ```, expected a string", - "invalid type: character, expected a string", - ), - ( - "invalid type: map, expected a sequence", - "invalid type: map, expected a sequence", - ), - ( - "invalid type: null, expected a string", - "invalid type: null, expected a string", - ), - ( - r#"invalid value: string "SECRET", expected a date"#, - "invalid value: string, expected a date", - ), - ( - "invalid value: SECRET thing, expected a date", - "invalid value: a value, expected a date", - ), - ( - "unknown variant `SECRET`, expected one of `ACTIVE`, `DRAFT`", - "unknown variant, expected one of `ACTIVE`, `DRAFT`", - ), - ( - "unknown variant `SE`, expected `CRET`, expected `A` or `B`", - "unknown variant, expected `A` or `B`", - ), - ( - "unknown field `SECRET`, there are no fields", - "unknown field, there are no fields", - ), - ("missing field `name`", "missing field `name`"), - ( - "invalid length 3, expected a tuple of size 2", - "invalid length 3, expected a tuple of size 2", - ), - ( - "expected `,` or `}` at line 1 column 9", - "expected `,` or `}` at line 1 column 9", - ), - ( - "invalid shop `SECRET`: expected ``", - "invalid shop `…`: expected `…`", - ), - (r#"bad "SECRET"#, r#"bad "…""#), - ] { - assert_eq!(serde_message(message), expected, "{message}"); - } - } - - #[test] - fn bodies_lose_query_strings_tokens_and_signatures() { - let body = concat!( - r#"{"errors":"Invalid token","url":"https://storage.googleapis.com/b/r.jsonl?X-Goog-Signature=AAA111&X-Goog-Credential=BBB","#, - r#""access_token": "shpat_0123456789abcdef", "refresh_token":'shprt_x1', "#, - "plain shpss_00112233 jwt eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl ", - "random 4f9a8c7e6d5b4a39281706f5e4d3c2b1a0 ", - "Authorization: Bearer abc.DEF-123 next ", - "GOOG4-RSA-SHA256 X-Goog-Signature=CCC&b=1 ", - "id gid://shopify/Product/1 request a1b2c3d4-e5f6 ", - "glued x=shpat_GLUED1 /eyJhbGciOiJIUzI1NiJ9.eyJzdWIi.GLUED2 ", - ); - let shown = http_body(body.as_bytes()); - for secret in [ - "AAA111", - "BBB", - "shpat_", - "shprt_", - "shpss_", - "eyJ", - "4f9a8c7e6d5b4a39281706f5e4d3c2b1a0", - "abc.DEF-123", - "CCC", - "GLUED1", - "GLUED2", - ] { - assert!(!shown.contains(secret), "{secret} in {shown}"); - } - for kept in [ - "Invalid token", - "https://storage.googleapis.com/b/r.jsonl?[redacted]", - r#""access_token": "[redacted]""#, - "Bearer [redacted] next", - "gid://shopify/Product/1", - "a1b2c3d4-e5f6", - "next", - ] { - assert!(shown.contains(kept), "{kept} not in {shown}"); - } - } - - #[test] - fn bodies_are_cut_at_one_kibibyte() { - let shown = http_body("é".repeat(2000).as_bytes()); - assert!(shown.ends_with('…')); - assert!(shown.len() <= BODY_LIMIT + '…'.len_utf8()); - // Tokens shrink to `[redacted]`: one cut at the end of what is read - // would show its start, which no longer looks like a token. - let token = format!("{} ", "a1".repeat(150)); - let body = token.repeat(BODY_SCAN / token.len() + 2); - let shown = http_body(body.as_bytes()); - assert!(shown.starts_with("[redacted] [redacted]"), "{shown}"); - assert!(!shown.contains("a1"), "{shown}"); - assert_eq!(http_body(b"short"), "short"); - } -} diff --git a/crates/shopify_api/src/schema.rs b/crates/shopify_api/src/schema.rs index bdca799..ca3a592 100644 --- a/crates/shopify_api/src/schema.rs +++ b/crates/shopify_api/src/schema.rs @@ -83,7 +83,8 @@ pub async fn download_public_admin_schema_with( if !response.is_success() { return Err(Error::http(&url, &response)); } - let value: Value = serde_json::from_slice(&response.body)?; + let value: Value = + crate::decode::from_slice(&response.body).map_err(|failure| failure.into_error())?; check(value) } @@ -109,14 +110,14 @@ fn check(value: Value) -> Result { 200, PUBLIC_ADMIN_SCHEMA_ENDPOINT, message.as_bytes(), - None, )); } if value.pointer("/data/__schema/types").is_none() { - return Err(Error::Decode { - path: "data.__schema".to_string(), - message: "the answer is not an introspection result".to_string(), - }); + return Err(Error::decode( + "data.__schema".to_string(), + "the answer is not an introspection result".to_string(), + None, + )); } Ok(value) } diff --git a/crates/shopify_api/src/transport.rs b/crates/shopify_api/src/transport.rs index e67b869..5e01589 100644 --- a/crates/shopify_api/src/transport.rs +++ b/crates/shopify_api/src/transport.rs @@ -285,7 +285,11 @@ impl ReqwestTransport { .redirect(reqwest::redirect::Policy::none()) .build() .map_err(|error| { - crate::Error::Config(format!("the HTTP client does not start: {error}")) + // A proxy's address may hold a password: errors leave it out. + crate::Error::Config(format!( + "the HTTP client does not start: {}", + error.without_url() + )) })?; Ok(Self { client }) } diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs index 30b773d..b5e5483 100644 --- a/crates/shopify_api/src/webhooks.rs +++ b/crates/shopify_api/src/webhooks.rs @@ -207,9 +207,7 @@ impl Webhook { /// The body read as `T`, the path of the first mismatch in the error. pub fn payload(&self) -> Result { - let mut deserializer = serde_json::Deserializer::from_slice(&self.body); - serde_path_to_error::deserialize(&mut deserializer) - .map_err(|error| Error::decode(error.path().to_string(), &error.inner().to_string())) + crate::decode::from_slice(&self.body).map_err(|failure| failure.into_error()) } } @@ -301,7 +299,7 @@ struct WireVersion { } fn subscription_of(selection: &impl Serialize) -> Result { - let wire: Wire = crate::graphql::decode(serde_json::to_value(selection)?)?; + let wire: Wire = crate::decode::reserialize(selection)?; Ok(WebhookSubscription { id: wire.id, topic: wire.topic, @@ -318,7 +316,7 @@ fn subscription_of(selection: &impl Serialize) -> Result { } fn refused(mutation: &'static str, errors: &impl Serialize) -> Result<()> { - let errors: Vec = crate::graphql::decode(serde_json::to_value(errors)?)?; + let errors: Vec = crate::decode::reserialize(errors)?; if errors.is_empty() { Ok(()) } else { @@ -468,16 +466,20 @@ impl Shopify { webhook_subscription: input, })) .await?; - let payload = data - .webhook_subscription_create - .ok_or_else(|| Error::Decode { - path: "webhookSubscriptionCreate".to_string(), - message: "Shopify returned nothing".to_string(), - })?; + let payload = data.webhook_subscription_create.ok_or_else(|| { + Error::decode( + "webhookSubscriptionCreate".to_string(), + "Shopify returned nothing".to_string(), + None, + ) + })?; refused("webhookSubscriptionCreate", &payload.user_errors)?; - let subscription = payload.webhook_subscription.ok_or_else(|| Error::Decode { - path: "webhookSubscriptionCreate.webhookSubscription".to_string(), - message: "Shopify returned no subscription".to_string(), + let subscription = payload.webhook_subscription.ok_or_else(|| { + Error::decode( + "webhookSubscriptionCreate.webhookSubscription".to_string(), + "Shopify returned no subscription".to_string(), + None, + ) })?; subscription_of(&subscription) } @@ -486,12 +488,13 @@ impl Shopify { let data = self .execute(delete::operation(delete::Variables { id: id.to_string() })) .await?; - let payload = data - .webhook_subscription_delete - .ok_or_else(|| Error::Decode { - path: "webhookSubscriptionDelete".to_string(), - message: "Shopify returned nothing".to_string(), - })?; + let payload = data.webhook_subscription_delete.ok_or_else(|| { + Error::decode( + "webhookSubscriptionDelete".to_string(), + "Shopify returned nothing".to_string(), + None, + ) + })?; refused("webhookSubscriptionDelete", &payload.user_errors) } @@ -508,16 +511,20 @@ impl Shopify { webhook_subscription: input!(update, spec, true), })) .await?; - let payload = data - .webhook_subscription_update - .ok_or_else(|| Error::Decode { - path: "webhookSubscriptionUpdate".to_string(), - message: "Shopify returned nothing".to_string(), - })?; + let payload = data.webhook_subscription_update.ok_or_else(|| { + Error::decode( + "webhookSubscriptionUpdate".to_string(), + "Shopify returned nothing".to_string(), + None, + ) + })?; refused("webhookSubscriptionUpdate", &payload.user_errors)?; - let subscription = payload.webhook_subscription.ok_or_else(|| Error::Decode { - path: "webhookSubscriptionUpdate.webhookSubscription".to_string(), - message: "Shopify returned no subscription".to_string(), + let subscription = payload.webhook_subscription.ok_or_else(|| { + Error::decode( + "webhookSubscriptionUpdate.webhookSubscription".to_string(), + "Shopify returned no subscription".to_string(), + None, + ) })?; subscription_of(&subscription) } diff --git a/crates/shopify_api/tests/auth.rs b/crates/shopify_api/tests/auth.rs index 41f874e..ff8e01b 100644 --- a/crates/shopify_api/tests/auth.rs +++ b/crates/shopify_api/tests/auth.rs @@ -251,7 +251,7 @@ async fn an_expired_refresh_token_says_what_to_do() { .unwrap(); let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); - assert!(matches!(error, Error::Auth(_)), "{error:?}"); + assert!(matches!(error, Error::Auth { .. }), "{error:?}"); assert!( error .to_string() @@ -277,7 +277,12 @@ async fn a_refused_grant_says_what_shopify_answered_and_never_the_secret() { let message = error.to_string(); assert_eq!( message, - "authentication failed: the token endpoint of test-shop.myshopify.com answered 400: shop_not_permitted: Client credentials cannot be performed on this shop." + "authentication failed: the token endpoint of test-shop.myshopify.com answered 400 (shop_not_permitted)" + ); + // What it wrote is there for code that asks. + assert_eq!( + error.sensitive_detail(), + Some("shop_not_permitted: Client credentials cannot be performed on this shop.") ); assert!(!format!("{error:?}").contains("top-secret")); } @@ -438,7 +443,7 @@ async fn a_failed_grant_answers_the_requests_that_wait_for_it() { .collect(); for call in calls { let error = call.await.unwrap().unwrap_err(); - assert!(matches!(error, Error::Auth(_)), "{error:?}"); + assert!(matches!(error, Error::Auth { .. }), "{error:?}"); } // One request to the token endpoint; the others got its failure. assert_eq!(token_requests(&mock).len(), 1); diff --git a/crates/shopify_api/tests/graphql.rs b/crates/shopify_api/tests/graphql.rs index 525921c..e590bed 100644 --- a/crates/shopify_api/tests/graphql.rs +++ b/crates/shopify_api/tests/graphql.rs @@ -329,9 +329,10 @@ async fn an_error_shows_no_value_shopify_echoes_in_its_extensions() { assert!(!shown.contains("storage.test"), "{shown}"); } let debug = format!("{error:?}"); - assert!(debug.contains(r#""code": "INVALID_VARIABLE""#), "{debug}"); - assert!(debug.contains(r#""value": .."#), "{debug}"); - assert!(debug.contains(r#""problems": .."#), "{debug}"); + assert!( + debug.contains(r#"Extensions { code: "INVALID_VARIABLE", others: 2 entries }"#), + "{debug}" + ); assert!(debug.contains("Variable $media"), "{debug}"); // The values stay available to the caller. let extensions = error.graphql_errors()[0].extensions.as_ref().unwrap(); @@ -352,7 +353,7 @@ async fn an_answer_that_does_not_fit_names_the_path() { } #[tokio::test] -async fn http_errors_say_what_shopify_answered() { +async fn http_errors_say_how_shopify_answered_and_keep_the_body_apart() { let mock = MockTransport::new(); mock.push(shopify_api::transport::HttpResponse::new( 403, @@ -364,7 +365,11 @@ async fn http_errors_say_what_shopify_answered() { assert_eq!(error.status(), Some(403)); assert_eq!( error.to_string(), - "Shopify answered 403 to https://test-shop.myshopify.com/admin/api/2026-10/graphql.json: [API] This action requires merchant approval for write_orders scope." + "Shopify answered 403 to https://test-shop.myshopify.com/admin/api/2026-10/graphql.json (no content type, 68 bytes)" + ); + assert_eq!( + error.raw_http_body(), + Some(&b"[API] This action requires merchant approval for write_orders scope."[..]) ); } From cc1258f576e9bd7f1c548d6942e043b8258f29da Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:41:53 +0200 Subject: [PATCH 029/135] fix: read an alias spelled like its field as an alias `draftOrderCreate: draftOrderCreate(...)` skipped the argument scan: the alias was detected by `alias != name`, so the colon stayed unread and the scan returned no arguments, and input objects in different orders compiled although GraphQL Ruby refuses them (fieldConflict). The colon token now says whether there is an alias. The analyzer docs say where it is stricter than the specification, and why. Co-Authored-By: Claude Opus 5.5 --- .../tests/ui/same_name_alias_field_order.rs | 7 ++++++ .../ui/same_name_alias_field_order.stderr | 6 +++++ crates/shopify_api_graphql/src/analyze.rs | 12 +++++++++ .../src/analyze/input_objects.rs | 10 ++++---- crates/shopify_api_graphql/tests/analyze.rs | 25 +++++++++++++++++++ 5 files changed, 55 insertions(+), 5 deletions(-) create mode 100644 crates/shopify_api/tests/ui/same_name_alias_field_order.rs create mode 100644 crates/shopify_api/tests/ui/same_name_alias_field_order.stderr diff --git a/crates/shopify_api/tests/ui/same_name_alias_field_order.rs b/crates/shopify_api/tests/ui/same_name_alias_field_order.rs new file mode 100644 index 0000000..e5e1ea1 --- /dev/null +++ b/crates/shopify_api/tests/ui/same_name_alias_field_order.rs @@ -0,0 +1,7 @@ +// An alias spelled like its field, with the fields of an input object in +// another order: Shopify (GraphQL Ruby) refuses it with `fieldConflict`. +fn main() { + let _ = shopify_api::graphql!( + r#"mutation { draftOrderCreate:draftOrderCreate(input:{note:"x" tags:["y"]}){draftOrder{id}} draftOrderCreate:draftOrderCreate(input:{tags:["y"] note:"x"}){draftOrder{id}} }"# + ); +} diff --git a/crates/shopify_api/tests/ui/same_name_alias_field_order.stderr b/crates/shopify_api/tests/ui/same_name_alias_field_order.stderr new file mode 100644 index 0000000..276f7de --- /dev/null +++ b/crates/shopify_api/tests/ui/same_name_alias_field_order.stderr @@ -0,0 +1,6 @@ +error: `draftOrderCreate` is selected twice with the fields of an input object in another order (`(input: {note: "x", tags: ["y"]})`), which Shopify refuses; write them in the same order, or give one of them an alias (line 1, column 91) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/same_name_alias_field_order.rs:5:9 + | +5 | ... r#"mutation { draftOrderCreate:draftOrderCreate(input:{note:"x" tags:["y"]}){draftOrder{id}} draftOrderCreate:draftOrderCreate(input:{tags:["y"] note:"x"}){draftOrder{id}} }"# + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index 645542a..f23d19d 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -1,5 +1,17 @@ //! Checks a GraphQL operation against a schema and describes the shape of //! its variables and of its result. +//! +//! # Stricter than the specification, on purpose +//! +//! Where Shopify's server (GraphQL Ruby) refuses what the specification +//! accepts, the analyzer refuses it too, so that an operation it accepts is +//! one Shopify runs. One response key selected twice must have the fields of +//! each input object of its arguments in the same order: the specification +//! says input fields are unordered (`{a: 1, b: 2}` is `{b: 2, a: 1}`), but +//! GraphQL Ruby compares their text and answers `fieldConflict`. An alias +//! spelled like its field (`draftOrderCreate: draftOrderCreate(...)`) is an +//! alias all the same. When the order cannot be read, the operation is +//! refused rather than guessed. mod input_objects; diff --git a/crates/shopify_api_graphql/src/analyze/input_objects.rs b/crates/shopify_api_graphql/src/analyze/input_objects.rs index a907682..f63f1c8 100644 --- a/crates/shopify_api_graphql/src/analyze/input_objects.rs +++ b/crates/shopify_api_graphql/src/analyze/input_objects.rs @@ -78,15 +78,15 @@ pub(super) fn argument_orders<'a>( return None; }; let mut after = lexer.next(); - if first != name { - // `alias: name` - if after.map(|(token, _)| token) != Some(Token::Punctuator(b':')) { - return None; - } + // `alias: name`, the alias spelled like the name or not: the colon says + // which it is. + if after.map(|(token, _)| token) == Some(Token::Punctuator(b':')) { if lexer.next().map(|(token, _)| token) != Some(Token::Name(name)) { return None; } after = lexer.next(); + } else if first != name { + return None; } let mut arguments = Vec::new(); if after.map(|(token, _)| token) != Some(Token::Punctuator(b'(')) { diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs index 6633759..d9a44a2 100644 --- a/crates/shopify_api_graphql/tests/analyze.rs +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -802,6 +802,31 @@ fn the_order_of_input_fields_is_found_after_any_text() { )); } +/// An alias spelled like its field is still an alias: the arguments after it +/// are read for the order of their input fields (round 4 review: Shopify's +/// GraphQL Ruby refuses this operation with `fieldConflict`). +#[test] +fn an_alias_spelled_like_its_field_keeps_the_order_of_input_fields() { + let refused = refusal( + "mutation { draftOrderCreate:draftOrderCreate(input:{note:\"x\" tags:[\"y\"]}){draftOrder{id}} draftOrderCreate:draftOrderCreate(input:{tags:[\"y\"] note:\"x\"}){draftOrder{id}} }", + ); + assert!( + refused.contains( + "`draftOrderCreate` is selected twice with the fields of an input object in another order" + ), + "{refused}" + ); + // In the same order, with spaces around the colon or none: one field. + check( + "mutation { draftOrderCreate : draftOrderCreate(input:{note:\"x\" tags:[\"y\"]}){draftOrder{id}} draftOrderCreate:draftOrderCreate(input:{note:\"x\" tags:[\"y\"]}){draftOrder{id}} }", + ); + // The alias of one, the bare name of the other. + let refused = refusal( + "mutation { draftOrderCreate(input:{note:\"x\" tags:[\"y\"]}){draftOrder{id}} draftOrderCreate:draftOrderCreate(input:{tags:[\"y\"] note:\"x\"}){draftOrder{id}} }", + ); + assert!(refused.contains("in another order"), "{refused}"); +} + #[test] fn directives_come_from_the_schema() { // Shopify's `@idempotent`, on a mutation field. From ab7bcb275283e5e17f1e77cfc0a084c5d6b60621 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:42:38 +0200 Subject: [PATCH 030/135] fix: choose the century of an RFC 850 date before checking the date `Tuesday, 29-Feb-00 08:49:37 GMT` read as 2100-02-29 first, which does not exist, and the parse gave up before trying 2000: a past Retry-After fell back to the ordinary backoff instead of no wait. The day, month and time are now read in a leap year, the century is chosen, then the date is built. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/graphql.rs | 32 +++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index 631b949..e4ec29c 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -257,7 +257,7 @@ fn rfc850_date( value: &str, now: chrono::DateTime, ) -> Option> { - use chrono::{Datelike, Months, NaiveDateTime}; + use chrono::{Datelike, Months, NaiveDateTime, Timelike}; let (weekday, rest) = value.split_once(", ")?; let (day, rest) = rest.split_once('-')?; let (month, rest) = rest.split_once('-')?; @@ -266,20 +266,23 @@ fn rfc850_date( return None; } let two_digits: i32 = year.parse().ok()?; + // The day, month and time, read in a leap year so that 29 February + // reads: the century is chosen before the date is checked. + let parts = NaiveDateTime::parse_from_str( + &format!("{day}-{month}-2000 {time}"), + "%d-%b-%Y %H:%M:%S GMT", + ) + .ok()?; let latest = now.checked_add_months(Months::new(50 * 12))?; + let at = |date: &NaiveDateTime| (date.month(), date.day(), date.num_seconds_from_midnight()); // The latest year ending in these digits that is not more than 50 years ahead. let mut full_year = now.year() - now.year().rem_euclid(100) + 100 + two_digits; - loop { - let text = format!("{day}-{month}-{full_year} {time}"); - let date = NaiveDateTime::parse_from_str(&text, "%d-%b-%Y %H:%M:%S GMT") - .ok()? - .and_utc(); - if date <= latest { - let named = date.format("%A").to_string(); - return (named == weekday).then_some(date); - } + while (full_year, at(&parts)) > (latest.year(), at(&latest.naive_utc())) { full_year -= 100; } + let date = parts.with_year(full_year)?.and_utc(); + let named = date.format("%A").to_string(); + (named == weekday).then_some(date) } /// The `data` and `extensions` of an answer without errors. fn into_data(raw: RawResponse) -> Result<(Value, Option)> { @@ -337,6 +340,15 @@ mod tests { assert_eq!(year("Saturday, 06-Nov-99 08:49:37 GMT"), Some(1999)); assert_eq!(year("Thursday, 06-Nov-70 08:49:37 GMT"), Some(2070)); assert_eq!(year("Monday, 06-Nov-00 08:49:37 GMT"), Some(2000)); + // 29 February: the century first (2100 is no leap year, 2000 is). + assert_eq!(year("Tuesday, 29-Feb-00 08:49:37 GMT"), Some(2000)); + assert_eq!( + retry_after_from("Tuesday, 29-Feb-00 08:49:37 GMT", in_2026), + Some(Duration::ZERO) + ); + assert_eq!(year("Saturday, 29-Feb-76 08:49:37 GMT"), Some(2076)); + // No year ending in `01` has a 29 February. + assert_eq!(year("Thursday, 29-Feb-01 08:49:37 GMT"), None); // A weekday that does not match its date is no date. assert_eq!(year("Monday, 06-Nov-69 08:49:37 GMT"), None); assert_eq!(year("Sunday, 06-Nov-1994 08:49:37 GMT"), None); From 3584fc98b04602f35c59c57502a8ec9ad6bb73c9 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:02:36 +0200 Subject: [PATCH 031/135] docs: drop comments that restate code or refer to review rounds Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 - crates/shopify_api/src/auth.rs | 1 - crates/shopify_api/src/client.rs | 2 +- crates/shopify_api/src/decode.rs | 2 -- crates/shopify_api/src/error.rs | 5 ++--- crates/shopify_api/src/oauth.rs | 2 -- crates/shopify_api_graphql/src/analyze.rs | 1 - crates/shopify_api_graphql/src/analyze/input_objects.rs | 3 +-- crates/shopify_api_graphql/tests/analyze.rs | 4 ++-- 9 files changed, 6 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dc2f565..f6d09cc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,6 @@ jobs: - uses: actions/checkout@v7 - uses: jdx/mise-action@v5 - uses: Swatinem/rust-cache@v2 - # `cargo check -p shopify_api --no-default-features --lib --locked`, then each feature alone. - run: mise run check:features msrv: diff --git a/crates/shopify_api/src/auth.rs b/crates/shopify_api/src/auth.rs index 6e9fe0d..6cbcb8b 100644 --- a/crates/shopify_api/src/auth.rs +++ b/crates/shopify_api/src/auth.rs @@ -310,7 +310,6 @@ impl TokenResponse { } } -/// `https://{shop}/admin/oauth/access_token`. pub(crate) fn token_url(shop: &ShopDomain) -> String { format!("https://{shop}/admin/oauth/access_token") } diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index 08b713c..b7de5bb 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -130,7 +130,7 @@ impl Shopify { &self.shared.endpoint } - /// The version `operation` goes to: the pinned one, else the one its + /// The version an operation goes to: the pinned one, else the one its /// schema was checked against. pub(crate) fn version_for(&self, checked_against: Option<&'static str>) -> Result { match (self.pinned, checked_against) { diff --git a/crates/shopify_api/src/decode.rs b/crates/shopify_api/src/decode.rs index c05bd2b..7872359 100644 --- a/crates/shopify_api/src/decode.rs +++ b/crates/shopify_api/src/decode.rs @@ -154,8 +154,6 @@ const FIXED: &[&str] = &[ ]; /// The kinds serde names an unexpected value by (`Unexpected`'s `Display`). -/// The longer first: `unit variant` before `unit value` is not an issue, but -/// `floating point` must not read as another kind. const KINDS: &[&str] = &[ "boolean", "integer", diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index 4f6247e..a36a9ae 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -33,8 +33,7 @@ pub type Result = std::result::Result; /// - of the token endpoint's refusal, its status and its standard OAuth error /// code; /// - no shop domain or API version that does not validate: a token given in -/// their place is not shown. -/// +/// their place is not shown; /// - of the partial `data` of a GraphQL error, and of its `extensions` but /// `code`, how many entries there are: no name, no value; /// - of a bulk operation, its ID when it is a `gid://` of Shopify, a status @@ -683,7 +682,7 @@ mod tests { const SIGNED_URL: &str = "https://me:USERINFO_SECRET@storage.test/k?sig=SIGNED_SECRET#SIGNED_SECRET"; - /// A body that holds every secret, the ways round 4 found. + /// A body that holds every secret, in every form a body may hold it. fn secret_body() -> String { format!( "{{\"access_token\":\t\"{TOKEN}\",\n\"client_secret\":\n\"QUOTED_SECRET\",\ diff --git a/crates/shopify_api/src/oauth.rs b/crates/shopify_api/src/oauth.rs index 13904c3..3bcfe73 100644 --- a/crates/shopify_api/src/oauth.rs +++ b/crates/shopify_api/src/oauth.rs @@ -700,7 +700,6 @@ mod tests { ); } - /// A timestamp at the edge of `i64` is rejected, never a panic, in both checks. #[test] fn extreme_timestamps_are_rejected_without_panicking() { for timestamp in [i64::MIN, i64::MAX] { @@ -729,7 +728,6 @@ mod tests { } } - /// Extreme `exp` and `nbf` claims are rejected, never a panic. #[test] fn extreme_session_token_times_do_not_panic() { let now = 1_700_000_000; diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index f23d19d..9a7a53e 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -551,7 +551,6 @@ type ArgumentOrders<'a> = Option)>>; struct Analyzer<'a> { schema: &'a Schema, - /// The text of the operation. source: &'a str, /// [`input_objects::argument_orders`] of the fields compared so far, by /// position. diff --git a/crates/shopify_api_graphql/src/analyze/input_objects.rs b/crates/shopify_api_graphql/src/analyze/input_objects.rs index f63f1c8..84f629f 100644 --- a/crates/shopify_api_graphql/src/analyze/input_objects.rs +++ b/crates/shopify_api_graphql/src/analyze/input_objects.rs @@ -342,8 +342,7 @@ mod tests { #[test] fn a_large_input_object_is_scanned_in_linear_time() { - // Looking each field up among the previous ones took about 50 s for this - // object in a debug build; a set takes well under one. + // A quadratic scan takes about 50 s on this object in a debug build. let fields: Vec = (0..100_000) .map(|index| format!("f{index}: {index}")) .collect(); diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs index d9a44a2..4721219 100644 --- a/crates/shopify_api_graphql/tests/analyze.rs +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -803,8 +803,8 @@ fn the_order_of_input_fields_is_found_after_any_text() { } /// An alias spelled like its field is still an alias: the arguments after it -/// are read for the order of their input fields (round 4 review: Shopify's -/// GraphQL Ruby refuses this operation with `fieldConflict`). +/// are read for the order of their input fields (GraphQL Ruby refuses this +/// operation with `fieldConflict`). #[test] fn an_alias_spelled_like_its_field_keeps_the_order_of_input_fields() { let refused = refusal( From 36023acb5da9ca1b0a61cc7269e2fc28346f1a3f Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:04:16 +0200 Subject: [PATCH 032/135] refactor: drop a forwarding helper, share the YYYY-MM check, narrow auth items to private Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/auth.rs | 19 +++++++------------ crates/shopify_api/src/error.rs | 6 +----- crates/shopify_api/src/graphql.rs | 6 ++---- crates/shopify_api/src/graphql/response.rs | 10 +++------- crates/shopify_api/src/version.rs | 14 +++++++++----- 5 files changed, 22 insertions(+), 33 deletions(-) diff --git a/crates/shopify_api/src/auth.rs b/crates/shopify_api/src/auth.rs index 6cbcb8b..a0dbe9e 100644 --- a/crates/shopify_api/src/auth.rs +++ b/crates/shopify_api/src/auth.rs @@ -310,7 +310,7 @@ impl TokenResponse { } } -pub(crate) fn token_url(shop: &ShopDomain) -> String { +fn token_url(shop: &ShopDomain) -> String { format!("https://{shop}/admin/oauth/access_token") } @@ -336,7 +336,7 @@ pub(crate) async fn request_token( let request = HttpRequest::new(Method::Post, &url) .with_header("Accept", "application/json") .with_header("User-Agent", user_agent) - .with_timeout(std::time::Duration::from_secs(30)); + .with_timeout(Duration::from_secs(30)); let request = match encoding { Encoding::Form => request.with_form(fields), Encoding::Json => { @@ -354,17 +354,12 @@ pub(crate) async fn request_token( if !response.is_success() { // What the endpoint wrote is kept apart: it may echo what it was sent. let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap_or_default(); - let code = body - .get("error") - .and_then(serde_json::Value::as_str) - .map(oauth_error_code); + let error = body.get("error").and_then(serde_json::Value::as_str); + let code = error.map(oauth_error_code); let description = body .get("error_description") .and_then(serde_json::Value::as_str); - let detail = match ( - body.get("error").and_then(serde_json::Value::as_str), - description, - ) { + let detail = match (error, description) { (Some(code), Some(description)) => format!("{code}: {description}"), (Some(code), None) => code.to_string(), _ => String::from_utf8_lossy(&response.body).into_owned(), @@ -394,11 +389,11 @@ pub(crate) async fn request_token( /// How long a failed renewal ahead of expiry holds back the next one, while /// the current token still works. -pub(crate) const RENEWAL_BACKOFF: Duration = Duration::from_secs(30); +const RENEWAL_BACKOFF: Duration = Duration::from_secs(30); /// How long a failed renewal is the answer of the requests that wait for a /// token, instead of each asking Shopify again. -pub(crate) const FAILURE_HOLD: Duration = Duration::from_secs(5); +const FAILURE_HOLD: Duration = Duration::from_secs(5); /// What the client needs to ask for a token. pub(crate) struct Endpoint { diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index a36a9ae..0fe140f 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -332,11 +332,7 @@ impl std::error::Error for Error { /// `version` when it is written `YYYY-MM`: digits cannot be a token. fn shown_version(version: &str) -> Option<&str> { - let bytes = version.as_bytes(); - (bytes.len() == 7 - && bytes[4] == b'-' - && bytes[..4].iter().chain(&bytes[5..]).all(u8::is_ascii_digit)) - .then_some(version) + crate::version::is_dated(version).then_some(version) } /// The kind of content of an answer, from this crate's list. diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index e4ec29c..b1da597 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -17,8 +17,6 @@ use crate::error::GraphqlErrors; use crate::transport::{HttpRequest, Method}; use crate::{ApiVersion, Error, Result, Shopify}; -pub(crate) use response::decode; - impl Shopify { /// Runs an operation and returns its typed `data`. /// @@ -55,7 +53,7 @@ impl Shopify { let raw = self.send_graphql(version, &body, operation.kind()).await?; let (data, extensions) = into_data(raw)?; Ok(Response { - data: decode(data)?, + data: crate::decode::from_value(data)?, extensions, }) } @@ -86,7 +84,7 @@ impl Shopify { query: &str, variables: impl Serialize, ) -> Result { - decode(self.graphql(query, variables).await?) + crate::decode::from_value(self.graphql(query, variables).await?) } /// Runs any query or mutation and returns the answer as Shopify sent diff --git a/crates/shopify_api/src/graphql/response.rs b/crates/shopify_api/src/graphql/response.rs index a043801..d2ac2f7 100644 --- a/crates/shopify_api/src/graphql/response.rs +++ b/crates/shopify_api/src/graphql/response.rs @@ -197,15 +197,10 @@ impl RawResponse { /// The `data` read as `T`, the path of the first mismatch in the error. pub fn data_as(&self) -> crate::Result { - decode(self.data.clone().unwrap_or(Value::Null)) + crate::decode::from_value(self.data.clone().unwrap_or(Value::Null)) } } -/// Reads `value` as `T`, naming the path of the first field that does not fit. -pub(crate) fn decode(value: Value) -> crate::Result { - crate::decode::from_value(value) -} - #[cfg(test)] mod tests { use super::*; @@ -266,7 +261,8 @@ mod tests { name: String, } let error = - decode::(json!({ "orders": [{ "name": "#1" }, { "id": 2 }] })).unwrap_err(); + crate::decode::from_value::(json!({ "orders": [{ "name": "#1" }, { "id": 2 }] })) + .unwrap_err(); assert_eq!( error.to_string(), "Shopify's answer does not match the operation at `orders[1]`: missing field `name`" diff --git a/crates/shopify_api/src/version.rs b/crates/shopify_api/src/version.rs index efa3a1a..b90a036 100644 --- a/crates/shopify_api/src/version.rs +++ b/crates/shopify_api/src/version.rs @@ -57,11 +57,7 @@ impl ApiVersion { if version == "unstable" { return Ok(Self::UNSTABLE); } - let bytes = version.as_bytes(); - let well_formed = bytes.len() == 7 - && bytes[4] == b'-' - && bytes[..4].iter().chain(&bytes[5..]).all(u8::is_ascii_digit); - if !well_formed { + if !is_dated(version) { return Err(invalid( "expected `YYYY-MM`, such as `2026-10`, or `unstable`", )); @@ -91,6 +87,14 @@ impl Default for ApiVersion { } } +/// Written `YYYY-MM`. +pub(crate) fn is_dated(version: &str) -> bool { + let bytes = version.as_bytes(); + bytes.len() == 7 + && bytes[4] == b'-' + && bytes[..4].iter().chain(&bytes[5..]).all(u8::is_ascii_digit) +} + impl fmt::Display for ApiVersion { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self.0 { From 05cde7bce233a0d84bf1697dce6b8877c71e5b79 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:06:02 +0200 Subject: [PATCH 033/135] deps: drop unused subtle, move to base64 0.23 and syn 3, cargo update base64 0.23 is the version reqwest and ureq already use, so the tree no longer builds two copies of it. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 62 ++++++++++++++++++++++++------------------------------ Cargo.toml | 5 ++--- 2 files changed, 30 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d73241a..3c09074 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -102,12 +102,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - [[package]] name = "base64" version = "0.23.1" @@ -622,7 +616,7 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64 0.23.1", + "base64", "bytes", "futures-channel", "futures-util", @@ -666,9 +660,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -680,9 +674,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -693,9 +687,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -707,15 +701,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -728,15 +722,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -1144,7 +1138,7 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64 0.23.1", + "base64", "bytes", "futures-core", "http", @@ -1439,7 +1433,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" name = "shopify_api" version = "1.0.0" dependencies = [ - "base64 0.22.1", + "base64", "chrono", "clap", "hex", @@ -1476,7 +1470,7 @@ dependencies = [ "proc-macro2", "quote", "shopify_api_graphql", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -1653,9 +1647,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -1861,7 +1855,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" dependencies = [ - "base64 0.23.1", + "base64", "flate2", "log", "percent-encoding", @@ -1878,7 +1872,7 @@ version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" dependencies = [ - "base64 0.23.1", + "base64", "http", "httparse", "log", @@ -2203,9 +2197,9 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -2264,9 +2258,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -2275,9 +2269,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 45188ee..e4e8203 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ shopify_api = { path = "crates/shopify_api", version = "=1.0.0" } shopify_api_graphql = { path = "crates/shopify_api_graphql", version = "=1.0.0" } shopify_api_macros = { path = "crates/shopify_api_macros", version = "=1.0.0" } -base64 = "0.22" +base64 = "0.23" chrono = { version = "0.4", default-features = false, features = ["clock", "serde", "std"] } clap = { version = "4.6", features = ["derive", "env"] } graphql-parser = "0.4" @@ -34,8 +34,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" serde_urlencoded = "0.7" sha2 = "0.11" -subtle = "2.6" -syn = { version = "2", features = ["full"] } +syn = { version = "3", features = ["full"] } tokio = { version = "1", default-features = false } tracing = { version = "0.1", default-features = false, features = ["std"] } toml = { version = "1", default-features = false, features = ["std", "parse", "serde"] } From 090f8511ac3844499b16b74773f32fa12b43c72e Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:09:56 +0200 Subject: [PATCH 034/135] perf: keep reqwest's body buffer, read a schema file's format without a full parse - ReqwestTransport converts the body Bytes into the Vec instead of copying it: a 200 MB download peaks at 419 MB instead of 619 MB. - Schema::from_json reads only the top-level `format` before the full parse, instead of building a whole serde_json::Value first. Loading the Admin schema in the macro (opt-level 0) takes 49 ms instead of 63 ms. Text that is not an object, or does not read, takes the old path, so every error stays the same. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/transport.rs | 2 +- crates/shopify_api_graphql/src/schema.rs | 29 ++++++++++++++++++++---- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/crates/shopify_api/src/transport.rs b/crates/shopify_api/src/transport.rs index 5e01589..7a2cae1 100644 --- a/crates/shopify_api/src/transport.rs +++ b/crates/shopify_api/src/transport.rs @@ -332,7 +332,7 @@ impl Transport for ReqwestTransport { Some((name.to_string(), value.to_str().ok()?.to_string())) }) .collect(); - let body = response.bytes().await.map_err(failed)?.to_vec(); + let body = Vec::from(response.bytes().await.map_err(failed)?); Ok(HttpResponse { status, headers, diff --git a/crates/shopify_api_graphql/src/schema.rs b/crates/shopify_api_graphql/src/schema.rs index 81cd5d2..5edfea2 100644 --- a/crates/shopify_api_graphql/src/schema.rs +++ b/crates/shopify_api_graphql/src/schema.rs @@ -476,10 +476,25 @@ fn load_inputs( impl Schema { /// Reads the form written by [`Schema::to_json`]. pub fn from_json(json: &str) -> Result { - let format = serde_json::from_str::(json) - .map_err(|error| schema_error(format!("Invalid schema file: {error}")))? - .get("format") - .and_then(Value::as_u64); + // Only `format`, without building the rest. Anything but an object + // that reads takes the full parse, for its error. + #[derive(Deserialize)] + struct Header { + format: Option, + } + let header = json + .trim_start() + .starts_with('{') + .then(|| serde_json::from_str::
(json).ok()) + .flatten(); + let format = match header { + Some(header) => header.format, + None => serde_json::from_str::(json) + .map_err(|error| schema_error(format!("Invalid schema file: {error}")))? + .get("format") + .cloned(), + }; + let format = format.as_ref().and_then(Value::as_u64); if format != Some(u64::from(FORMAT)) { return Err(schema_error(match format { Some(format) => format!( @@ -1101,6 +1116,12 @@ mod tests { "Not a schema file of shopify_api: it has no `format`".to_string() )) ); + assert_eq!( + Schema::from_json(r#"[1]"#), + Err(SchemaError( + "Not a schema file of shopify_api: it has no `format`".to_string() + )) + ); assert_eq!( Schema::from_json(r#"{"format":9,"apiVersion":"2026-10","query":"Q","types":{}}"#), Err(SchemaError( From b94d702e649656e5a24628a1023a651554060f76 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:35:41 +0200 Subject: [PATCH 035/135] chore: ignore target/ in every crate Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 604f452..19866d8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -/target +target/ .DS_Store Makefile .env From 9e8d8261554c6c30533ec04853c7b21afc067cb5 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:32:23 +0200 Subject: [PATCH 036/135] feat(bulk): read bulk results as they download `Transport::send_streaming` returns the answer once its headers arrive, its body a `BodyStream`. Its default goes through `send`, so existing transports keep compiling. `ReqwestTransport` streams with `Response::chunk`, without reqwest's `stream` feature; the request's timeout bounds the headers and each chunk rather than the whole body. `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, which splits the JSONL as chunks arrive and decodes each line through the same path as before. Memory follows the longest line, capped by `max_line_length` (64 MiB by default). `bulk_query_grouped` and `download_bulk_results_grouped` return `BulkGroups`, one top-level object and its children at a time. The Vec methods collect the stream. `MockTransport::push_chunks` and `push_streaming` script chunked bodies. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + Cargo.toml | 1 + crates/shopify_api/Cargo.toml | 4 +- crates/shopify_api/src/bulk.rs | 187 +++++- crates/shopify_api/src/bulk/rows.rs | 769 ++++++++++++++++++++++++ crates/shopify_api/src/error.rs | 9 +- crates/shopify_api/src/testing.rs | 126 +++- crates/shopify_api/src/transport.rs | 304 ++++++++-- crates/shopify_api/tests/bulk_stream.rs | 451 ++++++++++++++ 9 files changed, 1776 insertions(+), 76 deletions(-) create mode 100644 crates/shopify_api/src/bulk/rows.rs create mode 100644 crates/shopify_api/tests/bulk_stream.rs diff --git a/Cargo.lock b/Cargo.lock index 3c09074..b727f34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1436,6 +1436,7 @@ dependencies = [ "base64", "chrono", "clap", + "futures-core", "hex", "hmac", "reqwest", diff --git a/Cargo.toml b/Cargo.toml index e4e8203..5493d8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ shopify_api_macros = { path = "crates/shopify_api_macros", version = "=1.0.0" } base64 = "0.23" chrono = { version = "0.4", default-features = false, features = ["clock", "serde", "std"] } clap = { version = "4.6", features = ["derive", "env"] } +futures-core = { version = "0.3.31", default-features = false } graphql-parser = "0.4" hex = "0.4" hmac = "0.13" diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index b9f277a..b6db1ea 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -37,6 +37,8 @@ rustdoc-args = ["--cfg", "docsrs"] shopify_api_macros.workspace = true chrono.workspace = true +# `Stream`, which the bulk downloads implement: the trait the async ecosystem shares. +futures-core.workspace = true reqwest = { workspace = true, optional = true } serde.workspace = true serde_json.workspace = true @@ -54,7 +56,7 @@ clap = { workspace = true, optional = true } shopify_api_graphql = { workspace = true, optional = true } [dev-dependencies] -tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time", "test-util"] } +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time", "test-util", "net", "io-util"] } trybuild.workspace = true [features] diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 9f75149..ba9c9b2 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -20,6 +20,12 @@ //! # } //! ``` //! +//! [`Shopify::bulk_query_rows`] holds every row in memory. For an export +//! of gigabytes, [`Shopify::bulk_query_stream`] reads the rows as the file +//! downloads ([`BulkRows`]), and [`Shopify::bulk_query_grouped`] each +//! top-level object with its nested objects ([`BulkGroups`]): the memory +//! they take follows the longest line, not the file. +//! //! The query of a bulk operation is a plain string. To have it checked when //! the crate compiles, declare it with [`graphql!`](crate::graphql!) and pass //! its `QUERY`: @@ -45,9 +51,17 @@ use crate::transport::{HttpRequest, Method}; use crate::{Error, Page, Result, Shopify, UserError}; use shopify_api_macros::__graphql_internal as graphql; -/// How long a download of results may take. +mod rows; + +pub use rows::{BulkGroups, BulkRows, DEFAULT_MAX_LINE_LENGTH}; + +/// How long a download waits for the answer, then for each chunk of it; a +/// transport that does not stream gives it the whole download. const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60); +/// What an [`Error::Http`] of a download keeps of the body: its first MiB. +const ERROR_BODY_LIMIT: usize = 1024 * 1024; + graphql! { mod run_query = file("graphql/operations/bulk_run_query.graphql"); } @@ -617,45 +631,185 @@ impl Shopify { /// Runs a bulk query to its end and reads every line of its results as /// `T`. Fails when the operation does not complete. /// + /// The rows are collected in a `Vec`, up to the first error: for an + /// export too large for memory, read them one by one with + /// [`Shopify::bulk_query_stream`]. + /// /// A nested connection writes its objects on lines of their own, with /// the `__parentId` of their parent: read the lines as `serde_json::Value`, - /// or as an enum of your types, to put them back together. + /// or as an enum of your types, to put them back together, or use + /// [`Shopify::bulk_query_grouped`]. pub async fn bulk_query_rows( &self, query: &str, options: BulkWaitOptions, ) -> Result> { + self.bulk_query_stream(query, options) + .await? + .collect() + .await + } + + /// Runs a bulk query to its end, then reads its results line by line + /// as they download: the memory it takes follows the longest line, not + /// the file. Fails when the operation does not complete. + /// + /// The stream ends after some errors and goes on after others: see + /// [`BulkRows`]. + /// + /// ```no_run + /// use serde::Deserialize; + /// use shopify_api::bulk::BulkWaitOptions; + /// + /// #[derive(Deserialize)] + /// struct Product { + /// id: String, + /// title: String, + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let mut products = shopify + /// .bulk_query_stream::( + /// "{ products { edges { node { id title } } } }", + /// BulkWaitOptions::default(), + /// ) + /// .await?; + /// while let Some(product) = products.next_row().await { + /// let product = product?; + /// println!("{} {}", product.id, product.title); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn bulk_query_stream( + &self, + query: &str, + options: BulkWaitOptions, + ) -> Result> { let operation = self.run_bulk_query(query).await?; - let operation = self.wait_for_bulk_operation(&operation.id, options).await?; + match self.completed_url(&operation.id, options).await? { + Some(url) => self.download_bulk_results_stream(&url).await, + None => Ok(BulkRows::new(None, "")), + } + } + + /// Runs a bulk query with `groupObjects` to its end, then reads its + /// results one top-level object at a time, with the objects of its + /// nested connections, as they download. Fails when the operation does + /// not complete. + /// + /// Grouping makes Shopify slower, and more likely to time out: use it + /// when you need the children with their parent. See [`BulkGroups`] + /// for the order it relies on and connections two levels deep. + /// + /// ```no_run + /// use serde::Deserialize; + /// use shopify_api::bulk::BulkWaitOptions; + /// + /// #[derive(Deserialize)] + /// struct Product { + /// id: String, + /// title: String, + /// } + /// + /// #[derive(Deserialize)] + /// struct Variant { + /// sku: Option, + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let mut products = shopify + /// .bulk_query_grouped::( + /// "{ products { edges { node { id title variants { edges { node { sku } } } } } } }", + /// BulkWaitOptions::default(), + /// ) + /// .await?; + /// while let Some(group) = products.next_group().await { + /// let (product, variants) = group?; + /// println!("{} has {} variants", product.title, variants.len()); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn bulk_query_grouped( + &self, + query: &str, + options: BulkWaitOptions, + ) -> Result> { + let operation = self.run_bulk_query_grouped(query, true).await?; + match self.completed_url(&operation.id, options).await? { + Some(url) => self.download_bulk_results_grouped(&url).await, + None => Ok(BulkGroups::new(None, "")), + } + } + + /// Waits for an operation, and returns the address of its results: + /// `None` when it found nothing. + async fn completed_url(&self, id: &str, options: BulkWaitOptions) -> Result> { + let operation = self.wait_for_bulk_operation(id, options).await?; if operation.status != BulkOperationStatus::Completed { return Err(not_completed(&operation)); } - match &operation.url { - Some(url) => self.download_bulk_results(url).await, - // An operation that found nothing has no file. - None => Ok(Vec::new()), - } + Ok(operation.url) } - /// Downloads the results of a bulk operation and reads each line as `T`. + /// Downloads the results of a bulk operation and reads each line as + /// `T`, up to the first error. /// - /// The file is held in memory while it is read: for an export of - /// gigabytes, download `url` with a client of your own and read it with - /// [`parse_jsonl`] chunk by chunk. The address is signed: errors leave - /// its query string out. + /// The rows are collected in a `Vec`: for an export too large for + /// memory, use [`Shopify::download_bulk_results_stream`]. The address + /// is signed: errors leave its query string out. pub async fn download_bulk_results(&self, url: &str) -> Result> { + self.download_bulk_results_stream(url) + .await? + .collect() + .await + } + + /// Downloads the results of a bulk operation, its `url` or its + /// `partial_data_url`, and reads each line as `T` as it arrives. See + /// [`BulkRows`]. + /// + /// It returns once the answer's headers arrive. An answer that is not a + /// success is an [`Error::Http`] with the first MiB of its body. The + /// address is signed: errors leave its query string out. + /// + /// The default transport waits 15 minutes at most for the answer, then + /// for each chunk, however long the whole download takes: read the rows + /// as they come, a storage server may close a connection left idle. + pub async fn download_bulk_results_stream( + &self, + url: &str, + ) -> Result> { + let body = self.open_bulk_results(url).await?; + Ok(BulkRows::new(Some(body), url)) + } + + /// [`Shopify::download_bulk_results_stream`], one top-level object and + /// its children at a time. The operation must have run with + /// `groupObjects`: see [`BulkGroups`]. + pub async fn download_bulk_results_grouped( + &self, + url: &str, + ) -> Result> { + let body = self.open_bulk_results(url).await?; + Ok(BulkGroups::new(Some(body), url)) + } + + async fn open_bulk_results(&self, url: &str) -> Result { let request = HttpRequest::new(Method::Get, url).with_timeout(DOWNLOAD_TIMEOUT); let response = self .shared .endpoint .transport - .send(request) + .send_streaming(request) .await .map_err(|source| Error::transport(url, source))?; if !response.is_success() { + let response = response.into_response(ERROR_BODY_LIMIT).await; return Err(Error::http(url, &response)); } - parse_jsonl(&response.body) + Ok(response.body) } } @@ -674,7 +828,8 @@ fn started( operation_of(&operation) } -/// Reads each non-empty line of a JSONL file as `T`. +/// Reads each non-empty line of a JSONL file already in memory as `T`. To +/// read one as it downloads, see [`BulkRows`]. pub fn parse_jsonl(body: &[u8]) -> Result> { body.split(|byte| *byte == b'\n') .enumerate() diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs new file mode 100644 index 0000000..7c2fecc --- /dev/null +++ b/crates/shopify_api/src/bulk/rows.rs @@ -0,0 +1,769 @@ +//! The results of a bulk operation, read line by line as they download. + +use std::collections::HashSet; +use std::fmt; +use std::marker::PhantomData; +use std::ops::Range; +use std::pin::Pin; +use std::task::{Context, Poll}; + +use futures_core::{FusedStream, Stream}; +use serde::Deserialize; +use serde::de::DeserializeOwned; + +use crate::transport::BodyStream; +use crate::{Error, Result}; + +/// The longest line [`BulkRows`] and [`BulkGroups`] read by default: 64 MiB. +pub const DEFAULT_MAX_LINE_LENGTH: usize = 64 * 1024 * 1024; + +/// A line: its number, from 1, and where it is in the buffer. +type Line = (usize, Range); + +/// A top-level object and its children. +type Grouped = Result<(P, Vec)>; + +/// The lines of a JSONL body, split as its chunks arrive. It holds the +/// line being read and the rest of the chunk it ends in, never the file. +struct Lines { + body: Option, + /// The address, without its query string, for errors. + url: String, + buffer: Vec, + /// Where the line being read starts in `buffer`. + start: usize, + /// How many bytes of that line were searched for its end already. + scanned: usize, + /// The number of the last line taken, from 1. + line: usize, + max: usize, + done: bool, +} + +impl Lines { + fn new(body: Option, url: &str) -> Self { + Self { + done: body.is_none(), + body, + url: crate::error::without_query(url), + buffer: Vec::new(), + start: 0, + scanned: 0, + line: 0, + max: DEFAULT_MAX_LINE_LENGTH, + } + } + + /// Stops reading: what is left of the body is dropped. + fn finish(&mut self) { + self.done = true; + self.body = None; + self.buffer = Vec::new(); + self.start = 0; + self.scanned = 0; + } + + fn too_long(&mut self, line: usize) -> Error { + self.finish(); + Error::Bulk(format!( + "line {line} of the results is longer than {} bytes", + self.max + )) + } + + /// The next line that is not blank: its number and where it is in + /// `buffer`, until the next poll. + fn poll_line(&mut self, context: &mut Context<'_>) -> Poll>> { + while !self.done { + let from = self.start + self.scanned; + if let Some(offset) = self.buffer[from..].iter().position(|byte| *byte == b'\n') { + let range = self.start..from + offset; + self.start = range.end + 1; + self.scanned = 0; + self.line += 1; + if range.len() > self.max { + return Poll::Ready(Some(Err(self.too_long(self.line)))); + } + if !is_blank(&self.buffer[range.clone()]) { + return Poll::Ready(Some(Ok((self.line, range)))); + } + continue; + } + self.scanned = self.buffer.len() - self.start; + if self.scanned > self.max { + return Poll::Ready(Some(Err(self.too_long(self.line + 1)))); + } + let Some(body) = self.body.as_mut() else { + // The last line, without a newline after it. + let range = self.start..self.buffer.len(); + self.start = range.end; + self.scanned = 0; + self.done = true; + if range.is_empty() || is_blank(&self.buffer[range.clone()]) { + break; + } + self.line += 1; + return Poll::Ready(Some(Ok((self.line, range)))); + }; + match body.as_mut().poll_next(context) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => self.body = None, + Poll::Ready(Some(Err(source))) => { + self.finish(); + return Poll::Ready(Some(Err(Error::transport(&self.url, source)))); + } + Poll::Ready(Some(Ok(chunk))) => { + // What was taken goes: the buffer holds the line being read. + self.buffer.drain(..self.start); + self.start = 0; + self.buffer.extend_from_slice(&chunk); + } + } + } + Poll::Ready(None) + } + + #[cfg(test)] + fn capacity(&self) -> usize { + self.buffer.capacity() + } +} + +/// A line of whitespace only, skipped as [`parse_jsonl`](super::parse_jsonl) skips it. +fn is_blank(line: &[u8]) -> bool { + line.iter().all(u8::is_ascii_whitespace) +} + +impl fmt::Debug for Lines { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("Lines") + .field("url", &self.url) + .field("line", &self.line) + .field("max", &self.max) + .field("done", &self.done) + .finish_non_exhaustive() + } +} + +/// The results of a bulk operation, each line read as `T` as the file +/// downloads. [`Shopify::bulk_query_stream`](crate::Shopify::bulk_query_stream) +/// and [`Shopify::download_bulk_results_stream`](crate::Shopify::download_bulk_results_stream) +/// return it. +/// +/// It holds one line at a time, and the rest of the chunk that line ends +/// in: the memory it takes follows the longest line, not the file. Read it +/// with [`BulkRows::next_row`], or as a [`Stream`]. +/// +/// Lines are split on `\n`; a `\r` before it, a last line without one and +/// blank lines are fine, and blank lines are skipped but counted. +/// +/// # Errors +/// +/// - A line that does not read as `T` is an [`Error::Decode`] that gives +/// its line number and nothing of its content (see [`Error`]). The +/// stream **goes on** with the next line: skip the row, or stop. +/// - A line longer than [`BulkRows::max_line_length`] is an [`Error::Bulk`], +/// and a download that fails halfway an [`Error::Transport`]. The stream +/// **ends** after either. +#[must_use = "a stream does nothing until it is read"] +pub struct BulkRows { + lines: Lines, + row: PhantomData T>, +} + +impl fmt::Debug for BulkRows { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BulkRows") + .field("lines", &self.lines) + .finish() + } +} + +impl BulkRows { + pub(crate) fn new(body: Option, url: &str) -> Self { + Self { + lines: Lines::new(body, url), + row: PhantomData, + } + } + + /// Refuses a line longer than `bytes`, newline left out, instead of + /// [`DEFAULT_MAX_LINE_LENGTH`]: a file without newlines would otherwise + /// be held whole. + pub fn max_line_length(mut self, bytes: usize) -> Self { + self.lines.max = bytes; + self + } + + /// The number of the last line read, from 1, blank lines included. + pub fn line(&self) -> usize { + self.lines.line + } +} + +impl BulkRows { + /// The next row, `None` at the end of the file. + pub async fn next_row(&mut self) -> Option> { + std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context)).await + } + + /// Every row, up to the first error. + pub(crate) async fn collect(mut self) -> Result> { + let mut rows = Vec::new(); + while let Some(row) = self.next_row().await { + rows.push(row?); + } + Ok(rows) + } +} + +impl Stream for BulkRows { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll>> { + let lines = &mut self.get_mut().lines; + lines.poll_line(context).map(|line| { + line.map(|line| { + let (number, range) = line?; + crate::decode::from_jsonl_line(&lines.buffer[range], number) + }) + }) + } +} + +impl FusedStream for BulkRows { + fn is_terminated(&self) -> bool { + self.lines.done + } +} + +/// What [`BulkGroups`] reads of each line to place it. +#[derive(Deserialize)] +struct Keys { + id: Option, + #[serde(rename = "__parentId")] + parent_id: Option, +} + +struct Group { + parent: P, + children: Vec, + /// The IDs of the objects of the group, the children of the next lines + /// belong to. + ids: HashSet, +} + +/// The results of a grouped bulk query, each top-level object with the +/// objects of its nested connections, as the file downloads. +/// [`Shopify::bulk_query_grouped`](crate::Shopify::bulk_query_grouped) and +/// [`Shopify::download_bulk_results_grouped`](crate::Shopify::download_bulk_results_grouped) +/// return it. +/// +/// A line without `__parentId` is a top-level object, read as `P`; a line +/// with one is a child, read as `C`. Each item is a top-level object and +/// its children, in the order of the file: the item is complete when the +/// next top-level object, or the end of the file, arrives. One group is +/// held at a time. +/// +/// # Nested connections two levels deep +/// +/// Shopify allows connections two levels deep: the objects of the second +/// level carry the `__parentId` of an object of the first, not of the +/// top-level one. They are in the same list as the first level, in the +/// order of the file: read `__parentId` in `C` to put them back in place. +/// +/// # The order it needs +/// +/// It needs each child after its parent, before the next top-level object: +/// the order Shopify writes with `groupObjects`, which +/// [`Shopify::bulk_query_grouped`](crate::Shopify::bulk_query_grouped) asks +/// for. Without it, Shopify only promises a child after its parent, +/// anywhere further in the file. A child whose parent is neither the +/// current top-level object nor one of its children is an [`Error::Bulk`] +/// rather than a child put in the wrong group. +/// +/// # Errors +/// +/// Any error ends the stream, a line that does not read as `P` or `C` +/// included: the lines after it could not be placed for sure. The errors +/// are those of [`BulkRows`], and the child out of place above. +#[must_use = "a stream does nothing until it is read"] +pub struct BulkGroups { + lines: Lines, + group: Option>, +} + +// The group is never pinned: it is only reached through `&mut`. +impl Unpin for BulkGroups {} + +impl fmt::Debug for BulkGroups { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BulkGroups") + .field("lines", &self.lines) + .field( + "children", + &self.group.as_ref().map(|group| group.children.len()), + ) + .finish() + } +} + +impl BulkGroups { + pub(crate) fn new(body: Option, url: &str) -> Self { + Self { + lines: Lines::new(body, url), + group: None, + } + } + + /// [`BulkRows::max_line_length`]. + pub fn max_line_length(mut self, bytes: usize) -> Self { + self.lines.max = bytes; + self + } + + /// The number of the last line read, from 1, blank lines included. + pub fn line(&self) -> usize { + self.lines.line + } + + fn fail(&mut self, error: Error) -> Poll>> { + self.lines.finish(); + self.group = None; + Poll::Ready(Some(Err(error))) + } +} + +impl BulkGroups { + /// The next top-level object and its children, `None` at the end of the file. + pub async fn next_group(&mut self) -> Option> { + std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context)).await + } +} + +impl Stream for BulkGroups { + type Item = Grouped; + + fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + loop { + let (number, range) = match this.lines.poll_line(context) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + let group = this.group.take(); + return Poll::Ready(group.map(|group| Ok((group.parent, group.children)))); + } + Poll::Ready(Some(Err(error))) => return this.fail(error), + Poll::Ready(Some(Ok(line))) => line, + }; + let line = &this.lines.buffer[range]; + let keys = match crate::decode::from_jsonl_line::(line, number) { + Ok(keys) => keys, + Err(error) => return this.fail(error), + }; + match keys.parent_id { + None => { + let parent = match crate::decode::from_jsonl_line::

(line, number) { + Ok(parent) => parent, + Err(error) => return this.fail(error), + }; + let next = Group { + parent, + children: Vec::new(), + ids: keys.id.into_iter().collect(), + }; + if let Some(done) = this.group.replace(next) { + return Poll::Ready(Some(Ok((done.parent, done.children)))); + } + } + Some(parent_id) => { + if !this + .group + .as_ref() + .is_some_and(|group| group.ids.contains(&parent_id)) + { + let error = Error::Bulk(format!( + "line {number} of the results is a child of neither the top-level object before it nor one of its children: run the query with `groupObjects`" + )); + return this.fail(error); + } + let child = match crate::decode::from_jsonl_line::(line, number) { + Ok(child) => child, + Err(error) => return this.fail(error), + }; + if let Some(group) = this.group.as_mut() { + group.ids.extend(keys.id); + group.children.push(child); + } + } + } + } + } +} + +impl FusedStream for BulkGroups { + fn is_terminated(&self) -> bool { + self.lines.done && self.group.is_none() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::transport::{TransportError, chunks}; + + fn rows_of(parts: Vec>) -> BulkRows { + BulkRows::new( + Some(chunks(parts.into_iter().map(Ok))), + "https://storage.test/r.jsonl", + ) + } + + async fn all(mut rows: BulkRows) -> Vec> { + let mut out = Vec::new(); + while let Some(row) = rows.next_row().await { + out.push(row); + } + out + } + + /// The rows and errors as text: what a split must not change. + fn shown(results: &[Result]) -> Vec { + results + .iter() + .map(|result| match result { + Ok(value) => value.to_string(), + Err(error) => format!("error: {error}"), + }) + .collect() + } + + /// What `parse_jsonl` gives line by line: each line on its own, numbered. + fn buffered(body: &[u8]) -> Vec { + body.split(|byte| *byte == b'\n') + .enumerate() + .filter(|(_, line)| !is_blank(line)) + .map(|(index, line)| { + match crate::decode::from_jsonl_line::(line, index + 1) { + Ok(value) => value.to_string(), + Err(error) => format!("error: {error}"), + } + }) + .collect() + } + + const BODY: &[u8] = "{\"id\":\"gid://shopify/Product/1\",\"title\":\"Café ☕ 𝄞\"}\r\n\ + \r\n\ + {\"id\":\"gid://shopify/ProductVariant/2\",\"__parentId\":\"gid://shopify/Product/1\"}\n\ + \n \n\ + {\"broken\": tru}\n\ + {\"id\":3,\"title\":\"Ünïcødé\"}" + .as_bytes(); + + #[tokio::test] + async fn every_split_in_two_or_three_reads_as_the_whole_file() { + let expected = buffered(BODY); + assert_eq!(expected.len(), 4); + assert!(expected[2].starts_with("error: "), "{expected:?}"); + for first in 0..=BODY.len() { + let parts = vec![BODY[..first].to_vec(), BODY[first..].to_vec()]; + assert_eq!( + shown(&all(rows_of(parts)).await), + expected, + "split at {first}" + ); + for second in first..=BODY.len() { + let parts = vec![ + BODY[..first].to_vec(), + BODY[first..second].to_vec(), + BODY[second..].to_vec(), + ]; + assert_eq!( + shown(&all(rows_of(parts)).await), + expected, + "split at {first} and {second}" + ); + } + } + } + + #[tokio::test] + async fn random_splits_read_as_the_whole_file() { + let mut body = Vec::new(); + for index in 0..300 { + let line = serde_json::json!({ "id": index, "title": "é".repeat(index % 7), "n": [index, index] }); + body.extend_from_slice(line.to_string().as_bytes()); + body.extend_from_slice(if index.is_multiple_of(3) { + b"\r\n" + } else { + b"\n" + }); + if index.is_multiple_of(11) { + body.extend_from_slice(b"\n"); + } + } + let expected = buffered(&body); + assert_eq!(expected.len(), 300); + let whole: Vec = crate::bulk::parse_jsonl(&body).unwrap(); + let whole: Vec = whole.iter().map(ToString::to_string).collect(); + assert_eq!(whole, expected); + // A fixed xorshift: the same splits on every run. + let mut state: u64 = 0x2545_f491_4f6c_dd1d; + for _ in 0..200 { + let mut parts = Vec::new(); + let mut at = 0; + while at < body.len() { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let size = (state % 97) as usize; + let end = (at + size).min(body.len()); + parts.push(body[at..end].to_vec()); + at = end; + } + assert_eq!(shown(&all(rows_of(parts)).await), expected); + } + let one_byte_each = body.iter().map(|byte| vec![*byte]).collect(); + assert_eq!(shown(&all(rows_of(one_byte_each)).await), expected); + } + + #[tokio::test] + async fn a_line_longer_than_the_limit_ends_the_stream() { + // Too long whether its newline comes with it or not. + for parts in [ + vec![b"{\"a\":1}\n{\"b\":\"0123456789\"}\n{\"c\":3}\n".to_vec()], + vec![ + b"{\"a\":1}\n{\"b\":\"01234".to_vec(), + b"56789\"}\n{\"c\":3}\n".to_vec(), + ], + vec![b"{\"a\":1}\n{\"b\":\"0123456789\"}".to_vec()], + ] { + let mut rows = rows_of::(parts).max_line_length(12); + assert_eq!(rows.next_row().await.unwrap().unwrap()["a"], 1); + let error = rows.next_row().await.unwrap().unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 2 of the results is longer than 12 bytes" + ); + assert!(rows.next_row().await.is_none()); + assert!(rows.is_terminated()); + } + // A line of exactly the limit is read; `\r` counts, `\n` does not. + let mut rows = rows_of::(vec![b"{\"b\":\"12345\"}\r\n".to_vec()]) + .max_line_length(14); + assert_eq!(rows.next_row().await.unwrap().unwrap()["b"], "12345"); + } + + #[tokio::test] + async fn a_file_without_newlines_is_not_held_whole() { + let chunk = vec![b'x'; 64 * 1024]; + // 1 GiB, never produced: the limit stops it after 1 MiB. + let endless = std::iter::repeat_n(chunk, 16 * 1024).map(Ok); + let mut rows: BulkRows = + BulkRows::new(Some(chunks(endless)), "https://storage.test/r.jsonl") + .max_line_length(1024 * 1024); + let error = rows.next_row().await.unwrap().unwrap_err(); + assert!(matches!(error, Error::Bulk(_)), "{error:?}"); + assert!(rows.next_row().await.is_none()); + } + + #[tokio::test] + async fn a_body_that_fails_halfway_ends_the_stream() { + let parts = vec![ + Ok(b"{\"a\":1}\n{\"a\":".to_vec()), + Err(TransportError::new("connection reset")), + Ok(b"2}\n".to_vec()), + ]; + let mut rows: BulkRows = BulkRows::new( + Some(chunks(parts)), + "https://storage.test/r.jsonl?sig=SECRET", + ); + assert_eq!(rows.next_row().await.unwrap().unwrap()["a"], 1); + let error = rows.next_row().await.unwrap().unwrap_err(); + assert_eq!( + error.to_string(), + "request to https://storage.test/r.jsonl failed: connection reset" + ); + assert!(rows.next_row().await.is_none()); + } + + #[tokio::test] + async fn a_decode_error_names_its_line_shows_nothing_of_it_and_the_stream_goes_on() { + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + struct Row { + id: u64, + } + let body = b"{\"id\":1}\n\n{\"id\":\"shpat_SECRET\"}\n{\"id\":3}\n".to_vec(); + let results = all(rows_of::(vec![body])).await; + assert_eq!(results.len(), 3); + assert_eq!(results[0].as_ref().unwrap().id, 1); + let error = results[1].as_ref().unwrap_err(); + let shown = format!("{error}\n{error:?}\n{error:#?}"); + assert!(!shown.contains("SECRET"), "{shown}"); + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `id`: invalid type: string, expected u64 at line 3 column 20" + ); + assert!(error.sensitive_detail().unwrap().contains("shpat_SECRET")); + assert_eq!(results[2].as_ref().unwrap().id, 3); + } + + /// The buffer follows the longest line, whatever the size of the file. + #[tokio::test] + async fn memory_follows_the_longest_line_not_the_file() { + let line = format!( + "{{\"id\":\"gid://shopify/Product/1\",\"title\":\"{}\"}}\n", + "a".repeat(200) + ); + let chunk = line.repeat(64).into_bytes(); + let chunk_len = chunk.len(); + // About 20 MB, generated as it is read. + let count = 20_000_000 / chunk_len; + let body = std::iter::repeat_n(chunk, count).map(Ok); + let mut rows: BulkRows = + BulkRows::new(Some(chunks(body)), "https://storage.test/r.jsonl"); + let mut read = 0; + let mut largest = 0; + while let Some(row) = rows.next_row().await { + row.unwrap(); + read += 1; + largest = largest.max(rows.lines.capacity()); + } + assert_eq!(read, count * 64); + // A chunk and a partial line, with the growth of a `Vec`. + assert!( + largest <= 2 * (chunk_len + line.len()), + "{largest} bytes held" + ); + } + + fn groups_of(body: &str) -> BulkGroups { + BulkGroups::new( + Some(chunks( + body.as_bytes() + .chunks(5) + .map(|part| Ok(part.to_vec())) + .collect::>(), + )), + "https://storage.test/r.jsonl", + ) + } + + async fn all_groups( + mut groups: BulkGroups, + ) -> Vec)>> { + let mut out = Vec::new(); + while let Some(group) = groups.next_group().await { + out.push(group); + } + out + } + + fn ids(values: &[serde_json::Value]) -> Vec<&str> { + values + .iter() + .map(|value| value["id"].as_str().unwrap()) + .collect() + } + + #[tokio::test] + async fn groups_hold_each_top_level_object_with_its_children() { + let body = r#"{"id":"P1"} +{"id":"V1","__parentId":"P1"} +{"id":"V2","__parentId":"P1"} + +{"id":"P2"} +{"id":"P3"} +{"id":"V3","__parentId":"P3"}"#; + let groups = all_groups(groups_of(body)).await; + let groups: Vec<_> = groups.into_iter().map(Result::unwrap).collect(); + assert_eq!(groups.len(), 3); + assert_eq!(groups[0].0["id"], "P1"); + assert_eq!(ids(&groups[0].1), ["V1", "V2"]); + assert_eq!(groups[1].0["id"], "P2"); + assert!(groups[1].1.is_empty()); + assert_eq!(ids(&groups[2].1), ["V3"]); + } + + #[tokio::test] + async fn the_second_level_joins_the_group_of_its_top_level_object() { + let body = r#"{"id":"P1"} +{"id":"V1","__parentId":"P1"} +{"id":"L1","__parentId":"V1"} +{"id":"L2","__parentId":"V1"} +{"id":"V2","__parentId":"P1"} +{"id":"L3","__parentId":"V2"} +{"id":"M1","__parentId":"P1"} +{"id":"P2"} +{"id":"V3","__parentId":"P2"} +{"id":"L4","__parentId":"V3"} +"#; + let groups: Vec<_> = all_groups(groups_of(body)) + .await + .into_iter() + .map(Result::unwrap) + .collect(); + assert_eq!(groups.len(), 2); + assert_eq!(ids(&groups[0].1), ["V1", "L1", "L2", "V2", "L3", "M1"]); + assert_eq!(groups[0].1[2]["__parentId"], "V1"); + assert_eq!(ids(&groups[1].1), ["V3", "L4"]); + } + + #[tokio::test] + async fn a_child_out_of_its_group_is_an_error_that_ends_the_stream() { + // V3's parent came before P2: the order without `groupObjects`. + let body = r#"{"id":"P1"} +{"id":"V1","__parentId":"P1"} +{"id":"P2"} +{"id":"V3","__parentId":"P1"} +{"id":"P3"} +"#; + let groups = all_groups(groups_of(body)).await; + assert_eq!(groups.len(), 2); + let (parent, children) = groups[0].as_ref().unwrap(); + assert_eq!(parent["id"], "P1"); + assert_eq!(ids(children), ["V1"]); + let error = groups[1].as_ref().unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 4 of the results is a child of neither the top-level object before it nor one of its children: run the query with `groupObjects`" + ); + + // Before any top-level object, or to an unknown parent. + for body in [ + "{\"id\":\"V1\",\"__parentId\":\"P1\"}\n{\"id\":\"P1\"}\n", + "{\"id\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P9\"}\n", + ] { + let groups = all_groups(groups_of(body)).await; + assert_eq!(groups.len(), 1, "{body}"); + assert!(matches!(groups[0], Err(Error::Bulk(_))), "{body}"); + } + } + + #[tokio::test] + async fn groups_read_typed_parents_and_children_and_hide_bad_values() { + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + struct Product { + id: String, + } + #[derive(Debug, Deserialize)] + #[allow(dead_code)] + struct Variant { + id: String, + price: u64, + } + let body = "{\"id\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P1\",\"price\":\"shpat_SECRET\"}\n{\"id\":\"P2\"}\n"; + let mut groups = groups_of::(body); + let error = groups.next_group().await.unwrap().unwrap_err(); + let shown = format!("{error}\n{error:?}"); + assert!(!shown.contains("SECRET"), "{shown}"); + assert!(shown.contains("line 2"), "{shown}"); + assert!(groups.next_group().await.is_none()); + assert!(groups.is_terminated()); + } +} diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index 0fe140f..17fca60 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -93,8 +93,9 @@ pub enum Error { /// Shopify's `X-Request-Id`, which its support asks for. `Debug` /// shows it when it is made of hexadecimal digits and dashes. request_id: Option, - /// The whole body, as it was received. It may hold secrets: read it - /// with [`Error::raw_http_body`]. Its `Debug` shows its length only. + /// The whole body, as it was received; of a bulk download, its first + /// MiB. It may hold secrets: read it with [`Error::raw_http_body`]. + /// Its `Debug` shows its length only. raw_body: RawBody, }, @@ -391,8 +392,8 @@ impl Error { } } - /// The whole body of the answer, for [`Error::Http`], exactly as it was - /// received. + /// The body of the answer, for [`Error::Http`], exactly as it was + /// received: the whole body, or the first MiB of a bulk download. /// /// **It may contain secrets** (a token, a signed address): do not log it /// or show it to a user. diff --git a/crates/shopify_api/src/testing.rs b/crates/shopify_api/src/testing.rs index 30ac6df..c0efb44 100644 --- a/crates/shopify_api/src/testing.rs +++ b/crates/shopify_api/src/testing.rs @@ -2,7 +2,8 @@ //! //! A [`MockTransport`] records the requests a client sends and answers them //! with what the test scripts: queued answers first, in order, then a -//! handler, then `404`. +//! handler, then `404`. A queued answer may stream its body in chunks you +//! choose ([`MockTransport::push_chunks`]), to test the bulk downloads. //! //! ``` //! use shopify_api::graphql; @@ -29,7 +30,9 @@ use std::time::Duration; use serde_json::{Value, json}; -use crate::transport::{BoxFuture, HttpRequest, HttpResponse, Transport, TransportError}; +use crate::transport::{ + BoxFuture, HttpRequest, HttpResponse, StreamingResponse, Transport, TransportError, +}; use crate::{RetryPolicy, Shopify}; type Handler = dyn Fn(&HttpRequest) -> Result + Send + Sync; @@ -40,9 +43,15 @@ pub struct MockTransport { state: Arc>, } +/// A queued answer. +enum Answer { + Whole(Result), + Streaming(StreamingResponse), +} + #[derive(Default)] struct State { - queue: VecDeque>, + queue: VecDeque, handler: Option>, requests: Vec, } @@ -81,13 +90,57 @@ impl MockTransport { /// Answers the next request that finds no answer queued before this one. pub fn push(&self, response: HttpResponse) -> &Self { - self.state().queue.push_back(Ok(response)); + self.state().queue.push_back(Answer::Whole(Ok(response))); self } /// Fails the next request, as a network failure. pub fn push_error(&self, error: TransportError) -> &Self { - self.state().queue.push_back(Err(error)); + self.state().queue.push_back(Answer::Whole(Err(error))); + self + } + + /// Answers the next request with `status` and a body sent in `chunks`, + /// each produced when it is read: split a body at the positions a test + /// needs, or generate a large one lazily. + /// + /// ``` + /// use shopify_api::testing::{MockTransport, client}; + /// + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> shopify_api::Result<()> { + /// let mock = MockTransport::new(); + /// // A line cut in two, and a two-byte character cut in two. + /// mock.push_chunks(200, [&b"{\"title\":\"Caf"[..], b"\xc3", b"\xa9\"}\n{\"ti", b"tle\":\"Hat\"}"]); + /// let shopify = client(&mock); + /// + /// let mut rows = shopify + /// .download_bulk_results_stream::("https://storage.test/results.jsonl") + /// .await?; + /// assert_eq!(rows.next_row().await.transpose()?.unwrap()["title"], "Café"); + /// assert_eq!(rows.next_row().await.transpose()?.unwrap()["title"], "Hat"); + /// assert!(rows.next_row().await.is_none()); + /// # Ok(()) + /// # } + /// ``` + pub fn push_chunks(&self, status: u16, chunks: I) -> &Self + where + I: IntoIterator, + I::Item: Into>, + I::IntoIter: Send + 'static, + { + let body = crate::transport::chunks(chunks.into_iter().map(|chunk| Ok(chunk.into()))); + self.push_streaming(StreamingResponse { + status, + headers: Vec::new(), + body, + }) + } + + /// Answers the next request with `response`, whose body is read as + /// the client polls it: a body that fails halfway, or one that waits. + pub fn push_streaming(&self, response: StreamingResponse) -> &Self { + self.state().queue.push_back(Answer::Streaming(response)); self } @@ -137,26 +190,57 @@ impl MockTransport { } } +impl MockTransport { + /// Records `request` and takes its answer. + fn answer(&self, request: &HttpRequest) -> Answer { + let mut state = self.state(); + state.requests.push(request.clone()); + if let Some(answer) = state.queue.pop_front() { + return answer; + } + let Some(handler) = state.handler.clone() else { + return Answer::Whole(Ok(HttpResponse::new( + 404, + format!("not mocked: {:?} {}", request.method, request.url), + ))); + }; + drop(state); + Answer::Whole(handler(request)) + } +} + impl Transport for MockTransport { fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result> { - let answer = { - let mut state = self.state(); - state.requests.push(request.clone()); - match state.queue.pop_front() { - Some(answer) => answer, - None => match state.handler.clone() { - Some(handler) => { - drop(state); - handler(&request) + let answer = self.answer(&request); + Box::pin(async move { + match answer { + Answer::Whole(answer) => answer, + Answer::Streaming(mut response) => { + let mut body = Vec::new(); + while let Some(chunk) = crate::transport::next_chunk(&mut response.body).await { + body.extend_from_slice(&chunk?); } - None => Ok(HttpResponse::new( - 404, - format!("not mocked: {:?} {}", request.method, request.url), - )), - }, + Ok(HttpResponse { + status: response.status, + headers: response.headers, + body, + }) + } } - }; - Box::pin(async move { answer }) + }) + } + + fn send_streaming( + &self, + request: HttpRequest, + ) -> BoxFuture<'_, Result> { + let answer = self.answer(&request); + Box::pin(async move { + match answer { + Answer::Whole(answer) => answer.map(StreamingResponse::from), + Answer::Streaming(response) => Ok(response), + } + }) } } diff --git a/crates/shopify_api/src/transport.rs b/crates/shopify_api/src/transport.rs index 7a2cae1..61fa927 100644 --- a/crates/shopify_api/src/transport.rs +++ b/crates/shopify_api/src/transport.rs @@ -4,11 +4,18 @@ use std::fmt; use std::future::Future; use std::pin::Pin; +use std::task::{Context, Poll}; use std::time::Duration; +use futures_core::Stream; + /// A boxed, sendable future, as [`Transport::send`] returns. pub type BoxFuture<'a, T> = Pin + Send + 'a>>; +/// The body of a [`StreamingResponse`], chunk by chunk. A chunk may be of +/// any size, and may end in the middle of a line or of a UTF-8 character. +pub type BodyStream = Pin, TransportError>> + Send>>; + /// Header names whose value is a secret, hidden by `Debug`. const SECRET_HEADERS: [&str; 5] = [ "x-shopify-access-token", @@ -187,6 +194,111 @@ impl HttpResponse { } } +/// An answer whose body is read as it arrives, as +/// [`Transport::send_streaming`] returns it. +/// +/// `Debug` hides the body, as [`HttpResponse`]'s does. +#[non_exhaustive] +pub struct StreamingResponse { + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: BodyStream, +} + +impl fmt::Debug for StreamingResponse { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("StreamingResponse") + .field("status", &self.status) + .field("headers", &shown_headers(&self.headers)) + .finish_non_exhaustive() + } +} + +impl StreamingResponse { + pub fn new( + status: u16, + body: impl Stream, TransportError>> + Send + 'static, + ) -> Self { + Self { + status, + headers: Vec::new(), + body: Box::pin(body), + } + } + + pub fn with_header(mut self, name: impl Into, value: impl Into) -> Self { + self.headers.push((name.into(), value.into())); + self + } + + pub fn is_success(&self) -> bool { + (200..300).contains(&self.status) + } + + /// The first value of a header, whatever the case of its name. + pub fn header(&self, name: &str) -> Option<&str> { + header(&self.headers, name) + } + + /// The answer with the first `limit` bytes of its body, the rest left + /// unread: what an error keeps of a body that may be of any size. + pub(crate) async fn into_response(mut self, limit: usize) -> HttpResponse { + let mut body = Vec::new(); + while body.len() < limit { + match next_chunk(&mut self.body).await { + Some(Ok(chunk)) => body.extend_from_slice(&chunk), + Some(Err(_)) | None => break, + } + } + body.truncate(limit); + HttpResponse { + status: self.status, + headers: self.headers, + body, + } + } +} + +/// The whole body as one chunk. +impl From for StreamingResponse { + fn from(response: HttpResponse) -> Self { + let body = (!response.body.is_empty()).then_some(Ok(response.body)); + Self { + status: response.status, + headers: response.headers, + body: chunks(body), + } + } +} + +/// The next chunk of `body`. +pub(crate) async fn next_chunk(body: &mut BodyStream) -> Option, TransportError>> { + std::future::poll_fn(|context| body.as_mut().poll_next(context)).await +} + +/// A body made of the chunks `iter` gives, produced as they are polled. +pub(crate) fn chunks(iter: I) -> BodyStream +where + I: IntoIterator, TransportError>>, + I::IntoIter: Send + 'static, +{ + Box::pin(Chunks(iter.into_iter())) +} + +struct Chunks(I); + +// The iterator is never pinned: it is only called through `&mut`. +impl Unpin for Chunks {} + +impl, TransportError>>> Stream for Chunks { + type Item = Result, TransportError>; + + fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(self.0.next()) + } +} + fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> { headers .iter() @@ -249,6 +361,25 @@ impl std::error::Error for TransportError { /// secret is never sent on to another host. pub trait Transport: Send + Sync + 'static { fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result>; + + /// Sends `request` and returns the answer as soon as its headers + /// arrive, its body read as the caller polls it. The bulk downloads go + /// through it, so that a file of gigabytes is never held in memory. + /// + /// When it streams, `request.timeout` bounds the wait for the headers + /// and for each chunk, not the whole body, which is read at its + /// consumer's pace. + /// + /// The default sends `request` with [`Transport::send`] and returns the + /// whole body as one chunk: a transport that implements only `send` + /// works, with the body in memory and `request.timeout` for the whole + /// exchange. + fn send_streaming( + &self, + request: HttpRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { self.send(request).await.map(StreamingResponse::from) }) + } } /// The `reqwest` this crate is built with, for [`ReqwestTransport::from_builder`]. @@ -257,7 +388,9 @@ pub trait Transport: Send + Sync + 'static { pub use reqwest; /// The default [`Transport`], over `reqwest`: no redirections, a 10-second -/// connection timeout and a 60-second request timeout. +/// connection timeout and a 60-second request timeout. A streamed answer +/// with a timeout of its own waits that long for its headers and for each +/// chunk instead, however long the whole body takes. #[cfg(any(feature = "rustls", feature = "native-tls"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))] #[derive(Debug, Clone)] @@ -295,44 +428,56 @@ impl ReqwestTransport { } } +#[cfg(any(feature = "rustls", feature = "native-tls"))] +impl ReqwestTransport { + fn builder(&self, request: HttpRequest) -> reqwest::RequestBuilder { + let method = match request.method { + Method::Get => reqwest::Method::GET, + Method::Post => reqwest::Method::POST, + }; + let mut builder = self.client.request(method, &request.url); + for (name, value) in &request.headers { + builder = builder.header(name, value); + } + if let Some(timeout) = request.timeout { + builder = builder.timeout(timeout); + } + if !request.body.is_empty() { + builder = builder.body(request.body); + } + builder + } +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +fn reqwest_failed(error: reqwest::Error) -> TransportError { + // Its address may hold a signature: errors leave it out. + let error = error.without_url(); + let message = error.to_string(); + if error.is_timeout() { + TransportError::timeout(message).with_source(error) + } else { + TransportError::new(message).with_source(error) + } +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +fn reqwest_headers(response: &reqwest::Response) -> Vec<(String, String)> { + response + .headers() + .iter() + .filter_map(|(name, value)| Some((name.to_string(), value.to_str().ok()?.to_string()))) + .collect() +} + #[cfg(any(feature = "rustls", feature = "native-tls"))] impl Transport for ReqwestTransport { fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result> { Box::pin(async move { - let failed = |error: reqwest::Error| { - // Its address may hold a signature: errors leave it out. - let error = error.without_url(); - let message = error.to_string(); - if error.is_timeout() { - TransportError::timeout(message).with_source(error) - } else { - TransportError::new(message).with_source(error) - } - }; - let method = match request.method { - Method::Get => reqwest::Method::GET, - Method::Post => reqwest::Method::POST, - }; - let mut builder = self.client.request(method, &request.url); - for (name, value) in &request.headers { - builder = builder.header(name, value); - } - if let Some(timeout) = request.timeout { - builder = builder.timeout(timeout); - } - if !request.body.is_empty() { - builder = builder.body(request.body); - } - let response = builder.send().await.map_err(failed)?; + let response = self.builder(request).send().await.map_err(reqwest_failed)?; let status = response.status().as_u16(); - let headers = response - .headers() - .iter() - .filter_map(|(name, value)| { - Some((name.to_string(), value.to_str().ok()?.to_string())) - }) - .collect(); - let body = Vec::from(response.bytes().await.map_err(failed)?); + let headers = reqwest_headers(&response); + let body = Vec::from(response.bytes().await.map_err(reqwest_failed)?); Ok(HttpResponse { status, headers, @@ -340,6 +485,97 @@ impl Transport for ReqwestTransport { }) }) } + + fn send_streaming( + &self, + request: HttpRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + let wait = request.timeout; + let mut builder = self.builder(request); + let response = match wait { + Some(wait) => { + // reqwest's timeout would cover the whole body: it is + // lifted, and `wait` bounds the headers and each chunk. + builder = builder.timeout(Duration::MAX); + tokio::time::timeout(wait, builder.send()) + .await + .map_err(|_| { + TransportError::timeout(format!("no answer within {wait:?}")) + })? + } + None => builder.send().await, + } + .map_err(reqwest_failed)?; + Ok(StreamingResponse { + status: response.status().as_u16(), + headers: reqwest_headers(&response), + body: Box::pin(ReqwestBody { + response: Some(response), + pending: None, + wait, + }), + }) + }) + } +} + +/// The chunk being read, with the answer it is read from. +#[cfg(any(feature = "rustls", feature = "native-tls"))] +type PendingChunk = + BoxFuture<'static, (reqwest::Response, Result>, TransportError>)>; + +/// The body of a reqwest answer as a [`Stream`], read with +/// `Response::chunk`, which needs no feature of reqwest. +#[cfg(any(feature = "rustls", feature = "native-tls"))] +struct ReqwestBody { + response: Option, + pending: Option, + wait: Option, +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +impl Stream for ReqwestBody { + type Item = Result, TransportError>; + + fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { + loop { + if let Some(pending) = self.pending.as_mut() { + let (response, chunk) = match pending.as_mut().poll(context) { + Poll::Ready(done) => done, + Poll::Pending => return Poll::Pending, + }; + self.pending = None; + return Poll::Ready(match chunk { + Ok(Some(chunk)) => { + self.response = Some(response); + Some(Ok(chunk)) + } + Ok(None) => None, + // The answer is dropped: the stream ends after its error. + Err(error) => Some(Err(error)), + }); + } + let Some(mut response) = self.response.take() else { + return Poll::Ready(None); + }; + let wait = self.wait; + // The timer starts when the chunk is asked for: a slow consumer + // does not count against it. + self.pending = Some(Box::pin(async move { + let chunk = match wait { + Some(wait) => match tokio::time::timeout(wait, response.chunk()).await { + Ok(chunk) => chunk.map_err(reqwest_failed), + Err(_) => Err(TransportError::timeout(format!( + "the body stalled for {wait:?}" + ))), + }, + None => response.chunk().await.map_err(reqwest_failed), + }; + (response, chunk.map(|chunk| chunk.map(Vec::from))) + })); + } + } } /// The transport a client uses when it is given none. diff --git a/crates/shopify_api/tests/bulk_stream.rs b/crates/shopify_api/tests/bulk_stream.rs new file mode 100644 index 0000000..527b6c1 --- /dev/null +++ b/crates/shopify_api/tests/bulk_stream.rs @@ -0,0 +1,451 @@ +//! Bulk results read as they download. +#![cfg(feature = "testing")] + +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll}; +use std::time::Duration; + +use serde::Deserialize; +use serde_json::{Value, json}; +use shopify_api::bulk::{BulkWaitOptions, parse_jsonl}; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::transport::{ + BoxFuture, HttpRequest, HttpResponse, StreamingResponse, Transport, TransportError, +}; +use shopify_api::{Error, Shopify}; + +const RESULTS_URL: &str = + "https://storage.googleapis.com/bulk-operation-outputs/1.jsonl?X-Goog-Signature=SECRET"; + +fn operation(status: &str, url: Option<&str>) -> Value { + json!({ + "id": "gid://shopify/BulkOperation/1", + "type": "QUERY", + "status": status, + "errorCode": null, + "createdAt": "2026-10-22T10:00:00Z", + "completedAt": null, + "objectCount": "3", + "rootObjectCount": "2", + "fileSize": null, + "url": url, + "partialDataUrl": null, + "query": "{ products { edges { node { id title } } } }", + }) +} + +fn fast() -> BulkWaitOptions { + BulkWaitOptions::new().poll_interval(Duration::from_millis(1)) +} + +/// Shopify starts the operation, then reports it completed. +fn push_run_and_completed(mock: &MockTransport, url: Option<&str>) { + mock.push_data(json!({ "bulkOperationRunQuery": { "bulkOperation": operation("CREATED", None), "userErrors": [] } })); + mock.push_data(json!({ "bulkOperation": operation("COMPLETED", url) })); +} + +#[derive(Debug, Deserialize, PartialEq)] +struct Product { + id: String, + title: String, +} + +#[tokio::test] +async fn a_bulk_query_streams_its_rows_from_chunks_cut_anywhere() { + let mock = MockTransport::new(); + push_run_and_completed(&mock, Some(RESULTS_URL)); + mock.push_chunks( + 200, + [ + &b"{\"id\":\"gid://shopify/Product/1\",\"title\":\"Caf"[..], + b"\xc3", + b"\xa9\"}\r\n\r\n{\"id\":\"gid://shopify/Product/2\",", + b"\"title\":\"Hat\"}\n{\"id\":\"gid://shopify/Product/3\",\"title\":\"Cap\"}", + ], + ); + let shopify = client(&mock); + + let mut rows = shopify + .bulk_query_stream::("{ products { edges { node { id title } } } }", fast()) + .await + .unwrap(); + let mut titles = Vec::new(); + while let Some(row) = rows.next_row().await { + titles.push(row.unwrap().title); + } + assert_eq!(titles, ["Café", "Hat", "Cap"]); + assert_eq!(rows.line(), 4); + + let sent = mock.requests(); + assert_eq!(sent.len(), 3); + assert_eq!(sent[2].url, RESULTS_URL); + assert_eq!(sent[2].header("X-Shopify-Access-Token"), None); + assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], false); +} + +#[tokio::test] +async fn an_operation_without_results_streams_nothing() { + let mock = MockTransport::new(); + push_run_and_completed(&mock, None); + let shopify = client(&mock); + + let mut rows = shopify + .bulk_query_stream::("{ products { edges { node { id title } } } }", fast()) + .await + .unwrap(); + assert!(rows.next_row().await.is_none()); + assert_eq!(mock.requests().len(), 2, "nothing to download"); +} + +#[tokio::test] +async fn a_refused_download_keeps_the_first_mib_of_its_body_and_hides_the_signature() { + let mock = MockTransport::new(); + let chunk = vec![b'x'; 256 * 1024]; + // 8 MiB of error body: the error keeps 1 MiB, the rest is not read. + let read = Arc::new(Mutex::new(0)); + let counter = read.clone(); + mock.push_chunks( + 403, + std::iter::repeat_n(chunk, 32).inspect(move |_| *counter.lock().unwrap() += 1), + ); + let shopify = client(&mock); + + let error = shopify + .download_bulk_results_stream::(RESULTS_URL) + .await + .unwrap_err(); + assert_eq!(error.status(), Some(403)); + assert_eq!(error.raw_http_body().unwrap().len(), 1024 * 1024); + assert_eq!(*read.lock().unwrap(), 4); + let shown = format!("{error}\n{error:?}"); + assert!(!shown.contains("SECRET"), "{shown}"); +} + +/// A transport written before `send_streaming`: it implements `send` only. +struct Buffered(Vec); + +impl Transport for Buffered { + fn send(&self, _: HttpRequest) -> BoxFuture<'_, Result> { + let response = HttpResponse::new(200, self.0.clone()); + Box::pin(async move { Ok(response) }) + } +} + +#[tokio::test] +async fn a_transport_that_only_sends_streams_through_the_default() { + let body = b"{\"id\":\"1\",\"title\":\"A\"}\n{\"id\":\"2\",\"title\":\"B\"}\n".to_vec(); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(Buffered(body.clone())) + .build() + .unwrap(); + + let mut rows = shopify + .download_bulk_results_stream::(RESULTS_URL) + .await + .unwrap(); + assert_eq!(rows.next_row().await.unwrap().unwrap().title, "A"); + assert_eq!(rows.next_row().await.unwrap().unwrap().title, "B"); + assert!(rows.next_row().await.is_none()); + + let collected: Vec = shopify.download_bulk_results(RESULTS_URL).await.unwrap(); + assert_eq!(collected, parse_jsonl::(&body).unwrap()); +} + +/// A body that gives `chunks`, then fails. +struct FailsAfter(Vec>); + +impl futures_core::Stream for FailsAfter { + type Item = Result, TransportError>; + + fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Some(if self.0.is_empty() { + Err(TransportError::new("connection reset")) + } else { + Ok(self.0.remove(0)) + })) + } +} + +#[tokio::test] +async fn the_vec_methods_stop_at_the_first_error_as_before() { + let mock = MockTransport::new(); + mock.push_streaming(StreamingResponse::new( + 200, + FailsAfter(vec![b"{\"id\":\"1\",\"title\":\"A\"}\n".to_vec()]), + )); + let shopify = client(&mock); + let error = shopify + .download_bulk_results::(RESULTS_URL) + .await + .unwrap_err(); + assert!(matches!(error, Error::Transport { .. }), "{error:?}"); + assert!(!error.to_string().contains("SECRET")); + + let body = b"{\"id\":\"1\",\"title\":\"A\"}\n{\"id\":2}\n{\"id\":\"3\",\"title\":\"C\"}\n"; + mock.push_chunks(200, [&body[..7], &body[7..]]); + let error = shopify + .download_bulk_results::(RESULTS_URL) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + parse_jsonl::(body).unwrap_err().to_string() + ); +} + +#[tokio::test] +async fn a_grouped_bulk_query_asks_for_grouping_and_yields_each_parent_with_its_children() { + let mock = MockTransport::new(); + mock.push_data(json!({ "bulkOperationRunQuery": { "bulkOperation": operation("CREATED", None), "userErrors": [] } })); + mock.push_data(json!({ "bulkOperation": operation("COMPLETED", Some(RESULTS_URL)) })); + mock.push_chunks( + 200, + [ + &b"{\"id\":\"P1\",\"title\":\"Shirt\"}\n{\"sku\":\"S\",\"__par"[..], + b"entId\":\"P1\"}\n{\"sku\":\"M\",\"__parentId\":\"P1\"}\n{\"id\":\"P2\",\"title\":\"Hat\"}\n", + ], + ); + let shopify = client(&mock); + + #[derive(Debug, Deserialize)] + struct Variant { + sku: String, + } + let mut groups = shopify + .bulk_query_grouped::( + "{ products { edges { node { id title variants { edges { node { sku } } } } } } }", + fast(), + ) + .await + .unwrap(); + let (shirt, variants) = groups.next_group().await.unwrap().unwrap(); + assert_eq!(shirt.title, "Shirt"); + assert_eq!( + variants.iter().map(|v| v.sku.as_str()).collect::>(), + ["S", "M"] + ); + let (hat, variants) = groups.next_group().await.unwrap().unwrap(); + assert_eq!(hat.title, "Hat"); + assert!(variants.is_empty()); + assert!(groups.next_group().await.is_none()); + + assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], true); +} + +/// The default transport against a server on this machine. +#[cfg(feature = "rustls")] +mod reqwest_transport { + use super::*; + use shopify_api::transport::{Method, ReqwestTransport}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + + async fn read_request(socket: &mut TcpStream) { + let mut request = Vec::new(); + let mut buffer = [0; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let read = socket.read(&mut buffer).await.unwrap(); + assert!(read > 0); + request.extend_from_slice(&buffer[..read]); + } + } + + async fn write_chunk(socket: &mut TcpStream, data: &[u8]) { + let mut chunk = format!("{:x}\r\n", data.len()).into_bytes(); + chunk.extend_from_slice(data); + chunk.extend_from_slice(b"\r\n"); + socket.write_all(&chunk).await.unwrap(); + socket.flush().await.unwrap(); + } + + async fn next(response: &mut StreamingResponse) -> Option, TransportError>> { + std::future::poll_fn(|context| { + futures_core::Stream::poll_next(response.body.as_mut(), context) + }) + .await + } + + const HEAD: &[u8] = b"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/jsonl\r\nTransfer-Encoding: chunked\r\n\r\n"; + + #[tokio::test] + async fn rows_arrive_before_the_rest_of_the_body_is_sent() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (release, released) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + read_request(&mut socket).await; + socket.write_all(HEAD).await.unwrap(); + write_chunk( + &mut socket, + b"{\"id\":\"1\",\"title\":\"A\"}\n{\"id\":\"2\",", + ) + .await; + // The rest waits until the first row was read. + released.await.unwrap(); + write_chunk(&mut socket, b"\"title\":\"B\"}\n").await; + socket.write_all(b"0\r\n\r\n").await.unwrap(); + }); + let shopify = Shopify::new("test-shop", shopify_api::Auth::access_token("t")).unwrap(); + + let mut rows = shopify + .download_bulk_results_stream::(&format!("http://{address}/r.jsonl?sig=x")) + .await + .unwrap(); + let first = tokio::time::timeout(Duration::from_secs(10), rows.next_row()) + .await + .expect("the first row before the end of the body"); + assert_eq!(first.unwrap().unwrap().title, "A"); + release.send(()).unwrap(); + assert_eq!(rows.next_row().await.unwrap().unwrap().title, "B"); + assert!(rows.next_row().await.is_none()); + server.await.unwrap(); + } + + #[tokio::test] + async fn the_timeout_bounds_each_chunk_not_the_whole_body() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + // A slow body, each chunk within the timeout. + let (mut socket, _) = listener.accept().await.unwrap(); + read_request(&mut socket).await; + socket.write_all(HEAD).await.unwrap(); + for _ in 0..6 { + tokio::time::sleep(Duration::from_millis(100)).await; + write_chunk(&mut socket, b"{}\n").await; + } + socket.write_all(b"0\r\n\r\n").await.unwrap(); + drop(socket); + // Then a body that stalls. + let (mut socket, _) = listener.accept().await.unwrap(); + read_request(&mut socket).await; + socket.write_all(HEAD).await.unwrap(); + write_chunk(&mut socket, b"{}\n").await; + tokio::time::sleep(Duration::from_secs(30)).await; + }); + let transport = ReqwestTransport::new().unwrap(); + let request = |url: String| { + let mut request = HttpRequest::new(Method::Get, url); + request.timeout = Some(Duration::from_millis(400)); + request + }; + + let started = std::time::Instant::now(); + let mut response = transport + .send_streaming(request(format!("http://{address}/slow"))) + .await + .unwrap(); + let mut body = Vec::new(); + while let Some(chunk) = next(&mut response).await { + body.extend_from_slice(&chunk.unwrap()); + } + assert_eq!(body, b"{}\n".repeat(6)); + assert!( + started.elapsed() > Duration::from_millis(400), + "longer than the timeout in all" + ); + + let mut response = transport + .send_streaming(request(format!("http://{address}/stalled"))) + .await + .unwrap(); + assert_eq!(next(&mut response).await.unwrap().unwrap(), b"{}\n"); + let error = next(&mut response).await.unwrap().unwrap_err(); + assert!(error.is_timeout(), "{error}"); + assert!( + next(&mut response).await.is_none(), + "the stream ends after its error" + ); + server.abort(); + } + + #[tokio::test] + async fn the_timeout_bounds_the_wait_for_the_headers() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (_socket, _) = listener.accept().await.unwrap(); + tokio::time::sleep(Duration::from_secs(30)).await; + }); + let mut request = HttpRequest::new(Method::Get, format!("http://{address}/silent")); + request.timeout = Some(Duration::from_millis(200)); + let error = ReqwestTransport::new() + .unwrap() + .send_streaming(request) + .await + .unwrap_err(); + assert!(error.is_timeout(), "{error}"); + server.abort(); + } +} + +/// Streams 200 MB generated as it is read, and prints the peak resident +/// memory of the process, then reads the same file whole for comparison. +/// `cargo test --release -p shopify_api --all-features --test bulk_stream -- --ignored --nocapture` +#[tokio::test] +#[ignore = "a measure, not a check: slow, and the numbers depend on the machine"] +async fn measure_the_memory_of_a_200_mb_export() { + fn resident_kib() -> u64 { + let output = std::process::Command::new("ps") + .args(["-o", "rss=", "-p", &std::process::id().to_string()]) + .output() + .unwrap(); + String::from_utf8(output.stdout) + .unwrap() + .trim() + .parse() + .unwrap() + } + let line = format!( + "{{\"id\":\"gid://shopify/Product/1234567890\",\"title\":\"{}\",\"price\":\"19.99\"}}\n", + "x".repeat(150) + ); + let chunk = line.repeat(256).into_bytes(); + let chunks = 200_000_000 / chunk.len(); + let total = chunk.len() * chunks; + + #[derive(Deserialize)] + #[allow(dead_code)] + struct Row { + id: String, + title: String, + price: String, + } + let mock = MockTransport::new(); + mock.push_chunks(200, std::iter::repeat_n(chunk.clone(), chunks)); + let shopify = client(&mock); + + let before = resident_kib(); + let mut rows = shopify + .download_bulk_results_stream::(RESULTS_URL) + .await + .unwrap(); + let mut count = 0usize; + let mut peak = before; + while let Some(row) = rows.next_row().await { + row.unwrap(); + count += 1; + if count.is_multiple_of(20_000) { + peak = peak.max(resident_kib()); + } + } + assert_eq!(count, 256 * chunks); + println!( + "streamed {} MB, {count} rows: resident {} KiB before, {} KiB at the peak (+{} KiB)", + total / 1_000_000, + before, + peak, + peak - before + ); + + let body = chunk.repeat(chunks); + let rows: Vec = parse_jsonl(&body).unwrap(); + println!( + "read whole: resident {} KiB with the file and its {} rows in memory", + resident_kib(), + rows.len() + ); +} From 3232678a0bda373b775ec00648af3879695dd4d7 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:32:50 +0200 Subject: [PATCH 037/135] feat(bulk): upload bulk variables from an iterator `run_bulk_mutation_iter` and `stage_bulk_variables_iter` take the items from an iterator and serialize each one straight into the multipart body, which holds the JSONL once instead of twice. The storage server needs the length of the body up front and Shopify caps the file at 100 MB, so the body stays in memory rather than streamed. The slice methods go through the iterator ones. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk.rs | 79 +++++++++++++---- crates/shopify_api/tests/bulk_stream.rs | 113 +++++++++++++++++++++++- 2 files changed, 175 insertions(+), 17 deletions(-) diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index ba9c9b2..db2cb80 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -443,7 +443,37 @@ impl Shopify { mutation: &str, variables: &[T], ) -> Result { - let path = self.stage_bulk_variables(variables).await?; + self.run_bulk_mutation_iter(mutation, variables).await + } + + /// [`Shopify::run_bulk_mutation`] over the items of an iterator, each + /// serialized as it is taken: the items need not all be in memory, only + /// the JSONL file, which Shopify caps at 100 MB. + /// + /// ```no_run + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let rows = (1..=50_000).map(|id| { + /// serde_json::json!({ "product": { "id": format!("gid://shopify/Product/{id}"), "status": "ARCHIVED" } }) + /// }); + /// let operation = shopify + /// .run_bulk_mutation_iter( + /// "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + /// rows, + /// ) + /// .await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn run_bulk_mutation_iter( + &self, + mutation: &str, + variables: I, + ) -> Result + where + I: IntoIterator, + I::Item: Serialize, + { + let path = self.stage_bulk_variables_iter(variables).await?; self.run_bulk_mutation_staged(mutation, &path, None).await } @@ -476,13 +506,19 @@ impl Shopify { /// Uploads `variables` as the JSONL file of a bulk mutation, one item per /// line, and returns its staged upload path. pub async fn stage_bulk_variables(&self, variables: &[T]) -> Result { - let mut jsonl = Vec::new(); - for item in variables { - serde_json::to_writer(&mut jsonl, item) - .map_err(|error| Error::variables(None, &error))?; - jsonl.push(b'\n'); - } + self.stage_bulk_variables_iter(variables).await + } + /// [`Shopify::stage_bulk_variables`] over the items of an iterator, + /// written straight into the body of the upload as they are taken. + /// + /// The upload target is reserved first: an item that does not + /// serialize fails after it, and the target goes unused. + pub async fn stage_bulk_variables_iter(&self, variables: I) -> Result + where + I: IntoIterator, + I::Item: Serialize, + { let data = self .execute(staged_uploads::operation(staged_uploads::Variables { input: vec![staged_uploads::StagedUploadInput { @@ -526,8 +562,17 @@ impl Shopify { Error::Bulk("the staged upload target has no `key` parameter".to_string()) })?; + // The storage server wants the length of the body up front: the + // file is built in memory, once, in the body itself. let (content_type, body) = - multipart(¶meters, "bulk_op_vars.jsonl", "text/jsonl", &jsonl); + multipart(¶meters, "bulk_op_vars.jsonl", "text/jsonl", |body| { + for item in variables { + serde_json::to_writer(&mut *body, &item) + .map_err(|error| Error::variables(None, &error))?; + body.push(b'\n'); + } + Ok(()) + })?; let request = HttpRequest::new(Method::Post, &url) .with_header("Content-Type", content_type) .with_body(body) @@ -838,14 +883,14 @@ pub fn parse_jsonl(body: &[u8]) -> Result> { .collect() } -/// A `multipart/form-data` body: the fields, then the file. Returns its -/// `Content-Type` and its bytes. +/// A `multipart/form-data` body: the fields, then the file `write_file` +/// writes. Returns its `Content-Type` and its bytes. fn multipart( fields: &[(String, String)], filename: &str, mime: &str, - file: &[u8], -) -> (String, Vec) { + write_file: impl FnOnce(&mut Vec) -> Result<()>, +) -> Result<(String, Vec)> { let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|elapsed| elapsed.as_nanos()) @@ -869,9 +914,9 @@ fn multipart( ) .as_bytes(), ); - body.extend_from_slice(file); + write_file(&mut body)?; body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); - (format!("multipart/form-data; boundary={boundary}"), body) + Ok((format!("multipart/form-data; boundary={boundary}"), body)) } #[cfg(test)] @@ -929,7 +974,11 @@ mod tests { #[test] fn builds_a_multipart_body() { let fields = vec![("key".to_string(), "tmp/1/bulk".to_string())]; - let (content_type, body) = multipart(&fields, "vars.jsonl", "text/jsonl", b"{}\n"); + let (content_type, body) = multipart(&fields, "vars.jsonl", "text/jsonl", |body| { + body.extend_from_slice(b"{}\n"); + Ok(()) + }) + .unwrap(); let boundary = content_type .strip_prefix("multipart/form-data; boundary=") .unwrap(); diff --git a/crates/shopify_api/tests/bulk_stream.rs b/crates/shopify_api/tests/bulk_stream.rs index 527b6c1..94952d3 100644 --- a/crates/shopify_api/tests/bulk_stream.rs +++ b/crates/shopify_api/tests/bulk_stream.rs @@ -1,4 +1,4 @@ -//! Bulk results read as they download. +//! Bulk results read as they download, and bulk variables uploaded from an iterator. #![cfg(feature = "testing")] use std::pin::Pin; @@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; use std::time::Duration; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use shopify_api::bulk::{BulkWaitOptions, parse_jsonl}; use shopify_api::testing::{MockTransport, client}; @@ -17,6 +17,7 @@ use shopify_api::{Error, Shopify}; const RESULTS_URL: &str = "https://storage.googleapis.com/bulk-operation-outputs/1.jsonl?X-Goog-Signature=SECRET"; +const UPLOAD_URL: &str = "https://shopify-staged-uploads.storage.googleapis.com/"; fn operation(status: &str, url: Option<&str>) -> Value { json!({ @@ -234,6 +235,114 @@ async fn a_grouped_bulk_query_asks_for_grouping_and_yields_each_parent_with_its_ assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], true); } +/// Shopify reserves an upload target; the storage server takes the file. +fn upload_mock() -> (MockTransport, Arc>>) { + let mock = MockTransport::new(); + let uploads = Arc::new(Mutex::new(Vec::new())); + let seen = uploads.clone(); + mock.respond_with(move |request| { + if request.url == UPLOAD_URL { + seen.lock().unwrap().push(request.clone()); + return Ok(HttpResponse::new(201, "")); + } + let name = request.json().unwrap()["operationName"].as_str().unwrap().to_string(); + let data = match name.as_str() { + "StagedUploadsCreate" => json!({ "stagedUploadsCreate": { + "stagedTargets": [{ + "url": UPLOAD_URL, + "resourceUrl": null, + "parameters": [{ "name": "key", "value": "tmp/1/bulk/vars.jsonl" }], + }], + "userErrors": [], + } }), + "BulkOperationRunMutation" => { + let mut started = operation("CREATED", None); + started["type"] = json!("MUTATION"); + json!({ "bulkOperationRunMutation": { "bulkOperation": started, "userErrors": [] } }) + } + other => panic!("unexpected operation {other}"), + }; + Ok(HttpResponse::json(200, &json!({ "data": data }))) + }); + (mock, uploads) +} + +/// The JSONL part of a multipart body. +fn uploaded_file(request: &HttpRequest) -> String { + let body = String::from_utf8(request.body.clone()).unwrap(); + let start = body.find("Content-Type: text/jsonl\r\n\r\n").unwrap() + 28; + let end = body.rfind("\r\n--").unwrap(); + body[start..end].to_string() +} + +#[tokio::test] +async fn bulk_variables_upload_from_an_iterator_as_from_a_slice() { + let (mock, uploads) = upload_mock(); + let shopify = client(&mock); + let mutation = "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }"; + + #[derive(Serialize)] + struct Row { + product: Value, + } + let taken = Arc::new(Mutex::new(0)); + let counter = taken.clone(); + let rows = (1..=1000).map(move |id| { + *counter.lock().unwrap() += 1; + Row { + product: json!({ "id": format!("gid://shopify/Product/{id}"), "title": "é\n\"" }), + } + }); + let started = shopify + .run_bulk_mutation_iter(mutation, rows) + .await + .unwrap(); + assert_eq!(started.kind, shopify_api::bulk::BulkOperationType::Mutation); + assert_eq!(*taken.lock().unwrap(), 1000); + + let slice: Vec = (1..=1000) + .map(|id| Row { + product: json!({ "id": format!("gid://shopify/Product/{id}"), "title": "é\n\"" }), + }) + .collect(); + shopify.run_bulk_mutation(mutation, &slice).await.unwrap(); + + let uploads = uploads.lock().unwrap(); + assert_eq!(uploads.len(), 2); + let from_iter = uploaded_file(&uploads[0]); + assert_eq!(from_iter, uploaded_file(&uploads[1])); + let lines: Vec = parse_jsonl(from_iter.as_bytes()).unwrap(); + assert_eq!(lines.len(), 1000); + assert_eq!(lines[999]["product"]["id"], "gid://shopify/Product/1000"); + assert_eq!(from_iter.matches('\n').count(), 1000, "one line per item"); + + let graphql = mock.graphql_requests(); + assert_eq!( + graphql[1].variables["stagedUploadPath"], + "tmp/1/bulk/vars.jsonl" + ); +} + +#[tokio::test] +async fn an_item_that_does_not_serialize_stops_the_upload() { + struct Leaky; + impl Serialize for Leaky { + fn serialize(&self, _: S) -> Result { + Err(serde::ser::Error::custom("cannot serialize shpat_SECRET")) + } + } + let (mock, uploads) = upload_mock(); + let shopify = client(&mock); + + let error = shopify + .stage_bulk_variables_iter([Leaky]) + .await + .unwrap_err(); + assert!(matches!(error, Error::Variables { .. }), "{error:?}"); + assert!(!format!("{error}{error:?}").contains("SECRET")); + assert!(uploads.lock().unwrap().is_empty(), "nothing uploaded"); +} + /// The default transport against a server on this machine. #[cfg(feature = "rustls")] mod reqwest_transport { From e61de0fa9dacf2d3674a80a45a993ea76cfb24a1 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:33:02 +0200 Subject: [PATCH 038/135] docs: streamed bulk results and iterator uploads README section on when to stream and when to collect, CHANGELOG and MIGRATION entries, and the bulk export example reads as it downloads. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++ MIGRATION.md | 2 +- README.md | 44 ++++++++++++++++++++++ crates/shopify_api/examples/bulk_export.rs | 12 ++++-- 4 files changed, 57 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8eb301b..24def77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: tokens are renewed once for all the clones of a client, before they expire and when Shopify refuses one with a `401`. `Auth::expiring_token` with a `TokenStore`. - Add: `Shopify::paginate`, `Page`. - Add: bulk operations: `bulk_query_rows`, `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, typed `BulkOperation` and statuses, adaptive polling. +- Add: bulk results read as they download, in memory that follows the longest line rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. +- Add: `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group. +- Add: `run_bulk_mutation_iter` and `stage_bulk_variables_iter` take the variables from an iterator; the JSONL is written straight into the body of the upload, in memory once. +- Add: `Transport::send_streaming`, with a default that goes through `send`, and `StreamingResponse`, `BodyStream`. `ReqwestTransport` streams: the timeout of the request bounds the wait for the headers and for each chunk, not the whole body. `MockTransport::push_chunks` and `push_streaming` script a body in chunks. - Add: `webhooks`: `Webhook::verify` (headers, signature with secret rotation, payload), subscriptions with `sync_webhook_subscriptions`, which updates in place and creates before it deletes. - Add: `oauth`: `ShopifyApp` with install links, callback and admin launch verification, code exchange, session tokens and token exchange, app proxies. - Add: `Transport` trait, `ReqwestTransport` (redirections always off, `from_builder` for your own settings), and `testing::MockTransport`, with `testing::client`, which retries without waiting, even for a scripted `Retry-After`. diff --git a/MIGRATION.md b/MIGRATION.md index 86e76f1..1a722e1 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -98,7 +98,7 @@ reference, or `()` for none. | `get_bulk_operation(id)` | `bulk_operation(id)` | | `list_bulk_operations(BulkOperationsFilter { .. })` | `bulk_operations(BulkOperationsFilter::new().first(10))`, a `Page` | | `wait_for_bulk(id, BulkWaitOptions { .. })` | `wait_for_bulk_operation(id, BulkWaitOptions::new().timeout(…))` | -| `Shopify::download_bulk_jsonl(url)` | `shopify.download_bulk_results(url)`, or `bulk_query_rows` for the whole cycle | +| `Shopify::download_bulk_jsonl(url)` | `shopify.download_bulk_results(url)`, or `bulk_query_rows` for the whole cycle; `download_bulk_results_stream(url)` and `bulk_query_stream` read the rows as they download | | `run_bulk_queries`, `run_bulk_mutations`, `BulkConcurrencyOptions` | Gone: call the single versions in a loop | | `ShopifyBulkOperation`, `ShopifyBulkStatus` | `bulk::BulkOperation`, `bulk::BulkOperationStatus` | diff --git a/README.md b/README.md index 420419b..6dd3831 100644 --- a/README.md +++ b/README.md @@ -234,6 +234,50 @@ let operation = shopify.run_bulk_mutation( `run_bulk_query`, `wait_for_bulk_operation`, `bulk_operations`, `cancel_bulk_operation` and `download_bulk_results` give each step on its own. +### Large exports: stream the rows + +`bulk_query_rows` holds every row in a `Vec`. For an export of gigabytes, +`bulk_query_stream` reads the file line by line as it downloads: memory +follows the longest line, not the file. + +```rust,ignore +let mut products = shopify + .bulk_query_stream::("{ products { edges { node { id title } } } }", BulkWaitOptions::default()) + .await?; +while let Some(product) = products.next_row().await { + let product = product?; // a line that does not read: skip it, or stop + save(product).await?; +} +``` + +`BulkRows` is also a `futures_core::Stream`. A line that does not read as +the type is an error and the stream goes on; a download that fails, or a +line longer than `max_line_length` (64 MiB by default), ends it. + +Nested connections write their objects on lines of their own, after their +parent. `bulk_query_grouped::` runs the query with +`groupObjects` and yields each product with its variants, one product in +memory at a time: + +```rust,ignore +let mut products = shopify + .bulk_query_grouped::( + "{ products { edges { node { id title variants { edges { node { id sku } } } } } } }", + BulkWaitOptions::default(), + ) + .await?; +while let Some(group) = products.next_group().await { + let (product, variants) = group?; +} +``` + +`download_bulk_results_stream` and `download_bulk_results_grouped` read the +results of an operation you ran yourself. For a bulk mutation over more +items than you want in memory, `run_bulk_mutation_iter` takes an iterator: +each item is serialized as it is taken. + +Use the `Vec` methods when the results fit in memory, the streams otherwise. + ## Webhooks Feature `webhooks`: diff --git a/crates/shopify_api/examples/bulk_export.rs b/crates/shopify_api/examples/bulk_export.rs index 13fe93b..29b5c87 100644 --- a/crates/shopify_api/examples/bulk_export.rs +++ b/crates/shopify_api/examples/bulk_export.rs @@ -40,10 +40,13 @@ async fn main() -> shopify_api::Result<()> { // The client credentials grant: a store of the organization that owns the app. let shopify = Shopify::new(shop, Auth::client_credentials(client_id, client_secret))?; - let rows: Vec = shopify - .bulk_query_rows(variants::QUERY, BulkWaitOptions::default()) + // Read as the file downloads: an export of any size, in little memory. + let mut rows = shopify + .bulk_query_stream::(variants::QUERY, BulkWaitOptions::default()) .await?; - for variant in &rows { + let mut count = 0; + while let Some(variant) = rows.next_row().await { + let variant = variant?; println!( "{} {:<12} {:>8} {:>5?} {}", variant.id, @@ -52,7 +55,8 @@ async fn main() -> shopify_api::Result<()> { variant.inventory_quantity, variant.product.title ); + count += 1; } - println!("{} variants", rows.len()); + println!("{count} variants"); Ok(()) } From bf95f52925cf68e80da363b46b1411aab6c29a31 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:48:48 +0200 Subject: [PATCH 039/135] fix(bulk): count a last blank line without a newline BulkRows::line() and BulkGroups::line() count blank lines, as documented, but a whitespace-only last line with no newline after it was not counted. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk/rows.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index 7c2fecc..ad187ab 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -94,15 +94,17 @@ impl Lines { return Poll::Ready(Some(Err(self.too_long(self.line + 1)))); } let Some(body) = self.body.as_mut() else { - // The last line, without a newline after it. let range = self.start..self.buffer.len(); self.start = range.end; self.scanned = 0; self.done = true; - if range.is_empty() || is_blank(&self.buffer[range.clone()]) { + if range.is_empty() { break; } self.line += 1; + if is_blank(&self.buffer[range.clone()]) { + break; + } return Poll::Ready(Some(Ok((self.line, range)))); }; match body.as_mut().poll_next(context) { @@ -530,6 +532,21 @@ mod tests { assert_eq!(shown(&all(rows_of(one_byte_each)).await), expected); } + #[tokio::test] + async fn a_last_blank_line_without_a_newline_is_counted() { + for (body, lines) in [ + (&b"{}\n \r"[..], 2), + (b"{}\n\n\t", 3), + (b"{}\n", 1), + (b"{}", 1), + ] { + let mut rows = rows_of::(vec![body.to_vec()]); + assert!(rows.next_row().await.unwrap().is_ok()); + assert!(rows.next_row().await.is_none()); + assert_eq!(rows.line(), lines, "{body:?}"); + } + } + #[tokio::test] async fn a_line_longer_than_the_limit_ends_the_stream() { // Too long whether its newline comes with it or not. From 30a93203c1426beaccb0cdaad82b46b83e295179 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:49:19 +0200 Subject: [PATCH 040/135] perf(bulk): release the buffer of a long line once it is read The line buffer kept the capacity of the longest line until the stream was dropped. It now shrinks when a chunk arrives and it is more than four times what it must hold (and over 64 KiB), and is freed at the end. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk/rows.rs | 45 ++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index ad187ab..53d206b 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -17,6 +17,10 @@ use crate::{Error, Result}; /// The longest line [`BulkRows`] and [`BulkGroups`] read by default: 64 MiB. pub const DEFAULT_MAX_LINE_LENGTH: usize = 64 * 1024 * 1024; +/// What the buffer may keep, whatever it holds: a buffer more than four +/// times what it holds, and than this, shrinks after a long line. +const KEPT_CAPACITY: usize = 64 * 1024; + /// A line: its number, from 1, and where it is in the buffer. type Line = (usize, Range); @@ -115,13 +119,17 @@ impl Lines { return Poll::Ready(Some(Err(Error::transport(&self.url, source)))); } Poll::Ready(Some(Ok(chunk))) => { - // What was taken goes: the buffer holds the line being read. self.buffer.drain(..self.start); self.start = 0; + let needed = (self.buffer.len() + chunk.len()).max(KEPT_CAPACITY); + if self.buffer.capacity() > 4 * needed { + self.buffer.shrink_to(needed); + } self.buffer.extend_from_slice(&chunk); } } } + self.buffer = Vec::new(); Poll::Ready(None) } @@ -658,6 +666,41 @@ mod tests { ); } + #[tokio::test] + async fn the_buffer_of_a_huge_line_is_released_once_it_is_read() { + let huge = format!("{{\"a\":\"{}\"}}\n", "x".repeat(16 * 1024 * 1024)); + let tiny = b"{\"b\":1}\n".to_vec(); + let parts = vec![huge.into_bytes(), tiny.clone(), tiny.clone(), tiny.clone()]; + let mut rows = rows_of::(parts); + rows.next_row().await.unwrap().unwrap(); + assert!(rows.lines.capacity() > 16 * 1024 * 1024); + rows.next_row().await.unwrap().unwrap(); + assert!( + rows.lines.capacity() <= 1024 * 1024, + "{} bytes held after a tiny line", + rows.lines.capacity() + ); + while let Some(row) = rows.next_row().await { + row.unwrap(); + } + assert_eq!(rows.lines.capacity(), 0); + } + + /// A buffer a few times larger than its chunks is kept: no + /// reallocation on each chunk. + #[tokio::test] + async fn the_buffer_is_kept_while_lines_stay_alike() { + let line = format!("{{\"a\":\"{}\"}}\n", "x".repeat(300 * 1024)); + let parts: Vec> = std::iter::repeat_n(line.into_bytes(), 8).collect(); + let mut rows = rows_of::(parts); + rows.next_row().await.unwrap().unwrap(); + let first = rows.lines.buffer.as_ptr(); + for _ in 0..7 { + rows.next_row().await.unwrap().unwrap(); + assert_eq!(rows.lines.buffer.as_ptr(), first); + } + } + fn groups_of(body: &str) -> BulkGroups { BulkGroups::new( Some(chunks( From 6d669f8181b1caa1cda0a82fcc182eb4285fc14b Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:49:43 +0200 Subject: [PATCH 041/135] perf(transport): copy only the kept bytes of an error body into_response copied each chunk whole before truncating to the limit, so a 32 MiB chunk allocated 32 MiB to keep 1 MiB. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/transport.rs | 30 +++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/shopify_api/src/transport.rs b/crates/shopify_api/src/transport.rs index 61fa927..d4a98f4 100644 --- a/crates/shopify_api/src/transport.rs +++ b/crates/shopify_api/src/transport.rs @@ -247,11 +247,13 @@ impl StreamingResponse { let mut body = Vec::new(); while body.len() < limit { match next_chunk(&mut self.body).await { - Some(Ok(chunk)) => body.extend_from_slice(&chunk), + Some(Ok(chunk)) => { + let kept = chunk.len().min(limit - body.len()); + body.extend_from_slice(&chunk[..kept]); + } Some(Err(_)) | None => break, } } - body.truncate(limit); HttpResponse { status: self.status, headers: self.headers, @@ -650,4 +652,28 @@ mod tests { assert!(!response.is_success()); assert_eq!(response.text(), "{\"errors\":\"Throttled\"}"); } + + #[tokio::test] + async fn an_error_body_copies_only_what_it_keeps() { + let huge = vec![b'x'; 32 * 1024 * 1024]; + let response = StreamingResponse::new(500, chunks([Ok(huge)])) + .into_response(1024) + .await; + assert_eq!(response.body.len(), 1024); + assert!( + response.body.capacity() <= 1024, + "{} bytes allocated", + response.body.capacity() + ); + + let parts = [ + Ok(b"abc".to_vec()), + Ok(b"defgh".to_vec()), + Ok(b"ij".to_vec()), + ]; + let response = StreamingResponse::new(500, chunks(parts)) + .into_response(6) + .await; + assert_eq!(response.body, b"abcdef"); + } } From fb8439d945bfaa0e141ca60bcb28f528910748b5 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:50:39 +0200 Subject: [PATCH 042/135] fix(bulk): name a missing parent id as the cause of a misplaced child BulkGroups places a child by its parent's `id`. A parent without one (or with an aliased one) ended grouping with an error asking for groupObjects, even when the query ran with it. The error now names the missing `id`, and bulk_query_grouped no longer suggests groupObjects, which it sets. BulkGroups, bulk_query_grouped and download_bulk_results_grouped document the requirement, which Shopify enforces on bulkOperationRunQuery. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk.rs | 13 ++-- crates/shopify_api/src/bulk/rows.rs | 86 +++++++++++++++++++++++-- crates/shopify_api/tests/bulk_stream.rs | 32 +++++++++ 3 files changed, 122 insertions(+), 9 deletions(-) diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index db2cb80..c0cc184 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -744,8 +744,10 @@ impl Shopify { /// not complete. /// /// Grouping makes Shopify slower, and more likely to time out: use it - /// when you need the children with their parent. See [`BulkGroups`] - /// for the order it relies on and connections two levels deep. + /// when you need the children with their parent. Every object that has + /// a nested connection must select `id`, without an alias: Shopify + /// refuses the query otherwise. See [`BulkGroups`] for the order it + /// relies on and connections two levels deep. /// /// ```no_run /// use serde::Deserialize; @@ -783,8 +785,8 @@ impl Shopify { ) -> Result> { let operation = self.run_bulk_query_grouped(query, true).await?; match self.completed_url(&operation.id, options).await? { - Some(url) => self.download_bulk_results_grouped(&url).await, - None => Ok(BulkGroups::new(None, "")), + Some(url) => Ok(self.download_bulk_results_grouped(&url).await?.grouped()), + None => Ok(BulkGroups::new(None, "").grouped()), } } @@ -832,7 +834,8 @@ impl Shopify { /// [`Shopify::download_bulk_results_stream`], one top-level object and /// its children at a time. The operation must have run with - /// `groupObjects`: see [`BulkGroups`]. + /// `groupObjects`, and every object of it that has a nested connection + /// must have an `id`, not aliased: see [`BulkGroups`]. pub async fn download_bulk_results_grouped( &self, url: &str, diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index 53d206b..fda8d5c 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -263,6 +263,8 @@ struct Group { /// The IDs of the objects of the group, the children of the next lines /// belong to. ids: HashSet, + /// An object of the group has no `id`: a child of it cannot be placed. + missing_id: bool, } /// The results of a grouped bulk query, each top-level object with the @@ -294,15 +296,26 @@ struct Group { /// current top-level object nor one of its children is an [`Error::Bulk`] /// rather than a child put in the wrong group. /// +/// # The `id` it needs +/// +/// A child is placed by matching its `__parentId` with the `id` of an +/// object before it: every object that has a nested connection must select +/// `id`, without an alias. Shopify refuses a bulk query that does not, so +/// this only matters for a file from elsewhere; a child of an object +/// without `id` is an [`Error::Bulk`] that says so. +/// /// # Errors /// /// Any error ends the stream, a line that does not read as `P` or `C` /// included: the lines after it could not be placed for sure. The errors -/// are those of [`BulkRows`], and the child out of place above. +/// are those of [`BulkRows`], and the child out of place or without a +/// matching `id` above. #[must_use = "a stream does nothing until it is read"] pub struct BulkGroups { lines: Lines, group: Option>, + /// The operation is known to have run with `groupObjects`. + grouped: bool, } // The group is never pinned: it is only reached through `&mut`. @@ -326,9 +339,26 @@ impl BulkGroups { Self { lines: Lines::new(body, url), group: None, + grouped: false, } } + pub(crate) fn grouped(mut self) -> Self { + self.grouped = true; + self + } + + fn misplaced(&self, number: usize) -> Error { + let message = if self.group.as_ref().is_some_and(|group| group.missing_id) { + "has a `__parentId` that no `id` before it matches, and an object before it has no `id`: select `id`, without an alias, on every object that has nested connections" + } else if self.grouped { + "is a child of neither the top-level object before it nor one of its children, though the query ran with `groupObjects`" + } else { + "is a child of neither the top-level object before it nor one of its children: run the query with `groupObjects`" + }; + Error::Bulk(format!("line {number} of the results {message}")) + } + /// [`BulkRows::max_line_length`]. pub fn max_line_length(mut self, bytes: usize) -> Self { self.lines.max = bytes; @@ -383,6 +413,7 @@ impl Stream for BulkGroups { let next = Group { parent, children: Vec::new(), + missing_id: keys.id.is_none(), ids: keys.id.into_iter().collect(), }; if let Some(done) = this.group.replace(next) { @@ -395,9 +426,7 @@ impl Stream for BulkGroups { .as_ref() .is_some_and(|group| group.ids.contains(&parent_id)) { - let error = Error::Bulk(format!( - "line {number} of the results is a child of neither the top-level object before it nor one of its children: run the query with `groupObjects`" - )); + let error = this.misplaced(number); return this.fail(error); } let child = match crate::decode::from_jsonl_line::(line, number) { @@ -405,6 +434,7 @@ impl Stream for BulkGroups { Err(error) => return this.fail(error), }; if let Some(group) = this.group.as_mut() { + group.missing_id |= keys.id.is_none(); group.ids.extend(keys.id); group.children.push(child); } @@ -804,6 +834,54 @@ mod tests { } } + #[tokio::test] + async fn a_parent_without_id_is_named_as_the_cause() { + const MISSING: &str = "has a `__parentId` that no `id` before it matches, and an object before it has no `id`: select `id`, without an alias, on every object that has nested connections"; + for (body, line) in [ + // A top-level object without `id`. + ( + "{\"title\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P1\"}\n", + 2, + ), + // A first-level child without `id`, parent of the second level. + ( + "{\"id\":\"P1\"}\n{\"sku\":\"V1\",\"__parentId\":\"P1\"}\n{\"id\":\"L1\",\"__parentId\":\"V1\"}\n", + 3, + ), + // An aliased `id`. + ( + "{\"productId\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P1\"}\n", + 2, + ), + ] { + for groups in [groups_of(body), groups_of(body).grouped()] { + let groups = all_groups(groups).await; + let error = groups.last().unwrap().as_ref().unwrap_err(); + assert_eq!( + error.to_string(), + format!("bulk operation: line {line} of the results {MISSING}"), + "{body}" + ); + } + } + + // A child without `id` has no child of its own to place: fine. + let body = "{\"id\":\"P1\"}\n{\"sku\":\"V1\",\"__parentId\":\"P1\"}\n"; + let groups = all_groups(groups_of(body)).await; + assert_eq!(groups[0].as_ref().unwrap().1.len(), 1); + } + + #[tokio::test] + async fn a_child_out_of_place_does_not_ask_for_group_objects_when_it_is_on() { + let body = "{\"id\":\"P1\"}\n{\"id\":\"P2\"}\n{\"id\":\"V1\",\"__parentId\":\"P1\"}\n"; + let groups = all_groups(groups_of(body).grouped()).await; + let error = groups.last().unwrap().as_ref().unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 3 of the results is a child of neither the top-level object before it nor one of its children, though the query ran with `groupObjects`" + ); + } + #[tokio::test] async fn groups_read_typed_parents_and_children_and_hide_bad_values() { #[derive(Debug, Deserialize)] diff --git a/crates/shopify_api/tests/bulk_stream.rs b/crates/shopify_api/tests/bulk_stream.rs index 94952d3..aa1c565 100644 --- a/crates/shopify_api/tests/bulk_stream.rs +++ b/crates/shopify_api/tests/bulk_stream.rs @@ -235,6 +235,38 @@ async fn a_grouped_bulk_query_asks_for_grouping_and_yields_each_parent_with_its_ assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], true); } +#[tokio::test] +async fn a_child_out_of_place_only_asks_for_grouping_when_it_may_be_off() { + let body = &b"{\"id\":\"P1\",\"title\":\"A\"}\n{\"id\":\"P2\",\"title\":\"B\"}\n{\"__parentId\":\"P1\"}\n"[..]; + let mock = MockTransport::new(); + push_run_and_completed(&mock, Some(RESULTS_URL)); + mock.push_chunks(200, [body]); + mock.push_chunks(200, [body]); + let shopify = client(&mock); + + let mut groups = shopify + .bulk_query_grouped::("{ products { edges { node { id } } } }", fast()) + .await + .unwrap(); + groups.next_group().await.unwrap().unwrap(); + let error = groups.next_group().await.unwrap().unwrap_err().to_string(); + assert!( + error.ends_with("though the query ran with `groupObjects`"), + "{error}" + ); + + let mut groups = shopify + .download_bulk_results_grouped::(RESULTS_URL) + .await + .unwrap(); + groups.next_group().await.unwrap().unwrap(); + let error = groups.next_group().await.unwrap().unwrap_err().to_string(); + assert!( + error.ends_with("run the query with `groupObjects`"), + "{error}" + ); +} + /// Shopify reserves an upload target; the storage server takes the file. fn upload_mock() -> (MockTransport, Arc>>) { let mock = MockTransport::new(); From 61a83f6bfebdb17fa6ac1991b7193c53098213d2 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:51:08 +0200 Subject: [PATCH 043/135] docs(bulk): state what streamed results hold, and when uploads reserve BulkGroups holds the group being read, children included, on top of the line being read. run_bulk_mutation, run_bulk_mutation_iter and stage_bulk_variables reserve the upload target before serializing, as stage_bulk_variables_iter already said. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk.rs | 16 ++++++++++++++-- crates/shopify_api/src/bulk/rows.rs | 5 +++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index c0cc184..1a7dcd9 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -23,8 +23,11 @@ //! [`Shopify::bulk_query_rows`] holds every row in memory. For an export //! of gigabytes, [`Shopify::bulk_query_stream`] reads the rows as the file //! downloads ([`BulkRows`]), and [`Shopify::bulk_query_grouped`] each -//! top-level object with its nested objects ([`BulkGroups`]): the memory -//! they take follows the longest line, not the file. +//! top-level object with its nested objects ([`BulkGroups`]). Neither holds +//! the file: [`BulkRows`] holds the line being read and the rest of the +//! chunk it ends in; [`BulkGroups`] holds that, and the group being read, +//! its top-level object with every child read so far and their IDs. A +//! product with 2,000 variants is held with its 2,000 variants. //! //! The query of a bulk operation is a plain string. To have it checked when //! the crate compiles, declare it with [`graphql!`](crate::graphql!) and pass @@ -423,6 +426,9 @@ impl Shopify { /// item, which holds the variables of that run. The items are uploaded /// as a JSONL file first. /// + /// The upload target is reserved first: an item that does not + /// serialize fails after it, and the target goes unused. + /// /// ```no_run /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { /// let rows = vec![ @@ -450,6 +456,9 @@ impl Shopify { /// serialized as it is taken: the items need not all be in memory, only /// the JSONL file, which Shopify caps at 100 MB. /// + /// The upload target is reserved first: an item that does not + /// serialize fails after it, and the target goes unused. + /// /// ```no_run /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { /// let rows = (1..=50_000).map(|id| { @@ -505,6 +514,9 @@ impl Shopify { /// Uploads `variables` as the JSONL file of a bulk mutation, one item per /// line, and returns its staged upload path. + /// + /// The upload target is reserved first: an item that does not + /// serialize fails after it, and the target goes unused. pub async fn stage_bulk_variables(&self, variables: &[T]) -> Result { self.stage_bulk_variables_iter(variables).await } diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index fda8d5c..f441194 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -162,7 +162,7 @@ impl fmt::Debug for Lines { /// return it. /// /// It holds one line at a time, and the rest of the chunk that line ends -/// in: the memory it takes follows the longest line, not the file. Read it +/// in: the memory it takes follows the line being read, not the file. Read it /// with [`BulkRows::next_row`], or as a [`Stream`]. /// /// Lines are split on `\n`; a `\r` before it, a last line without one and @@ -277,7 +277,8 @@ struct Group { /// with one is a child, read as `C`. Each item is a top-level object and /// its children, in the order of the file: the item is complete when the /// next top-level object, or the end of the file, arrives. One group is -/// held at a time. +/// held at a time, with every child read so far: its memory follows the +/// largest group, as well as the line being read. /// /// # Nested connections two levels deep /// From bde32f98c978e9c78ff7a70f8ca4e057d370907b Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:51:52 +0200 Subject: [PATCH 044/135] chore: drop comments that restate the code Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk/rows.rs | 2 -- crates/shopify_api/src/testing.rs | 2 -- crates/shopify_api/src/transport.rs | 1 - crates/shopify_api/tests/bulk_stream.rs | 1 - 4 files changed, 6 deletions(-) diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index f441194..b3f0e03 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -24,7 +24,6 @@ const KEPT_CAPACITY: usize = 64 * 1024; /// A line: its number, from 1, and where it is in the buffer. type Line = (usize, Range); -/// A top-level object and its children. type Grouped = Result<(P, Vec)>; /// The lines of a JSONL body, split as its chunks arrive. It holds the @@ -668,7 +667,6 @@ mod tests { assert_eq!(results[2].as_ref().unwrap().id, 3); } - /// The buffer follows the longest line, whatever the size of the file. #[tokio::test] async fn memory_follows_the_longest_line_not_the_file() { let line = format!( diff --git a/crates/shopify_api/src/testing.rs b/crates/shopify_api/src/testing.rs index c0efb44..d699192 100644 --- a/crates/shopify_api/src/testing.rs +++ b/crates/shopify_api/src/testing.rs @@ -43,7 +43,6 @@ pub struct MockTransport { state: Arc>, } -/// A queued answer. enum Answer { Whole(Result), Streaming(StreamingResponse), @@ -191,7 +190,6 @@ impl MockTransport { } impl MockTransport { - /// Records `request` and takes its answer. fn answer(&self, request: &HttpRequest) -> Answer { let mut state = self.state(); state.requests.push(request.clone()); diff --git a/crates/shopify_api/src/transport.rs b/crates/shopify_api/src/transport.rs index d4a98f4..4d1d276 100644 --- a/crates/shopify_api/src/transport.rs +++ b/crates/shopify_api/src/transport.rs @@ -274,7 +274,6 @@ impl From for StreamingResponse { } } -/// The next chunk of `body`. pub(crate) async fn next_chunk(body: &mut BodyStream) -> Option, TransportError>> { std::future::poll_fn(|context| body.as_mut().poll_next(context)).await } diff --git a/crates/shopify_api/tests/bulk_stream.rs b/crates/shopify_api/tests/bulk_stream.rs index aa1c565..370e7a6 100644 --- a/crates/shopify_api/tests/bulk_stream.rs +++ b/crates/shopify_api/tests/bulk_stream.rs @@ -40,7 +40,6 @@ fn fast() -> BulkWaitOptions { BulkWaitOptions::new().poll_interval(Duration::from_millis(1)) } -/// Shopify starts the operation, then reports it completed. fn push_run_and_completed(mock: &MockTransport, url: Option<&str>) { mock.push_data(json!({ "bulkOperationRunQuery": { "bulkOperation": operation("CREATED", None), "userErrors": [] } })); mock.push_data(json!({ "bulkOperation": operation("COMPLETED", url) })); From a9874986f485d82fb6b47b73190b2d061e8265e4 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:51:52 +0200 Subject: [PATCH 045/135] docs: memory follows the line being read; grouping needs parent ids Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- README.md | 6 ++++-- crates/shopify_api/src/bulk.rs | 4 ++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24def77..bbe0506 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,8 +13,8 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: tokens are renewed once for all the clones of a client, before they expire and when Shopify refuses one with a `401`. `Auth::expiring_token` with a `TokenStore`. - Add: `Shopify::paginate`, `Page`. - Add: bulk operations: `bulk_query_rows`, `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, typed `BulkOperation` and statuses, adaptive polling. -- Add: bulk results read as they download, in memory that follows the longest line rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. -- Add: `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group. +- Add: bulk results read as they download, in memory that follows the line being read rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. +- Add: `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group; so is a child whose parent has no unaliased `id`, which the error names. - Add: `run_bulk_mutation_iter` and `stage_bulk_variables_iter` take the variables from an iterator; the JSONL is written straight into the body of the upload, in memory once. - Add: `Transport::send_streaming`, with a default that goes through `send`, and `StreamingResponse`, `BodyStream`. `ReqwestTransport` streams: the timeout of the request bounds the wait for the headers and for each chunk, not the whole body. `MockTransport::push_chunks` and `push_streaming` script a body in chunks. - Add: `webhooks`: `Webhook::verify` (headers, signature with secret rotation, payload), subscriptions with `sync_webhook_subscriptions`, which updates in place and creates before it deletes. diff --git a/README.md b/README.md index 6dd3831..98b7308 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ let operation = shopify.run_bulk_mutation( `bulk_query_rows` holds every row in a `Vec`. For an export of gigabytes, `bulk_query_stream` reads the file line by line as it downloads: memory -follows the longest line, not the file. +follows the line being read, not the file. ```rust,ignore let mut products = shopify @@ -257,7 +257,9 @@ line longer than `max_line_length` (64 MiB by default), ends it. Nested connections write their objects on lines of their own, after their parent. `bulk_query_grouped::` runs the query with `groupObjects` and yields each product with its variants, one product in -memory at a time: +memory at a time. Every object that has a nested connection must select +`id`, without an alias: Shopify refuses the query otherwise. + ```rust,ignore let mut products = shopify diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 1a7dcd9..c0d1002 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -708,8 +708,8 @@ impl Shopify { } /// Runs a bulk query to its end, then reads its results line by line - /// as they download: the memory it takes follows the longest line, not - /// the file. Fails when the operation does not complete. + /// as they download: the memory it takes follows the line being read, + /// not the file. Fails when the operation does not complete. /// /// The stream ends after some errors and goes on after others: see /// [`BulkRows`]. From 154cf79c5e5a38cc935abe2565a04ea6a6a64f06 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:06:18 +0200 Subject: [PATCH 046/135] fix(bulk): keep the buffer while lines stay alike The buffer shrank to the chunk at hand, so equal lines cut into small chunks shrank it at the start of each line and regrew it: 192 reallocations for 32 lines of 1 MiB. It now keeps what it held over the last 16 to 32 lines, and shrinks only past four times that: 6 reallocations, as before the shrink, and a huge line's buffer is still released 32 lines after it, and at the end of the file. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk/rows.rs | 105 ++++++++++++++++++++++------ 1 file changed, 83 insertions(+), 22 deletions(-) diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index b3f0e03..54c1063 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -18,9 +18,13 @@ use crate::{Error, Result}; pub const DEFAULT_MAX_LINE_LENGTH: usize = 64 * 1024 * 1024; /// What the buffer may keep, whatever it holds: a buffer more than four -/// times what it holds, and than this, shrinks after a long line. +/// times what it held lately, and than this, shrinks after a long line. const KEPT_CAPACITY: usize = 64 * 1024; +/// How many lines the buffer remembers what it held: lines of the same +/// size, cut into small chunks, reuse its capacity rather than regrow it. +const KEPT_LINES: usize = 16; + /// A line: its number, from 1, and where it is in the buffer. type Line = (usize, Range); @@ -41,6 +45,13 @@ struct Lines { line: usize, max: usize, done: bool, + /// The most `buffer` held since line `window`, and in the + /// `KEPT_LINES` lines before. + held: usize, + held_before: usize, + window: usize, + #[cfg(test)] + shrinks: usize, } impl Lines { @@ -54,6 +65,11 @@ impl Lines { scanned: 0, line: 0, max: DEFAULT_MAX_LINE_LENGTH, + held: 0, + held_before: 0, + window: 0, + #[cfg(test)] + shrinks: 0, } } @@ -120,11 +136,25 @@ impl Lines { Poll::Ready(Some(Ok(chunk))) => { self.buffer.drain(..self.start); self.start = 0; - let needed = (self.buffer.len() + chunk.len()).max(KEPT_CAPACITY); - if self.buffer.capacity() > 4 * needed { - self.buffer.shrink_to(needed); + let lines = self.line - self.window; + if lines >= KEPT_LINES { + self.held_before = if lines < 2 * KEPT_LINES { self.held } else { 0 }; + self.held = 0; + self.window = self.line; + } + let kept = (self.buffer.len() + chunk.len()) + .max(self.held) + .max(self.held_before) + .max(KEPT_CAPACITY); + if self.buffer.capacity() > 4 * kept { + self.buffer.shrink_to(kept); + #[cfg(test)] + { + self.shrinks += 1; + } } self.buffer.extend_from_slice(&chunk); + self.held = self.held.max(self.buffer.len()); } } } @@ -695,19 +725,47 @@ mod tests { ); } + fn cut(line: &[u8], size: usize) -> impl Iterator> + '_ { + line.chunks(size).map(<[u8]>::to_vec) + } + + fn line_of(bytes: usize) -> Vec { + format!("{{\"a\":\"{}\"}}\n", "x".repeat(bytes)).into_bytes() + } + #[tokio::test] - async fn the_buffer_of_a_huge_line_is_released_once_it_is_read() { - let huge = format!("{{\"a\":\"{}\"}}\n", "x".repeat(16 * 1024 * 1024)); - let tiny = b"{\"b\":1}\n".to_vec(); - let parts = vec![huge.into_bytes(), tiny.clone(), tiny.clone(), tiny.clone()]; + async fn the_buffer_is_kept_while_lines_stay_alike() { + let line = line_of(1024 * 1024); + for size in [line.len(), 32 * 1024, 1024] { + let parts = (0..16).flat_map(|_| cut(&line, size)).collect(); + let mut rows = rows_of::(parts); + rows.next_row().await.unwrap().unwrap(); + let capacity = rows.lines.capacity(); + while let Some(row) = rows.next_row().await { + row.unwrap(); + if !rows.lines.done { + assert_eq!(rows.lines.capacity(), capacity, "chunks of {size}"); + } + } + assert_eq!(rows.lines.shrinks, 0, "chunks of {size}"); + } + } + + #[tokio::test] + async fn the_buffer_of_a_huge_line_is_released_a_few_lines_later() { + let mut parts: Vec> = cut(&line_of(16 * 1024 * 1024), 32 * 1024).collect(); + parts.extend(std::iter::repeat_n(b"{\"b\":1}\n".to_vec(), 100)); let mut rows = rows_of::(parts); rows.next_row().await.unwrap().unwrap(); assert!(rows.lines.capacity() > 16 * 1024 * 1024); - rows.next_row().await.unwrap().unwrap(); + for _ in 0..2 * KEPT_LINES { + rows.next_row().await.unwrap().unwrap(); + } assert!( rows.lines.capacity() <= 1024 * 1024, - "{} bytes held after a tiny line", - rows.lines.capacity() + "{} bytes held after {} tiny lines", + rows.lines.capacity(), + 2 * KEPT_LINES ); while let Some(row) = rows.next_row().await { row.unwrap(); @@ -715,18 +773,21 @@ mod tests { assert_eq!(rows.lines.capacity(), 0); } - /// A buffer a few times larger than its chunks is kept: no - /// reallocation on each chunk. #[tokio::test] - async fn the_buffer_is_kept_while_lines_stay_alike() { - let line = format!("{{\"a\":\"{}\"}}\n", "x".repeat(300 * 1024)); - let parts: Vec> = std::iter::repeat_n(line.into_bytes(), 8).collect(); - let mut rows = rows_of::(parts); - rows.next_row().await.unwrap().unwrap(); - let first = rows.lines.buffer.as_ptr(); - for _ in 0..7 { - rows.next_row().await.unwrap().unwrap(); - assert_eq!(rows.lines.buffer.as_ptr(), first); + async fn alternating_huge_and_tiny_lines_keep_the_buffer() { + let huge = line_of(1024 * 1024); + for size in [huge.len(), 32 * 1024, 1024] { + let parts = (0..16) + .flat_map(|_| cut(&huge, size).chain([b"{}\n".to_vec()])) + .collect(); + let mut rows = rows_of::(parts); + let mut read = 0; + while let Some(row) = rows.next_row().await { + row.unwrap(); + read += 1; + } + assert_eq!(read, 32); + assert_eq!(rows.lines.shrinks, 0, "chunks of {size}"); } } From f2355f71677d055ba213ef64910f6d7aa90fe093 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:06:48 +0200 Subject: [PATCH 047/135] chore: drop comments the names already say Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk/rows.rs | 10 ---------- crates/shopify_api/src/transport.rs | 3 --- crates/shopify_api/tests/bulk_stream.rs | 9 --------- 3 files changed, 22 deletions(-) diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index 54c1063..8994579 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -73,7 +73,6 @@ impl Lines { } } - /// Stops reading: what is left of the body is dropped. fn finish(&mut self) { self.done = true; self.body = None; @@ -278,7 +277,6 @@ impl FusedStream for BulkRows { } } -/// What [`BulkGroups`] reads of each line to place it. #[derive(Deserialize)] struct Keys { id: Option, @@ -500,7 +498,6 @@ mod tests { out } - /// The rows and errors as text: what a split must not change. fn shown(results: &[Result]) -> Vec { results .iter() @@ -511,7 +508,6 @@ mod tests { .collect() } - /// What `parse_jsonl` gives line by line: each line on its own, numbered. fn buffered(body: &[u8]) -> Vec { body.split(|byte| *byte == b'\n') .enumerate() @@ -617,7 +613,6 @@ mod tests { #[tokio::test] async fn a_line_longer_than_the_limit_ends_the_stream() { - // Too long whether its newline comes with it or not. for parts in [ vec![b"{\"a\":1}\n{\"b\":\"0123456789\"}\n{\"c\":3}\n".to_vec()], vec![ @@ -705,7 +700,6 @@ mod tests { ); let chunk = line.repeat(64).into_bytes(); let chunk_len = chunk.len(); - // About 20 MB, generated as it is read. let count = 20_000_000 / chunk_len; let body = std::iter::repeat_n(chunk, count).map(Ok); let mut rows: BulkRows = @@ -883,7 +877,6 @@ mod tests { "bulk operation: line 4 of the results is a child of neither the top-level object before it nor one of its children: run the query with `groupObjects`" ); - // Before any top-level object, or to an unknown parent. for body in [ "{\"id\":\"V1\",\"__parentId\":\"P1\"}\n{\"id\":\"P1\"}\n", "{\"id\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P9\"}\n", @@ -898,17 +891,14 @@ mod tests { async fn a_parent_without_id_is_named_as_the_cause() { const MISSING: &str = "has a `__parentId` that no `id` before it matches, and an object before it has no `id`: select `id`, without an alias, on every object that has nested connections"; for (body, line) in [ - // A top-level object without `id`. ( "{\"title\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P1\"}\n", 2, ), - // A first-level child without `id`, parent of the second level. ( "{\"id\":\"P1\"}\n{\"sku\":\"V1\",\"__parentId\":\"P1\"}\n{\"id\":\"L1\",\"__parentId\":\"V1\"}\n", 3, ), - // An aliased `id`. ( "{\"productId\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P1\"}\n", 2, diff --git a/crates/shopify_api/src/transport.rs b/crates/shopify_api/src/transport.rs index 4d1d276..31fc586 100644 --- a/crates/shopify_api/src/transport.rs +++ b/crates/shopify_api/src/transport.rs @@ -262,7 +262,6 @@ impl StreamingResponse { } } -/// The whole body as one chunk. impl From for StreamingResponse { fn from(response: HttpResponse) -> Self { let body = (!response.body.is_empty()).then_some(Ok(response.body)); @@ -521,7 +520,6 @@ impl Transport for ReqwestTransport { } } -/// The chunk being read, with the answer it is read from. #[cfg(any(feature = "rustls", feature = "native-tls"))] type PendingChunk = BoxFuture<'static, (reqwest::Response, Result>, TransportError>)>; @@ -553,7 +551,6 @@ impl Stream for ReqwestBody { Some(Ok(chunk)) } Ok(None) => None, - // The answer is dropped: the stream ends after its error. Err(error) => Some(Err(error)), }); } diff --git a/crates/shopify_api/tests/bulk_stream.rs b/crates/shopify_api/tests/bulk_stream.rs index 370e7a6..eafa1e3 100644 --- a/crates/shopify_api/tests/bulk_stream.rs +++ b/crates/shopify_api/tests/bulk_stream.rs @@ -102,7 +102,6 @@ async fn an_operation_without_results_streams_nothing() { async fn a_refused_download_keeps_the_first_mib_of_its_body_and_hides_the_signature() { let mock = MockTransport::new(); let chunk = vec![b'x'; 256 * 1024]; - // 8 MiB of error body: the error keeps 1 MiB, the rest is not read. let read = Arc::new(Mutex::new(0)); let counter = read.clone(); mock.push_chunks( @@ -122,7 +121,6 @@ async fn a_refused_download_keeps_the_first_mib_of_its_body_and_hides_the_signat assert!(!shown.contains("SECRET"), "{shown}"); } -/// A transport written before `send_streaming`: it implements `send` only. struct Buffered(Vec); impl Transport for Buffered { @@ -153,7 +151,6 @@ async fn a_transport_that_only_sends_streams_through_the_default() { assert_eq!(collected, parse_jsonl::(&body).unwrap()); } -/// A body that gives `chunks`, then fails. struct FailsAfter(Vec>); impl futures_core::Stream for FailsAfter { @@ -266,7 +263,6 @@ async fn a_child_out_of_place_only_asks_for_grouping_when_it_may_be_off() { ); } -/// Shopify reserves an upload target; the storage server takes the file. fn upload_mock() -> (MockTransport, Arc>>) { let mock = MockTransport::new(); let uploads = Arc::new(Mutex::new(Vec::new())); @@ -298,7 +294,6 @@ fn upload_mock() -> (MockTransport, Arc>>) { (mock, uploads) } -/// The JSONL part of a multipart body. fn uploaded_file(request: &HttpRequest) -> String { let body = String::from_utf8(request.body.clone()).unwrap(); let start = body.find("Content-Type: text/jsonl\r\n\r\n").unwrap() + 28; @@ -374,7 +369,6 @@ async fn an_item_that_does_not_serialize_stops_the_upload() { assert!(uploads.lock().unwrap().is_empty(), "nothing uploaded"); } -/// The default transport against a server on this machine. #[cfg(feature = "rustls")] mod reqwest_transport { use super::*; @@ -423,7 +417,6 @@ mod reqwest_transport { b"{\"id\":\"1\",\"title\":\"A\"}\n{\"id\":\"2\",", ) .await; - // The rest waits until the first row was read. released.await.unwrap(); write_chunk(&mut socket, b"\"title\":\"B\"}\n").await; socket.write_all(b"0\r\n\r\n").await.unwrap(); @@ -449,7 +442,6 @@ mod reqwest_transport { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let server = tokio::spawn(async move { - // A slow body, each chunk within the timeout. let (mut socket, _) = listener.accept().await.unwrap(); read_request(&mut socket).await; socket.write_all(HEAD).await.unwrap(); @@ -459,7 +451,6 @@ mod reqwest_transport { } socket.write_all(b"0\r\n\r\n").await.unwrap(); drop(socket); - // Then a body that stalls. let (mut socket, _) = listener.accept().await.unwrap(); read_request(&mut socket).await; socket.write_all(HEAD).await.unwrap(); From 298319f77207c87b155bf9d7c86ce7a8255c21a6 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:13:28 +0200 Subject: [PATCH 048/135] docs(bulk): say the line buffer keeps the room of recent lines Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- crates/shopify_api/src/bulk.rs | 6 +++--- crates/shopify_api/src/bulk/rows.rs | 7 +++++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 98b7308..ad5a569 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ let operation = shopify.run_bulk_mutation( `bulk_query_rows` holds every row in a `Vec`. For an export of gigabytes, `bulk_query_stream` reads the file line by line as it downloads: memory -follows the line being read, not the file. +follows the lines being read (the longest of the last few dozen), not the file. ```rust,ignore let mut products = shopify diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index c0d1002..2469695 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -25,7 +25,7 @@ //! downloads ([`BulkRows`]), and [`Shopify::bulk_query_grouped`] each //! top-level object with its nested objects ([`BulkGroups`]). Neither holds //! the file: [`BulkRows`] holds the line being read and the rest of the -//! chunk it ends in; [`BulkGroups`] holds that, and the group being read, +//! chunk it ends in, in a buffer sized for the longest recent line; [`BulkGroups`] holds that, and the group being read, //! its top-level object with every child read so far and their IDs. A //! product with 2,000 variants is held with its 2,000 variants. //! @@ -708,8 +708,8 @@ impl Shopify { } /// Runs a bulk query to its end, then reads its results line by line - /// as they download: the memory it takes follows the line being read, - /// not the file. Fails when the operation does not complete. + /// as they download: the memory it takes follows the lines being read, + /// not the file (see [`BulkRows`]). Fails when the operation does not complete. /// /// The stream ends after some errors and goes on after others: see /// [`BulkRows`]. diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index 8994579..a54b52f 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -190,8 +190,11 @@ impl fmt::Debug for Lines { /// return it. /// /// It holds one line at a time, and the rest of the chunk that line ends -/// in: the memory it takes follows the line being read, not the file. Read it -/// with [`BulkRows::next_row`], or as a [`Stream`]. +/// in: the memory it takes follows the lines being read, not the file. To +/// avoid reallocating for every line, its buffer keeps the room the longest +/// of the last 16 to 32 lines needed, and gives it back once lines stay four +/// times smaller for that long, or when the file ends. Read it with +/// [`BulkRows::next_row`], or as a [`Stream`]. /// /// Lines are split on `\n`; a `\r` before it, a last line without one and /// blank lines are fine, and blank lines are skipped but counted. From b59b16a5d710aaec37fe3245e2dd4bce3e0017e2 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:20:35 +0200 Subject: [PATCH 049/135] feat(graphql): several modules in one graphql! block MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `graphql! { … }` takes any number of modules, each with its own attributes, visibility and source; `;` goes between them and is optional after the last one. The bulk and webhook operations of the crate now sit in one block each. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk.rs | 15 --- crates/shopify_api/src/webhooks.rs | 11 +-- crates/shopify_api_macros/src/lib.rs | 137 +++++++++++++++++---------- 3 files changed, 86 insertions(+), 77 deletions(-) diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 2469695..3916072 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -67,25 +67,10 @@ const ERROR_BODY_LIMIT: usize = 1024 * 1024; graphql! { mod run_query = file("graphql/operations/bulk_run_query.graphql"); -} - -graphql! { mod run_mutation = file("graphql/operations/bulk_run_mutation.graphql"); -} - -graphql! { mod get = file("graphql/operations/bulk_get.graphql"); -} - -graphql! { mod list = file("graphql/operations/bulk_list.graphql"); -} - -graphql! { mod cancel = file("graphql/operations/bulk_cancel.graphql"); -} - -graphql! { mod staged_uploads = file("graphql/operations/bulk_staged_uploads.graphql"); } diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs index b5e5483..782fa87 100644 --- a/crates/shopify_api/src/webhooks.rs +++ b/crates/shopify_api/src/webhooks.rs @@ -223,14 +223,9 @@ pub fn topic_enum(topic: &str) -> String { graphql! { mod list = file("graphql/operations/webhooks_list.graphql"); -} - -graphql! { mod create = file("graphql/operations/webhooks_create.graphql"); -} - -graphql! { mod update = file("graphql/operations/webhooks_update.graphql"); + mod delete = file("graphql/operations/webhooks_delete.graphql"); } /// The input of `create` or `update` for a spec. An update sends every @@ -252,10 +247,6 @@ macro_rules! input { }}; } -graphql! { - mod delete = file("graphql/operations/webhooks_delete.graphql"); -} - /// A webhook subscription of a shop. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[non_exhaustive] diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index dc8ec3b..1e688a6 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -63,40 +63,59 @@ impl Parse for Source { } } -/// `graphql!(SOURCE, name = value, …)` or `graphql! { pub mod name = SOURCE; }`. +/// `graphql!(SOURCE, name = value, …)`, or modules: +/// `graphql! { pub mod name = SOURCE; mod other = SOURCE }`. enum Input { Expression { source: Source, variables: Vec<(Ident, Expr)>, }, - Module { - attributes: Vec, - visibility: Visibility, - name: Ident, - source: Source, - }, + Modules(Vec), +} + +struct Module { + attributes: Vec, + visibility: Visibility, + name: Ident, + source: Source, } impl Parse for Input { fn parse(input: ParseStream) -> syn::Result { - let attributes = input.call(Attribute::parse_outer)?; - let visibility: Visibility = input.parse()?; + let mut attributes = input.call(Attribute::parse_outer)?; + let mut visibility: Visibility = input.parse()?; if input.peek(Token![mod]) { - input.parse::()?; - let name: Ident = input.parse()?; - input.parse::()?; - let source: Source = input.parse()?; - input.parse::>()?; - if !input.is_empty() { - return Err(input.error("expected the end of the `graphql!` module")); + let mut modules = Vec::new(); + loop { + input.parse::()?; + let name: Ident = input.parse()?; + input.parse::()?; + let source: Source = input.parse()?; + modules.push(Module { + attributes, + visibility, + name, + source, + }); + if input.is_empty() { + break; + } + input.parse::().map_err(|error| { + syn::Error::new(error.span(), "expected `;` after the module") + })?; + if input.is_empty() { + break; + } + attributes = input.call(Attribute::parse_outer)?; + visibility = input.parse()?; + if !input.peek(Token![mod]) { + return Err(input.error( + "expected another module, `mod name = \"…\";`, or the end of `graphql!`", + )); + } } - return Ok(Self::Module { - attributes, - visibility, - name, - source, - }); + return Ok(Self::Modules(modules)); } if let Some(attribute) = attributes.first() { @@ -504,13 +523,13 @@ fn expand_expression( } /// `graphql! { mod name = "…"; }`: the operation as a module that names its types. -fn expand_module( - schema: &LoadedSchema, - attributes: &[Attribute], - visibility: &Visibility, - name: &Ident, - source: &Source, -) -> syn::Result { +fn expand_module(schema: &LoadedSchema, module: &Module) -> syn::Result { + let Module { + attributes, + visibility, + name, + source, + } = module; let krate = quote!(::shopify_api); let text = Text::read(source)?; let operation = schema.check(&text)?; @@ -576,12 +595,13 @@ fn expand(input: Input, schema: Result) -> syn::Result expand_expression(&schema, &source, &variables), - Input::Module { - attributes, - visibility, - name, - source, - } => expand_module(&schema, &attributes, &visibility, &name, &source), + Input::Modules(modules) => { + let mut expanded = TokenStream::new(); + for module in &modules { + expanded.extend(expand_module(&schema, module)?); + } + Ok(expanded) + } } } @@ -711,24 +731,33 @@ mod tests { let module: Input = syn::parse_str("#[doc = \"Docs.\"] pub mod shop_name = \"{ shop { name } }\";") .unwrap(); - let Input::Module { - attributes, name, .. - } = module - else { + let Input::Modules(modules) = module else { panic!("a module"); }; - assert_eq!(name, "shop_name"); - assert_eq!(attributes.len(), 1); - - let module: Input = - syn::parse_str(r#"pub(crate) mod shop_name = file("graphql/shop.graphql");"#).unwrap(); - assert!(matches!( - module, - Input::Module { - source: Source::File(_), - .. - } - )); + assert_eq!(modules.len(), 1); + assert_eq!(modules[0].name, "shop_name"); + assert_eq!(modules[0].attributes.len(), 1); + + // Several modules, `;` between them and optional after the last. + for text in [ + r#"#[doc = "A."] pub mod a = "{ shop { name } }"; pub(crate) mod b = file("b.graphql"); mod c = "{ shop { id } }""#, + r#"#[doc = "A."] pub mod a = "{ shop { name } }"; pub(crate) mod b = file("b.graphql"); mod c = "{ shop { id } }";"#, + ] { + let Input::Modules(modules) = syn::parse_str::(text).unwrap() else { + panic!("modules"); + }; + let names: Vec = modules + .iter() + .map(|module| module.name.to_string()) + .collect(); + assert_eq!(names, ["a", "b", "c"]); + assert_eq!(modules[0].attributes.len(), 1); + assert!(modules[1].attributes.is_empty()); + assert!(matches!(modules[0].visibility, Visibility::Public(_))); + assert!(matches!(modules[1].visibility, Visibility::Restricted(_))); + assert!(matches!(modules[1].source, Source::File(_))); + assert!(matches!(modules[2].visibility, Visibility::Inherited)); + } for (source, message) in [ ( @@ -750,7 +779,11 @@ mod tests { ), ( r#"mod shop = "{ shop { name } }"; 1"#, - "expected the end of the `graphql!` module", + "expected another module, `mod name = \"…\";`, or the end of `graphql!`", + ), + ( + r#"mod a = "{ shop { name } }" mod b = "{ shop { id } }""#, + "expected `;` after the module", ), ] { let error = syn::parse_str::(source) From 275e37f1ea83825e89e8acec29492fa848242cfc Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:21:21 +0200 Subject: [PATCH 050/135] perf(graphql): keep each variable as the JSON it is sent as An operation held its variables as a serde_json::Value tree, built by serialization, then serialized again into the body. It now keeps each variable as its JSON text (serde_json's raw_value) and writes the body around them once: a value that is JSON already, such as an input object of input!, is copied, not read back. variables_json() reads the variables back, by value; body() reads the body back. Both are for inspection; sending goes through neither. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/Cargo.toml | 2 +- crates/shopify_api/src/graphql.rs | 11 +- crates/shopify_api/src/graphql/operation.rs | 114 +++++++++++++++----- 3 files changed, 95 insertions(+), 32 deletions(-) diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index b6db1ea..7d15e8e 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -41,7 +41,7 @@ chrono.workspace = true futures-core.workspace = true reqwest = { workspace = true, optional = true } serde.workspace = true -serde_json.workspace = true +serde_json = { workspace = true, features = ["raw_value"] } serde_urlencoded.workspace = true # `rt`: a token renewal runs in its own task, so a caller that gives up does not cancel it. tokio = { workspace = true, features = ["rt", "sync", "time"] } diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index b1da597..931066b 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -49,8 +49,8 @@ impl Shopify { operation: Operation, ) -> Result> { let version = self.version_for(operation.checked_against())?; - let body = operation.body()?; - let raw = self.send_graphql(version, &body, operation.kind()).await?; + let body = operation.body_json()?; + let raw = self.send_graphql(version, body, operation.kind()).await?; let (data, extensions) = into_data(raw)?; Ok(Response { data: crate::decode::from_value(data)?, @@ -98,7 +98,9 @@ impl Shopify { body.insert("variables".to_string(), Value::Object(variables)); } let version = self.version_for(None)?; - self.send_graphql(version, &Value::Object(body), OperationKind::of(query)) + let body = serde_json::to_vec(&Value::Object(body)) + .map_err(|error| Error::variables(None, &error))?; + self.send_graphql(version, body, OperationKind::of(query)) .await } @@ -107,11 +109,10 @@ impl Shopify { pub(crate) async fn send_graphql( &self, version: ApiVersion, - body: &Value, + body: Vec, kind: OperationKind, ) -> Result { let url = self.graphql_url(version); - let body = serde_json::to_vec(body).map_err(|error| Error::variables(None, &error))?; let endpoint = self.endpoint(); let mut token = self.shared.tokens.get(endpoint).await?; let mut retries = 0; diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs index 8d77ed5..9643728 100644 --- a/crates/shopify_api/src/graphql/operation.rs +++ b/crates/shopify_api/src/graphql/operation.rs @@ -3,7 +3,8 @@ use std::borrow::Cow; use std::marker::PhantomData; -use serde::Serialize; +use serde::ser::{Serialize, SerializeMap, Serializer}; +use serde_json::value::RawValue; use serde_json::{Map, Value}; use crate::{ApiVersion, Error, Result}; @@ -211,7 +212,8 @@ pub struct Operation { name: Option>, /// The Admin API version of the schema the operation was checked against. checked_against: Option<&'static str>, - variables: std::result::Result, VariablesFailure>, + /// Each variable as the JSON it is sent as, in the order it was set. + variables: std::result::Result)>, VariablesFailure>, data: PhantomData D>, } @@ -224,7 +226,7 @@ impl Operation { query, name: None, checked_against: None, - variables: Ok(Map::new()), + variables: Ok(Vec::new()), data: PhantomData, } } @@ -242,7 +244,7 @@ impl Operation { kind, name: name.map(Cow::Borrowed), checked_against: Some(checked_against), - variables: Ok(Map::new()), + variables: Ok(Vec::new()), data: PhantomData, } } @@ -282,11 +284,12 @@ impl Operation { } } - fn set(mut self, name: &str, value: serde_json::Result) -> Self { + fn set(mut self, name: &str, value: serde_json::Result>) -> Self { match (&mut self.variables, value) { - (Ok(variables), Ok(value)) => { - variables.insert(name.to_string(), value); - } + (Ok(variables), Ok(value)) => match variables.iter_mut().find(|(set, _)| set == name) { + Some((_, set)) => *set = value, + None => variables.push((name.to_string(), value)), + }, (Ok(_), Err(error)) => { self.variables = Err(VariablesFailure::of(Error::variables(Some(name), &error))) } @@ -298,39 +301,98 @@ impl Operation { /// Sets a variable to a value convertible to `T`, the Rust type of its /// GraphQL type. pub fn variable>(self, name: &str, value: V) -> Self { - self.set(name, serde_json::to_value(value.into_variable())) + self.set( + name, + serde_json::value::to_raw_value(&value.into_variable()), + ) } /// Sets a variable to any serializable value, checked by nothing. pub fn json_variable(self, name: &str, value: V) -> Self { - self.set(name, serde_json::to_value(value)) + self.set(name, serde_json::value::to_raw_value(&value)) } /// Replaces the variables with the fields of a serializable struct or map. pub fn variables(mut self, variables: V) -> Self { - self.variables = variables_of(variables).map_err(VariablesFailure::of); + self.variables = variables_of(variables) + .and_then(|variables| { + variables + .into_iter() + .map( + |(name, value)| match serde_json::value::to_raw_value(&value) { + Ok(value) => Ok((name, value)), + Err(error) => Err(Error::variables(Some(&name), &error)), + }, + ) + .collect() + }) + .map_err(VariablesFailure::of); self } - /// The variables, as they are sent. - pub fn variables_json(&self) -> Result<&Map> { - self.variables + /// The variables, read back from the JSON they are sent as. + pub fn variables_json(&self) -> Result> { + let variables = self + .variables .as_ref() - .map_err(|failure| failure.to_error()) + .map_err(|failure| failure.to_error())?; + variables + .iter() + .map(|(name, value)| match serde_json::from_str(value.get()) { + Ok(value) => Ok((name.clone(), value)), + Err(error) => Err(Error::variables(Some(name), &error)), + }) + .collect() } - /// The body Shopify receives: `query`, `variables` and `operationName`. + /// The body Shopify receives: `query`, `variables` and `operationName`, + /// read back from the JSON it is sent as. pub fn body(&self) -> Result { - let mut body = Map::new(); - body.insert("query".to_string(), Value::String(self.query.to_string())); - let variables = self.variables_json()?; - if !variables.is_empty() { - body.insert("variables".to_string(), Value::Object(variables.clone())); + serde_json::from_slice(&self.body_json()?).map_err(|error| Error::variables(None, &error)) + } + + /// The body as it is sent. + pub(crate) fn body_json(&self) -> Result> { + let variables = self + .variables + .as_ref() + .map_err(|failure| failure.to_error())?; + let body = Body { + query: &self.query, + variables, + name: self.name.as_deref(), + }; + serde_json::to_vec(&body).map_err(|error| Error::variables(None, &error)) + } +} + +struct Body<'a> { + query: &'a str, + variables: &'a [(String, Box)], + name: Option<&'a str>, +} + +impl Serialize for Body<'_> { + fn serialize(&self, serializer: S) -> std::result::Result { + struct Variables<'a>(&'a [(String, Box)]); + impl Serialize for Variables<'_> { + fn serialize( + &self, + serializer: S, + ) -> std::result::Result { + serializer.collect_map(self.0.iter().map(|(name, value)| (name, value))) + } + } + + let mut body = serializer.serialize_map(None)?; + body.serialize_entry("query", self.query)?; + if !self.variables.is_empty() { + body.serialize_entry("variables", &Variables(self.variables))?; } - if let Some(name) = &self.name { - body.insert("operationName".to_string(), Value::String(name.to_string())); + if let Some(name) = self.name { + body.serialize_entry("operationName", name)?; } - Ok(Value::Object(body)) + body.end() } } @@ -526,7 +588,7 @@ mod tests { use serde_json::json; fn variables(operation: Operation) -> Value { - Value::Object(operation.variables_json().unwrap().clone()) + Value::Object(operation.variables_json().unwrap()) } #[test] @@ -651,7 +713,7 @@ mod tests { #[test] fn variables_can_come_from_a_struct() { - #[derive(Serialize)] + #[derive(serde::Serialize)] struct Variables { first: i64, #[serde(skip_serializing_if = "Option::is_none")] From f65855863646415704a9cf3f5d71c19842755e4b Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:23:29 +0200 Subject: [PATCH 051/135] feat(graphql): input values as checked literals in inline graphql! A variable of an inline graphql! takes a value written for its GraphQL type, read by the type expected where it stands: null, an object { field: value, field?: option }, a list [a, b] or [for x in xs if c => value], a bare enum value, raw(string) for an enum value known at run time, or any Rust expression. shopify_api_graphql::literal checks each value against the schema, at the token: unknown or repeated fields, every missing required field, null on a non-null type, ?: on a required field, unknown enum values (listed), raw() outside an enum, a value of the wrong form. Deprecated fields and enum values warn. A Rust expression goes through a trait generated for its place, whose diagnostic names the GraphQL type; in a field, an Option is refused with a message that points to field?: and field: null, since null for None would clear the field. Scalar variables given plain Rust values convert as before. A literal is written straight to the JSON sent: nested tuples of fields, no serde_json::Value. Maybe (Absent, Null, Value) is what field?: takes when null is a choice made at run time. InputObject is the type an input object position takes as a Rust value. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/graphql.rs | 3 + crates/shopify_api/src/graphql/input.rs | 65 ++ crates/shopify_api/src/graphql/literal.rs | 219 +++++ crates/shopify_api/src/graphql/operation.rs | 6 + crates/shopify_api/src/lib.rs | 5 +- .../tests/ui/literal_unknown_field.rs | 6 + .../tests/ui/literal_unknown_field.stderr | 6 + crates/shopify_api_graphql/src/analyze.rs | 2 +- crates/shopify_api_graphql/src/codegen.rs | 22 +- crates/shopify_api_graphql/src/lib.rs | 15 +- crates/shopify_api_graphql/src/literal.rs | 918 ++++++++++++++++++ crates/shopify_api_graphql/tests/literal.rs | 463 +++++++++ crates/shopify_api_macros/src/lib.rs | 75 +- crates/shopify_api_macros/src/value.rs | 306 ++++++ 14 files changed, 2073 insertions(+), 38 deletions(-) create mode 100644 crates/shopify_api/src/graphql/input.rs create mode 100644 crates/shopify_api/src/graphql/literal.rs create mode 100644 crates/shopify_api/tests/ui/literal_unknown_field.rs create mode 100644 crates/shopify_api/tests/ui/literal_unknown_field.stderr create mode 100644 crates/shopify_api_graphql/src/literal.rs create mode 100644 crates/shopify_api_graphql/tests/literal.rs create mode 100644 crates/shopify_api_macros/src/value.rs diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index 931066b..c6759ce 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -1,6 +1,8 @@ //! Running GraphQL operations: typed ones from [`graphql!`](crate::graphql!), //! untyped ones from any text. +mod input; +pub mod literal; pub(crate) mod operation; mod response; @@ -8,6 +10,7 @@ use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::{Map, Value}; +pub use input::{InputObject, Maybe}; pub use operation::{IntoVariable, Operation, OperationKind}; pub use response::{ Cost, GraphqlError, Location, RawResponse, Response, ThrottleStatus, UserError, diff --git a/crates/shopify_api/src/graphql/input.rs b/crates/shopify_api/src/graphql/input.rs new file mode 100644 index 0000000..9e3e4a5 --- /dev/null +++ b/crates/shopify_api/src/graphql/input.rs @@ -0,0 +1,65 @@ +//! Input objects built by [`input!`](crate::input!), and the field values +//! that may be left out. + +use serde::{Serialize, Serializer}; +use serde_json::value::RawValue; + +/// An input object of the schema, built and checked by `input!`: +/// `input!(MetafieldsSetInput { … })`. +/// +/// `TYPE` identifies the GraphQL input type: a hash of its name, so that +/// every `input!` of `MetafieldsSetInput`, in any module or crate, gives the +/// same Rust type, and values of different input types do not mix. A +/// `graphql!` module names it after the GraphQL type +/// (`metafields_set::MetafieldsSetInput`); messages of `graphql!` and +/// `input!` name the GraphQL type too. +/// +/// The value is opaque: it holds the JSON it is sent as, written when it is +/// built. +#[derive(Clone)] +pub struct InputObject { + name: &'static str, + json: Box, +} + +impl InputObject { + /// What `input!` builds. + #[doc(hidden)] + pub fn __new(name: &'static str, fields: &impl Serialize) -> Self { + Self { + name, + json: crate::__private::literal::to_raw(fields), + } + } +} + +impl Serialize for InputObject { + fn serialize(&self, serializer: S) -> Result { + self.json.serialize(serializer) + } +} + +impl std::fmt::Debug for InputObject { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "{} {}", self.name, self.json.get()) + } +} + +/// A field given with `field?: value` in [`graphql!`](crate::graphql!) and +/// `input!`, when sending `null` is a choice made at run +/// time: an `Option` covers absent or value, `Maybe` adds `null`. +#[derive(Debug, Clone, PartialEq, Default)] +pub enum Maybe { + /// The field is not sent: Shopify keeps what it has. + #[default] + Absent, + /// The field is sent as `null`: Shopify clears it. + Null, + Value(T), +} + +impl From for Maybe { + fn from(value: T) -> Self { + Self::Value(value) + } +} diff --git a/crates/shopify_api/src/graphql/literal.rs b/crates/shopify_api/src/graphql/literal.rs new file mode 100644 index 0000000..a5c706a --- /dev/null +++ b/crates/shopify_api/src/graphql/literal.rs @@ -0,0 +1,219 @@ +//! What the code `graphql!` and `input!` generate for a literal value +//! (`{ title: "x" }`, `[a, b]`, `raw(…)`) refers to. Not a public API. +//! +//! An object literal is a list of fields nested in tuples, +//! `Object((Field("id", id), (Optional("vendor", vendor), ())))`, written in +//! its order; the macros check its fields and their values first. + +use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer}; +use serde_json::value::RawValue; + +use crate::Maybe; + +/// The JSON of a value the macros accept. +pub fn to_raw(value: &impl Serialize) -> Box { + // The macros only accept strings, numbers, booleans, `serde_json::Value`, + // input objects, and lists and objects of them: none fails to serialize. + serde_json::value::to_raw_value(value) + .expect("the values `graphql!` and `input!` accept always serialize") +} + +#[derive(Debug)] +pub struct Object(pub F); + +#[derive(Debug)] +pub struct Field(pub &'static str, pub V); + +/// `name?: value`: not sent when absent. +#[derive(Debug)] +pub struct Optional(pub &'static str, pub Maybe); + +pub trait Fields { + fn write(&self, map: &mut M) -> Result<(), M::Error>; +} + +impl Fields for () { + fn write(&self, _: &mut M) -> Result<(), M::Error> { + Ok(()) + } +} + +impl Fields for (Field, R) { + fn write(&self, map: &mut M) -> Result<(), M::Error> { + map.serialize_entry(self.0.0, &self.0.1)?; + self.1.write(map) + } +} + +impl Fields for (Optional, R) { + fn write(&self, map: &mut M) -> Result<(), M::Error> { + match &self.0.1 { + Maybe::Absent => {} + Maybe::Null => map.serialize_entry(self.0.0, &())?, + Maybe::Value(value) => map.serialize_entry(self.0.0, value)?, + } + self.1.write(map) + } +} + +impl Serialize for Object { + fn serialize(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(None)?; + self.0.write(&mut map)?; + map.end() + } +} + +/// `[a, b]`: its items, of types that may differ, nested in tuples. +#[derive(Debug)] +pub struct List(pub I); + +pub trait Items { + fn write(&self, seq: &mut S) -> Result<(), S::Error>; +} + +impl Items for () { + fn write(&self, _: &mut S) -> Result<(), S::Error> { + Ok(()) + } +} + +impl Items for (V, R) { + fn write(&self, seq: &mut S) -> Result<(), S::Error> { + seq.serialize_element(&self.0)?; + self.1.write(seq) + } +} + +impl Serialize for List { + fn serialize(&self, serializer: S) -> Result { + let mut seq = serializer.serialize_seq(None)?; + self.0.write(&mut seq)?; + seq.end() + } +} + +/// The value of `raw(…)`: any string, sent as the enum value. +#[diagnostic::on_unimplemented( + message = "`raw(…)` takes the enum value as a string, not `{Self}`", + label = "a `String`, a `&str` or anything else `Into`" +)] +pub trait RawString { + fn into_string(self) -> String; +} + +impl> RawString for T { + fn into_string(self) -> String { + self.into() + } +} + +pub fn raw(value: impl RawString) -> String { + value.into_string() +} + +/// `field?: raw(…)` on a field that may be `null`. +#[diagnostic::on_unimplemented( + message = "`field?: raw(…)` takes an `Option` or a `shopify_api::Maybe` of a string, not `{Self}`", + label = "`None` and `Maybe::Absent` leave the field out" +)] +pub trait RawOptional { + fn into_maybe(self) -> Maybe; +} + +impl RawOptional for Option { + fn into_maybe(self) -> Maybe { + option(self.map(RawString::into_string)) + } +} + +impl RawOptional for Maybe { + fn into_maybe(self) -> Maybe { + match self { + Maybe::Absent => Maybe::Absent, + Maybe::Null => Maybe::Null, + Maybe::Value(value) => Maybe::Value(value.into_string()), + } + } +} + +pub fn raw_optional(value: impl RawOptional) -> Maybe { + value.into_maybe() +} + +/// `field?: raw(…)` on a non-null field with a default: an `Option` only, +/// since `null` is refused there. +#[diagnostic::on_unimplemented( + message = "`field?: raw(…)` takes an `Option` of a string here, not `{Self}`", + label = "the field is non-null: `None` leaves it out, and `null` is refused" +)] +pub trait RawOption { + fn into_maybe(self) -> Maybe; +} + +impl RawOption for Option { + fn into_maybe(self) -> Maybe { + option(self.map(RawString::into_string)) + } +} + +pub fn raw_option(value: impl RawOption) -> Maybe { + value.into_maybe() +} + +/// The value of `field?: value`: `None` leaves the field out. +pub trait IntoMaybe { + fn into_maybe(self) -> Maybe; +} + +impl IntoMaybe for Option { + fn into_maybe(self) -> Maybe { + option(self) + } +} + +impl IntoMaybe for Maybe { + fn into_maybe(self) -> Maybe { + self + } +} + +fn option(value: Option) -> Maybe { + match value { + Some(value) => Maybe::Value(value), + None => Maybe::Absent, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn objects_and_lists_serialize_in_their_order_and_leave_out_absent_fields() { + let object = Object(( + Field("type", "single_line_text_field"), + ( + Optional("a", Maybe::<&str>::Absent), + ( + Optional("b", Maybe::<&str>::Null), + ( + Optional("c", option(Some(1))), + (Field("list", List(("x", (2, ((), ()))))), ()), + ), + ), + ), + )); + assert_eq!( + to_raw(&object).get(), + r#"{"type":"single_line_text_field","b":null,"c":1,"list":["x",2,null]}"# + ); + assert_eq!(to_raw(&Object(())).get(), "{}"); + assert_eq!(to_raw(&List(())).get(), "[]"); + assert_eq!( + raw_optional(Maybe::Value("A")), + Maybe::Value("A".to_string()) + ); + assert_eq!(raw_option(None::<&str>), Maybe::Absent); + } +} diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs index 9643728..f5305e3 100644 --- a/crates/shopify_api/src/graphql/operation.rs +++ b/crates/shopify_api/src/graphql/operation.rs @@ -312,6 +312,12 @@ impl Operation { self.set(name, serde_json::value::to_raw_value(&value)) } + /// What `graphql!` sets a variable written as a literal to. + #[doc(hidden)] + pub fn __literal_variable(self, name: &str, value: Box) -> Self { + self.set(name, Ok(value)) + } + /// Replaces the variables with the fields of a serializable struct or map. pub fn variables(mut self, variables: V) -> Self { self.variables = variables_of(variables) diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index 9dadc57..d6a4dce 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -82,8 +82,8 @@ pub use auth::{AssociatedUser, Auth, TokenData, TokenStore}; pub use client::{RetryPolicy, Shopify, ShopifyBuilder, USER_AGENT}; pub use error::{Error, GraphqlErrors, RawBody, Result, SensitiveDetail}; pub use graphql::{ - Cost, GraphqlError, IntoVariable, Location, Operation, OperationKind, RawResponse, Response, - ThrottleStatus, UserError, + Cost, GraphqlError, InputObject, IntoVariable, Location, Maybe, Operation, OperationKind, + RawResponse, Response, ThrottleStatus, UserError, }; pub use pagination::Page; pub use shop::ShopDomain; @@ -97,6 +97,7 @@ pub use shopify_api_macros::graphql; /// What the code `graphql!` generates refers to. Not a public API. #[doc(hidden)] pub mod __private { + pub use crate::graphql::literal; pub use serde; pub use serde_json; } diff --git a/crates/shopify_api/tests/ui/literal_unknown_field.rs b/crates/shopify_api/tests/ui/literal_unknown_field.rs new file mode 100644 index 0000000..5a45097 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_unknown_field.rs @@ -0,0 +1,6 @@ +fn main() { + let _ = shopify_api::graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + product = { id: "gid://shopify/Product/1", titel: "Shirt" }, + ); +} diff --git a/crates/shopify_api/tests/ui/literal_unknown_field.stderr b/crates/shopify_api/tests/ui/literal_unknown_field.stderr new file mode 100644 index 0000000..7f8b7b8 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_unknown_field.stderr @@ -0,0 +1,6 @@ +error: Input object `ProductUpdateInput` has no field `titel` (did you mean `title`?) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_unknown_field.rs:4:52 + | +4 | product = { id: "gid://shopify/Product/1", titel: "Shirt" }, + | ^^^^^ diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index 9a7a53e..3ed8cb8 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -1397,7 +1397,7 @@ fn variable_fits(variable: &Variable, null_default: bool, location: &InputValue) } /// ` (did you mean `x`?)` for the candidate closest to `name`, or nothing. -fn did_you_mean<'a>(name: &str, candidates: impl Iterator) -> String { +pub(crate) fn did_you_mean<'a>(name: &str, candidates: impl Iterator) -> String { let lowered = name.to_lowercase(); // Half of the name may differ, within three edits: `frist` → `first`, `CREATED` → `CREATED_AT`. let limit = (name.len() / 2).clamp(1, 3); diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs index 4e82b59..88c8f67 100644 --- a/crates/shopify_api_graphql/src/codegen.rs +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use proc_macro2::{Ident, Span, TokenStream}; -use quote::quote; +use quote::{quote, quote_spanned}; use crate::analyze::{ FieldBase, Operation, Scalar, SelectedField, Selection, Variable, VariableBase, @@ -229,6 +229,26 @@ pub fn variable_type(variable: &Variable, krate: &TokenStream) -> Option` for the input object +/// `name`: the 64-bit FNV-1a hash of the name, the same in every crate. +pub fn input_object_id(name: &str) -> u64 { + name.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3) + }) +} + +/// A compiler warning at `span` that gives `note`: the use of a +/// `#[deprecated]` constant. +pub fn deprecation_warning(span: Span, note: &str) -> TokenStream { + quote_spanned! {span=> + const _: () = { + #[deprecated(note = #note)] + const SHOPIFY_DEPRECATION: () = (); + SHOPIFY_DEPRECATION + }; + } +} + struct InputTypes<'a> { schema: &'a Schema, krate: &'a TokenStream, diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs index ebedd6d..34db2e0 100644 --- a/crates/shopify_api_graphql/src/lib.rs +++ b/crates/shopify_api_graphql/src/lib.rs @@ -1,17 +1,20 @@ //! Compile-time support for the typed Shopify Admin GraphQL operations of //! [`shopify_api`](https://docs.rs/shopify_api). //! -//! [`analyze`](fn@analyze) checks an operation against a [`Schema`] and describes the -//! shape of its variables and of its result; [`codegen`] turns that -//! description into Rust types. The `graphql!` macro is a thin layer over -//! both. [`project`] finds the API version of a crate (the one its -//! `Cargo.toml` declares, else the latest), and downloads that version's -//! schema (with the `download` feature). No schema is bundled. +//! [`analyze`](fn@analyze) checks an operation against a [`Schema`] and +//! describes the shape of its variables and of its result; [`codegen`] turns +//! that description into Rust types. [`literal`] checks the values written in +//! Rust for input types (`{ title: "x" }`) and writes the code that sends +//! them. The `graphql!` macro is a thin layer over them. [`project`] finds +//! the API version of a crate (the one its `Cargo.toml` declares, else the +//! latest), and downloads that version's schema (with the `download` +//! feature). No schema is bundled. #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] pub mod analyze; pub mod codegen; +pub mod literal; pub mod project; mod restrict; pub mod schema; diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs new file mode 100644 index 0000000..c809444 --- /dev/null +++ b/crates/shopify_api_graphql/src/literal.rs @@ -0,0 +1,918 @@ +//! Values written in Rust for an input type: the variables of an inline +//! `graphql!`, and `input!`. The macros parse them into [`Value`]s; +//! [`Literals`] checks each one against the type expected where it stands +//! and writes the code that sends it. +//! +//! What a value means depends on that type: +//! +//! - `null` is `null`, where the type is nullable; +//! - `{ field: value, field?: option, … }` is an object where an input object +//! is expected, every field checked; +//! - `[value, …]` and `[for pattern in iterable if condition => value]` are +//! lists where a list is expected; +//! - a lone identifier is a value of the enum where an enum is expected, +//! `raw(string)` a value nothing checks; +//! - anything else is a Rust expression, whose type rustc checks with a +//! trait written for the place: it names the GraphQL type when it refuses +//! one. An `Option` is refused in a field: `field?:` leaves the field out +//! when it is `None`, `field: null` sends `null`. + +use std::collections::BTreeMap; +use std::fmt; + +use proc_macro2::{Ident, Span, TokenStream}; +use quote::{format_ident, quote, quote_spanned}; + +use crate::analyze::{Scalar, Variable, did_you_mean}; +use crate::codegen::{deprecation_warning, input_object_id, variable_type}; +use crate::schema::{InputValue, Schema, TypeDef, TypeRef}; + +/// A value, as the macros parse it. +#[derive(Debug, Clone)] +pub enum Value { + /// `null`. + Null(Span), + /// `raw(value)`, `keyword` being the span of `raw`. + Raw { + keyword: Span, + value: Expr, + }, + /// A lone identifier: a value of the enum where an enum is expected, a + /// Rust variable elsewhere. + Ident(Ident), + Object(Object), + List(List), + For(Box), + /// Any other Rust expression. + Rust(Expr), +} + +/// A Rust expression, and where to point at it. +#[derive(Debug, Clone)] +pub struct Expr { + pub tokens: TokenStream, + pub span: Span, +} + +/// `{ field: value, … }`. +#[derive(Debug, Clone)] +pub struct Object { + /// Of the braces. + pub span: Span, + pub fields: Vec, +} + +#[derive(Debug, Clone)] +pub struct Field { + /// The name of the GraphQL field, `type` included. + pub name: String, + pub name_span: Span, + /// The span of the `?` of `field?: value`. + pub optional: Option, + pub value: Value, +} + +/// `[value, …]`. +#[derive(Debug, Clone)] +pub struct List { + /// Of the brackets. + pub span: Span, + pub items: Vec, + /// The same text read as a Rust array expression, when it is one. + pub rust: Option, +} + +/// `[for pattern in iterable if filter => item]`. +#[derive(Debug, Clone)] +pub struct For { + /// Of the brackets. + pub span: Span, + pub pattern: TokenStream, + pub iterable: TokenStream, + pub filter: Option, + pub item: Value, +} + +/// A value that does not fit the schema, and the token at fault. +#[derive(Debug, Clone)] +pub struct Error { + pub span: Span, + pub message: String, +} + +impl fmt::Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.message) + } +} + +impl std::error::Error for Error {} + +fn error(span: Span, message: impl Into) -> Result { + Err(Error { + span, + message: message.into(), + }) +} + +/// How an inline variable is set on the operation. +#[derive(Debug, Clone)] +pub enum VariableValue { + /// A Rust expression converted to `ty` by `IntoVariable`, as + /// `Operation::variable::` does. + Converted { ty: TokenStream, value: Expr }, + /// An expression of the JSON of the value, for + /// `Operation::__literal_variable`. + Literal(TokenStream), +} + +/// Where a value stands, for messages. +#[derive(Clone)] +enum Site { + Variable(String), + Field { name: String, parent: String }, + Item(Box), +} + +impl fmt::Display for Site { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Variable(name) => write!(formatter, "`${name}`"), + Self::Field { name, parent } => write!(formatter, "`{name}` of `{parent}`"), + Self::Item(site) => write!(formatter, "an item of {site}"), + } + } +} + +/// What a value of a type may be: an `Option` stands for a nullable +/// variable or list item, not for a field. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Place { + Variable, + Field, + Item, +} + +/// Checks values against a schema and writes their code. The code refers +/// to items [`Literals::finish`] returns, to put in the same block. +pub struct Literals<'a> { + schema: &'a Schema, + krate: TokenStream, + items: Vec, + count: usize, +} + +impl fmt::Debug for Literals<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("Literals") + .field("api_version", &self.schema.api_version) + .field("items", &self.items.len()) + .finish() + } +} + +impl<'a> Literals<'a> { + /// `krate` is the path of the `shopify_api` crate in the generated code. + pub fn new(schema: &'a Schema, krate: TokenStream) -> Self { + Self { + schema, + krate, + items: Vec::new(), + count: 0, + } + } + + /// The traits, functions and warnings the code written so far needs. + pub fn finish(self) -> TokenStream { + let items = self.items; + quote!(#(#items)*) + } + + /// The value of an inline variable. A Rust expression for a scalar, a + /// list of scalars, or `raw(…)` for an enum, converts as it always did + /// (`IntoVariable`, an `Option` sending `null`); anything else is written + /// as JSON when the operation is built. + pub fn variable(&mut self, variable: &Variable, value: &Value) -> Result { + let ty = &variable.ty; + let site = Site::Variable(variable.name.clone()); + let scalar = matches!(self.schema.get(ty.name()), Some(TypeDef::Scalar)); + let converted = |value: Expr| VariableValue::Converted { + ty: variable_type(variable, &self.krate) + .expect("a variable of a scalar or an enum has a Rust type"), + value, + }; + match value { + Value::Rust(expr) if scalar => return Ok(converted(expr.clone())), + Value::Ident(ident) if scalar => return Ok(converted(ident_expr(ident))), + Value::List(List { + items, + rust: Some(rust), + .. + }) if scalar + && items + .iter() + .all(|item| matches!(item, Value::Rust(_) | Value::Ident(_))) => + { + return Ok(converted(rust.clone())); + } + Value::Raw { keyword, value } => { + self.enum_only(ty, *keyword, &site)?; + return Ok(converted(value.clone())); + } + _ => {} + } + let code = self.value(value, ty, &site, Place::Variable)?; + let krate = &self.krate; + Ok(VariableValue::Literal( + quote!(#krate::__private::literal::to_raw(&#code)), + )) + } + + /// `input!(name { … })`: an `InputObject` of the input object `name`. + pub fn input_object( + &mut self, + name: &str, + span: Span, + object: &Object, + ) -> Result { + let schema = self.schema; + let fields = match schema.get(name) { + Some(TypeDef::Input { fields }) => fields, + Some(other) => { + return error( + span, + format!( + "`{name}` is {}, not an input object: `input!` builds the input objects of the schema", + other.kind_name() + ), + ); + } + None => { + let inputs = schema + .types + .iter() + .filter(|(_, definition)| matches!(definition, TypeDef::Input { .. })) + .map(|(name, _)| name.as_str()); + return error( + span, + format!( + "The schema has no input object `{name}`{}", + did_you_mean(name, inputs) + ), + ); + } + }; + let code = self.object(name, fields, object)?; + let krate = &self.krate; + let id = input_object_id(name); + Ok(quote_spanned! {span=> + #krate::InputObject::<#id>::__new(#name, &#code) + }) + } + + /// The code of a value of type `ty`: an expression of a serializable value. + fn value( + &mut self, + value: &Value, + ty: &TypeRef, + site: &Site, + place: Place, + ) -> Result { + let krate = self.krate.clone(); + let inner = ty.nullable(); + match value { + Value::Null(span) => { + if ty.is_non_null() { + return error( + *span, + format!("`null` is not allowed for {site}, of type `{ty}`"), + ); + } + Ok(quote_spanned!(*span=> ())) + } + Value::Raw { keyword, value } => { + self.enum_only(ty, *keyword, site)?; + let tokens = &value.tokens; + Ok(quote_spanned!(value.span=> #krate::__private::literal::raw(#tokens))) + } + Value::Ident(ident) => match self.enum_values(inner) { + Some((name, values, deprecated)) => { + self.enum_value(ident, name, values, deprecated, site) + } + None => self.expression(&ident_expr(ident), ty, site, place), + }, + Value::Object(object) => match self.input_fields(inner) { + Some((name, fields)) => self.object(name, fields, object), + None => error( + object.span, + format!("{site} expects {}, not an object", self.what(ty)), + ), + }, + Value::List(list) => match (inner, &list.rust) { + (TypeRef::List(item), _) => { + let site = Site::Item(Box::new(site.clone())); + let mut items = Vec::new(); + for value in &list.items { + items.push(self.value(value, item, &site, Place::Item)?); + } + let nested = items + .iter() + .rev() + .fold(quote!(()), |rest, item| quote!((#item, #rest))); + Ok(quote!(#krate::__private::literal::List(#nested))) + } + (_, Some(rust)) => self.expression(rust, ty, site, place), + (_, None) => error( + list.span, + format!("{site} expects {}, not a list", self.what(ty)), + ), + }, + Value::For(comprehension) => { + let TypeRef::List(item) = inner else { + return error( + comprehension.span, + format!("{site} expects {}, not a list", self.what(ty)), + ); + }; + let site = Site::Item(Box::new(site.clone())); + let value = self.value(&comprehension.item, item, &site, Place::Item)?; + let For { + pattern, + iterable, + filter, + .. + } = &**comprehension; + // Each item is written in its turn of the loop, so that it may + // borrow what the loop gives. + let items = Ident::new("__shopify_api_items", Span::mixed_site()); + let push = quote!(#items.push(#krate::__private::literal::to_raw(&#value));); + let body = match filter { + Some(filter) => quote!(if #filter { #push }), + None => push, + }; + Ok(quote! {{ + let mut #items = ::std::vec::Vec::new(); + for #pattern in #iterable { #body } + #items + }}) + } + Value::Rust(expr) => self.expression(expr, ty, site, place), + } + } + + /// The fields of an object literal, for the input object `name`. + fn object( + &mut self, + name: &str, + definitions: &BTreeMap, + object: &Object, + ) -> Result { + let krate = self.krate.clone(); + let mut given: Vec<&str> = Vec::new(); + let mut fields = Vec::new(); + for field in &object.fields { + let key = field.name.as_str(); + let Some(definition) = definitions.get(key) else { + return error( + field.name_span, + format!( + "Input object `{name}` has no field `{key}`{}", + did_you_mean(key, definitions.keys().map(String::as_str)) + ), + ); + }; + if given.contains(&key) { + return error( + field.name_span, + format!("The field `{key}` of `{name}` is given twice"), + ); + } + given.push(key); + if let Some(reason) = &definition.deprecation { + let note = format!( + "`{name}.{key}` is deprecated in the Shopify Admin API {}: {reason}", + self.schema.api_version + ); + self.items.push(deprecation_warning(field.name_span, ¬e)); + } + let site = Site::Field { + name: key.to_string(), + parent: name.to_string(), + }; + let code = match field.optional { + Some(question) => { + if definition.is_required() { + return error( + question, + format!( + "{site} is required (`{}`): it cannot be left out, so `?:` does not apply; write `{key}: …`", + definition.ty + ), + ); + } + let value = self.optional(field, definition, &site)?; + quote!(#krate::__private::literal::Optional(#key, #value)) + } + None => { + let value = self.value(&field.value, &definition.ty, &site, Place::Field)?; + quote!(#krate::__private::literal::Field(#key, #value)) + } + }; + fields.push(code); + } + let missing: Vec = definitions + .iter() + .filter(|(key, definition)| definition.is_required() && !given.contains(&key.as_str())) + .map(|(key, definition)| format!("`{key}: {}`", definition.ty)) + .collect(); + if !missing.is_empty() { + let (fields, them) = if missing.len() == 1 { + ("field", "it") + } else { + ("fields", "them") + }; + return error( + object.span, + format!( + "Input object `{name}` requires the {fields} {}: add {them}", + join(&missing, "and") + ), + ); + } + let nested = fields + .iter() + .rev() + .fold(quote!(()), |rest, field| quote!((#field, #rest))); + Ok(quote!(#krate::__private::literal::Object(#nested))) + } + + /// `field?: value`, the field being optional: `Maybe` of the value. + fn optional( + &mut self, + field: &Field, + definition: &InputValue, + site: &Site, + ) -> Result { + let krate = self.krate.clone(); + let key = &field.name; + // Non-null with a default: absent is fine, `null` is not. + let null_refused = definition.ty.is_non_null(); + let expr = match &field.value { + Value::Raw { keyword, value } => { + self.enum_only(&definition.ty, *keyword, site)?; + let tokens = &value.tokens; + let convert = if null_refused { + quote!(raw_option) + } else { + quote!(raw_optional) + }; + return Ok( + quote_spanned!(value.span=> #krate::__private::literal::#convert(#tokens)), + ); + } + Value::Rust(expr) => expr.clone(), + Value::Ident(ident) => ident_expr(ident), + Value::Null(span) => { + return error(*span, format!("`{key}?: null` is `{key}: null`")); + } + Value::Object(Object { span, .. }) | Value::List(List { span, .. }) => { + return error(*span, literal_after_question(key)); + } + Value::For(comprehension) => { + return error(comprehension.span, literal_after_question(key)); + } + }; + if self.is_enum(&definition.ty) { + return error( + expr.span, + format!( + "{site} holds a value of the enum `{}`: for a string known at run time, write `{key}?: raw(…)`, with an `Option` of it", + definition.ty.name() + ), + ); + } + + let value_bound = self.expect(&definition.ty, Place::Field, site); + let n = self.next(); + let bound = format_ident!("__ShopifyApiOptional{n}"); + let check = format_ident!("__shopify_api_optional{n}"); + let what = escape(&self.what(&definition.ty)); + let (message, label, maybe_bound) = if null_refused { + let no_null = format_ident!("__ShopifyApiNoNull{n}"); + let refusal = escape(&format!( + "{site} is non-null (`{}`): `{key}?:` takes an `Option`, not a `Maybe`, whose `Null` it refuses", + definition.ty + )); + self.items.push(quote! { + #[diagnostic::on_unimplemented(message = #refusal, label = "an `Option`: `None` leaves the field out")] + trait #no_null {} + }); + ( + format!("`{key}?:` takes an `Option` of {what}, not `{{Self}}`"), + "`None` leaves the field out".to_string(), + quote!(#value_bound + #no_null), + ) + } else { + ( + format!( + "`{key}?:` takes an `Option` or a `shopify_api::Maybe` of {what}, not `{{Self}}`" + ), + "`None` and `Maybe::Absent` leave the field out, `Maybe::Null` sends `null`" + .to_string(), + quote!(#value_bound), + ) + }; + // `IntoMaybe` as a supertrait: one refusal, which names the field. + self.items.push(quote! { + #[diagnostic::on_unimplemented(message = #message, label = #label)] + trait #bound: #krate::__private::literal::IntoMaybe {} + impl #bound for ::core::option::Option {} + impl #bound for #krate::Maybe {} + fn #check>(value: V) -> #krate::Maybe { + #krate::__private::literal::IntoMaybe::into_maybe(value) + } + }); + let tokens = &expr.tokens; + Ok(quote_spanned!(expr.span=> #check(#tokens))) + } + + /// A Rust expression for a value of type `ty`, checked by a trait. + fn expression( + &mut self, + expr: &Expr, + ty: &TypeRef, + site: &Site, + place: Place, + ) -> Result { + if self.is_enum(ty) { + let name = ty.name(); + let message = match ty.nullable() { + TypeRef::List(_) => format!( + "{site} expects a list of values of the enum `{name}`: write them bare, `[{}, …]`, or `[for value in … => raw(value)]` for strings known at run time", + self.first_value(name) + ), + _ => format!( + "{site} expects a value of the enum `{name}`: write it bare, as `{}`, or `raw(…)` for a string known at run time", + self.first_value(name) + ), + }; + return error(expr.span, message); + } + let bound = self.expect(ty, place, site); + let check = format_ident!("__shopify_api_check{}", self.next()); + self.items.push(quote! { + fn #check(value: V) -> V { + value + } + }); + let tokens = &expr.tokens; + Ok(quote_spanned!(expr.span=> #check(#tokens))) + } + + /// The trait a Rust expression of type `ty` must implement at `place`, + /// whose refusal names the GraphQL type. + fn expect(&mut self, ty: &TypeRef, place: Place, site: &Site) -> Ident { + let bound = format_ident!("__ShopifyApiExpect{}", self.next()); + let krate = self.krate.clone(); + let what = self.what(ty); + let mut label = accepted(self.schema, ty.nullable()); + let mut impls = Vec::new(); + let inner = ty.nullable(); + if !ty.is_non_null() && place != Place::Field { + label.push_str(", or an `Option` of it, `None` sending `null`"); + let non_null = TypeRef::NonNull(Box::new(inner.clone())); + let value = self.expect(&non_null, place, site); + impls.push(quote!(impl #bound for V {})); + impls.push(quote!(impl #bound for ::core::option::Option {})); + } else { + match inner { + TypeRef::List(item) => { + let item = self.expect(item, Place::Item, &Site::Item(Box::new(site.clone()))); + impls.push(quote! { + impl #bound for ::std::vec::Vec {} + impl<'a, V: #item> #bound for &'a ::std::vec::Vec {} + impl<'a, V: #item> #bound for &'a [V] {} + impl #bound for [V; N] {} + }); + } + TypeRef::Named(name) => match self.schema.get(name) { + Some(TypeDef::Input { .. }) => { + let id = input_object_id(name); + impls.push(quote! { + impl #bound for #krate::InputObject<#id> {} + impl<'a> #bound for &'a #krate::InputObject<#id> {} + }); + } + _ => { + for ty in scalar_types(Scalar::of(name), &krate) { + impls.push(quote!(impl<'a> #bound for #ty {})); + } + } + }, + TypeRef::NonNull(_) => unreachable!("`nullable` removes the `!`"), + } + if place == Place::Field { + impls.push(self.no_option(&bound, ty, site)); + } + } + // The type of an `InputObject` is a hash: the message names the + // expected GraphQL type and leaves the given one to rustc's help. + let given = if self.holds_input(ty) { + "" + } else { + ", not `{Self}`" + }; + let message = format!( + "{} expects {}{given}", + escape(&site.to_string()), + escape(&what) + ); + let label = escape(&label); + self.items.push(quote! { + #[diagnostic::on_unimplemented(message = #message, label = #label)] + trait #bound {} + #(#impls)* + }); + bound + } + + /// Refuses an `Option` in a field, saying what to write instead: sending + /// `null` for `None` would clear the field. + fn no_option(&mut self, bound: &Ident, ty: &TypeRef, site: &Site) -> TokenStream { + let n = self.next(); + let no_option = format_ident!("__ShopifyApiNoOption{n}"); + let Site::Field { name, .. } = site else { + unreachable!("a field has a field site") + }; + let what = self.what(ty); + let (message, label) = if ty.is_non_null() { + ( + format!("{site} is required (`{ty}`): it takes {what}, not an `Option`"), + "the field is required: give a value".to_string(), + ) + } else { + ( + format!( + "{site} takes {what}, not an `Option`: write `{name}?: value` to leave the field out when it is `None`, or `{name}: null` to send `null`" + ), + format!("`{name}: None` would send `null`, which clears the field"), + ) + }; + let (message, label) = (escape(&message), escape(&label)); + quote! { + #[diagnostic::on_unimplemented(message = #message, label = #label)] + trait #no_option {} + impl #bound for ::core::option::Option {} + } + } + + /// A value of the enum `name`, written bare. + fn enum_value( + &mut self, + ident: &Ident, + name: &str, + values: &[String], + deprecated: &BTreeMap, + site: &Site, + ) -> Result { + let given = unraw(ident); + if !values.contains(&given) { + let listed: Vec = values + .iter() + .take(LISTED_VALUES) + .map(|value| format!("`{value}`")) + .collect(); + let mut list = join(&listed, "or"); + if values.len() > LISTED_VALUES { + list = format!("{}, … ({} values)", listed.join(", "), values.len()); + } + let run_time = if given.chars().any(char::is_lowercase) { + format!("; for a string known at run time, write `raw({given})`") + } else { + String::new() + }; + return error( + ident.span(), + format!( + "`{given}` is not a value of the enum `{name}`{}: {site} takes {list}{run_time}", + did_you_mean(&given, values.iter().map(String::as_str)) + ), + ); + } + if let Some(reason) = deprecated.get(&given) { + let note = format!( + "`{name}.{given}` is deprecated in the Shopify Admin API {}: {reason}", + self.schema.api_version + ); + self.items.push(deprecation_warning(ident.span(), ¬e)); + } + Ok(quote_spanned!(ident.span()=> #given)) + } + + /// Refuses `raw(…)` where no enum value is expected. + fn enum_only(&self, ty: &TypeRef, keyword: Span, site: &Site) -> Result<(), Error> { + if self.enum_values(ty.nullable()).is_some() { + return Ok(()); + } + error( + keyword, + format!( + "`raw(…)` is only for a value of an enum: {site} expects {}", + self.what(ty) + ), + ) + } + + fn enum_values( + &self, + ty: &TypeRef, + ) -> Option<(&'a str, &'a [String], &'a BTreeMap)> { + let schema = self.schema; + match ty { + TypeRef::Named(name) => match schema.get(name) { + Some(TypeDef::Enum { values, deprecated }) => { + let (name, _) = schema.types.get_key_value(name)?; + Some((name.as_str(), values.as_slice(), deprecated)) + } + _ => None, + }, + _ => None, + } + } + + fn input_fields(&self, ty: &TypeRef) -> Option<(&'a str, &'a BTreeMap)> { + let schema = self.schema; + match ty { + TypeRef::Named(name) => match schema.get(name) { + Some(TypeDef::Input { fields }) => { + let (name, _) = schema.types.get_key_value(name)?; + Some((name.as_str(), fields)) + } + _ => None, + }, + _ => None, + } + } + + /// The innermost type of `ty` is an input object. + fn holds_input(&self, ty: &TypeRef) -> bool { + matches!(self.schema.get(ty.name()), Some(TypeDef::Input { .. })) + } + + /// The innermost type of `ty` is an enum. + fn is_enum(&self, ty: &TypeRef) -> bool { + matches!(self.schema.get(ty.name()), Some(TypeDef::Enum { .. })) + } + + fn first_value(&self, name: &str) -> &str { + match self.schema.get(name) { + Some(TypeDef::Enum { values, .. }) => values.first().map_or("VALUE", String::as_str), + _ => "VALUE", + } + } + + /// A type in words: "a `String`", "a list of `MetafieldsSetInput`, built with …". + fn what(&self, ty: &TypeRef) -> String { + match ty.nullable() { + TypeRef::List(item) => format!("a list of {}", self.items_of(item)), + other => { + let name = other.name(); + match self.schema.get(name) { + Some(TypeDef::Input { .. }) => { + format!("a `{name}`, built with `input!({name} {{ … }})`") + } + Some(TypeDef::Enum { .. }) => format!("a value of the enum `{name}`"), + _ => { + let article = if name.starts_with(['A', 'E', 'I', 'O', 'U']) { + "an" + } else { + "a" + }; + match Scalar::of(name) { + Scalar::String if !matches!(name, "String") => { + format!("{article} `{name}` (a string)") + } + _ => format!("{article} `{name}`"), + } + } + } + } + } + } + + fn items_of(&self, ty: &TypeRef) -> String { + match ty.nullable() { + TypeRef::List(item) => format!("lists of {}", self.items_of(item)), + other => { + let name = other.name(); + match self.schema.get(name) { + Some(TypeDef::Input { .. }) => { + format!("`{name}`, built with `input!({name} {{ … }})`") + } + Some(TypeDef::Enum { .. }) => format!("values of the enum `{name}`"), + _ => format!("`{name}`"), + } + } + } + } + + fn next(&mut self) -> usize { + self.count += 1; + self.count + } +} + +fn literal_after_question(key: &str) -> String { + format!( + "`{key}?:` takes a Rust expression, an `Option` or a `shopify_api::Maybe` whose `None` leaves the field out; write `{key}: …` for this value" + ) +} + +/// How many values of an enum a message lists. +const LISTED_VALUES: usize = 30; + +/// The Rust types accepted for a value of `ty`, the `!` removed. +fn accepted(schema: &Schema, ty: &TypeRef) -> String { + match ty { + TypeRef::List(_) => "a `Vec`, a slice or an array".to_string(), + other => { + let name = other.name(); + if let Some(TypeDef::Input { .. }) = schema.get(name) { + return format!("build it with `input!({name} {{ … }})`"); + } + match Scalar::of(name) { + Scalar::String => "`String`, `&str`, `&String` or `Cow`", + Scalar::Int => "any integer type", + Scalar::Float => "`f64`, `f32`, `i32` or `u32`", + Scalar::Boolean => "`bool`", + Scalar::Json => "`serde_json::Value` or `&Value`", + } + .to_string() + } + } +} + +/// The Rust types of a scalar, as `IntoVariable` accepts them; they may +/// borrow for `'a`. +fn scalar_types(scalar: Scalar, krate: &TokenStream) -> Vec { + match scalar { + Scalar::String => vec![ + quote!(::std::string::String), + quote!(&'a ::core::primitive::str), + quote!(&'a ::std::string::String), + quote!(::std::borrow::Cow<'a, ::core::primitive::str>), + ], + Scalar::Int => [ + "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "usize", "isize", + ] + .iter() + .map(|name| { + let ident = Ident::new(name, Span::call_site()); + quote!(::core::primitive::#ident) + }) + .collect(), + Scalar::Float => ["f32", "f64", "i32", "u32"] + .iter() + .map(|name| { + let ident = Ident::new(name, Span::call_site()); + quote!(::core::primitive::#ident) + }) + .collect(), + Scalar::Boolean => vec![quote!(::core::primitive::bool)], + Scalar::Json => vec![ + quote!(#krate::__private::serde_json::Value), + quote!(&'a #krate::__private::serde_json::Value), + ], + } +} + +fn ident_expr(ident: &Ident) -> Expr { + Expr { + tokens: quote!(#ident), + span: ident.span(), + } +} + +/// The name of an identifier, without the `r#` of a raw one. +fn unraw(ident: &Ident) -> String { + let name = ident.to_string(); + match name.strip_prefix("r#") { + Some(name) => name.to_string(), + None => name, + } +} + +/// `a`, `a and b`, `a, b and c`. +fn join(items: &[String], last: &str) -> String { + match items { + [] => String::new(), + [one] => one.clone(), + [init @ .., tail] => format!("{} {last} {tail}", init.join(", ")), + } +} + +/// Text for `#[diagnostic::on_unimplemented]`, where braces are placeholders. +fn escape(text: &str) -> String { + text.replace('{', "{{").replace('}', "}}") +} diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs new file mode 100644 index 0000000..dfd4120 --- /dev/null +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -0,0 +1,463 @@ +//! Values written in Rust for input types, checked against the Shopify Admin +//! schema 2026-10: what is refused, with which message, and how what is +//! accepted is sent. + +use std::collections::BTreeMap; +use std::sync::OnceLock; + +use proc_macro2::{Ident, Span}; +use quote::quote; +use shopify_api_graphql::codegen::input_object_id; +use shopify_api_graphql::literal::{ + Expr, Field, For, List, Literals, Object, Value, VariableValue, +}; +use shopify_api_graphql::{Schema, TypeDef, analyze}; + +fn admin() -> &'static Schema { + static ADMIN: OnceLock = OnceLock::new(); + ADMIN.get_or_init(|| { + Schema::from_json(include_str!("../../shopify_api/graphql/admin.schema.json")).unwrap() + }) +} + +fn rust(text: &str) -> Value { + Value::Rust(Expr { + tokens: text.parse().unwrap(), + span: Span::call_site(), + }) +} + +fn ident(name: &str) -> Value { + Value::Ident(Ident::new(name, Span::call_site())) +} + +fn null() -> Value { + Value::Null(Span::call_site()) +} + +fn raw(text: &str) -> Value { + Value::Raw { + keyword: Span::call_site(), + value: Expr { + tokens: text.parse().unwrap(), + span: Span::call_site(), + }, + } +} + +/// An object; a name ending with `?` is `name?: value`. +fn object(fields: Vec<(&str, Value)>) -> Object { + Object { + span: Span::call_site(), + fields: fields + .into_iter() + .map(|(name, value)| Field { + name: name.trim_end_matches('?').to_string(), + name_span: Span::call_site(), + optional: name.ends_with('?').then(Span::call_site), + value, + }) + .collect(), + } +} + +fn list(items: Vec) -> Value { + Value::List(List { + span: Span::call_site(), + items, + rust: None, + }) +} + +/// The code of `input!(name { … })` and the items it needs, or the refusal. +fn input(name: &str, fields: Vec<(&str, Value)>) -> Result<(String, String), String> { + let mut literals = Literals::new(admin(), quote!(::shopify_api)); + let code = literals + .input_object(name, Span::call_site(), &object(fields)) + .map_err(|error| error.message)?; + Ok((code.to_string(), literals.finish().to_string())) +} + +fn refusal(name: &str, fields: Vec<(&str, Value)>) -> String { + match input(name, fields) { + Ok((code, _)) => panic!("accepted: {code}"), + Err(message) => message, + } +} + +#[test] +fn an_object_is_sent_field_by_field_in_its_order() { + let (code, items) = input( + "ProductUpdateInput", + vec![ + ("id", rust("product_id")), + ("title", rust("format!(\"{name} (promo)\")")), + ("status", ident("ACTIVE")), + ("descriptionHtml", null()), + ("vendor?", rust("new_vendor")), + ( + "seo", + Value::Object(object(vec![("title", rust("seo_title"))])), + ), + ( + "metafields", + Value::For(Box::new(For { + span: Span::call_site(), + pattern: quote!(m), + iterable: quote!(&rows), + filter: Some(quote!(!m.value.is_empty())), + item: Value::Object(object(vec![ + ("key", rust("&m.key")), + ("type", rust("\"single_line_text_field\"")), + ])), + })), + ), + ("tags", list(vec![rust("\"a\""), rust("tag")])), + ], + ) + .unwrap(); + let id = input_object_id("ProductUpdateInput"); + assert!( + code.starts_with(&format!( + ":: shopify_api :: InputObject :: < {id}u64 > :: __new (\"ProductUpdateInput\" , & :: shopify_api :: __private :: literal :: Object ((:: shopify_api :: __private :: literal :: Field (\"id\" , __shopify_api_check" + )), + "{code}" + ); + let keys: Vec<&str> = code + .match_indices("literal :: Field (\"") + .chain(code.match_indices("literal :: Optional (\"")) + .map(|(at, matched)| { + let rest = &code[at + matched.len()..]; + &rest[..rest.find('"').unwrap()] + }) + .collect(); + assert_eq!( + keys, + [ + "id", + "title", + "status", + "descriptionHtml", + "seo", + "title", + "metafields", + "key", + "type", + "tags", + "vendor" + ] + ); + // The enum value is a string; `null` is `()`; the list is built in a loop. + assert!(code.contains("Field (\"status\" , \"ACTIVE\")"), "{code}"); + assert!(code.contains("Field (\"descriptionHtml\" , ())"), "{code}"); + assert!( + code.contains("for m in & rows { if ! m . value . is_empty ()"), + "{code}" + ); + // Each Rust expression goes through a trait that names its place. + assert!( + items.contains( + "message = \"`title` of `ProductUpdateInput` expects a `String`, not `{Self}`\"" + ), + "{items}" + ); + assert!( + items.contains("message = \"`vendor?:` takes an `Option` or a `shopify_api::Maybe` of a `String`, not `{Self}`\""), + "{items}" + ); + assert!( + items.contains("message = \"`vendor` of `ProductUpdateInput` takes a `String`, not an `Option`: write `vendor?: value` to leave the field out when it is `None`, or `vendor: null` to send `null`\""), + "{items}" + ); +} + +#[test] +fn fields_are_checked_against_the_input_object() { + assert_eq!( + refusal( + "ProductUpdateInput", + vec![("id", rust("id")), ("titel", rust("title"))] + ), + "Input object `ProductUpdateInput` has no field `titel` (did you mean `title`?)" + ); + assert_eq!( + refusal( + "ProductUpdateInput", + vec![("title", rust("a")), ("title", rust("b"))] + ), + "The field `title` of `ProductUpdateInput` is given twice" + ); + assert_eq!( + refusal( + "MetafieldsSetInput", + vec![("namespace", rust("\"custom\""))] + ), + "Input object `MetafieldsSetInput` requires the fields `key: String!`, `ownerId: ID!` and `value: String!`: add them" + ); + assert_eq!( + refusal( + "MetafieldsSetInput", + vec![("ownerId", rust("id")), ("key", rust("key"))] + ), + "Input object `MetafieldsSetInput` requires the field `value: String!`: add it" + ); + // The fields of a nested object, and of the items of a list. + assert_eq!( + refusal( + "ProductUpdateInput", + vec![( + "metafields", + list(vec![Value::Object(object(vec![("kee", rust("k"))]))]) + )] + ), + "Input object `MetafieldInput` has no field `kee` (did you mean `key`?)" + ); +} + +#[test] +fn null_and_absence_follow_nullability_and_defaults() { + assert_eq!( + refusal( + "MetafieldsSetInput", + vec![ + ("ownerId", null()), + ("key", rust("k")), + ("value", rust("v")) + ] + ), + "`null` is not allowed for `ownerId` of `MetafieldsSetInput`, of type `ID!`" + ); + assert_eq!( + refusal( + "MetafieldsSetInput", + vec![ + ("ownerId?", rust("id")), + ("key", rust("k")), + ("value", rust("v")) + ] + ), + "`ownerId` of `MetafieldsSetInput` is required (`ID!`): it cannot be left out, so `?:` does not apply; write `ownerId: …`" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("vendor?", null())]), + "`vendor?: null` is `vendor: null`" + ); + assert_eq!( + refusal( + "ProductUpdateInput", + vec![("seo?", Value::Object(object(vec![])))] + ), + "`seo?:` takes a Rust expression, an `Option` or a `shopify_api::Maybe` whose `None` leaves the field out; write `seo: …` for this value" + ); + // Non-null with a default: `?:` takes an `Option`, not a `Maybe`. + let (_, items) = input( + "InventoryTransferCreateInput", + vec![("lineItems?", rust("line_items"))], + ) + .unwrap(); + assert!( + items.contains("`lineItems` of `InventoryTransferCreateInput` is non-null (`[InventoryTransferLineItemInput!]!`): `lineItems?:` takes an `Option`, not a `Maybe`, whose `Null` it refuses"), + "{items}" + ); + assert!( + items.contains("message = \"`lineItems?:` takes an `Option` of a list of `InventoryTransferLineItemInput`, built with `input!(InventoryTransferLineItemInput {{ … }})`, not `{Self}`\""), + "{items}" + ); +} + +#[test] +fn enum_values_are_checked_and_raw_is_only_for_enums() { + assert_eq!( + refusal("ProductUpdateInput", vec![("status", ident("ACTIV"))]), + "`ACTIV` is not a value of the enum `ProductStatus` (did you mean `ACTIVE`?): `status` of `ProductUpdateInput` takes `ACTIVE`, `ARCHIVED`, `DRAFT` or `UNLISTED`" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("status", ident("status"))]), + "`status` is not a value of the enum `ProductStatus`: `status` of `ProductUpdateInput` takes `ACTIVE`, `ARCHIVED`, `DRAFT` or `UNLISTED`; for a string known at run time, write `raw(status)`" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("status", rust("\"ACTIVE\""))]), + "`status` of `ProductUpdateInput` expects a value of the enum `ProductStatus`: write it bare, as `ACTIVE`, or `raw(…)` for a string known at run time" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("status?", rust("status"))]), + "`status` of `ProductUpdateInput` holds a value of the enum `ProductStatus`: for a string known at run time, write `status?: raw(…)`, with an `Option` of it" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("title", raw("title"))]), + "`raw(…)` is only for a value of an enum: `title` of `ProductUpdateInput` expects a `String`" + ); + assert_eq!( + refusal( + "CollectionSourceInclusionConditionProductStatusInput", + vec![("values", rust("statuses"))] + ), + "`values` of `CollectionSourceInclusionConditionProductStatusInput` expects a list of values of the enum `ProductStatus`: write them bare, `[ACTIVE, …]`, or `[for value in … => raw(value)]` for strings known at run time" + ); + // A long enum is listed in part. + let exemptions = refusal( + "CompanyLocationInput", + vec![ + ("name", rust("name")), + ("taxExemptions", list(vec![ident("NONE")])), + ], + ); + assert!( + exemptions.starts_with("`NONE` is not a value of the enum `TaxExemption`: an item of `taxExemptions` of `CompanyLocationInput` takes `CA_STATUS_CARD_EXEMPTION`, "), + "{exemptions}" + ); + assert!(exemptions.ends_with(" values)"), "{exemptions}"); + + let (code, _) = input( + "ProductUpdateInput", + vec![("status", raw("status")), ("id", rust("id"))], + ) + .unwrap(); + assert!( + code.contains( + "Field (\"status\" , :: shopify_api :: __private :: literal :: raw (status))" + ), + "{code}" + ); +} + +#[test] +fn a_value_has_the_form_of_its_type() { + assert_eq!( + refusal( + "ProductUpdateInput", + vec![("title", Value::Object(object(vec![("value", rust("v"))])))] + ), + "`title` of `ProductUpdateInput` expects a `String`, not an object" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("title", list(vec![rust("t")]))]), + "`title` of `ProductUpdateInput` expects a `String`, not a list" + ); + // No single value where a list is expected. + assert_eq!( + refusal( + "ProductUpdateInput", + vec![("metafields", Value::Object(object(vec![])))] + ), + "`metafields` of `ProductUpdateInput` expects a list of `MetafieldInput`, built with `input!(MetafieldInput { … })`, not an object" + ); + assert_eq!( + refusal( + "ProductCreateInput", + vec![("productOptions", list(vec![null()]))] + ), + "`null` is not allowed for an item of `productOptions` of `ProductCreateInput`, of type `OptionCreateInput!`" + ); +} + +#[test] +fn input_takes_an_input_object_of_the_schema() { + assert_eq!( + refusal("MetafieldSetInput", vec![]), + "The schema has no input object `MetafieldSetInput` (did you mean `MetafieldsSetInput`?)" + ); + assert_eq!( + refusal("Product", vec![]), + "`Product` is an object, not an input object: `input!` builds the input objects of the schema" + ); +} + +#[test] +fn deprecated_fields_and_enum_values_warn() { + let (_, items) = input("ProductVariantsBulkInput", vec![("barcode", rust("code"))]).unwrap(); + assert!( + items.contains("deprecated (note = \"`ProductVariantsBulkInput.barcode` is deprecated in the Shopify Admin API 2026-10: Use `barcodes` instead.\")"), + "{items}" + ); + let (_, items) = input( + "DeliveryCarrierCalculatedOptionDefinitionUpdateInput", + vec![("id", rust("id")), ("currency", ident("ANG"))], + ) + .unwrap(); + assert!( + items.contains("deprecated (note = \"`CurrencyCode.ANG` is deprecated in the Shopify Admin API 2026-10: Use `XCG` instead.\")"), + "{items}" + ); +} + +fn variable(source: &str, value: Value) -> Result { + let operation = analyze(admin(), source).unwrap(); + let mut literals = Literals::new(admin(), quote!(::shopify_api)); + literals + .variable(&operation.variables[0], &value) + .map_err(|error| error.message) +} + +#[test] +fn inline_variables_of_scalars_convert_as_before_and_others_are_literals() { + let converted = |value: VariableValue| match value { + VariableValue::Converted { ty, value } => format!("{ty} = {}", value.tokens), + VariableValue::Literal(code) => panic!("a literal: {code}"), + }; + let ids = "query($ids: [ID!]!) { nodes(ids: $ids) { id } }"; + assert_eq!( + converted( + variable( + "query($first: Int!) { products(first: $first) { nodes { id } } }", + rust("{ compute() }") + ) + .unwrap() + ), + ":: core :: primitive :: i64 = { compute () }" + ); + let array = Value::List(List { + span: Span::call_site(), + items: vec![ident("a"), rust("&b")], + rust: Some(Expr { + tokens: quote!([a, &b]), + span: Span::call_site(), + }), + }); + assert_eq!( + converted(variable(ids, array).unwrap()), + ":: std :: vec :: Vec < :: std :: string :: String > = [a , & b]" + ); + let sort = "query($sortKey: ProductSortKeys) { products(first: 1, sortKey: $sortKey) { nodes { id } } }"; + assert_eq!( + converted(variable(sort, raw("key")).unwrap()), + ":: core :: option :: Option < :: std :: string :: String > = key" + ); + assert!(matches!( + variable(sort, ident("TITLE")).unwrap(), + VariableValue::Literal(_) + )); + assert_eq!( + variable(sort, rust("key")).unwrap_err(), + "`$sortKey` expects a value of the enum `ProductSortKeys`: write it bare, as `CREATED_AT`, or `raw(…)` for a string known at run time" + ); + assert_eq!( + variable(ids, raw("id")).unwrap_err(), + "`raw(…)` is only for a value of an enum: `$ids` expects a list of `ID`" + ); + let metafields = "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }"; + let VariableValue::Literal(code) = variable(metafields, rust("rows")).unwrap() else { + panic!("a literal"); + }; + assert!(code.to_string().contains("__shopify_api_check"), "{code}"); + assert_eq!( + variable(metafields, Value::Object(object(vec![]))).unwrap_err(), + "`$metafields` expects a list of `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })`, not an object" + ); +} + +#[test] +fn input_object_ids_differ_for_every_input_object_of_the_schema() { + // FNV-1a: the same in every crate and every build. + assert_eq!(input_object_id(""), 0xcbf2_9ce4_8422_2325); + assert_eq!(input_object_id("a"), 0xaf63_dc4c_8601_ec8c); + let mut seen = BTreeMap::new(); + for (name, definition) in &admin().types { + if let TypeDef::Input { .. } = definition + && let Some(other) = seen.insert(input_object_id(name), name) + { + panic!("`{name}` and `{other}` have the same id"); + } + } + assert!(seen.len() > 500); +} diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 1e688a6..aa24f50 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -2,6 +2,8 @@ //! which re-exports and documents it. #![forbid(unsafe_code)] +mod value; + use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; @@ -10,8 +12,9 @@ use std::time::SystemTime; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, quote_spanned}; use shopify_api_graphql::codegen::{ - DATA_TYPE, VARIABLES_TYPE, data_types, variable_type, variables_types, + DATA_TYPE, VARIABLES_TYPE, data_types, deprecation_warning, variables_types, }; +use shopify_api_graphql::literal::{self, Literals, Value, VariableValue}; use shopify_api_graphql::project::{ DownloadError, metadata_snippet, previous_api_version, up_to_date_schema, }; @@ -21,7 +24,7 @@ use shopify_api_graphql::{ }; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; -use syn::{Attribute, Expr, Ident, LitStr, Token, Visibility}; +use syn::{Attribute, Ident, LitStr, Token, Visibility}; /// The schema of `shopify_api`'s own operations, relative to its `Cargo.toml`: /// the Admin schema cut down to what they use. A crate that depends on @@ -68,7 +71,7 @@ impl Parse for Source { enum Input { Expression { source: Source, - variables: Vec<(Ident, Expr)>, + variables: Vec<(Ident, Value)>, }, Modules(Vec), } @@ -141,7 +144,7 @@ impl Parse for Input { syn::Error::new(error.span(), "expected a variable: `name = value`") })?; input.parse::()?; - variables.push((name, input.parse()?)); + variables.push((name, value::parse_value(input)?)); } Ok(Self::Expression { source, variables }) } @@ -290,6 +293,18 @@ impl LoadedSchema { } } + /// A refusal of a literal value, at its token. + fn literal_error(&self, error: literal::Error) -> syn::Error { + syn::Error::new( + error.span, + format!( + "{}\n(checked against the Shopify Admin API {})", + error.message, + self.schema().api_version + ), + ) + } + /// Checks an operation, pointing a refusal at its text. fn check(&self, text: &Text) -> syn::Result { analyze(self.schema(), &text.query.value()).map_err(|error| { @@ -390,13 +405,7 @@ fn deprecation_warnings(schema: &Schema, operation: &Operation, text: &Text) -> "`{}` is deprecated in the Shopify Admin API {}: {} (line {line}, column {column} of the operation)", deprecation.coordinate, schema.api_version, deprecation.reason ); - quote_spanned! {text.span()=> - const _: () = { - #[deprecated(note = #note)] - const SHOPIFY_DEPRECATION: () = (); - SHOPIFY_DEPRECATION - }; - } + deprecation_warning(text.span(), ¬e) }); quote!(#(#warnings)*) } @@ -429,14 +438,14 @@ fn constructor( fn expand_expression( schema: &LoadedSchema, source: &Source, - variables: &[(Ident, Expr)], + variables: &[(Ident, Value)], ) -> syn::Result { let krate = quote!(::shopify_api); let text = Text::read(source)?; let operation = schema.check(&text)?; // Each value with the variable it is for. - let mut given: Vec<(&Variable, &Expr)> = Vec::new(); + let mut given: Vec<(&Variable, &Value)> = Vec::new(); for (name, value) in variables { let Some(declared) = operation .variables @@ -486,22 +495,31 @@ fn expand_expression( // Evaluated before the generated types are in scope, so that the // values cannot name them by accident. - let locals: Vec = (0..given.len()) - .map(|index| { - Ident::new( - &format!("__shopify_api_variable_{index}"), - Span::mixed_site(), - ) - }) - .collect(); - let values = given.iter().map(|(_, value)| value); - let setters = given.iter().zip(&locals).map(|((declared, value), local)| { + let mut literals = Literals::new(schema.schema(), krate.clone()); + let mut values = Vec::new(); + let mut setters = Vec::new(); + for (index, (declared, value)) in given.iter().enumerate() { + let local = Ident::new( + &format!("__shopify_api_variable_{index}"), + Span::mixed_site(), + ); let key = &declared.name; - match variable_type(declared, &krate) { - Some(ty) => quote_spanned!(value.span()=> .variable::<#ty, _>(#key, #local)), - None => quote_spanned!(value.span()=> .json_variable(#key, #local)), + match literals + .variable(declared, value) + .map_err(|error| schema.literal_error(error))? + { + VariableValue::Converted { ty, value } => { + let tokens = &value.tokens; + values.push(quote!(let #local = #tokens;)); + setters.push(quote_spanned!(value.span=> .variable::<#ty, _>(#key, #local))); + } + VariableValue::Literal(code) => { + values.push(quote!(let #local = #code;)); + setters.push(quote!(.__literal_variable(#key, #local))); + } } - }); + } + let checks = literals.finish(); let tracking = schema.tracking(); let file = text.tracking(); @@ -510,7 +528,8 @@ fn expand_expression( let query = &text.query; let constructor = constructor(schema.schema(), &operation, "e!(#query), &krate); Ok(quote! {{ - #(let #locals = #values;)* + #checks + #(#values)* { #tracking #file diff --git a/crates/shopify_api_macros/src/value.rs b/crates/shopify_api_macros/src/value.rs new file mode 100644 index 0000000..ff0bffd --- /dev/null +++ b/crates/shopify_api_macros/src/value.rs @@ -0,0 +1,306 @@ +//! Reads the values of inline variables and of `input!` into +//! [`Value`]s, which `shopify_api_graphql::literal` checks against the +//! schema. +//! +//! The text alone decides what is read; the type expected where the value +//! stands decides what it means: +//! +//! - `{` starts an object when it is empty or starts with `name:` or +//! `name?:`, which no Rust block does; `{ compute() }` stays a block. +//! - `[a, b]` is kept both as a list of values and as the Rust array it +//! also is: a list where a list is expected, the array elsewhere. `[x; 3]` +//! is an array. +//! - `null`, `raw(…)` and a lone identifier are those forms only when they +//! are the whole value: `null.clone()` or `raw(x).len()` are Rust. + +use proc_macro2::{Delimiter, Spacing, Span, TokenTree}; +use quote::ToTokens; +use shopify_api_graphql::literal::{Expr, Field, For, List, Object, Value}; +use syn::buffer::Cursor; +use syn::ext::IdentExt; +use syn::parse::{ParseStream, Parser}; +use syn::spanned::Spanned; +use syn::{Ident, Token}; + +pub(crate) fn parse_value(input: ParseStream) -> syn::Result { + let cursor = input.cursor(); + if let Some((ident, rest)) = cursor.ident() { + if ident == "null" && ends_after(input, 1) { + input.call(Ident::parse_any)?; + return Ok(Value::Null(ident.span())); + } + if ident == "raw" && rest.group(Delimiter::Parenthesis).is_some() && ends_after(input, 2) { + input.call(Ident::parse_any)?; + let content; + syn::parenthesized!(content in input); + let value: syn::Expr = content.parse().map_err(|error| { + syn::Error::new( + error.span(), + "`raw(…)` takes the value of the enum, as a string", + ) + })?; + if !content.is_empty() { + return Err(content.error("`raw(…)` takes one value")); + } + return Ok(Value::Raw { + keyword: ident.span(), + value: expr(&value), + }); + } + if ends_after(input, 1) { + return Ok(Value::Ident(input.call(Ident::parse_any)?)); + } + } + if let Some((inside, _, _)) = cursor.group(Delimiter::Brace) + && ends_after(input, 1) + && is_object(inside) + { + let content; + let braces = syn::braced!(content in input); + return parse_object(&content, braces.span.join()); + } + if cursor.group(Delimiter::Bracket).is_some() && ends_after(input, 1) { + let Some(TokenTree::Group(group)) = input.parse::>()? else { + unreachable!("a bracketed group was seen"); + }; + return parse_brackets(group); + } + let value: syn::Expr = input.parse()?; + Ok(Value::Rust(expr(&value))) +} + +/// `{ name: value, name?: value, … }`, its braces read. +pub(crate) fn parse_object(content: ParseStream, span: Span) -> syn::Result { + let mut fields = Vec::new(); + while !content.is_empty() { + let name = content + .call(Ident::parse_any) + .map_err(|error| syn::Error::new(error.span(), "expected a field: `name: value`"))?; + let optional = content + .parse::>()? + .map(|question| question.span); + if !content.peek(Token![:]) || content.peek(Token![::]) { + return Err(syn::Error::new( + name.span(), + format!("expected `:` after the field: `{name}: value`"), + )); + } + content.parse::()?; + let value = parse_value(content)?; + fields.push(Field { + name: name.unraw().to_string(), + name_span: name.span(), + optional, + value, + }); + if content.is_empty() { + break; + } + content + .parse::() + .map_err(|error| syn::Error::new(error.span(), "expected `,` between two fields"))?; + } + Ok(Value::Object(Object { span, fields })) +} + +fn parse_brackets(group: proc_macro2::Group) -> syn::Result { + let span = group.span(); + let content = group.stream(); + if matches!(content.clone().into_iter().next(), Some(TokenTree::Ident(ident)) if ident == "for") + { + return (|input: ParseStream| parse_for(input, span)).parse2(content); + } + let items = (|input: ParseStream| { + let mut items = Vec::new(); + while !input.is_empty() { + items.push(parse_value(input)?); + if input.is_empty() { + break; + } + input.parse::()?; + } + Ok(items) + }) + .parse2(content); + let rust = syn::parse2::(TokenTree::Group(group).into_token_stream()) + .ok() + .map(|array| expr(&array)); + match (items, rust) { + (Ok(items), rust) => Ok(Value::List(List { span, items, rust })), + (Err(_), Some(rust)) => Ok(Value::Rust(rust)), + (Err(error), None) => Err(error), + } +} + +/// `for pattern in iterable if filter => item`, inside the brackets. +fn parse_for(input: ParseStream, span: Span) -> syn::Result { + input.parse::()?; + let pattern = syn::Pat::parse_multi_with_leading_vert(input)?; + input.parse::()?; + let iterable = syn::Expr::parse_without_eager_brace(input)?; + let filter = match input.parse::>()? { + Some(_) => Some(syn::Expr::parse_without_eager_brace(input)?.into_token_stream()), + None => None, + }; + input.parse::]>().map_err(|error| { + syn::Error::new( + error.span(), + "expected `=>` and the value of each item: `[for x in xs => value]`", + ) + })?; + let item = parse_value(input)?; + if !input.is_empty() { + return Err(input.error("expected `]`: one value follows `=>`")); + } + Ok(Value::For(Box::new(For { + span, + pattern: pattern.into_token_stream(), + iterable: iterable.into_token_stream(), + filter, + item, + }))) +} + +fn expr(value: &syn::Expr) -> Expr { + Expr { + tokens: value.to_token_stream(), + span: value.span(), + } +} + +/// The value ends after `count` token trees: at the end, or at a `,`. +fn ends_after(input: ParseStream, count: usize) -> bool { + let mut cursor = input.cursor(); + for _ in 0..count { + match cursor.token_tree() { + Some((_, next)) => cursor = next, + None => return false, + } + } + cursor.eof() || matches!(cursor.punct(), Some((punct, _)) if punct.as_char() == ',') +} + +/// The inside of braces reads as an object: empty, or `name:` (not +/// `name::`) or `name?:` first. +fn is_object(inside: Cursor) -> bool { + if inside.eof() { + return true; + } + let Some((_, rest)) = inside.ident() else { + return false; + }; + let is = |cursor: Cursor, character: char| matches!(cursor.punct(), Some((punct, _)) if punct.as_char() == character); + match rest.punct() { + Some((colon, after)) if colon.as_char() == ':' => { + !(colon.spacing() == Spacing::Joint && is(after, ':')) + } + Some((question, after)) if question.as_char() == '?' => is(after, ':'), + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(text: &str) -> Value { + parse_value.parse_str(text).unwrap() + } + + fn kind(value: &Value) -> String { + match value { + Value::Null(_) => "null".to_string(), + Value::Raw { value, .. } => format!("raw({})", value.tokens), + Value::Ident(ident) => format!("ident {ident}"), + Value::Object(object) => { + let fields: Vec = object + .fields + .iter() + .map(|field| { + let question = if field.optional.is_some() { "?" } else { "" }; + format!("{}{question}: {}", field.name, kind(&field.value)) + }) + .collect(); + format!("{{{}}}", fields.join(", ")) + } + Value::List(list) => { + let items: Vec = list.items.iter().map(kind).collect(); + let rust = if list.rust.is_some() { + " (also rust)" + } else { + "" + }; + format!("[{}]{rust}", items.join(", ")) + } + Value::For(comprehension) => format!( + "for {} in {}{} => {}", + comprehension.pattern, + comprehension.iterable, + comprehension + .filter + .as_ref() + .map(|filter| format!(" if {filter}")) + .unwrap_or_default(), + kind(&comprehension.item) + ), + Value::Rust(expr) => format!("rust {}", expr.tokens), + } + } + + #[test] + fn reads_each_form_from_the_text_alone() { + for (text, read) in [ + ("null", "null"), + ("null.clone()", "rust null . clone ()"), + ("raw(status)", "raw(status)"), + ("raw(a).len()", "rust raw (a) . len ()"), + ("ACTIVE", "ident ACTIVE"), + ("{}", "{}"), + ("{ compute() }", "rust { compute () }"), + ("{ x }", "rust { x }"), + ("{ a::b() }", "rust { a :: b () }"), + ( + "{ id: id, type: \"t\", vendor?: v, seo: { title: t }, }", + "{id: ident id, type: rust \"t\", vendor?: ident v, seo: {title: ident t}}", + ), + ("[a, b]", "[ident a, ident b] (also rust)"), + ("[x; 3]", "rust [x ; 3]"), + ("[{ a: 1 }, null]", "[{a: rust 1}, null]"), + ("[a, b].to_vec()", "rust [a , b] . to_vec ()"), + ( + "[for m in &rows if !m.value.is_empty() => { key: &m.key }]", + "for m in & rows if ! m . value . is_empty () => {key: rust & m . key}", + ), + ( + "[for (i, m) in rows.iter().enumerate() => i]", + "for (i , m) in rows . iter () . enumerate () => ident i", + ), + ("format!(\"{name}\")", "rust format ! (\"{name}\")"), + ("Some(x)", "rust Some (x)"), + ] { + assert_eq!(kind(&parse(text)), read, "{text}"); + } + } + + #[test] + fn says_what_is_wrong_in_an_object() { + for (text, message) in [ + ("{ a: 1 b: 2 }", "expected `,` between two fields"), + ("{ a: 1, b }", "expected `:` after the field: `b: value`"), + ("{ a: 1, 2: 3 }", "expected a field: `name: value`"), + ("raw()", "`raw(…)` takes the value of the enum, as a string"), + ("raw(a, b)", "`raw(…)` takes one value"), + ( + "[for x in xs x]", + "expected `=>` and the value of each item: `[for x in xs => value]`", + ), + ( + "[for x in xs => x, y]", + "expected `]`: one value follows `=>`", + ), + ] { + let error = parse_value.parse_str(text).expect_err(text); + assert_eq!(error.to_string(), message, "{text}"); + } + } +} From 854b637e356baa4eec7580c0024746601f385d52 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:24:37 +0200 Subject: [PATCH 052/135] feat(graphql): input! builds input objects, one Rust type per GraphQL name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit input!(MetafieldsSetInput { … }) builds an input object ahead of a call, in a loop for instance, with the checks and the grammar of the literals of graphql!. Its value is an InputObject: opaque, holding its JSON, Clone, Debug and Serialize. TYPE is the 64-bit FNV-1a hash of the GraphQL name, so every input! of one type gives the same Rust type in any module or crate, and values of different types do not mix. The messages of the macros name the GraphQL types; a test checks that no two input objects of the Admin schema share a hash. The fields are checked against the schema of the crate where input! is written. compile-fail tests: one per refusal of a literal. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/docs/input.md | 54 ++++++++++++++ crates/shopify_api/src/graphql/input.rs | 19 ++++- crates/shopify_api/src/lib.rs | 7 +- .../tests/ui/input_unknown_type.rs | 3 + .../tests/ui/input_unknown_type.stderr | 6 ++ .../ui/literal_deprecated_field_denied.rs | 5 ++ .../ui/literal_deprecated_field_denied.stderr | 11 +++ .../tests/ui/literal_duplicate_field.rs | 3 + .../tests/ui/literal_duplicate_field.stderr | 6 ++ .../ui/literal_maybe_non_null_with_default.rs | 7 ++ ...literal_maybe_non_null_with_default.stderr | 26 +++++++ .../tests/ui/literal_missing_required.rs | 3 + .../tests/ui/literal_missing_required.stderr | 6 ++ .../tests/ui/literal_null_on_non_null.rs | 3 + .../tests/ui/literal_null_on_non_null.stderr | 6 ++ .../tests/ui/literal_object_for_scalar.rs | 3 + .../tests/ui/literal_object_for_scalar.stderr | 6 ++ .../tests/ui/literal_option_in_field.rs | 4 ++ .../tests/ui/literal_option_in_field.stderr | 26 +++++++ .../tests/ui/literal_optional_required.rs | 4 ++ .../tests/ui/literal_optional_required.stderr | 6 ++ .../tests/ui/literal_raw_outside_enum.rs | 3 + .../tests/ui/literal_raw_outside_enum.stderr | 6 ++ .../tests/ui/literal_unknown_enum_value.rs | 3 + .../ui/literal_unknown_enum_value.stderr | 6 ++ .../tests/ui/literal_wrong_input_type.rs | 7 ++ .../tests/ui/literal_wrong_input_type.stderr | 43 +++++++++++ crates/shopify_api_graphql/src/lib.rs | 8 +-- crates/shopify_api_macros/src/lib.rs | 71 ++++++++++++++++++- 29 files changed, 351 insertions(+), 10 deletions(-) create mode 100644 crates/shopify_api/docs/input.md create mode 100644 crates/shopify_api/tests/ui/input_unknown_type.rs create mode 100644 crates/shopify_api/tests/ui/input_unknown_type.stderr create mode 100644 crates/shopify_api/tests/ui/literal_deprecated_field_denied.rs create mode 100644 crates/shopify_api/tests/ui/literal_deprecated_field_denied.stderr create mode 100644 crates/shopify_api/tests/ui/literal_duplicate_field.rs create mode 100644 crates/shopify_api/tests/ui/literal_duplicate_field.stderr create mode 100644 crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.rs create mode 100644 crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr create mode 100644 crates/shopify_api/tests/ui/literal_missing_required.rs create mode 100644 crates/shopify_api/tests/ui/literal_missing_required.stderr create mode 100644 crates/shopify_api/tests/ui/literal_null_on_non_null.rs create mode 100644 crates/shopify_api/tests/ui/literal_null_on_non_null.stderr create mode 100644 crates/shopify_api/tests/ui/literal_object_for_scalar.rs create mode 100644 crates/shopify_api/tests/ui/literal_object_for_scalar.stderr create mode 100644 crates/shopify_api/tests/ui/literal_option_in_field.rs create mode 100644 crates/shopify_api/tests/ui/literal_option_in_field.stderr create mode 100644 crates/shopify_api/tests/ui/literal_optional_required.rs create mode 100644 crates/shopify_api/tests/ui/literal_optional_required.stderr create mode 100644 crates/shopify_api/tests/ui/literal_raw_outside_enum.rs create mode 100644 crates/shopify_api/tests/ui/literal_raw_outside_enum.stderr create mode 100644 crates/shopify_api/tests/ui/literal_unknown_enum_value.rs create mode 100644 crates/shopify_api/tests/ui/literal_unknown_enum_value.stderr create mode 100644 crates/shopify_api/tests/ui/literal_wrong_input_type.rs create mode 100644 crates/shopify_api/tests/ui/literal_wrong_input_type.stderr diff --git a/crates/shopify_api/docs/input.md b/crates/shopify_api/docs/input.md new file mode 100644 index 0000000..d2a8f5b --- /dev/null +++ b/crates/shopify_api/docs/input.md @@ -0,0 +1,54 @@ +The value is an [`InputObject`]: opaque, holding the JSON it is sent as, and +of one Rust type per GraphQL input object, whatever the module or the crate +of the `input!`. Values of several `input!` of one type go in one `Vec`, which +a variable of an inline [`graphql!`] or the `Variables` of a module takes as +it is: + +```rust,no_run +use shopify_api::{Shopify, graphql, input}; + +struct Row { product_id: String, color: String, digest: Option } + +async fn set_colors(shopify: &Shopify, rows: &[Row]) -> shopify_api::Result<()> { + let mut metafields = Vec::new(); + for row in rows { + if row.color.is_empty() { + continue; + } + metafields.push(input!(MetafieldsSetInput { + ownerId: &row.product_id, + namespace: "custom", + key: "color", + value: &row.color, + type: "single_line_text_field", + compareDigest?: row.digest.as_deref(), + })); + } + shopify + .execute(graphql!( + "mutation($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { userErrors { field message } } + }", + metafields = metafields, + )) + .await?; + Ok(()) +} +``` + +`TypeName` is an input object of the crate's schema; another name is a +compile error, with the closest input object. The fields follow the rules of +the [literals of `graphql!`](crate::graphql!#input-values): GraphQL names, every +required field, `?:` for a field that may be left out, enum values bare or +`raw(…)`, nested objects and lists, `[for … => …]`. + +A value of another input type is refused where one is expected, with a +message that names both places in GraphQL terms: + +```text +error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` +``` + +The fields are checked against the schema of the crate where `input!` is +written. A value built in another crate, against another schema or version, +has the same Rust type as long as the GraphQL name is the same. diff --git a/crates/shopify_api/src/graphql/input.rs b/crates/shopify_api/src/graphql/input.rs index 9e3e4a5..97db02a 100644 --- a/crates/shopify_api/src/graphql/input.rs +++ b/crates/shopify_api/src/graphql/input.rs @@ -4,8 +4,8 @@ use serde::{Serialize, Serializer}; use serde_json::value::RawValue; -/// An input object of the schema, built and checked by `input!`: -/// `input!(MetafieldsSetInput { … })`. +/// An input object of the schema, built and checked by +/// [`input!`](crate::input!): `input!(MetafieldsSetInput { … })`. /// /// `TYPE` identifies the GraphQL input type: a hash of its name, so that /// every `input!` of `MetafieldsSetInput`, in any module or crate, gives the @@ -46,8 +46,21 @@ impl std::fmt::Debug for InputObject { } /// A field given with `field?: value` in [`graphql!`](crate::graphql!) and -/// `input!`, when sending `null` is a choice made at run +/// [`input!`](crate::input!), when sending `null` is a choice made at run /// time: an `Option` covers absent or value, `Maybe` adds `null`. +/// +/// ```no_run +/// use shopify_api::{Maybe, input}; +/// +/// # fn vendor(clear: bool, vendor: Option) { +/// let vendor = match (clear, vendor) { +/// (true, _) => Maybe::Null, +/// (false, Some(vendor)) => Maybe::Value(vendor), +/// (false, None) => Maybe::Absent, +/// }; +/// let product = input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor?: vendor }); +/// # } +/// ``` #[derive(Debug, Clone, PartialEq, Default)] pub enum Maybe { /// The field is not sent: Shopify keeps what it has. diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index d6a4dce..4fbedb5 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -94,7 +94,12 @@ pub use version::ApiVersion; #[doc = include_str!("../docs/graphql.md")] pub use shopify_api_macros::graphql; -/// What the code `graphql!` generates refers to. Not a public API. +/// Builds an input object of the schema, checked like a literal of +/// [`graphql!`]: `input!(MetafieldsSetInput { key: "color", … })`. +#[doc = include_str!("../docs/input.md")] +pub use shopify_api_macros::input; + +/// What the code `graphql!` and `input!` generate refers to. Not a public API. #[doc(hidden)] pub mod __private { pub use crate::graphql::literal; diff --git a/crates/shopify_api/tests/ui/input_unknown_type.rs b/crates/shopify_api/tests/ui/input_unknown_type.rs new file mode 100644 index 0000000..db0dd7a --- /dev/null +++ b/crates/shopify_api/tests/ui/input_unknown_type.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(MetafieldSetInput { ownerId: "gid://shopify/Product/1", key: "color", value: "blue" }); +} diff --git a/crates/shopify_api/tests/ui/input_unknown_type.stderr b/crates/shopify_api/tests/ui/input_unknown_type.stderr new file mode 100644 index 0000000..dcdfd2e --- /dev/null +++ b/crates/shopify_api/tests/ui/input_unknown_type.stderr @@ -0,0 +1,6 @@ +error: The schema has no input object `MetafieldSetInput` (did you mean `MetafieldsSetInput`?) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/input_unknown_type.rs:2:33 + | +2 | let _ = shopify_api::input!(MetafieldSetInput { ownerId: "gid://shopify/Product/1", key: "color", value: "blue" }); + | ^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_deprecated_field_denied.rs b/crates/shopify_api/tests/ui/literal_deprecated_field_denied.rs new file mode 100644 index 0000000..d73b996 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_deprecated_field_denied.rs @@ -0,0 +1,5 @@ +#![deny(deprecated)] + +fn main() { + let _ = shopify_api::input!(ProductVariantsBulkInput { barcode: "1234", price: "10.00" }); +} diff --git a/crates/shopify_api/tests/ui/literal_deprecated_field_denied.stderr b/crates/shopify_api/tests/ui/literal_deprecated_field_denied.stderr new file mode 100644 index 0000000..b7ab067 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_deprecated_field_denied.stderr @@ -0,0 +1,11 @@ +error: use of deprecated constant `main::_::SHOPIFY_DEPRECATION`: `ProductVariantsBulkInput.barcode` is deprecated in the Shopify Admin API 2026-10: Use `barcodes` instead. + --> tests/ui/literal_deprecated_field_denied.rs:4:60 + | +4 | let _ = shopify_api::input!(ProductVariantsBulkInput { barcode: "1234", price: "10.00" }); + | ^^^^^^^ + | +note: the lint level is defined here + --> tests/ui/literal_deprecated_field_denied.rs:1:9 + | +1 | #![deny(deprecated)] + | ^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_duplicate_field.rs b/crates/shopify_api/tests/ui/literal_duplicate_field.rs new file mode 100644 index 0000000..696a451 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_duplicate_field.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: "Shirt", title: "Hat" }); +} diff --git a/crates/shopify_api/tests/ui/literal_duplicate_field.stderr b/crates/shopify_api/tests/ui/literal_duplicate_field.stderr new file mode 100644 index 0000000..eac21cd --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_duplicate_field.stderr @@ -0,0 +1,6 @@ +error: The field `title` of `ProductUpdateInput` is given twice + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_duplicate_field.rs:2:101 + | +2 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: "Shirt", title: "Hat" }); + | ^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.rs b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.rs new file mode 100644 index 0000000..388b533 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.rs @@ -0,0 +1,7 @@ +use shopify_api::{Maybe, input}; + +fn main() { + let item = input!(InventoryTransferLineItemInput { inventoryItemId: "gid://shopify/InventoryItem/1", quantity: 2 }); + let line_items: Maybe> = Maybe::Value(vec![item]); + let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); +} diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr new file mode 100644 index 0000000..7db96ad --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -0,0 +1,26 @@ +error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[InventoryTransferLineItemInput!]!`): `lineItems?:` takes an `Option`, not a `Maybe`, whose `Null` it refuses + --> tests/ui/literal_maybe_non_null_with_default.rs:6:63 + | +6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); + | --------------------------------------------------^^^^^^^^^^--- + | | | + | | an `Option`: `None` leaves the field out + | required by a bound introduced by this call + | + = help: the trait `__ShopifyApiNoNull4` is not implemented for `Vec>` +help: this trait has no implementations, consider adding one + --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 + | +6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required for `Maybe>>` to implement `__ShopifyApiOptional4>>` + --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 + | +6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `__shopify_api_optional4` + --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 + | +6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `__shopify_api_optional4` + = note: this error originates in the macro `input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_missing_required.rs b/crates/shopify_api/tests/ui/literal_missing_required.rs new file mode 100644 index 0000000..6367406 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_missing_required.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(MetafieldsSetInput { ownerId: "gid://shopify/Product/1", namespace: "custom" }); +} diff --git a/crates/shopify_api/tests/ui/literal_missing_required.stderr b/crates/shopify_api/tests/ui/literal_missing_required.stderr new file mode 100644 index 0000000..b3b7e05 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_missing_required.stderr @@ -0,0 +1,6 @@ +error: Input object `MetafieldsSetInput` requires the fields `key: String!` and `value: String!`: add them + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_missing_required.rs:2:52 + | +2 | let _ = shopify_api::input!(MetafieldsSetInput { ownerId: "gid://shopify/Product/1", namespace: "custom" }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_null_on_non_null.rs b/crates/shopify_api/tests/ui/literal_null_on_non_null.rs new file mode 100644 index 0000000..07e0e94 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_null_on_non_null.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(MetafieldsSetInput { ownerId: null, key: "color", value: "blue" }); +} diff --git a/crates/shopify_api/tests/ui/literal_null_on_non_null.stderr b/crates/shopify_api/tests/ui/literal_null_on_non_null.stderr new file mode 100644 index 0000000..fcc76b1 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_null_on_non_null.stderr @@ -0,0 +1,6 @@ +error: `null` is not allowed for `ownerId` of `MetafieldsSetInput`, of type `ID!` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_null_on_non_null.rs:2:63 + | +2 | let _ = shopify_api::input!(MetafieldsSetInput { ownerId: null, key: "color", value: "blue" }); + | ^^^^ diff --git a/crates/shopify_api/tests/ui/literal_object_for_scalar.rs b/crates/shopify_api/tests/ui/literal_object_for_scalar.rs new file mode 100644 index 0000000..ec3c703 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_object_for_scalar.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: { value: "Shirt" } }); +} diff --git a/crates/shopify_api/tests/ui/literal_object_for_scalar.stderr b/crates/shopify_api/tests/ui/literal_object_for_scalar.stderr new file mode 100644 index 0000000..cf47500 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_object_for_scalar.stderr @@ -0,0 +1,6 @@ +error: `title` of `ProductUpdateInput` expects a `String`, not an object + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_object_for_scalar.rs:2:92 + | +2 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: { value: "Shirt" } }); + | ^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.rs b/crates/shopify_api/tests/ui/literal_option_in_field.rs new file mode 100644 index 0000000..106e256 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_option_in_field.rs @@ -0,0 +1,4 @@ +fn main() { + let vendor: Option = None; + let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); +} diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr new file mode 100644 index 0000000..1af6ef3 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -0,0 +1,26 @@ +error[E0277]: `vendor` of `ProductUpdateInput` takes a `String`, not an `Option`: write `vendor?: value` to leave the field out when it is `None`, or `vendor: null` to send `null` + --> tests/ui/literal_option_in_field.rs:3:93 + | +3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); + | --------------------------------------------------------------------------------^^^^^^--- + | | | + | | `vendor: None` would send `null`, which clears the field + | required by a bound introduced by this call + | + = help: the trait `__ShopifyApiNoOption5` is not implemented for `String` +help: this trait has no implementations, consider adding one + --> tests/ui/literal_option_in_field.rs:3:13 + | +3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required for `Option` to implement `__ShopifyApiExpect4` + --> tests/ui/literal_option_in_field.rs:3:13 + | +3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `__shopify_api_check6` + --> tests/ui/literal_option_in_field.rs:3:13 + | +3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `__shopify_api_check6` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_optional_required.rs b/crates/shopify_api/tests/ui/literal_optional_required.rs new file mode 100644 index 0000000..b0bc236 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_optional_required.rs @@ -0,0 +1,4 @@ +fn main() { + let owner: Option<&str> = None; + let _ = shopify_api::input!(MetafieldsSetInput { ownerId?: owner, key: "color", value: "blue" }); +} diff --git a/crates/shopify_api/tests/ui/literal_optional_required.stderr b/crates/shopify_api/tests/ui/literal_optional_required.stderr new file mode 100644 index 0000000..8367366 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_optional_required.stderr @@ -0,0 +1,6 @@ +error: `ownerId` of `MetafieldsSetInput` is required (`ID!`): it cannot be left out, so `?:` does not apply; write `ownerId: …` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_optional_required.rs:3:61 + | +3 | let _ = shopify_api::input!(MetafieldsSetInput { ownerId?: owner, key: "color", value: "blue" }); + | ^ diff --git a/crates/shopify_api/tests/ui/literal_raw_outside_enum.rs b/crates/shopify_api/tests/ui/literal_raw_outside_enum.rs new file mode 100644 index 0000000..7b09838 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_raw_outside_enum.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: raw("Shirt") }); +} diff --git a/crates/shopify_api/tests/ui/literal_raw_outside_enum.stderr b/crates/shopify_api/tests/ui/literal_raw_outside_enum.stderr new file mode 100644 index 0000000..d8511a6 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_raw_outside_enum.stderr @@ -0,0 +1,6 @@ +error: `raw(…)` is only for a value of an enum: `title` of `ProductUpdateInput` expects a `String` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_raw_outside_enum.rs:2:92 + | +2 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: raw("Shirt") }); + | ^^^ diff --git a/crates/shopify_api/tests/ui/literal_unknown_enum_value.rs b/crates/shopify_api/tests/ui/literal_unknown_enum_value.rs new file mode 100644 index 0000000..8790d49 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_unknown_enum_value.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", status: ACTIV }); +} diff --git a/crates/shopify_api/tests/ui/literal_unknown_enum_value.stderr b/crates/shopify_api/tests/ui/literal_unknown_enum_value.stderr new file mode 100644 index 0000000..d217d02 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_unknown_enum_value.stderr @@ -0,0 +1,6 @@ +error: `ACTIV` is not a value of the enum `ProductStatus` (did you mean `ACTIVE`?): `status` of `ProductUpdateInput` takes `ACTIVE`, `ARCHIVED`, `DRAFT` or `UNLISTED` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_unknown_enum_value.rs:2:93 + | +2 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", status: ACTIV }); + | ^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.rs b/crates/shopify_api/tests/ui/literal_wrong_input_type.rs new file mode 100644 index 0000000..3c00671 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.rs @@ -0,0 +1,7 @@ +fn main() { + let seo = vec![shopify_api::input!(SEOInput { title: "Shirt" })]; + let _ = shopify_api::graphql!( + "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", + metafields = seo, + ); +} diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr new file mode 100644 index 0000000..337b142 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -0,0 +1,43 @@ +error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` + --> tests/ui/literal_wrong_input_type.rs:5:22 + | +3 | let _ = shopify_api::graphql!( + | _____________- +4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", +5 | | metafields = seo, + | | ^^^ build it with `input!(MetafieldsSetInput { … })` +6 | | ); + | |_____- required by a bound introduced by this call + | + = help: the trait `__ShopifyApiExpect2` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2` + --> tests/ui/literal_wrong_input_type.rs:3:13 + | +3 | let _ = shopify_api::graphql!( + | _____________^ +4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", +5 | | metafields = seo, +6 | | ); + | | ^ + | | | + | |_____`&InputObject<960560859991546817>` + | `InputObject<960560859991546817>` +note: required for `Vec>` to implement `main::__ShopifyApiExpect1` + --> tests/ui/literal_wrong_input_type.rs:3:13 + | +3 | let _ = shopify_api::graphql!( + | _____________^ +4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", +5 | | metafields = seo, +6 | | ); + | |_____^ +note: required by a bound in `main::__shopify_api_check3` + --> tests/ui/literal_wrong_input_type.rs:3:13 + | +3 | let _ = shopify_api::graphql!( + | _____________^ +4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", +5 | | metafields = seo, +6 | | ); + | |_____^ required by this bound in `__shopify_api_check3` + = note: this error originates in the macro `shopify_api::graphql` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs index 34db2e0..9797c01 100644 --- a/crates/shopify_api_graphql/src/lib.rs +++ b/crates/shopify_api_graphql/src/lib.rs @@ -5,10 +5,10 @@ //! describes the shape of its variables and of its result; [`codegen`] turns //! that description into Rust types. [`literal`] checks the values written in //! Rust for input types (`{ title: "x" }`) and writes the code that sends -//! them. The `graphql!` macro is a thin layer over them. [`project`] finds -//! the API version of a crate (the one its `Cargo.toml` declares, else the -//! latest), and downloads that version's schema (with the `download` -//! feature). No schema is bundled. +//! them. The `graphql!` and `input!` macros are a thin layer over them. +//! [`project`] finds the API version of a crate (the one its `Cargo.toml` +//! declares, else the latest), and downloads that version's schema (with the +//! `download` feature). No schema is bundled. #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index aa24f50..a575de1 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -1,5 +1,5 @@ -//! The `graphql!` macro of `shopify_api`. Use it through `shopify_api::graphql!`, -//! which re-exports and documents it. +//! The `graphql!` and `input!` macros of `shopify_api`. Use them through +//! `shopify_api`, which re-exports and documents them. #![forbid(unsafe_code)] mod value; @@ -150,6 +150,32 @@ impl Parse for Input { } } +/// `input!(TypeName { field: value, … })`. +struct InputObject { + name: Ident, + object: Value, +} + +impl Parse for InputObject { + fn parse(input: ParseStream) -> syn::Result { + const FORM: &str = + "expected an input object of the schema: `input!(TypeName { field: value, … })`"; + let name: Ident = input + .parse() + .map_err(|error| syn::Error::new(error.span(), FORM))?; + if !input.peek(syn::token::Brace) { + return Err(input.error(FORM)); + } + let content; + let braces = syn::braced!(content in input); + let object = value::parse_object(&content, braces.span.join())?; + if !input.is_empty() { + return Err(input.error("expected the end of `input!`")); + } + Ok(Self { name, object }) + } +} + /// The text of an operation, where to point at it, and the file it was read from. struct Text { query: LitStr, @@ -624,6 +650,28 @@ fn expand(input: Input, schema: Result) -> syn::Result, +) -> syn::Result { + let schema = schema.map_err(|message| syn::Error::new(Span::call_site(), message))?; + let Value::Object(object) = &input.object else { + unreachable!("`input!` reads an object"); + }; + let mut literals = Literals::new(schema.schema(), quote!(::shopify_api)); + let value = literals + .input_object(&input.name.to_string(), input.name.span(), object) + .map_err(|error| schema.literal_error(error))?; + let checks = literals.finish(); + let tracking = schema.tracking(); + Ok(quote! {{ + #tracking + #checks + #value + }}) +} + /// See `shopify_api::graphql!`. #[proc_macro] pub fn graphql(input: proc_macro::TokenStream) -> proc_macro::TokenStream { @@ -633,6 +681,15 @@ pub fn graphql(input: proc_macro::TokenStream) -> proc_macro::TokenStream { .into() } +/// See `shopify_api::input!`. +#[proc_macro] +pub fn input(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as InputObject); + expand_input(input, LoadedSchema::load()) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + /// `graphql!` for the operations of `shopify_api` itself, checked against its /// `graphql/internal.schema.json`. Not for other crates. #[doc(hidden)] @@ -644,6 +701,16 @@ pub fn __graphql_internal(input: proc_macro::TokenStream) -> proc_macro::TokenSt .into() } +/// `input!` for `shopify_api` itself. Not for other crates. +#[doc(hidden)] +#[proc_macro] +pub fn __input_internal(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as InputObject); + expand_input(input, LoadedSchema::internal()) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + #[cfg(test)] mod tests { use super::*; From c8379ecf79225a617139a31183601ce3283ef82b Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:25:58 +0200 Subject: [PATCH 053/135] feat(graphql)!: modules name the input! types; Variables runs as it is MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A graphql! module no longer generates a struct per input object, whose ..Default::default() could leave out a required field. It names, for each input object its variables may hold, the type input! builds: pub type MetafieldsSetInput = InputObject<…>. A function can return Vec, and one Vec goes to a module and to an inline operation alike. Operation implements From, and execute and execute_response take impl Into>: shopify.execute(metafields_set::Variables { … }). operation(variables) still builds the operation, setting each variable as its JSON, with no serde_json::Value in between. Variables implements Default only when no variable is required, and PartialEq only when it holds no input object. The bulk and webhook operations of the crate build their inputs with input! and run their Variables. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/docs/graphql.md | 54 +-- crates/shopify_api/src/bulk.rs | 37 +- crates/shopify_api/src/graphql.rs | 11 +- crates/shopify_api/src/webhooks.rs | 45 ++- crates/shopify_api/tests/graphql.rs | 16 +- crates/shopify_api/tests/literals.rs | 401 ++++++++++++++++++++++ crates/shopify_api_graphql/src/codegen.rs | 255 ++++++-------- crates/shopify_api_macros/src/lib.rs | 24 +- 8 files changed, 596 insertions(+), 247 deletions(-) create mode 100644 crates/shopify_api/tests/literals.rs diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 9fdff98..d89bf0a 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -124,18 +124,19 @@ spellings work: | `JSON` | `Value`, `&Value` | | Nullable | The bare value, or an `Option` of it | | List | A `Vec`, a slice, an array or a `&Vec` of accepted values | -| Input object | Any serializable value, such as `json!({ … })`, checked by nothing: use a module to check its fields | +| Input object | A value of [`input!`](crate::input!), or a `Vec`, a slice or an array of them for a list | Another type is a compile error on the value: `` `&str` is not a value for a GraphQL variable of Rust type `i64` `` (see [`IntoVariable`]). # Named operations -A module names the types of an operation: to share it, to return its data -from a function, or to build input objects whose fields are checked. +A module names the types of an operation: to share it, or to return its +data from a function. One `graphql!` holds any number of modules, each with +its attributes, visibility and source; `;` goes between them. ```rust,no_run -use shopify_api::{Shopify, graphql}; +use shopify_api::{Shopify, graphql, input}; graphql! { /// Writes metafields and returns what Shopify refused. @@ -145,20 +146,28 @@ graphql! { userErrors { field message code } } }"; + pub(crate) mod shop_name = "query ShopName { shop { name } }"; } -async fn set_color(shopify: &Shopify, product_id: &str) -> shopify_api::Result> { - let variables = metafields_set::Variables { - metafields: vec![metafields_set::MetafieldsSetInput { - owner_id: product_id.to_string(), - namespace: Some("custom".to_string()), - key: "color".to_string(), - value: "blue".to_string(), - ..Default::default() - }], - }; - let data: metafields_set::Data = shopify.execute(metafields_set::operation(variables)).await?; +struct Row { product_id: String, color: String } + +fn color_metafields(rows: &[Row]) -> Vec { + rows.iter() + .filter(|row| !row.color.is_empty()) + .map(|row| input!(MetafieldsSetInput { + ownerId: &row.product_id, + namespace: "custom", + key: "color", + value: &row.color, + type: "single_line_text_field", + })) + .collect() +} +async fn set_colors(shopify: &Shopify, rows: &[Row]) -> shopify_api::Result> { + let data = shopify + .execute(metafields_set::Variables { metafields: color_metafields(rows) }) + .await?; let payload = data.metafields_set.expect("a payload"); Ok(payload.user_errors.into_iter().map(|error| error.message).collect()) } @@ -169,15 +178,15 @@ async fn set_color(shopify: &Shopify, product_id: &str) -> shopify_api::Result` implements `From`. | +| Input objects | `pub type MetafieldsSetInput = InputObject<…>` for each input object the variables may hold, the type every [`input!`](crate::input!)`(MetafieldsSetInput { … })` builds. | | `operation(variables)` | The operation, for `execute`. Takes nothing when there are no variables. | -In `Variables` and in input objects, a field that may be left out is an -`Option`, not sent when `None`; the structs implement `Default`. A deprecated -input field is `#[deprecated]`: setting it warns. An explicit `null` cannot be -written this way: use [`Shopify::graphql`] with a `json!` value for the few -mutations that need one. +In `Variables`, a variable that may be left out is an `Option`, not sent when +`None`. `Variables` implements `Default` when no variable is required, so that +`..Default::default()` never leaves out a required one, and `PartialEq` when it +holds no input object. A variable of an enum is a `String` there, which +nothing checks. Operations kept in files read the same, and editors that know GraphQL help writing them: @@ -185,6 +194,7 @@ writing them: ```rust,ignore graphql! { pub mod order = file("graphql/order.graphql"); + pub mod orders = file("graphql/orders.graphql"); } ``` diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 3916072..bfefd61 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -52,7 +52,7 @@ use tokio::time::Instant; use crate::transport::{HttpRequest, Method}; use crate::{Error, Page, Result, Shopify, UserError}; -use shopify_api_macros::__graphql_internal as graphql; +use shopify_api_macros::{__graphql_internal as graphql, __input_internal as input}; mod rows; @@ -392,10 +392,10 @@ impl Shopify { group_objects: bool, ) -> Result { let data = self - .execute(run_query::operation(run_query::Variables { + .execute(run_query::Variables { query: query.to_string(), group_objects, - })) + }) .await?; let payload = data .bulk_operation_run_query @@ -481,11 +481,11 @@ impl Shopify { client_identifier: Option<&str>, ) -> Result { let data = self - .execute(run_mutation::operation(run_mutation::Variables { + .execute(run_mutation::Variables { mutation: mutation.to_string(), staged_upload_path: staged_upload_path.to_string(), client_identifier: client_identifier.map(str::to_string), - })) + }) .await?; let payload = data .bulk_operation_run_mutation @@ -517,15 +517,14 @@ impl Shopify { I::Item: Serialize, { let data = self - .execute(staged_uploads::operation(staged_uploads::Variables { - input: vec![staged_uploads::StagedUploadInput { - filename: "bulk_op_vars.jsonl".to_string(), - mime_type: "text/jsonl".to_string(), - resource: "BULK_MUTATION_VARIABLES".to_string(), - http_method: Some("POST".to_string()), - ..Default::default() - }], - })) + .execute(staged_uploads::Variables { + input: vec![input!(StagedUploadInput { + filename: "bulk_op_vars.jsonl", + mimeType: "text/jsonl", + resource: BULK_MUTATION_VARIABLES, + httpMethod: POST, + })], + }) .await?; let payload = data .staged_uploads_create @@ -589,9 +588,7 @@ impl Shopify { /// A bulk operation by ID, `None` when the shop has none of that ID. pub async fn bulk_operation(&self, id: &str) -> Result> { - let data = self - .execute(get::operation(get::Variables { id: id.to_string() })) - .await?; + let data = self.execute(get::Variables { id: id.to_string() }).await?; data.bulk_operation.as_ref().map(operation_of).transpose() } @@ -601,12 +598,12 @@ impl Shopify { filter: BulkOperationsFilter, ) -> Result> { let data = self - .execute(list::operation(list::Variables { + .execute(list::Variables { first: i64::from(filter.first), after: filter.after, query: filter.query, reverse: Some(true), - })) + }) .await?; let connection = data.bulk_operations; let items = connection @@ -624,7 +621,7 @@ impl Shopify { /// Asks Shopify to cancel a running bulk operation. pub async fn cancel_bulk_operation(&self, id: &str) -> Result { let data = self - .execute(cancel::operation(cancel::Variables { id: id.to_string() })) + .execute(cancel::Variables { id: id.to_string() }) .await?; let payload = data .bulk_operation_cancel diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index c6759ce..6c91b0d 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -21,7 +21,8 @@ use crate::transport::{HttpRequest, Method}; use crate::{ApiVersion, Error, Result, Shopify}; impl Shopify { - /// Runs an operation and returns its typed `data`. + /// Runs an operation and returns its typed `data`: an [`Operation`], or + /// the `Variables` of a [`graphql!`](crate::graphql!) module. /// /// Fails when Shopify answers with `errors` (after retrying a throttled /// request), and when `data` does not fit the operation. The `userErrors` @@ -41,7 +42,10 @@ impl Shopify { /// # Ok(()) /// # } /// ``` - pub async fn execute(&self, operation: Operation) -> Result { + pub async fn execute( + &self, + operation: impl Into>, + ) -> Result { Ok(self.execute_response(operation).await?.data) } @@ -49,8 +53,9 @@ impl Shopify { /// the operation and the state of the rate limit. pub async fn execute_response( &self, - operation: Operation, + operation: impl Into>, ) -> Result> { + let operation = operation.into(); let version = self.version_for(operation.checked_against())?; let body = operation.body_json()?; let raw = self.send_graphql(version, body, operation.kind()).await?; diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs index 782fa87..b9adbc1 100644 --- a/crates/shopify_api/src/webhooks.rs +++ b/crates/shopify_api/src/webhooks.rs @@ -34,7 +34,7 @@ use serde::{Deserialize, Serialize}; use sha2::Sha256; use crate::{Error, Result, ShopDomain, Shopify, UserError}; -use shopify_api_macros::__graphql_internal as graphql; +use shopify_api_macros::{__graphql_internal as graphql, __input_internal as input}; /// Whether `hmac_header` (`X-Shopify-Hmac-Sha256`) is the signature of /// `body` with `secret`, the client secret of the app. Compares in constant time. @@ -230,21 +230,19 @@ graphql! { /// The input of `create` or `update` for a spec. An update sends every /// option, empty when the spec has none, so that it replaces the old ones. -macro_rules! input { - ($module:ident, $spec:expr, $replace:expr) => {{ - let spec: &WebhookSubscriptionSpec = $spec; - let replace: bool = $replace; - let list = |values: &Vec| (replace || !values.is_empty()).then(|| values.clone()); - $module::WebhookSubscriptionInput { - uri: Some(spec.uri.clone()), - format: Some(spec.format.clone().unwrap_or_else(|| "JSON".to_string())), - filter: spec.filter.clone().or_else(|| replace.then(String::new)), - include_fields: list(&spec.include_fields), - metafield_namespaces: list(&spec.metafield_namespaces), - name: spec.name.clone(), - ..Default::default() - } - }}; +fn subscription_input( + spec: &WebhookSubscriptionSpec, + replace: bool, +) -> create::WebhookSubscriptionInput { + let list = |values: &Vec| (replace || !values.is_empty()).then(|| values.clone()); + input!(WebhookSubscriptionInput { + uri: &spec.uri, + format: raw(spec.format.as_deref().unwrap_or("JSON")), + filter?: spec.filter.as_deref().or(replace.then_some("")), + includeFields?: list(&spec.include_fields), + metafieldNamespaces?: list(&spec.metafield_namespaces), + name?: spec.name.as_deref(), + }) } /// A webhook subscription of a shop. @@ -450,12 +448,11 @@ impl Shopify { &self, spec: &WebhookSubscriptionSpec, ) -> Result { - let input = input!(create, spec, false); let data = self - .execute(create::operation(create::Variables { + .execute(create::Variables { topic: spec.topic.clone(), - webhook_subscription: input, - })) + webhook_subscription: subscription_input(spec, false), + }) .await?; let payload = data.webhook_subscription_create.ok_or_else(|| { Error::decode( @@ -477,7 +474,7 @@ impl Shopify { pub async fn delete_webhook_subscription(&self, id: &str) -> Result<()> { let data = self - .execute(delete::operation(delete::Variables { id: id.to_string() })) + .execute(delete::Variables { id: id.to_string() }) .await?; let payload = data.webhook_subscription_delete.ok_or_else(|| { Error::decode( @@ -497,10 +494,10 @@ impl Shopify { spec: &WebhookSubscriptionSpec, ) -> Result { let data = self - .execute(update::operation(update::Variables { + .execute(update::Variables { id: id.to_string(), - webhook_subscription: input!(update, spec, true), - })) + webhook_subscription: subscription_input(spec, true), + }) .await?; let payload = data.webhook_subscription_update.ok_or_else(|| { Error::decode( diff --git a/crates/shopify_api/tests/graphql.rs b/crates/shopify_api/tests/graphql.rs index e590bed..6b5552d 100644 --- a/crates/shopify_api/tests/graphql.rs +++ b/crates/shopify_api/tests/graphql.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use shopify_api::testing::{MockTransport, client}; -use shopify_api::{ApiVersion, Error, OperationKind, graphql}; +use shopify_api::{ApiVersion, Error, OperationKind, graphql, input}; graphql! { /// Writes metafields and reports what Shopify refused. @@ -165,13 +165,12 @@ async fn a_module_names_its_types_and_builds_input_objects() { let shopify = client(&mock); let variables = metafields_set::Variables { - metafields: vec![metafields_set::MetafieldsSetInput { - owner_id: "gid://shopify/Product/1".to_string(), - namespace: Some("custom".to_string()), - key: "color".to_string(), - value: "blue".to_string(), - ..Default::default() - }], + metafields: vec![input!(MetafieldsSetInput { + ownerId: "gid://shopify/Product/1", + namespace: "custom", + key: "color", + value: "blue", + })], }; let data: metafields_set::Data = shopify .execute(metafields_set::operation(variables)) @@ -184,7 +183,6 @@ async fn a_module_names_its_types_and_builds_input_objects() { assert_eq!(metafields_set::NAME, Some("MetafieldsSet")); assert_eq!(metafields_set::KIND, OperationKind::Mutation); assert_eq!(metafields_set::API_VERSION, ApiVersion::DEFAULT.to_string()); - // Fields left to `None` are not sent. assert_eq!( mock.graphql_requests()[0].variables, json!({ "metafields": [{ "ownerId": "gid://shopify/Product/1", "namespace": "custom", "key": "color", "value": "blue" }] }) diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs new file mode 100644 index 0000000..ad9d544 --- /dev/null +++ b/crates/shopify_api/tests/literals.rs @@ -0,0 +1,401 @@ +//! Values written in Rust for input types: object literals in inline +//! operations, `input!`, and the `Variables` of modules. Each test reads the +//! exact body sent. +#![cfg(feature = "testing")] + +use serde_json::json; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::{Maybe, graphql, input}; + +const PRODUCT_UPDATE: &str = "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { field message } } }"; + +graphql! { + /// Writes metafields. + pub mod metafields_set = "mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { metafields { id key } userErrors { field message } } + }"; + mod shop_name = "query ShopName { shop { name } }"; + pub(crate) mod recent_products = "query RecentProducts($first: Int!, $sortKey: ProductSortKeys) { + products(first: $first, sortKey: $sortKey) { nodes { id } } + }"; + mod product_count = "query ProductCount($query: String) { productsCount(query: $query) { count } }" +} + +/// The body of the last request, as sent. +fn sent(mock: &MockTransport) -> String { + String::from_utf8(mock.last_request().unwrap().body).unwrap() +} + +/// A body of `query` with `variables`, written as `shopify_api` writes it. +fn body(query: &str, variables: &str) -> String { + format!( + r#"{{"query":{},"variables":{variables}}}"#, + serde_json::to_string(query).unwrap() + ) +} + +struct Row { + product_id: String, + key: &'static str, + value: &'static str, + digest: Option, +} + +fn rows() -> Vec { + let row = |id: u32, key, value, digest: Option<&str>| Row { + product_id: format!("gid://shopify/Product/{id}"), + key, + value, + digest: digest.map(str::to_string), + }; + vec![ + row(1, "color", "blue", None), + row(2, "color", "", None), + row(3, "color", "red", Some("d3")), + ] +} + +fn color_metafields(rows: &[Row]) -> Vec { + let mut metafields = Vec::new(); + for row in rows { + if row.value.is_empty() { + continue; + } + metafields.push(input!(MetafieldsSetInput { + ownerId: &row.product_id, + namespace: "custom", + key: row.key, + value: row.value, + type: "single_line_text_field", + compareDigest?: row.digest.as_deref(), + })); + } + metafields +} + +const COLOR_METAFIELDS: &str = r#"[{"ownerId":"gid://shopify/Product/1","namespace":"custom","key":"color","value":"blue","type":"single_line_text_field"},{"ownerId":"gid://shopify/Product/3","namespace":"custom","key":"color","value":"red","type":"single_line_text_field","compareDigest":"d3"}]"#; + +#[tokio::test] +async fn an_object_literal_sends_values_nulls_enums_nested_objects_and_built_lists() { + let mock = MockTransport::new(); + mock.push_data(json!({ "productUpdate": { "userErrors": [] } })); + let shopify = client(&mock); + let product_id = "gid://shopify/Product/1"; + let name = "Shirt"; + let new_vendor: Option = None; + let seo_title = "Shirt, on sale".to_string(); + let rows = rows(); + + let data = shopify + .execute(graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { field message } } }", + product = { + id: product_id, + title: format!("{name} (promo)"), + status: ACTIVE, + descriptionHtml: null, + vendor?: new_vendor, + seo: { title: &seo_title }, + metafields: [for m in &rows if !m.value.is_empty() => { + namespace: "custom", key: m.key, value: m.value, type: "single_line_text_field", + }], + }, + )) + .await + .unwrap(); + + assert!(data.product_update.unwrap().user_errors.is_empty()); + assert_eq!( + sent(&mock), + body( + PRODUCT_UPDATE, + r#"{"product":{"id":"gid://shopify/Product/1","title":"Shirt (promo)","status":"ACTIVE","descriptionHtml":null,"seo":{"title":"Shirt, on sale"},"metafields":[{"namespace":"custom","key":"color","value":"blue","type":"single_line_text_field"},{"namespace":"custom","key":"color","value":"red","type":"single_line_text_field"}]}}"# + ) + ); +} + +#[tokio::test] +async fn a_field_with_a_question_mark_is_left_out_sent_null_or_sent() { + let mock = MockTransport::new(); + mock.push_data(json!({ "productUpdate": { "userErrors": [] } })); + let shopify = client(&mock); + let clear_description = true; + let status: Option = Some("DRAFT".to_string()); + + shopify + .execute(graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { field message } } }", + product = { + id: "gid://shopify/Product/1", + vendor?: Some("Acme"), + handle?: None::, + descriptionHtml?: if clear_description { Maybe::Null } else { Maybe::Value("

x

") }, + productType?: Maybe::Value("Shirts".to_string()), + templateSuffix?: Maybe::<&str>::Absent, + giftCardTemplateSuffix?: Maybe::::default(), + status?: raw(status.as_deref()), + tags: ["a", "b"], + collectionsToJoin: [], + }, + )) + .await + .unwrap(); + + assert_eq!( + sent(&mock), + body( + PRODUCT_UPDATE, + r#"{"product":{"id":"gid://shopify/Product/1","vendor":"Acme","descriptionHtml":null,"productType":"Shirts","status":"DRAFT","tags":["a","b"],"collectionsToJoin":[]}}"# + ) + ); +} + +#[tokio::test] +async fn enum_variables_take_a_bare_value_or_raw_and_scalars_take_rust_as_before() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(shopify_api::transport::HttpResponse::json( + 200, + &json!({ "data": { "products": { "nodes": [] }, "nodes": [] } }), + )) + }); + let shopify = client(&mock); + let query = "query($first: Int!, $sortKey: ProductSortKeys, $ids: [ID!]!) { products(first: $first, sortKey: $sortKey) { nodes { id } } nodes(ids: $ids) { id } }"; + let (a, b) = ( + "gid://shopify/Product/1", + "gid://shopify/Product/2".to_string(), + ); + + shopify + .execute(graphql!( + "query($first: Int!, $sortKey: ProductSortKeys, $ids: [ID!]!) { products(first: $first, sortKey: $sortKey) { nodes { id } } nodes(ids: $ids) { id } }", + first = { 1 + 1 }, + sortKey = TITLE, + ids = [a, &b], + )) + .await + .unwrap(); + assert_eq!( + sent(&mock), + body( + query, + r#"{"first":2,"sortKey":"TITLE","ids":["gid://shopify/Product/1","gid://shopify/Product/2"]}"# + ) + ); + + let sort_key: Option<&str> = None; + shopify + .execute(graphql!( + "query($first: Int!, $sortKey: ProductSortKeys, $ids: [ID!]!) { products(first: $first, sortKey: $sortKey) { nodes { id } } nodes(ids: $ids) { id } }", + first = 1_u8, + sortKey = raw(sort_key), + ids = [for id in [a, b.as_str()] => id], + )) + .await + .unwrap(); + assert_eq!( + sent(&mock), + body( + query, + r#"{"first":1,"sortKey":null,"ids":["gid://shopify/Product/1","gid://shopify/Product/2"]}"# + ) + ); + + shopify + .execute(recent_products::Variables { + first: 5, + sort_key: Some("CREATED_AT".to_string()), + }) + .await + .unwrap(); + assert_eq!( + mock.graphql_requests().last().unwrap().variables, + json!({ "first": 5, "sortKey": "CREATED_AT" }) + ); +} + +#[tokio::test] +async fn one_vec_of_input_objects_goes_to_an_inline_operation_and_to_a_module() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(shopify_api::transport::HttpResponse::json( + 200, + &json!({ "data": { "metafieldsSet": { "metafields": [], "userErrors": [] } } }), + )) + }); + let shopify = client(&mock); + let metafields = color_metafields(&rows()); + + let inline = "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }"; + shopify + .execute(graphql!( + "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", + metafields = &metafields, + )) + .await + .unwrap(); + assert_eq!( + sent(&mock), + body(inline, &format!(r#"{{"metafields":{COLOR_METAFIELDS}}}"#)) + ); + + let data = shopify + .execute(metafields_set::Variables { metafields }) + .await + .unwrap(); + assert!(data.metafields_set.unwrap().user_errors.is_empty()); + assert_eq!( + sent(&mock), + format!( + r#"{{"query":{},"variables":{{"metafields":{COLOR_METAFIELDS}}},"operationName":"MetafieldsSet"}}"#, + serde_json::to_string(metafields_set::QUERY).unwrap() + ) + ); + + // `operation(variables)` still builds the operation. + let operation = metafields_set::operation(metafields_set::Variables { + metafields: color_metafields(&rows()), + }); + assert_eq!( + operation.variables_json().unwrap()["metafields"][1]["compareDigest"], + "d3" + ); +} + +#[tokio::test] +async fn input_objects_of_two_call_sites_share_one_vec_and_a_module_type() { + let mock = MockTransport::new(); + mock.push_data(json!({ "metafieldsSet": { "metafields": [], "userErrors": [] } })); + let shopify = client(&mock); + + let metafields: Vec = rows() + .iter() + .map(|row| match &row.digest { + Some(digest) => input!(MetafieldsSetInput { + ownerId: &row.product_id, + key: "color", + value: row.value, + compareDigest: digest, + }), + None => input!(MetafieldsSetInput { + ownerId: &row.product_id, + key: "color", + value: row.value, + type: "single_line_text_field", + }), + }) + .collect(); + let first = metafields[0].clone(); + assert_eq!( + format!("{first:?}"), + r#"MetafieldsSetInput {"ownerId":"gid://shopify/Product/1","key":"color","value":"blue","type":"single_line_text_field"}"# + ); + assert_eq!( + serde_json::to_string(&first).unwrap(), + r#"{"ownerId":"gid://shopify/Product/1","key":"color","value":"blue","type":"single_line_text_field"}"# + ); + + shopify + .execute(metafields_set::Variables { metafields }) + .await + .unwrap(); + assert_eq!( + mock.graphql_requests()[0].variables, + json!({ "metafields": [ + { "ownerId": "gid://shopify/Product/1", "key": "color", "value": "blue", "type": "single_line_text_field" }, + { "ownerId": "gid://shopify/Product/2", "key": "color", "value": "", "type": "single_line_text_field" }, + { "ownerId": "gid://shopify/Product/3", "key": "color", "value": "red", "compareDigest": "d3" }, + ] }) + ); +} + +#[tokio::test] +async fn the_modules_of_one_block_each_run() { + let mock = MockTransport::new(); + mock.push_data(json!({ "shop": { "name": "Test shop" } })); + mock.push_data(json!({ "products": { "nodes": [{ "id": "gid://shopify/Product/1" }] } })); + mock.push_data(json!({ "productsCount": { "count": 3 } })); + let shopify = client(&mock); + + let data: shop_name::Data = shopify.execute(shop_name::operation()).await.unwrap(); + assert_eq!(data.shop.name, "Test shop"); + let data = shopify + .execute(recent_products::Variables { + first: 1, + sort_key: None, + }) + .await + .unwrap(); + assert_eq!(data.products.nodes[0].id, "gid://shopify/Product/1"); + // No variable is required: `Default` cannot leave one out. + let data = shopify + .execute(product_count::Variables::default()) + .await + .unwrap(); + assert_eq!(data.products_count.unwrap().count, 3); + + let names: Vec> = mock + .graphql_requests() + .into_iter() + .map(|request| request.operation_name) + .collect(); + assert_eq!( + names, + [ + Some("ShopName".to_string()), + Some("RecentProducts".to_string()), + Some("ProductCount".to_string()) + ] + ); + assert_eq!(mock.graphql_requests()[1].variables, json!({ "first": 1 })); +} + +#[tokio::test] +async fn a_nullable_input_variable_takes_null_an_option_or_a_literal() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(shopify_api::transport::HttpResponse::json( + 200, + &json!({ "data": { "productCreate": { "product": null } } }), + )) + }); + let shopify = client(&mock); + let query = "mutation($product: ProductCreateInput, $media: [CreateMediaInput!]) { productCreate(product: $product, media: $media) { product { id } } }"; + + shopify + .execute(graphql!( + "mutation($product: ProductCreateInput, $media: [CreateMediaInput!]) { productCreate(product: $product, media: $media) { product { id } } }", + product = { title: "Shirt", status: DRAFT }, + media = null, + )) + .await + .unwrap(); + assert_eq!( + sent(&mock), + body( + query, + r#"{"product":{"title":"Shirt","status":"DRAFT"},"media":null}"# + ) + ); + + let image = input!(CreateMediaInput { + originalSource: "https://example.com/shirt.jpg", + mediaContentType: IMAGE, + }); + let product = Some(input!(ProductCreateInput { title: "Shirt" })); + shopify + .execute(graphql!( + "mutation($product: ProductCreateInput, $media: [CreateMediaInput!]) { productCreate(product: $product, media: $media) { product { id } } }", + product = product, + media = [image], + )) + .await + .unwrap(); + assert_eq!( + sent(&mock), + body( + query, + r#"{"product":{"title":"Shirt"},"media":[{"originalSource":"https://example.com/shirt.jpg","mediaContentType":"IMAGE"}]}"# + ) + ); +} diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs index 88c8f67..8ad64b1 100644 --- a/crates/shopify_api_graphql/src/codegen.rs +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -1,6 +1,6 @@ //! Rust types for the result and the variables of an analyzed operation. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, quote_spanned}; @@ -8,7 +8,7 @@ use quote::{quote, quote_spanned}; use crate::analyze::{ FieldBase, Operation, Scalar, SelectedField, Selection, Variable, VariableBase, }; -use crate::schema::{InputValue, Schema, TypeDef, TypeRef}; +use crate::schema::{Schema, TypeDef, TypeRef}; /// The name of the type generated for the `data` of an operation. pub const DATA_TYPE: &str = "Data"; @@ -219,7 +219,7 @@ pub fn data_types(operation: &Operation, krate: &TokenStream) -> TokenStream { // ─── Variables ─────────────────────────────────────────────────────── /// The Rust type a variable value is converted to, or `None` when the variable -/// holds an input object, which has no type outside a `graphql!` module. +/// holds an input object, which is an [`InputObject`](https://docs.rs/shopify_api/latest/shopify_api/struct.InputObject.html). pub fn variable_type(variable: &Variable, krate: &TokenStream) -> Option { let base = match variable.base { VariableBase::Scalar(scalar) => scalar_type(scalar, krate), @@ -249,171 +249,126 @@ pub fn deprecation_warning(span: Span, note: &str) -> TokenStream { } } -struct InputTypes<'a> { - schema: &'a Schema, - krate: &'a TokenStream, - generated: BTreeSet, - items: Vec, -} - -impl InputTypes<'_> { - /// The Rust type of a named input type, generating input objects on the way. - fn named(&mut self, name: &str) -> TokenStream { - match self.schema.get(name) { - Some(TypeDef::Input { fields }) => { - if self.generated.insert(name.to_string()) { - self.input_object(name, fields); - } - let ident = Ident::new(name, Span::call_site()); - quote!(#ident) - } - Some(TypeDef::Enum { .. }) => scalar_type(Scalar::String, self.krate), - _ => scalar_type(Scalar::of(name), self.krate), +/// The input objects a value of input type `name` may hold, `name` included. +fn reachable_inputs<'a>(schema: &'a Schema, name: &'a str, found: &mut BTreeSet<&'a str>) { + if let Some(TypeDef::Input { fields }) = schema.get(name) + && found.insert(name) + { + for field in fields.values() { + reachable_inputs(schema, field.ty.name(), found); } } - - fn input_object(&mut self, name: &str, fields: &BTreeMap) { - let mut taken = BTreeSet::new(); - let fields: Vec = fields - .iter() - .map(|(field, value)| { - let mut base = self.named(value.ty.name()); - // A value cannot contain itself: break direct cycles with a box. - let nested_directly = !contains_list(&value.ty); - if nested_directly && self.reaches(value.ty.name(), name) { - base = quote!(::std::boxed::Box<#base>); - } - let note = value.deprecation.as_ref().map(|reason| { - format!( - "`{name}.{field}` is deprecated in the Shopify Admin API {}: {reason}", - self.schema.api_version - ) - }); - input_field(field, value, note, &base, &mut taken) - }) - .collect(); - - let doc = format!(" The input object `{name}`. Fields left to `None` are not sent."); - self.items - .push(input_struct(name, &doc, &fields, self.krate)); - } - - /// Whether a value of input type `from` can hold one of type `to` without a list in between. - fn reaches(&self, from: &str, to: &str) -> bool { - let mut seen = BTreeSet::new(); - let mut stack = vec![from]; - while let Some(name) = stack.pop() { - if name == to { - return true; - } - if !seen.insert(name) { - continue; - } - if let Some(TypeDef::Input { fields }) = self.schema.get(name) { - stack.extend( - fields - .values() - .filter(|value| !contains_list(&value.ty)) - .map(|value| value.ty.name()), - ); - } - } - false - } } -fn contains_list(ty: &TypeRef) -> bool { - match ty { - TypeRef::Named(_) => false, - TypeRef::List(_) => true, - TypeRef::NonNull(inner) => contains_list(inner), - } -} - -/// A field of an input object or of the variables. A value that may be left -/// out is an `Option` that is not sent when `None`. A deprecated input field -/// is marked `#[deprecated]` with `note`, so that setting it warns. -fn input_field( - name: &str, - value: &InputValue, - note: Option, - base: &TokenStream, - taken: &mut BTreeSet, +/// [`VARIABLES_TYPE`], `operation(variables)`, `From` for the +/// operation, and a type alias, named as in the schema, for each input object +/// the variables may hold. +/// +/// `constructor` builds the operation without its variables; `krate` is the +/// path of the `shopify_api` crate in the generated code. +pub fn variables_types( + schema: &Schema, + operation: &Operation, + krate: &TokenStream, + constructor: &TokenStream, ) -> TokenStream { - let (ident, rename) = field_ident(name, taken); - let ty = &value.ty; - let doc = format!(" `{name}: {ty}`"); - let deprecated = note.map(|note| quote!(#[deprecated(note = #note)])); - if value.is_required() { - let ty = wrap(ty, base); + let mut inputs = BTreeSet::new(); + for variable in &operation.variables { + reachable_inputs(schema, variable.ty.name(), &mut inputs); + } + let aliases = inputs.iter().map(|name| { + let ident = Ident::new(name, Span::call_site()); + let id = input_object_id(name); + let doc = format!(" The input object `{name}`: build it with `input!({name} {{ … }})`."); quote! { #[doc = #doc] - #deprecated - #rename - pub #ident: #ty, + #[allow(dead_code)] + pub type #ident = #krate::InputObject<#id>; } - } else { - // `wrap` of a nullable type is already an `Option`. - let ty = wrap(ty.nullable(), base); - quote! { - #[doc = #doc] - #deprecated - #rename - #[serde(skip_serializing_if = "::core::option::Option::is_none")] - pub #ident: #ty, + }); + + let mut taken = BTreeSet::new(); + let mut fields = Vec::new(); + let mut setters = Vec::new(); + for variable in &operation.variables { + let base = match variable.base { + VariableBase::Scalar(scalar) => scalar_type(scalar, krate), + VariableBase::Enum => scalar_type(Scalar::String, krate), + VariableBase::Input => { + let ident = Ident::new(variable.ty.name(), Span::call_site()); + quote!(#ident) + } + }; + let (ident, rename) = field_ident(&variable.name, &mut taken); + let key = &variable.name; + let doc = format!(" `${key}: {}`", variable.ty); + if variable.is_required() { + let ty = wrap(&variable.ty, &base); + fields.push(quote! { + #[doc = #doc] + #rename + pub #ident: #ty, + }); + setters.push(quote! { + let operation = operation.json_variable(#key, variables.#ident); + }); + } else { + // `wrap` of a nullable type is already an `Option`. + let ty = wrap(variable.ty.nullable(), &base); + fields.push(quote! { + #[doc = #doc] + #rename + #[serde(skip_serializing_if = "::core::option::Option::is_none")] + pub #ident: #ty, + }); + setters.push(quote! { + let operation = match variables.#ident { + ::core::option::Option::Some(value) => operation.json_variable(#key, value), + ::core::option::Option::None => operation, + }; + }); } } -} -/// A struct that is only sent: an input object, or the variables. -fn input_struct(name: &str, doc: &str, fields: &[TokenStream], krate: &TokenStream) -> TokenStream { - let ident = Ident::new(name, Span::call_site()); + // `Default` only when it cannot leave out a required variable; + // `InputObject` has no `PartialEq`. + let mut derives = vec![ + quote!(::core::fmt::Debug), + quote!(::core::clone::Clone), + quote!(#krate::__private::serde::Serialize), + ]; + if inputs.is_empty() { + derives.push(quote!(::core::cmp::PartialEq)); + } + if !operation.variables.iter().any(Variable::is_required) { + derives.push(quote!(::core::default::Default)); + } let serde = serde_path(krate); + let data = Ident::new(DATA_TYPE, Span::call_site()); + let variables = Ident::new(VARIABLES_TYPE, Span::call_site()); quote! { - #[doc = #doc] - #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq, ::core::default::Default, #krate::__private::serde::Serialize)] + #(#aliases)* + + /// The variables of the operation; those left to `None` are not + /// sent. `Shopify::execute` runs it. + #[derive(#(#derives),*)] #[serde(crate = #serde)] - pub struct #ident { + pub struct #variables { #(#fields)* } - } -} -/// [`VARIABLES_TYPE`] and the input objects it refers to, named as in the schema. -pub fn variables_types(schema: &Schema, operation: &Operation, krate: &TokenStream) -> TokenStream { - let mut inputs = InputTypes { - schema, - krate, - generated: BTreeSet::new(), - items: Vec::new(), - }; - let mut taken = BTreeSet::new(); - let fields: Vec = operation - .variables - .iter() - .map(|variable| { - let base = inputs.named(variable.ty.name()); - let value = InputValue { - ty: variable.ty.clone(), - // A variable with a default may be left out, as an argument with one. - has_default: variable.has_default, - deprecation: None, - }; - input_field(&variable.name, &value, None, &base, &mut taken) - }) - .collect(); - - let items = inputs.items; - let variables = input_struct( - VARIABLES_TYPE, - " The variables of the operation. Those left to `None` are not sent.", - &fields, - krate, - ); - quote! { - #(#items)* + /// The operation with its variables, for `Shopify::execute`. + pub fn operation(variables: #variables) -> #krate::Operation<#data> { + let operation = #constructor; + #(#setters)* + operation + } - #variables + impl ::core::convert::From<#variables> for #krate::Operation<#data> { + fn from(variables: #variables) -> Self { + operation(variables) + } + } } } diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index a575de1..1077348 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -11,9 +11,7 @@ use std::time::SystemTime; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, quote_spanned}; -use shopify_api_graphql::codegen::{ - DATA_TYPE, VARIABLES_TYPE, data_types, deprecation_warning, variables_types, -}; +use shopify_api_graphql::codegen::{DATA_TYPE, data_types, deprecation_warning, variables_types}; use shopify_api_graphql::literal::{self, Literals, Value, VariableValue}; use shopify_api_graphql::project::{ DownloadError, metadata_snippet, previous_api_version, up_to_date_schema, @@ -580,26 +578,15 @@ fn expand_module(schema: &LoadedSchema, module: &Module) -> syn::Result #krate::Operation<#data> { #constructor } - }; - (TokenStream::new(), function) + } } else { - let variables = format_ident!("{}", VARIABLES_TYPE); - let function = quote! { - /// The operation with its variables, for `Shopify::execute`. - pub fn operation(variables: #variables) -> #krate::Operation<#data> { - #constructor.variables(variables) - } - }; - ( - variables_types(schema.schema(), &operation, &krate), - function, - ) + variables_types(schema.schema(), &operation, &krate, &constructor) }; let tracking = schema.tracking(); @@ -631,7 +618,6 @@ fn expand_module(schema: &LoadedSchema, module: &Module) -> syn::Result Date: Fri, 23 Oct 2026 12:26:13 +0200 Subject: [PATCH 054/135] docs: input values, input! and named modules The reference of graphql! gains the grammar of input values (the forms, the four ways to write a field, the Option rule, raw, how {, [, null and raw read where Rust could read them too) and its limits. The README's Operations section shows an inline literal, input! in a loop and a block of named modules; CHANGELOG and MIGRATION cover 0.10 and the 1.0 previews. A metafields example runs all three. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +- MIGRATION.md | 30 +++++ README.md | 110 +++++++++++++++--- crates/shopify_api/Cargo.toml | 4 + crates/shopify_api/docs/graphql.md | 134 ++++++++++++++++++++-- crates/shopify_api/examples/metafields.rs | 95 +++++++++++++++ crates/shopify_api/src/lib.rs | 3 +- crates/shopify_api_graphql/README.md | 5 +- crates/shopify_api_macros/README.md | 7 +- 9 files changed, 361 insertions(+), 34 deletions(-) create mode 100644 crates/shopify_api/examples/metafields.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index bbe0506..c19f998 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,12 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATION.md). -- Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`, with typed input objects) or read from a file (`file("…graphql")`). +- Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`) or read from a file (`file("…graphql")`). +- Add: input values written as literals in an inline `graphql!`, checked against the schema at the token: `product = { id: id, status: ACTIVE, descriptionHtml: null, vendor?: vendor, seo: { title: t }, metafields: [for m in &rows if cond => { … }] }`. Field names are the GraphQL ones (`type` included); an unknown or repeated field, a missing required field (each one named), `null` on a non-null type, an unknown enum value (the valid ones listed) and a value of the wrong form are compile errors; deprecated fields and enum values warn. `field?: value` leaves the field out for `None`; an `Option` given to `field: value` does not compile, since `null` would clear the field. `raw(string)` sends an enum value unchecked. Rust expressions are checked by traits whose errors name the GraphQL type. Literals are written straight to JSON, with no `serde_json::Value` in between. +- Add: `input!(TypeName { … })` builds an input object ahead of the call, with the same checks, as an `InputObject`: one Rust type per GraphQL name, the same in every module and crate, so that the values of several `input!` go in one `Vec`. +- Add: `Maybe` (`Absent`, `Null`, `Value`), for `field?:` when `null` is a choice made at run time. +- Add: one `graphql! { … }` holds several modules, `;` between them. A module's `Variables` runs as it is, `shopify.execute(module::Variables { … })`, and it names each input object its variables may hold: `pub type MetafieldsSetInput = InputObject<…>`. +- Breaking (against the 1.0 previews): the input structs of modules (`MetafieldsSetInput { owner_id, ..Default::default() }`) are gone, for `input!`, which cannot leave out a required field. `Variables` implements `Default` only when no variable is required, and `PartialEq` only when it holds no input object. An input object variable of an inline `graphql!` takes a literal or values of `input!`, no longer any `Serialize` value such as `json!`. An enum variable takes a bare value (`sortKey = TITLE`) or `raw(string)`, no longer a string. `execute` and `execute_response` take `impl Into>`. `Operation` keeps each variable as the JSON it is sent as: `variables_json` returns the variables read back, by value. - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. - Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. diff --git a/MIGRATION.md b/MIGRATION.md index 1a722e1..568164d 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -87,6 +87,20 @@ let data: ShopQuery = shopify.graphql_as("query { shop { name } }", ()).await?; Variables are now anything that serializes to an object, by value or by reference, or `()` for none. +With `graphql!`, an input object is a literal checked against the schema, +in place of a `json!` value: + +```rust,ignore +// 0.10 +shopify.graphql::(mutation, &json!({ "product": { "id": id, "title": title } })).await?; + +// 1.0 +shopify.execute(graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + product = { id: id, title: title }, +)).await?; +``` + ## Bulk operations | 0.10 | 1.0 | @@ -142,3 +156,19 @@ Topics are accepted as `orders/create` or `ORDERS_CREATE`. - `utils::read_json_tree`: `serde_json::Value::pointer`. - `utils::deserialize_from_value` and `deserialize_from_str`: errors name the path of a mismatch. - The `debug` and `graphql-client` features, and the `simple_logger` dependency: logs go through `tracing`. + +# Upgrading from a 1.0 preview + +The input objects of `graphql!` changed before the release. + +| 1.0 preview | 1.0 | +| --- | --- | +| `module::MetafieldsSetInput { owner_id: id.to_string(), namespace: Some("custom".into()), ..Default::default() }` | `input!(MetafieldsSetInput { ownerId: id, namespace: "custom", … })`: GraphQL field names, every required field, `?:` for an `Option` | +| `module::MetafieldsSetInput` as a struct | The same name, a type alias of the `InputObject` every `input!(MetafieldsSetInput { … })` builds | +| An inline input object variable given `json!({ … })` or any `Serialize` value | An object literal, `product = { id: id, … }`, or values of `input!`; `json!` goes through `Shopify::graphql` | +| An enum variable given a string, `sortKey = "TITLE"` or `sortKey = key` | `sortKey = TITLE`, checked, or `sortKey = raw(key)` | +| No way to send `null` for an input field | `field: null`, or `field?: Maybe::Null` | +| One module per `graphql! { … }` | Several, `;` between them | +| `shopify.execute(module::operation(module::Variables { … }))` | The same, or `shopify.execute(module::Variables { … })` | +| `Variables` always `Default` and `PartialEq` | `Default` when no variable is required, `PartialEq` when it holds no input object | +| `Operation::variables_json()` returned `&Map` | It returns the `Map`, read back from the JSON kept for each variable | diff --git a/README.md b/README.md index ad5a569..255d5fd 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,8 @@ async fn main() -> shopify_api::Result<()> { - **Checked operations.** A field, argument, enum value or variable that does not exist is a compile error, with a suggestion. A deprecated one is a compiler warning with Shopify's reason. -- **Typed variables and results**, input objects included, generated with no - build script and no generated file. +- **Typed variables and results**, input objects included, written as + literals checked field by field, with no build script and no generated file. - **Tokens handled**: static tokens, the client credentials grant, expiring offline tokens. Obtained, renewed before they expire, renewed once when Shopify refuses one, and saved where you say. @@ -82,32 +82,92 @@ println!("{} {:?} {}", order.name, order.display_financial_status, order.total_p Values are converted to the variable's type: any integer for an `Int`, `&str` or `String` for an `ID`, a bare value or an `Option` for a nullable variable, a slice or an array for a list. A value of the wrong type does not compile. +An enum value is written bare, `sortKey = TITLE`, and checked. + +### Input objects + +An input object is written as an object literal, checked against the schema +field by field while the crate compiles: + +```rust,ignore +shopify.execute(graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { field message } } }", + product = { + id: product_id, // any Rust expression + title: format!("{name} (promo)"), + status: ACTIVE, // an enum value, checked + descriptionHtml: null, // sends null + vendor?: new_vendor, // an Option: None leaves the field out + seo: { title: seo_title }, // a nested object + metafields: [for m in &rows if !m.value.is_empty() => { + namespace: "custom", key: &m.key, value: &m.value, type: "single_line_text_field", + }], + }, +)).await?; +``` + +A field is written one of four ways: + +| Field | Sends | +| --- | --- | +| `title: value` | The value | +| `title: null` | `null`: Shopify clears the field | +| `title?: option` | The value of `Some`; nothing for `None`, so Shopify keeps what it has | +| `title?: maybe` | A `shopify_api::Maybe`: `Value`, `Null`, or nothing for `Absent` | + +`title: option` does not compile: sending `null` for `None` would clear the +field, so the error points to `title?:` or `title: null`. An unknown field, a +field given twice, a missing required field, `null` for a non-null field, an +unknown enum value and `?:` on a required field are compile errors at the +token. For an enum value known only at run time, `raw(value)` sends the +string unchecked: `status: raw(row.status)`. + +`input!` builds an input object ahead of the call, in a loop for instance. +Every `input!` of one GraphQL type gives the same Rust type, so the values of +two call sites go in one `Vec`: + +```rust,ignore +use shopify_api::input; + +let mut metafields = Vec::new(); +for row in &rows { + if row.color.is_empty() { continue; } + metafields.push(input!(MetafieldsSetInput { + ownerId: &row.product_id, namespace: "custom", key: "color", value: &row.color, + type: "single_line_text_field", compareDigest?: row.digest.as_deref(), + })); +} +shopify.execute(graphql!( + "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", + metafields = metafields, +)).await?; +``` + +A value of another input type is refused, the message naming both GraphQL +types: `` an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` ``. ### Named -`graphql! { pub mod name = "…"; }` names the types, for functions, sharing and -typed input objects: +`graphql! { pub mod name = "…"; … }` names the types, for functions and +sharing. One block holds several modules. `Variables` runs as it is, and each +input object the variables hold is a type of the module: ```rust,ignore graphql! { pub mod metafields_set = "mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { - metafieldsSet(metafields: $metafields) { - metafields { id key } - userErrors { field message code } - } + metafieldsSet(metafields: $metafields) { metafields { id key } userErrors { field message code } } }"; + pub mod shop_name = "query ShopName { shop { name } }"; } -let variables = metafields_set::Variables { - metafields: vec![metafields_set::MetafieldsSetInput { - owner_id: product_id.to_string(), - namespace: Some("custom".to_string()), - key: "color".to_string(), - value: "blue".to_string(), - ..Default::default() - }], -}; -let data: metafields_set::Data = shopify.execute(metafields_set::operation(variables)).await?; +fn color_metafields(rows: &[Row]) -> Vec { + rows.iter() + .map(|row| input!(MetafieldsSetInput { ownerId: &row.product_id, key: "color", value: &row.color })) + .collect() +} + +let data = shopify.execute(metafields_set::Variables { metafields: color_metafields(&rows) }).await?; +let shop = shopify.execute(shop_name::operation()).await?; ``` ### From a file @@ -124,7 +184,19 @@ For an operation built at run time, `shopify.graphql(query, variables)` returns `data` as a `serde_json::Value`, `graphql_as::` reads it as your type, and `graphql_raw` returns the whole answer, `errors` included. -The full reference of `graphql!`, with the mapping of every GraphQL type, is +### Limits + +- A literal and an `input!` are checked against the schema of the crate + where they are written; values of `input!` from another crate have the same + type for the same GraphQL name. +- There is no `if`/`else` value form: a Rust expression returning an `Option`, + a `Maybe` or a value of `input!` covers it. +- rustc's own errors, outside those of the macros, show an input object as + `InputObject`, `N` a hash of its name. +- Enum fields of a module's `Variables` and `raw(…)` are strings nothing checks. + +The full reference of `graphql!`, with the mapping of every GraphQL type and +the rules of literals, is [on docs.rs](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html). ## API versions diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index 7d15e8e..954f585 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -88,5 +88,9 @@ required-features = ["rustls"] name = "bulk_export" required-features = ["rustls"] +[[example]] +name = "metafields" +required-features = ["rustls"] + [lints] workspace = true diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index d89bf0a..6de791e 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -112,23 +112,127 @@ carry them, convert them to your own types, or use a [module](#named-operations) Values follow the operation as `name = value`. A variable that is non-null without a default needs one; the others can be left out, and are then not sent. -A value is converted to the Rust type of its variable, so the usual -spellings work: + +A Rust value for a scalar variable is converted to the Rust type of the +variable, so the usual spellings work: | Variable | Accepted values | | --- | --- | -| `String`, `ID`, enums, string-encoded scalars | `String`, `&str`, `&String`, `Cow` | +| `String`, `ID`, string-encoded scalars | `String`, `&str`, `&String`, `Cow` | | `Int` | Any integer type | | `Float` | `f32`, `f64`, `i32`, `u32` | | `Boolean` | `bool` | | `JSON` | `Value`, `&Value` | -| Nullable | The bare value, or an `Option` of it | +| Nullable | The bare value, or an `Option` of it: `None` sends `null` | | List | A `Vec`, a slice, an array or a `&Vec` of accepted values | -| Input object | A value of [`input!`](crate::input!), or a `Vec`, a slice or an array of them for a list | Another type is a compile error on the value: `` `&str` is not a value for a GraphQL variable of Rust type `i64` `` (see [`IntoVariable`]). +An enum value is written bare, and checked: `sortKey = TITLE`. A string +known at run time goes through `raw(…)`, which nothing checks: +`sortKey = raw(key)`, an `Option` for a nullable variable. + +An input object is written as an object literal, checked field by field +against the schema, or given as a value built by [`input!`](crate::input!): + +```rust,no_run +use shopify_api::{Shopify, graphql}; + +struct Row { key: String, value: String } + +async fn promote(shopify: &Shopify, product_id: &str, name: &str, new_vendor: Option, rows: &[Row]) + -> shopify_api::Result<()> { + let data = shopify + .execute(graphql!( + "mutation($product: ProductUpdateInput!) { + productUpdate(product: $product) { userErrors { field message } } + }", + product = { + id: product_id, + title: format!("{name} (promo)"), + status: ACTIVE, + descriptionHtml: null, + vendor?: new_vendor, + seo: { title: name }, + metafields: [for row in rows if !row.value.is_empty() => { + namespace: "custom", key: &row.key, value: &row.value, type: "single_line_text_field", + }], + }, + )) + .await?; + for error in data.product_update.into_iter().flat_map(|payload| payload.user_errors) { + eprintln!("{:?}: {}", error.field, error.message); + } + Ok(()) +} +``` + +# Input values + +A value written for an input type reads by the GraphQL type expected where +it stands: + +| Form | Where | Sent | +| --- | --- | --- | +| `null` | A nullable type | `null` | +| `{ field: value, field?: option, … }` | An input object | The object, its fields in the order written | +| `[value, …]` | A list | The list; a single value is not taken for a list | +| `[for pattern in iterable => value]`, `[for … if condition => value]` | A list | One item per turn of the loop | +| `NAME` | An enum | The value, checked against the enum | +| `raw(string)` | An enum | The string, as is: any `Into` | +| Any other Rust expression | Anywhere | Its value, its type checked as below | + +In an object, the field names are the GraphQL ones, Rust keywords included +(`type: "single_line_text_field"`). A field that does not exist, a field +given twice, a required field left out (every one is named), `null` for a +non-null type, an unknown enum value (the valid ones are listed) and an +object or a list where the type wants another form are compile errors that +point at the token. A deprecated field or enum value is a warning that gives +Shopify's reason. + +A field is written one of four ways: + +| Field | Sends | +| --- | --- | +| `title: value` | The value | +| `title: null` | `null`: Shopify clears the field | +| `title?: option` | The value of `Some`; nothing for `None`, so Shopify keeps what it has | +| `title?: maybe` | A [`Maybe`]: `Value`, `Null` or nothing for `Absent` | + +An `Option` given to `title: …` does not compile: sending `null` for `None` +would clear the field. The error says to write `title?: …` or `title: null`. +A required field (non-null without a default) cannot take `?:`; a non-null +field with a default takes an `Option` there, not a [`Maybe`], whose `Null` it +refuses. On an enum field, `status?: raw(option)` takes an `Option` or a +`Maybe` of a string. A variable keeps its own rule: `name = option` sends +`null` for `None`. + +A Rust expression is checked by a trait written for its place, whose error +names the GraphQL type: `` `title` of `ProductUpdateInput` expects a `String`, +not `i32` ``. It takes what a variable takes (the table above), except for an +`Option` in a field. Where an input object is expected, it takes a value of +[`input!`](crate::input!) for that type, or a `Vec`, a slice or an array of +them for a list: `` `$metafields` expects a list of `MetafieldsSetInput`, built +with `input!(MetafieldsSetInput { … })` ``. An enum takes a bare value or +`raw(…)`, never another expression. + +What reads as what, when Rust could read it too: + +- `{` starts an object when the braces are empty or start with `name:` or + `name?:`, which no Rust block does: `first = { compute() }` stays a block. +- `[a, b]` is a list where a list is expected and a Rust array elsewhere; + `[x; 3]` is an array. A variable of a list of scalars given plain Rust + values, `ids = [a, b]`, is converted as before. +- `null` and `raw(…)` are those forms only as a whole value: a Rust variable + named `null` is written `(null)`, a function `raw` is called as + `self::raw(x)` or `(raw(x))`. +- A lone identifier is an enum value where an enum is expected, and a Rust + variable everywhere else. + +Nothing goes through a `serde_json::Value`: each literal is written straight +to the JSON sent, and a value of `input!` holds its JSON already. + # Named operations A module names the types of an operation: to share it, or to return its @@ -245,7 +349,21 @@ scripts an answer that leaves out a non-null field. # Limits -- Subscriptions are refused, and one `graphql!` takes one operation. -- The error points at the whole operation; the line and column in its message - locate the mistake inside it. +- Subscriptions are refused, and one inline `graphql!` takes one operation. +- An error in the operation points at the whole operation; the line and + column in its message locate the mistake inside it. An error in a value + points at the value. +- A literal or an `input!` is checked against the schema of the crate where + it is written. Values of `input!` from another crate have the same Rust + type, checked against that crate's schema. +- rustc's own errors, outside the messages of `graphql!` and `input!`, name an + input object `InputObject`, `N` being a hash of its GraphQL name: when a + `Vec` mixes two input types, for one. +- A `Maybe::Null` alone has no type to infer: write `field: null`, or + `Maybe::::Null`. +- A value is a literal, a list built by `for`, or a Rust expression: there is + no `if`/`else` form; an expression that returns an `Option`, a `Maybe` or a + value of `input!` covers it. +- Enum values are checked where they are written; the `String` fields of + `Variables` and `raw(…)` are not. - The generated code refers to `::shopify_api`: the dependency cannot be renamed. diff --git a/crates/shopify_api/examples/metafields.rs b/crates/shopify_api/examples/metafields.rs new file mode 100644 index 0000000..8b292c0 --- /dev/null +++ b/crates/shopify_api/examples/metafields.rs @@ -0,0 +1,95 @@ +//! Sets a `custom.color` metafield on the products listed on the command +//! line, then archives those without a color. +//! +//! ```bash +//! SHOPIFY_SHOP=my-shop SHOPIFY_ACCESS_TOKEN=shpat_… cargo run -p shopify_api --example metafields -- \ +//! gid://shopify/Product/1=blue gid://shopify/Product/2= +//! ``` + +use shopify_api::{Auth, Shopify, graphql, input}; + +graphql! { + /// Writes metafields and returns what Shopify refused. + mod metafields_set = "mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { + metafields { id key value } + userErrors { field message } + } + }"; + mod shop_name = "query ShopName { shop { name } }"; +} + +struct Row { + product_id: String, + color: String, +} + +fn color_metafields(rows: &[Row]) -> Vec { + let mut metafields = Vec::new(); + for row in rows { + if row.color.is_empty() { + continue; + } + metafields.push(input!(MetafieldsSetInput { + ownerId: &row.product_id, + namespace: "custom", + key: "color", + value: &row.color, + type: "single_line_text_field", + })); + } + metafields +} + +#[tokio::main] +async fn main() -> shopify_api::Result<()> { + let shop = std::env::var("SHOPIFY_SHOP").expect("SHOPIFY_SHOP"); + let token = std::env::var("SHOPIFY_ACCESS_TOKEN").expect("SHOPIFY_ACCESS_TOKEN"); + let shopify = Shopify::new(shop, Auth::access_token(token))?; + let rows: Vec = std::env::args() + .skip(1) + .filter_map(|argument| { + let (product_id, color) = argument.split_once('=')?; + Some(Row { + product_id: product_id.to_string(), + color: color.to_string(), + }) + }) + .collect(); + + let shop = shopify.execute(shop_name::operation()).await?; + println!("{}", shop.shop.name); + + let data = shopify + .execute(metafields_set::Variables { + metafields: color_metafields(&rows), + }) + .await?; + if let Some(payload) = data.metafields_set { + for metafield in payload.metafields.into_iter().flatten() { + println!("{} = {}", metafield.key, metafield.value); + } + for error in payload.user_errors { + eprintln!("{:?}: {}", error.field, error.message); + } + } + + for row in rows.iter().filter(|row| row.color.is_empty()) { + let data = shopify + .execute(graphql!( + "mutation($product: ProductUpdateInput!) { + productUpdate(product: $product) { userErrors { field message } } + }", + product = { id: &row.product_id, status: ARCHIVED }, + )) + .await?; + for error in data + .product_update + .into_iter() + .flat_map(|payload| payload.user_errors) + { + eprintln!("{}: {:?}: {}", row.product_id, error.field, error.message); + } + } + Ok(()) +} diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index 4fbedb5..81a2e57 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -38,7 +38,8 @@ //! ``` //! //! See the [`graphql!`] macro for the mapping of types, named operations, -//! input objects and the schema of other API versions. +//! input values and the schema of other API versions, and [`input!`] for an +//! input object built ahead of a call. //! //! # Features //! diff --git a/crates/shopify_api_graphql/README.md b/crates/shopify_api_graphql/README.md index dd06124..261f109 100644 --- a/crates/shopify_api_graphql/README.md +++ b/crates/shopify_api_graphql/README.md @@ -1,8 +1,9 @@ # shopify_api_graphql The compile-time half of [`shopify_api`](https://crates.io/crates/shopify_api)'s -`graphql!` macro: it reads Shopify's Admin GraphQL schema, checks an operation -against it, and generates the Rust types of its variables and of its result. +`graphql!` and `input!` macros: it reads Shopify's Admin GraphQL schema, +checks an operation against it, generates the Rust types of its variables and +of its result, and checks the input values written in Rust. You do not need to depend on it directly: use `shopify_api::graphql!`. It is a separate crate so that the macro and the `shopify-api` command line share it. diff --git a/crates/shopify_api_macros/README.md b/crates/shopify_api_macros/README.md index c22e27c..e2f876e 100644 --- a/crates/shopify_api_macros/README.md +++ b/crates/shopify_api_macros/README.md @@ -1,5 +1,6 @@ # shopify_api_macros -The `graphql!` procedural macro of [`shopify_api`](https://crates.io/crates/shopify_api). -Use it through `shopify_api::graphql!`, which documents it: the generated code -refers to `shopify_api` and does not compile without it. +The `graphql!` and `input!` procedural macros of [`shopify_api`](https://crates.io/crates/shopify_api). +Use them through `shopify_api::graphql!` and `shopify_api::input!`, which +document them: the generated code refers to `shopify_api` and does not compile +without it. From 56bf90ccad1b36f3a2253328b1d9588e74165b9c Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:10:47 +0200 Subject: [PATCH 055/135] fix(graphql): no generated name is in scope of the values MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A check generated for a value of `graphql!` or `input!` was a function in the block where the value was evaluated: a closure, function or local of the caller's with its name was replaced by it, or refused. Each Rust expression is now the argument of a method of a type declared in a block of its own, the receiver of the call, called by value so that no trait method wins over it. Variables are arguments of the setters, outside the block of the operation's types. No local is declared where a constant of the caller's could match it: the list of `[for … => …]` is named after a name its pattern binds, with mixed-site hygiene, and a pattern that binds none is refused with a message that says what to write. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/tests/literals.rs | 162 ++++++++++++++++++ .../tests/ui/literal_for_binds_no_name.rs | 3 + .../tests/ui/literal_for_binds_no_name.stderr | 6 + ...literal_maybe_non_null_with_default.stderr | 9 +- .../tests/ui/literal_option_in_field.stderr | 13 +- .../tests/ui/literal_wrong_input_type.stderr | 13 +- crates/shopify_api_graphql/src/literal.rs | 121 ++++++++++--- crates/shopify_api_graphql/tests/literal.rs | 14 +- crates/shopify_api_macros/src/lib.rs | 34 ++-- crates/shopify_api_macros/src/value.rs | 50 ++++++ 10 files changed, 349 insertions(+), 76 deletions(-) create mode 100644 crates/shopify_api/tests/ui/literal_for_binds_no_name.rs create mode 100644 crates/shopify_api/tests/ui/literal_for_binds_no_name.stderr diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs index ad9d544..0174835 100644 --- a/crates/shopify_api/tests/literals.rs +++ b/crates/shopify_api/tests/literals.rs @@ -399,3 +399,165 @@ async fn a_nullable_input_variable_takes_null_an_option_or_a_literal() { ) ); } + +/// Names like the ones the macros generate, or generated before, given to +/// the caller's locals, closures, functions, constants and trait methods: +/// the values sent are the caller's. +mod hygiene { + #![allow(non_upper_case_globals, non_snake_case, dead_code)] + + use serde_json::{Value, json}; + use shopify_api::{graphql, input}; + + /// A trait method by value for every type, named like the methods the + /// generated code calls. + trait Capture: Sized { + fn check(self, _: &str) -> &'static str { + "captured" + } + fn optional(self, _: Option<&str>) -> Option<&'static str> { + Some("captured") + } + fn push(self, _: &str) {} + fn variable(self, _: &str, _: V) -> Self { + self + } + fn __literal_variable(self, _: &str, _: V) -> Self { + self + } + } + impl Capture for T {} + + fn json(value: impl serde::Serialize) -> Value { + serde_json::to_value(value).unwrap() + } + + #[test] + fn locals_and_closures() { + let __shopify_api_check1 = |text: &str| format!("closure:{text}"); + let __shopify_api_check3 = |text: &str| format!("closure:{text}"); + let __shopify_api_optional1 = |text: &str| Some(format!("closure:{text}")); + let __shopify_api_checks = "local"; + let __shopify_api_items = vec!["local"]; + let __shopify_api_variable_0 = "local"; + let check = |text: &str| format!("closure:{text}"); + let Checks = "local"; + let value = input!(ProductUpdateInput { + title: __shopify_api_check3("a"), + vendor: __shopify_api_check1("b"), + handle: check("c"), + productType: __shopify_api_checks, + descriptionHtml: __shopify_api_variable_0, + templateSuffix?: __shopify_api_optional1("d"), + tags: [for tag in &__shopify_api_items => Checks.to_string() + tag], + }); + assert_eq!( + json(&value), + json!({ + "title": "closure:a", + "vendor": "closure:b", + "handle": "closure:c", + "productType": "local", + "descriptionHtml": "local", + "templateSuffix": "closure:d", + "tags": ["locallocal"], + }) + ); + + let operation = graphql!( + "mutation($product: ProductUpdateInput!, $media: [CreateMediaInput!], $first: Int) { productUpdate(product: $product, media: $media) { product { variants(first: $first) { nodes { id } } } userErrors { message } } }", + product = { title: __shopify_api_check3("e"), tags: __shopify_api_items.clone() }, + media = [for alt in [__shopify_api_variable_0] => { originalSource: check(alt), mediaContentType: IMAGE, alt: alt }], + first = __shopify_api_items.len(), + ); + assert_eq!( + operation.body().unwrap()["variables"], + json!({ + "product": { "title": "closure:e", "tags": ["local"] }, + "media": [{ "originalSource": "closure:local", "mediaContentType": "IMAGE", "alt": "local" }], + "first": 1, + }) + ); + } + + mod items { + use super::*; + + const __shopify_api_check1: &str = "const"; + const __shopify_api_checks: &str = "const"; + const __shopify_api_items: [&str; 1] = ["const"]; + const __shopify_api_variable_0: &str = "const"; + const Checks: &str = "const"; + const checks: &str = "const"; + const items: &str = "const"; + static __shopify_api_optional1: &str = "static"; + fn __shopify_api_check2(text: &str) -> String { + format!("fn:{text}") + } + fn check(text: &str) -> String { + format!("fn:{text}") + } + fn optional(text: Option<&str>) -> Option { + text.map(|text| format!("fn:{text}")) + } + + #[test] + fn functions_constants_and_statics() { + let value = input!(ProductUpdateInput { + title: __shopify_api_check2("a"), + vendor: check("b"), + handle: __shopify_api_check1, + productType: __shopify_api_checks, + descriptionHtml: Checks, + templateSuffix?: optional(Some(__shopify_api_optional1)), + tags: [for tag in __shopify_api_items => check(tag)], + }); + assert_eq!( + json(&value), + json!({ + "title": "fn:a", + "vendor": "fn:b", + "handle": "const", + "productType": "const", + "descriptionHtml": "const", + "templateSuffix": "fn:static", + "tags": ["fn:const"], + }) + ); + let operation = graphql!( + "mutation($product: ProductUpdateInput!, $media: [CreateMediaInput!], $first: Int) { productUpdate(product: $product, media: $media) { product { variants(first: $first) { nodes { id } } } userErrors { message } } }", + product = { title: __shopify_api_variable_0, tags: [for tag in [checks, items] => tag] }, + first = __shopify_api_items.len(), + ); + assert_eq!( + operation.body().unwrap()["variables"], + json!({ "product": { "title": "const", "tags": ["const", "const"] }, "first": 1 }) + ); + } + } + + struct Product { + title: &'static str, + } + + impl Product { + const SUFFIX: &'static str = "suffix"; + + /// In a method, where `Self` and `self` are the caller's. + fn input(&self) -> Value { + json(input!(ProductUpdateInput { + title: self.title, + templateSuffix: Self::SUFFIX, + tags: [for tag in [Self::SUFFIX] => tag], + })) + } + } + + #[test] + fn self_and_self_type_are_the_callers() { + assert_eq!( + Product { title: "t" }.input(), + json!({ "title": "t", "templateSuffix": "suffix", "tags": ["suffix"] }) + ); + } +} diff --git a/crates/shopify_api/tests/ui/literal_for_binds_no_name.rs b/crates/shopify_api/tests/ui/literal_for_binds_no_name.rs new file mode 100644 index 0000000..d162b5f --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_for_binds_no_name.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(ProductUpdateInput { tags: [for _ in 0..3 => "sale"] }); +} diff --git a/crates/shopify_api/tests/ui/literal_for_binds_no_name.stderr b/crates/shopify_api/tests/ui/literal_for_binds_no_name.stderr new file mode 100644 index 0000000..b951a32 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_for_binds_no_name.stderr @@ -0,0 +1,6 @@ +error: The pattern of `[for pattern in … => …]` binds no name: name what it gives, as `[for _item in … => …]` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_for_binds_no_name.rs:2:60 + | +2 | let _ = shopify_api::input!(ProductUpdateInput { tags: [for _ in 0..3 => "sale"] }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr index 7db96ad..6d660f5 100644 --- a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -2,10 +2,7 @@ error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[Inven --> tests/ui/literal_maybe_non_null_with_default.rs:6:63 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); - | --------------------------------------------------^^^^^^^^^^--- - | | | - | | an `Option`: `None` leaves the field out - | required by a bound introduced by this call + | ^^^^^^^^^^ an `Option`: `None` leaves the field out | = help: the trait `__ShopifyApiNoNull4` is not implemented for `Vec>` help: this trait has no implementations, consider adding one @@ -18,9 +15,9 @@ note: required for `Maybe>>` to implement | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required by a bound in `__shopify_api_optional4` +note: required by a bound in `main::Checks::optional` --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `__shopify_api_optional4` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::optional` = note: this error originates in the macro `input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr index 1af6ef3..90530dc 100644 --- a/crates/shopify_api/tests/ui/literal_option_in_field.stderr +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -2,25 +2,22 @@ error[E0277]: `vendor` of `ProductUpdateInput` takes a `String`, not an `Option` --> tests/ui/literal_option_in_field.rs:3:93 | 3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); - | --------------------------------------------------------------------------------^^^^^^--- - | | | - | | `vendor: None` would send `null`, which clears the field - | required by a bound introduced by this call + | ^^^^^^ `vendor: None` would send `null`, which clears the field | - = help: the trait `__ShopifyApiNoOption5` is not implemented for `String` + = help: the trait `__ShopifyApiNoOption4` is not implemented for `String` help: this trait has no implementations, consider adding one --> tests/ui/literal_option_in_field.rs:3:13 | 3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required for `Option` to implement `__ShopifyApiExpect4` +note: required for `Option` to implement `__ShopifyApiExpect3` --> tests/ui/literal_option_in_field.rs:3:13 | 3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required by a bound in `__shopify_api_check6` +note: required by a bound in `main::Checks::check` --> tests/ui/literal_option_in_field.rs:3:13 | 3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `__shopify_api_check6` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::check` = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr index 337b142..e9c630c 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -1,13 +1,8 @@ error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` --> tests/ui/literal_wrong_input_type.rs:5:22 | -3 | let _ = shopify_api::graphql!( - | _____________- -4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", -5 | | metafields = seo, - | | ^^^ build it with `input!(MetafieldsSetInput { … })` -6 | | ); - | |_____- required by a bound introduced by this call +5 | metafields = seo, + | ^^^ build it with `input!(MetafieldsSetInput { … })` | = help: the trait `__ShopifyApiExpect2` is not implemented for `InputObject<2493993284262097346>` help: the following other types implement trait `__ShopifyApiExpect2` @@ -31,7 +26,7 @@ note: required for `Vec>` to implement `main::_ 5 | | metafields = seo, 6 | | ); | |_____^ -note: required by a bound in `main::__shopify_api_check3` +note: required by a bound in `main::Checks::check` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -39,5 +34,5 @@ note: required by a bound in `main::__shopify_api_check3` 4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", 5 | | metafields = seo, 6 | | ); - | |_____^ required by this bound in `__shopify_api_check3` + | |_____^ required by this bound in `Checks::check` = note: this error originates in the macro `shopify_api::graphql` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index c809444..6111f3c 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -20,7 +20,7 @@ use std::collections::BTreeMap; use std::fmt; -use proc_macro2::{Ident, Span, TokenStream}; +use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; use quote::{format_ident, quote, quote_spanned}; use crate::analyze::{Scalar, Variable, did_you_mean}; @@ -88,6 +88,8 @@ pub struct For { /// Of the brackets. pub span: Span, pub pattern: TokenStream, + /// A name the pattern binds, if it binds one. + pub binding: Option, pub iterable: TokenStream, pub filter: Option, pub item: Value, @@ -153,8 +155,13 @@ enum Place { Item, } -/// Checks values against a schema and writes their code. The code refers -/// to items [`Literals::finish`] returns, to put in the same block. +/// Checks values against a schema and writes their code. +/// +/// No name the code declares is in scope where a Rust expression of a value +/// is evaluated, so that none captures or shadows a name of the caller's: +/// each expression is checked by the method of a type declared in a block +/// of its own, the receiver of the call, and the code declares no local +/// that a constant of the caller's could match. pub struct Literals<'a> { schema: &'a Schema, krate: TokenStream, @@ -183,7 +190,7 @@ impl<'a> Literals<'a> { } } - /// The traits, functions and warnings the code written so far needs. + /// The warnings the code written so far gives: unnamed constants. pub fn finish(self) -> TokenStream { let items = self.items; quote!(#(#items)*) @@ -339,14 +346,28 @@ impl<'a> Literals<'a> { let value = self.value(&comprehension.item, item, &site, Place::Item)?; let For { pattern, + binding, iterable, filter, .. } = &**comprehension; + // The list is a local named after a name the pattern binds: + // the pattern compiles, so no constant of that name is in + // scope. Its mixed-site hygiene keeps the two apart. + let Some(binding) = binding else { + return error( + comprehension.span, + "The pattern of `[for pattern in … => …]` binds no name: name what it gives, as `[for _item in … => …]`", + ); + }; + let name = binding.to_string(); + let items = match name.strip_prefix("r#") { + Some(name) => Ident::new_raw(name, Span::mixed_site()), + None => Ident::new(&name, Span::mixed_site()), + }; // Each item is written in its turn of the loop, so that it may // borrow what the loop gives. - let items = Ident::new("__shopify_api_items", Span::mixed_site()); - let push = quote!(#items.push(#krate::__private::literal::to_raw(&#value));); + let push = quote!(::std::vec::Vec::push(&mut #items, #krate::__private::literal::to_raw(&#value));); let body = match filter { Some(filter) => quote!(if #filter { #push }), None => push, @@ -493,10 +514,10 @@ impl<'a> Literals<'a> { ); } - let value_bound = self.expect(&definition.ty, Place::Field, site); + let mut items = Vec::new(); + let value_bound = self.expect(&definition.ty, Place::Field, site, &mut items); let n = self.next(); let bound = format_ident!("__ShopifyApiOptional{n}"); - let check = format_ident!("__shopify_api_optional{n}"); let what = escape(&self.what(&definition.ty)); let (message, label, maybe_bound) = if null_refused { let no_null = format_ident!("__ShopifyApiNoNull{n}"); @@ -504,7 +525,7 @@ impl<'a> Literals<'a> { "{site} is non-null (`{}`): `{key}?:` takes an `Option`, not a `Maybe`, whose `Null` it refuses", definition.ty )); - self.items.push(quote! { + items.push(quote! { #[diagnostic::on_unimplemented(message = #refusal, label = "an `Option`: `None` leaves the field out")] trait #no_null {} }); @@ -524,17 +545,22 @@ impl<'a> Literals<'a> { ) }; // `IntoMaybe` as a supertrait: one refusal, which names the field. - self.items.push(quote! { + items.push(quote! { #[diagnostic::on_unimplemented(message = #message, label = #label)] trait #bound: #krate::__private::literal::IntoMaybe {} impl #bound for ::core::option::Option {} impl #bound for #krate::Maybe {} - fn #check>(value: V) -> #krate::Maybe { - #krate::__private::literal::IntoMaybe::into_maybe(value) - } }); - let tokens = &expr.tokens; - Ok(quote_spanned!(expr.span=> #check(#tokens))) + let checks = checks( + &items, + quote! { + fn optional>(self, value: V) -> #krate::Maybe { + #krate::__private::literal::IntoMaybe::into_maybe(value) + } + }, + ); + let tokens = argument(&expr); + Ok(quote_spanned!(expr.span=> #checks.optional(#tokens))) } /// A Rust expression for a value of type `ty`, checked by a trait. @@ -559,20 +585,29 @@ impl<'a> Literals<'a> { }; return error(expr.span, message); } - let bound = self.expect(ty, place, site); - let check = format_ident!("__shopify_api_check{}", self.next()); - self.items.push(quote! { - fn #check(value: V) -> V { - value - } - }); - let tokens = &expr.tokens; - Ok(quote_spanned!(expr.span=> #check(#tokens))) + let mut items = Vec::new(); + let bound = self.expect(ty, place, site, &mut items); + let checks = checks( + &items, + quote! { + fn check(self, value: V) -> V { + value + } + }, + ); + let tokens = argument(expr); + Ok(quote_spanned!(expr.span=> #checks.check(#tokens))) } /// The trait a Rust expression of type `ty` must implement at `place`, /// whose refusal names the GraphQL type. - fn expect(&mut self, ty: &TypeRef, place: Place, site: &Site) -> Ident { + fn expect( + &mut self, + ty: &TypeRef, + place: Place, + site: &Site, + items: &mut Vec, + ) -> Ident { let bound = format_ident!("__ShopifyApiExpect{}", self.next()); let krate = self.krate.clone(); let what = self.what(ty); @@ -582,13 +617,18 @@ impl<'a> Literals<'a> { if !ty.is_non_null() && place != Place::Field { label.push_str(", or an `Option` of it, `None` sending `null`"); let non_null = TypeRef::NonNull(Box::new(inner.clone())); - let value = self.expect(&non_null, place, site); + let value = self.expect(&non_null, place, site, items); impls.push(quote!(impl #bound for V {})); impls.push(quote!(impl #bound for ::core::option::Option {})); } else { match inner { TypeRef::List(item) => { - let item = self.expect(item, Place::Item, &Site::Item(Box::new(site.clone()))); + let item = self.expect( + item, + Place::Item, + &Site::Item(Box::new(site.clone())), + items, + ); impls.push(quote! { impl #bound for ::std::vec::Vec {} impl<'a, V: #item> #bound for &'a ::std::vec::Vec {} @@ -629,7 +669,7 @@ impl<'a> Literals<'a> { escape(&what) ); let label = escape(&label); - self.items.push(quote! { + items.push(quote! { #[diagnostic::on_unimplemented(message = #message, label = #label)] trait #bound {} #(#impls)* @@ -887,6 +927,31 @@ fn scalar_types(scalar: Scalar, krate: &TokenStream) -> Vec { } } +/// The receiver of a check: a value of a type declared, with what its +/// method needs, in a block that no expression of the caller's is in. By +/// value, so that no trait method of the same name wins over the method. +fn checks(items: &[TokenStream], method: TokenStream) -> TokenStream { + quote! { + ({ + #(#items)* + struct Checks; + impl Checks { + #method + } + Checks + }) + } +} + +/// An expression of the caller's as an argument, in parentheses of the +/// macro's at its place: its braces are not a method argument of the +/// caller's to lint, and a refusal points at it. +pub fn argument(expr: &Expr) -> TokenStream { + let mut group = Group::new(Delimiter::Parenthesis, expr.tokens.clone()); + group.set_span(Span::mixed_site().located_at(expr.span)); + TokenTree::Group(group).into() +} + fn ident_expr(ident: &Ident) -> Expr { Expr { tokens: quote!(#ident), diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index dfd4120..821e0e5 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -69,13 +69,15 @@ fn list(items: Vec) -> Value { }) } -/// The code of `input!(name { … })` and the items it needs, or the refusal. +/// The code of `input!(name { … })` and, after it, its warnings, or the +/// refusal. fn input(name: &str, fields: Vec<(&str, Value)>) -> Result<(String, String), String> { let mut literals = Literals::new(admin(), quote!(::shopify_api)); let code = literals .input_object(name, Span::call_site(), &object(fields)) .map_err(|error| error.message)?; - Ok((code.to_string(), literals.finish().to_string())) + let all = format!("{code} {}", literals.finish()); + Ok((code.to_string(), all)) } fn refusal(name: &str, fields: Vec<(&str, Value)>) -> String { @@ -104,6 +106,7 @@ fn an_object_is_sent_field_by_field_in_its_order() { Value::For(Box::new(For { span: Span::call_site(), pattern: quote!(m), + binding: Some(Ident::new("m", Span::call_site())), iterable: quote!(&rows), filter: Some(quote!(!m.value.is_empty())), item: Value::Object(object(vec![ @@ -119,7 +122,7 @@ fn an_object_is_sent_field_by_field_in_its_order() { let id = input_object_id("ProductUpdateInput"); assert!( code.starts_with(&format!( - ":: shopify_api :: InputObject :: < {id}u64 > :: __new (\"ProductUpdateInput\" , & :: shopify_api :: __private :: literal :: Object ((:: shopify_api :: __private :: literal :: Field (\"id\" , __shopify_api_check" + ":: shopify_api :: InputObject :: < {id}u64 > :: __new (\"ProductUpdateInput\" , & :: shopify_api :: __private :: literal :: Object ((:: shopify_api :: __private :: literal :: Field (\"id\" , ({{" )), "{code}" ); @@ -439,7 +442,10 @@ fn inline_variables_of_scalars_convert_as_before_and_others_are_literals() { let VariableValue::Literal(code) = variable(metafields, rust("rows")).unwrap() else { panic!("a literal"); }; - assert!(code.to_string().contains("__shopify_api_check"), "{code}"); + assert!( + code.to_string().contains("Checks }) . check ((rows))"), + "{code}" + ); assert_eq!( variable(metafields, Value::Object(object(vec![]))).unwrap_err(), "`$metafields` expects a list of `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })`, not an object" diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 1077348..2db5f65 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -517,33 +517,26 @@ fn expand_expression( )); } - // Evaluated before the generated types are in scope, so that the - // values cannot name them by accident. + // The values are arguments of the setters, outside the block that + // declares the types of the operation: they cannot name them. let mut literals = Literals::new(schema.schema(), krate.clone()); - let mut values = Vec::new(); let mut setters = Vec::new(); - for (index, (declared, value)) in given.iter().enumerate() { - let local = Ident::new( - &format!("__shopify_api_variable_{index}"), - Span::mixed_site(), - ); + for (declared, value) in &given { let key = &declared.name; match literals .variable(declared, value) .map_err(|error| schema.literal_error(error))? { VariableValue::Converted { ty, value } => { - let tokens = &value.tokens; - values.push(quote!(let #local = #tokens;)); - setters.push(quote_spanned!(value.span=> .variable::<#ty, _>(#key, #local))); + let tokens = literal::argument(&value); + setters.push(quote_spanned!(value.span=> .variable::<#ty, _>(#key, #tokens))); } VariableValue::Literal(code) => { - values.push(quote!(let #local = #code;)); - setters.push(quote!(.__literal_variable(#key, #local))); + setters.push(quote!(.__literal_variable(#key, #code))); } } } - let checks = literals.finish(); + let literal_warnings = literals.finish(); let tracking = schema.tracking(); let file = text.tracking(); @@ -551,18 +544,17 @@ fn expand_expression( let types = data_types(&operation, &krate); let query = &text.query; let constructor = constructor(schema.schema(), &operation, "e!(#query), &krate); - Ok(quote! {{ - #checks - #(#values)* - { + Ok(quote! { + ({ #tracking #file #warnings + #literal_warnings #types #constructor - #(#setters)* - } - }}) + }) + #(#setters)* + }) } /// `graphql! { mod name = "…"; }`: the operation as a module that names its types. diff --git a/crates/shopify_api_macros/src/value.rs b/crates/shopify_api_macros/src/value.rs index ff0bffd..31b4c42 100644 --- a/crates/shopify_api_macros/src/value.rs +++ b/crates/shopify_api_macros/src/value.rs @@ -154,6 +154,7 @@ fn parse_for(input: ParseStream, span: Span) -> syn::Result { } Ok(Value::For(Box::new(For { span, + binding: binding(&pattern), pattern: pattern.into_token_stream(), iterable: iterable.into_token_stream(), filter, @@ -161,6 +162,33 @@ fn parse_for(input: ParseStream, span: Span) -> syn::Result { }))) } +/// The first name `pattern` binds. A lone identifier that starts with a +/// capital is taken for a constant, a unit struct or a variant. +fn binding(pattern: &syn::Pat) -> Option { + use syn::Pat; + match pattern { + Pat::Ident(pattern) => { + let name = pattern.ident.unraw().to_string(); + if name != "_" && !name.starts_with(|first: char| first.is_uppercase()) { + return Some(pattern.ident.clone()); + } + pattern + .subpat + .as_ref() + .and_then(|(_, pattern)| binding(pattern)) + } + Pat::Or(pattern) => pattern.cases.first().and_then(binding), + Pat::Paren(pattern) => binding(&pattern.pat), + Pat::Reference(pattern) => binding(&pattern.pat), + Pat::Type(pattern) => binding(&pattern.pat), + Pat::Tuple(pattern) => pattern.elems.iter().find_map(binding), + Pat::TupleStruct(pattern) => pattern.elems.iter().find_map(binding), + Pat::Slice(pattern) => pattern.elems.iter().find_map(binding), + Pat::Struct(pattern) => pattern.fields.iter().find_map(|field| binding(&field.pat)), + _ => None, + } +} + fn expr(value: &syn::Expr) -> Expr { Expr { tokens: value.to_token_stream(), @@ -282,6 +310,28 @@ mod tests { } } + #[test] + fn finds_a_name_the_pattern_of_a_for_binds() { + for (pattern, name) in [ + ("m", Some("m")), + ("(i, m)", Some("i")), + ("(_, m)", Some("m")), + ("&Row { id, .. }", Some("id")), + ("Some(x) | None", Some("x")), + ("ref mut r#type", Some("r#type")), + ("whole @ (_, _)", Some("whole")), + ("_", None), + ("(_, Marker)", None), + ("[_, _]", None), + ] { + let Value::For(comprehension) = parse(&format!("[for {pattern} in xs => 1]")) else { + panic!("{pattern}"); + }; + let found = comprehension.binding.map(|ident| ident.to_string()); + assert_eq!(found.as_deref(), name, "{pattern}"); + } + } + #[test] fn says_what_is_wrong_in_an_object() { for (text, message) in [ From 2a5c19f7eeea69f77e9739d965a31720220111d2 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:18:41 +0200 Subject: [PATCH 056/135] fix(graphql)!: refuse values Shopify would not read as written A `Float` that is NaN or infinite was sent as `null`, turning an update into a clear; an `Int` beyond 32 bits was sent as is; a top-level `null` went to a non-null `JSON`; and a value whose `Serialize` failed made `input!` panic, printing the serializer's message. The value is now checked when it is built, and a refusal is kept: in the `InputObject`, and in the variable of the `Operation`. The operation fails with the new `Error::InvalidValue` before anything is sent; its `Display` names the place, `$product.metafields[2].value`, and the reason, never the value; a serializer's message stays behind `sensitive_detail()`. It covers the literals of `graphql!`, `input!`, the `Variables` of modules and `Operation::variable`, whose `T` is now a sealed `VariableType`. An `InputObject` that is refused fails to serialize on its own too. Nothing in the generated or runtime code panics on a value any more. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/error.rs | 71 +++- crates/shopify_api/src/graphql.rs | 2 + crates/shopify_api/src/graphql/check.rs | 325 ++++++++++++++++++ crates/shopify_api/src/graphql/input.rs | 33 +- crates/shopify_api/src/graphql/literal.rs | 221 +++++++++++- crates/shopify_api/src/graphql/operation.rs | 183 ++++++++-- crates/shopify_api/src/lib.rs | 4 +- crates/shopify_api/tests/literals.rs | 131 +++++++ .../tests/ui/wrong_value_type.stderr | 4 +- crates/shopify_api_graphql/src/codegen.rs | 5 +- crates/shopify_api_graphql/src/literal.rs | 68 +++- crates/shopify_api_graphql/tests/literal.rs | 47 ++- 12 files changed, 1013 insertions(+), 81 deletions(-) create mode 100644 crates/shopify_api/src/graphql/check.rs diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index 17fca60..6ef734e 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -2,7 +2,7 @@ use std::fmt; -use crate::graphql::{Cost, GraphqlError, UserError}; +use crate::graphql::{Cost, GraphqlError, InvalidValueReason, UserError}; use crate::transport::{HttpResponse, TransportError}; /// `Result`. @@ -28,6 +28,8 @@ pub type Result = std::result::Result; /// `[key]`; /// - nothing of what a `Serialize` implementation wrote: [`Error::Variables`] /// says which variable does not serialize, and why in this crate's words; +/// - no value of a variable: [`Error::InvalidValue`] says where the value +/// stands and why it is refused; /// - of an address, the scheme, the host and the path only: no user, no /// password, no query string (a signature), no fragment; /// - of the token endpoint's refusal, its status and its standard OAuth error @@ -139,6 +141,26 @@ pub enum Error { detail: Option, }, + /// A value of a variable that Shopify would not read as it was + /// written, refused before anything is sent: a `Float` that is NaN or + /// infinite (JSON writes it as `null`), an `Int` outside of 32 bits, a + /// top-level `null` for a non-null `JSON`, or a value that does not + /// serialize. [`input!`](crate::input!), the values of + /// [`graphql!`](crate::graphql!) and [`Operation::variable`](crate::Operation::variable) + /// keep it when the value is built; the operation fails with it when it + /// is sent or its body is read. + #[non_exhaustive] + InvalidValue { + /// Where the value stands: the variable, then the fields and + /// indexes of the schema, `$product.metafields[2].value`. A variable + /// whose name is not a GraphQL name is `$[variable]`. + path: String, + reason: InvalidValueReason, + /// The message of the `Serialize` implementation that failed: it may + /// quote the value. See [`Error::sensitive_detail`]. + detail: Option, + }, + /// A token could not be obtained or renewed. #[non_exhaustive] Auth { @@ -207,6 +229,9 @@ impl fmt::Display for Error { "Shopify's answer does not match the operation at `{path}`: {message}" ), Self::Variables { message, .. } => write!(formatter, "invalid variables: {message}"), + Self::InvalidValue { path, reason, .. } => { + write!(formatter, "invalid value at `{path}`: {reason}") + } Self::Auth { message, .. } => write!(formatter, "authentication failed: {message}"), Self::UserErrors { mutation, errors } => { write!(formatter, "{mutation} refused: {}", UserErrors(errors)) @@ -296,6 +321,16 @@ impl fmt::Debug for Error { .field("message", message) .field("detail", detail) .finish(), + Self::InvalidValue { + path, + reason, + detail, + } => formatter + .debug_struct("InvalidValue") + .field("path", path) + .field("reason", reason) + .field("detail", detail) + .finish(), Self::Auth { message, detail } => formatter .debug_struct("Auth") .field("message", message) @@ -405,9 +440,9 @@ impl Error { } /// The text this crate does not show, for [`Error::Decode`] (serde's - /// message), [`Error::Variables`] (the message of the `Serialize` - /// implementation that failed) and [`Error::Auth`] (what the token - /// endpoint said). + /// message), [`Error::Variables`] and [`Error::InvalidValue`] (the + /// message of the `Serialize` implementation that failed) and + /// [`Error::Auth`] (what the token endpoint said). /// /// **It may contain secrets**: serde quotes the value that does not fit, /// a map key, or what a type's own implementation wrote, and a token @@ -416,6 +451,7 @@ impl Error { match self { Self::Decode { detail, .. } | Self::Variables { detail, .. } + | Self::InvalidValue { detail, .. } | Self::Auth { detail, .. } => detail.as_ref().map(SensitiveDetail::as_str), _ => None, } @@ -513,7 +549,7 @@ impl Error { } /// A GraphQL name: what a variable is called in an operation. -fn is_graphql_name(name: &str) -> bool { +pub(crate) fn is_graphql_name(name: &str) -> bool { let mut bytes = name.bytes(); bytes .next() @@ -549,6 +585,10 @@ impl fmt::Debug for RawBody { pub struct SensitiveDetail(String); impl SensitiveDetail { + pub(crate) fn new(detail: String) -> Self { + Self(detail) + } + /// The message. It may contain secrets: do not log it. pub fn as_str(&self) -> &str { &self.0 @@ -903,6 +943,25 @@ mod tests { .variables_json() .unwrap_err(), )); + errors.push(( + "InvalidValue", + crate::graphql::Operation::::new("query { shop { id } }") + .variable::(&format!("{TOKEN}\""), f64::NAN) + .variables_json() + .unwrap_err(), + )); + errors.push(( + "InvalidValue, does not serialize", + crate::graphql::Operation::::new("query { shop { id } }") + .__literal_variable( + "x", + Err(crate::graphql::check::Invalid::unserializable( + &serde_json::to_value(Leaky).unwrap_err(), + )), + ) + .variables_json() + .unwrap_err(), + )); errors.push(( "Variables of graphql_raw", crate::graphql::operation::variables_of(BTreeMap::from([("x", Leaky)])).unwrap_err(), @@ -980,6 +1039,7 @@ mod tests { "Http", "InvalidApiVersion", "InvalidShop", + "InvalidValue", "NoTransport", "Throttled", "Timeout", @@ -1007,6 +1067,7 @@ mod tests { Error::Throttled { .. } => "Throttled", Error::Decode { .. } => "Decode", Error::Variables { .. } => "Variables", + Error::InvalidValue { .. } => "InvalidValue", Error::Auth { .. } => "Auth", Error::UserErrors { .. } => "UserErrors", Error::Bulk(_) => "Bulk", diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index 6c91b0d..a862e1e 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -1,6 +1,7 @@ //! Running GraphQL operations: typed ones from [`graphql!`](crate::graphql!), //! untyped ones from any text. +pub(crate) mod check; mod input; pub mod literal; pub(crate) mod operation; @@ -10,6 +11,7 @@ use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::{Map, Value}; +pub use check::{InvalidValueReason, VariableType}; pub use input::{InputObject, Maybe}; pub use operation::{IntoVariable, Operation, OperationKind}; pub use response::{ diff --git a/crates/shopify_api/src/graphql/check.rs b/crates/shopify_api/src/graphql/check.rs new file mode 100644 index 0000000..7854119 --- /dev/null +++ b/crates/shopify_api/src/graphql/check.rs @@ -0,0 +1,325 @@ +//! What a value must be for Shopify to read it as it was written, checked +//! when the value is built: a finite `Float`, an `Int` of 32 bits, no `null` +//! for a non-null `JSON`, a value that serializes. A value that is not is +//! kept as an [`Invalid`], and the operation that holds it fails with +//! [`Error::InvalidValue`] before anything is sent. + +use std::borrow::Cow; + +use serde::Serialize; +use serde_json::Value; + +use crate::error::{SensitiveDetail, is_graphql_name}; +use crate::{Error, InputObject}; + +/// Why a value is refused, in [`Error::InvalidValue`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum InvalidValueReason { + /// A `Float` that is NaN or infinite, which JSON writes as `null`. + NotFiniteFloat, + /// An `Int` outside of the 32 bits of GraphQL's `Int`. + IntOutOfRange, + /// A top-level `null` where the type is a non-null `JSON`. + NullJson, + /// A value whose `Serialize` implementation failed. + Unserializable, +} + +impl std::fmt::Display for InvalidValueReason { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(match self { + Self::NotFiniteFloat => "not a finite Float", + Self::IntOutOfRange => "Int out of 32-bit range", + Self::NullJson => "null for a non-null JSON field", + Self::Unserializable => "could not serialize", + }) + } +} + +/// A value that is refused, and where it stands. Not a public API. +#[derive(Clone, Debug)] +pub struct Invalid { + /// From the value out: the innermost step first. + path: Vec, + reason: InvalidValueReason, + detail: Option, +} + +#[derive(Clone, Debug)] +enum Step { + Field(&'static str), + Index(usize), +} + +impl Invalid { + pub(crate) fn new(reason: InvalidValueReason) -> Self { + Self { + path: Vec::new(), + reason, + detail: None, + } + } + + pub(crate) fn unserializable(error: &serde_json::Error) -> Self { + Self { + detail: Some(SensitiveDetail::new(error.to_string())), + ..Self::new(InvalidValueReason::Unserializable) + } + } + + pub(crate) fn field(mut self, name: &'static str) -> Self { + self.path.push(Step::Field(name)); + self + } + + pub(crate) fn index(mut self, index: usize) -> Self { + self.path.push(Step::Index(index)); + self + } + + /// `root` and the path from it: `ProductInput.metafields[2].value`. + fn path_from(&self, root: &str) -> String { + let mut path = root.to_string(); + for step in self.path.iter().rev() { + match step { + Step::Field(name) => { + path.push('.'); + path.push_str(name); + } + Step::Index(index) => path.push_str(&format!("[{index}]")), + } + } + path + } + + /// The message of the error of an input object that is serialized on + /// its own: it holds no part of the value. + pub(crate) fn message(&self, input_object: &str) -> String { + format!( + "invalid value at `{}`: {}", + self.path_from(input_object), + self.reason + ) + } + + /// The error of the variable `name`: the name is shown when it is a + /// GraphQL name. + pub(crate) fn into_error(self, name: &str) -> Error { + let root = if is_graphql_name(name) { + format!("${name}") + } else { + "$[variable]".to_string() + }; + Error::InvalidValue { + path: self.path_from(&root), + reason: self.reason, + detail: self.detail, + } + } +} + +fn int(fits: bool) -> Result<(), Invalid> { + if fits { + Ok(()) + } else { + Err(Invalid::new(InvalidValueReason::IntOutOfRange)) + } +} + +fn float(value: f64) -> Result<(), Invalid> { + if value.is_finite() { + Ok(()) + } else { + Err(Invalid::new(InvalidValueReason::NotFiniteFloat)) + } +} + +fn json(value: &Value) -> Result<(), Invalid> { + if value.is_null() { + Err(Invalid::new(InvalidValueReason::NullJson)) + } else { + Ok(()) + } +} + +fn items<'a, T: 'a>( + items: impl IntoIterator, + check: impl Fn(&T) -> Result<(), Invalid>, +) -> Result<(), Invalid> { + for (index, item) in items.into_iter().enumerate() { + check(item).map_err(|invalid| invalid.index(index))?; + } + Ok(()) +} + +/// The Rust type of a GraphQL variable, as [`graphql!`](crate::graphql!) +/// picks it: `String` (strings, IDs, enum values and Shopify's +/// string-encoded scalars), `i64` (`Int`), `f64` (`Float`), `bool`, `Value` +/// (`JSON`), an [`InputObject`], an `Option` of one for a nullable type and +/// a `Vec` for a list. +/// +/// Its value is checked when the variable is set: an `i64` must fit in the +/// 32 bits of a GraphQL `Int`, an `f64` must be finite, a `Value` must not +/// be `null` where its type is non-null. A value that is not makes the +/// operation fail with [`Error::InvalidValue`] before it is sent. This +/// trait is sealed. +pub trait VariableType: Serialize + sealed::Sealed {} + +pub(crate) mod sealed { + use super::Invalid; + + pub trait Sealed { + /// Checks the value; `nullable` when its GraphQL type is. + fn check(&self, nullable: bool) -> Result<(), Invalid>; + } +} + +macro_rules! variable_type { + ($($ty:ty => |$value:ident, $nullable:ident| $check:expr),+ $(,)?) => {$( + impl VariableType for $ty {} + impl sealed::Sealed for $ty { + fn check(&self, $nullable: bool) -> Result<(), Invalid> { + let $value = self; + $check + } + } + )+}; +} + +variable_type!( + String => |_value, _nullable| Ok(()), + bool => |_value, _nullable| Ok(()), + i64 => |value, _nullable| int(i32::try_from(*value).is_ok()), + f64 => |value, _nullable| float(*value), + Value => |value, nullable| if nullable { Ok(()) } else { json(value) }, +); + +impl VariableType for InputObject {} +impl sealed::Sealed for InputObject { + fn check(&self, _: bool) -> Result<(), Invalid> { + self.invalid() + } +} + +impl VariableType for Option {} +impl sealed::Sealed for Option { + fn check(&self, _: bool) -> Result<(), Invalid> { + match self { + Some(value) => value.check(true), + None => Ok(()), + } + } +} + +impl VariableType for Vec {} +impl sealed::Sealed for Vec { + fn check(&self, _: bool) -> Result<(), Invalid> { + items(self, |item| item.check(false)) + } +} + +/// The value of a Rust expression in a literal of `graphql!` or `input!`, +/// checked for the scalar `K` it stands for: [`Int`], [`Float`], [`Json`] +/// (non-null) or [`Plain`] (anything else). Not a public API. +pub trait Validate { + fn validate(&self) -> Result<(), Invalid>; +} + +#[derive(Debug)] +pub enum Int {} +#[derive(Debug)] +pub enum Float {} +/// A non-null `JSON`. +#[derive(Debug)] +pub enum Json {} +#[derive(Debug)] +pub enum Plain {} + +macro_rules! validate { + ($kind:ty: $($ty:ty => |$value:ident| $check:expr),+ $(,)?) => {$( + impl Validate<$kind> for $ty { + fn validate(&self) -> Result<(), Invalid> { + let $value = self; + $check + } + } + )+}; +} + +validate!(Int: + i8 => |_value| Ok(()), + i16 => |_value| Ok(()), + i32 => |_value| Ok(()), + i64 => |value| int(i32::try_from(*value).is_ok()), + isize => |value| int(i32::try_from(*value).is_ok()), + u8 => |_value| Ok(()), + u16 => |_value| Ok(()), + u32 => |value| int(i32::try_from(*value).is_ok()), + u64 => |value| int(i32::try_from(*value).is_ok()), + usize => |value| int(i32::try_from(*value).is_ok()), +); +validate!(Float: + f32 => |value| float(f64::from(*value)), + f64 => |value| float(*value), + i32 => |_value| Ok(()), + u32 => |_value| Ok(()), +); +validate!(Json: + Value => |value| json(value), + &Value => |value| json(value), +); +validate!(Plain: + String => |_value| Ok(()), + &str => |_value| Ok(()), + &String => |_value| Ok(()), + Cow<'_, str> => |_value| Ok(()), + bool => |_value| Ok(()), + Value => |_value| Ok(()), + &Value => |_value| Ok(()), +); + +impl Validate for InputObject { + fn validate(&self) -> Result<(), Invalid> { + self.invalid() + } +} + +impl Validate for &InputObject { + fn validate(&self) -> Result<(), Invalid> { + self.invalid() + } +} + +impl> Validate for Option { + fn validate(&self) -> Result<(), Invalid> { + match self { + Some(value) => value.validate(), + None => Ok(()), + } + } +} + +impl> Validate for Vec { + fn validate(&self) -> Result<(), Invalid> { + items(self, V::validate) + } +} + +impl> Validate for &Vec { + fn validate(&self) -> Result<(), Invalid> { + items(*self, V::validate) + } +} + +impl> Validate for &[V] { + fn validate(&self) -> Result<(), Invalid> { + items(*self, V::validate) + } +} + +impl, const N: usize> Validate for [V; N] { + fn validate(&self) -> Result<(), Invalid> { + items(self, V::validate) + } +} diff --git a/crates/shopify_api/src/graphql/input.rs b/crates/shopify_api/src/graphql/input.rs index 97db02a..c9ef93c 100644 --- a/crates/shopify_api/src/graphql/input.rs +++ b/crates/shopify_api/src/graphql/input.rs @@ -4,6 +4,8 @@ use serde::{Serialize, Serializer}; use serde_json::value::RawValue; +use super::check::Invalid; + /// An input object of the schema, built and checked by /// [`input!`](crate::input!): `input!(MetafieldsSetInput { … })`. /// @@ -15,33 +17,48 @@ use serde_json::value::RawValue; /// `input!` name the GraphQL type too. /// /// The value is opaque: it holds the JSON it is sent as, written when it is -/// built. +/// built. A value Shopify would not read as written (a `Float` that is not +/// finite, an `Int` beyond 32 bits, `null` for a non-null `JSON`) is kept as +/// refused: the operation that holds it fails with +/// [`Error::InvalidValue`](crate::Error::InvalidValue) before it is sent, +/// and serializing it on its own fails. #[derive(Clone)] pub struct InputObject { name: &'static str, - json: Box, + json: Result, Invalid>, } impl InputObject { /// What `input!` builds. #[doc(hidden)] - pub fn __new(name: &'static str, fields: &impl Serialize) -> Self { - Self { - name, - json: crate::__private::literal::to_raw(fields), + pub fn __new(name: &'static str, json: Result, Invalid>) -> Self { + Self { name, json } + } + + /// Why the value is refused, if it is. + pub(crate) fn invalid(&self) -> Result<(), Invalid> { + match &self.json { + Ok(_) => Ok(()), + Err(invalid) => Err(invalid.clone()), } } } impl Serialize for InputObject { fn serialize(&self, serializer: S) -> Result { - self.json.serialize(serializer) + match &self.json { + Ok(json) => json.serialize(serializer), + Err(invalid) => Err(serde::ser::Error::custom(invalid.message(self.name))), + } } } impl std::fmt::Debug for InputObject { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(formatter, "{} {}", self.name, self.json.get()) + match &self.json { + Ok(json) => write!(formatter, "{} {}", self.name, json.get()), + Err(invalid) => formatter.write_str(&invalid.message(self.name)), + } } } diff --git a/crates/shopify_api/src/graphql/literal.rs b/crates/shopify_api/src/graphql/literal.rs index a5c706a..36488ce 100644 --- a/crates/shopify_api/src/graphql/literal.rs +++ b/crates/shopify_api/src/graphql/literal.rs @@ -3,19 +3,119 @@ //! //! An object literal is a list of fields nested in tuples, //! `Object((Field("id", id), (Optional("vendor", vendor), ())))`, written in -//! its order; the macros check its fields and their values first. +//! its order; the macros check its fields and their values first. A Rust +//! expression in it is a [`Leaf`], checked for the scalar it stands for when +//! the value is built. + +use std::marker::PhantomData; use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer}; use serde_json::value::RawValue; +pub use super::check::{Float, Int, Invalid, Json, Plain, Validate}; use crate::Maybe; -/// The JSON of a value the macros accept. -pub fn to_raw(value: &impl Serialize) -> Box { - // The macros only accept strings, numbers, booleans, `serde_json::Value`, - // input objects, and lists and objects of them: none fails to serialize. - serde_json::value::to_raw_value(value) - .expect("the values `graphql!` and `input!` accept always serialize") +/// The JSON of a value, or why it is refused. +pub fn to_raw(value: &(impl Check + Serialize)) -> Result, Invalid> { + value.check()?; + serde_json::value::to_raw_value(value).map_err(|error| Invalid::unserializable(&error)) +} + +/// A value of a literal, checked before it is serialized. +pub trait Check { + fn check(&self) -> Result<(), Invalid>; +} + +/// `null`, an enum value, the string of `raw(…)`, a literal Rust value +/// whose type cannot be refused. +macro_rules! unchecked { + ($($ty:ty),+) => {$( + impl Check for $ty { + fn check(&self) -> Result<(), Invalid> { + Ok(()) + } + } + )+}; +} + +unchecked!((), &str, String, bool); + +impl Check for &T { + fn check(&self) -> Result<(), Invalid> { + (**self).check() + } +} + +/// A Rust expression for a value of the scalar `K`. +#[derive(Debug)] +pub struct Leaf(V, PhantomData K>); + +pub fn leaf(value: V) -> Leaf { + Leaf(value, PhantomData) +} + +/// `field?: value`, the value checked as a `K`. +pub fn optional(value: Maybe) -> Maybe> { + match value { + Maybe::Absent => Maybe::Absent, + Maybe::Null => Maybe::Null, + Maybe::Value(value) => Maybe::Value(leaf(value)), + } +} + +impl, K> Check for Leaf { + fn check(&self) -> Result<(), Invalid> { + self.0.validate() + } +} + +impl Serialize for Leaf { + fn serialize(&self, serializer: S) -> Result { + self.0.serialize(serializer) + } +} + +/// The items of `[for … => …]`, each written in its turn of the loop, and +/// the first that is refused. +#[derive(Debug)] +pub struct Collected { + items: Vec>, + invalid: Option, +} + +impl Collected { + #[allow(clippy::new_without_default)] + pub fn new() -> Self { + Self { + items: Vec::new(), + invalid: None, + } + } + + pub fn push(&mut self, value: &(impl Check + Serialize)) { + if self.invalid.is_some() { + return; + } + match to_raw(value) { + Ok(item) => self.items.push(item), + Err(invalid) => self.invalid = Some(invalid.index(self.items.len())), + } + } +} + +impl Check for Collected { + fn check(&self) -> Result<(), Invalid> { + match &self.invalid { + Some(invalid) => Err(invalid.clone()), + None => Ok(()), + } + } +} + +impl Serialize for Collected { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq(&self.items) + } } #[derive(Debug)] @@ -29,23 +129,43 @@ pub struct Field(pub &'static str, pub V); pub struct Optional(pub &'static str, pub Maybe); pub trait Fields { + fn check(&self) -> Result<(), Invalid>; fn write(&self, map: &mut M) -> Result<(), M::Error>; } impl Fields for () { + fn check(&self) -> Result<(), Invalid> { + Ok(()) + } + fn write(&self, _: &mut M) -> Result<(), M::Error> { Ok(()) } } -impl Fields for (Field, R) { +impl Fields for (Field, R) { + fn check(&self) -> Result<(), Invalid> { + self.0 + .1 + .check() + .map_err(|invalid| invalid.field(self.0.0))?; + self.1.check() + } + fn write(&self, map: &mut M) -> Result<(), M::Error> { map.serialize_entry(self.0.0, &self.0.1)?; self.1.write(map) } } -impl Fields for (Optional, R) { +impl Fields for (Optional, R) { + fn check(&self) -> Result<(), Invalid> { + if let Maybe::Value(value) = &self.0.1 { + value.check().map_err(|invalid| invalid.field(self.0.0))?; + } + self.1.check() + } + fn write(&self, map: &mut M) -> Result<(), M::Error> { match &self.0.1 { Maybe::Absent => {} @@ -56,6 +176,12 @@ impl Fields for (Optional, R) { } } +impl Check for Object { + fn check(&self) -> Result<(), Invalid> { + self.0.check() + } +} + impl Serialize for Object { fn serialize(&self, serializer: S) -> Result { let mut map = serializer.serialize_map(None)?; @@ -69,22 +195,39 @@ impl Serialize for Object { pub struct List(pub I); pub trait Items { + /// Checks the items, the first being at `index`. + fn check(&self, index: usize) -> Result<(), Invalid>; fn write(&self, seq: &mut S) -> Result<(), S::Error>; } impl Items for () { + fn check(&self, _: usize) -> Result<(), Invalid> { + Ok(()) + } + fn write(&self, _: &mut S) -> Result<(), S::Error> { Ok(()) } } -impl Items for (V, R) { +impl Items for (V, R) { + fn check(&self, index: usize) -> Result<(), Invalid> { + self.0.check().map_err(|invalid| invalid.index(index))?; + self.1.check(index + 1) + } + fn write(&self, seq: &mut S) -> Result<(), S::Error> { seq.serialize_element(&self.0)?; self.1.write(seq) } } +impl Check for List { + fn check(&self) -> Result<(), Invalid> { + self.0.check(0) + } +} + impl Serialize for List { fn serialize(&self, serializer: S) -> Result { let mut seq = serializer.serialize_seq(None)?; @@ -198,22 +341,70 @@ mod tests { ( Optional("b", Maybe::<&str>::Null), ( - Optional("c", option(Some(1))), - (Field("list", List(("x", (2, ((), ()))))), ()), + Optional("c", optional::(option(Some(1)))), + ( + Field("list", List(("x", (leaf::(2), ((), ()))))), + (), + ), ), ), ), )); assert_eq!( - to_raw(&object).get(), + to_raw(&object).unwrap().get(), r#"{"type":"single_line_text_field","b":null,"c":1,"list":["x",2,null]}"# ); - assert_eq!(to_raw(&Object(())).get(), "{}"); - assert_eq!(to_raw(&List(())).get(), "[]"); + assert_eq!(to_raw(&Object(())).unwrap().get(), "{}"); + assert_eq!(to_raw(&List(())).unwrap().get(), "[]"); assert_eq!( raw_optional(Maybe::Value("A")), Maybe::Value("A".to_string()) ); assert_eq!(raw_option(None::<&str>), Maybe::Absent); } + + #[test] + fn a_value_is_checked_for_its_scalar_and_refused_with_where_it_stands() { + use serde_json::Value; + + let refused = |value: Result, Invalid>| value.unwrap_err().message("T"); + assert_eq!( + refused(to_raw(&Object(( + Optional("j", optional::(Maybe::Value(Value::Null))), + () + )))), + "invalid value at `T.j`: null for a non-null JSON field" + ); + assert_eq!( + refused(to_raw(&Object(( + Field( + "list", + List(( + leaf::(1.0), + (leaf::(vec![Some(f32::NAN)]), ()) + )) + ), + () + )))), + "invalid value at `T.list[1][0]`: not a finite Float" + ); + let mut collected = Collected::new(); + for quantity in [1_usize, 2, 1 << 40, 3, usize::MAX] { + collected.push(&Object((Field("quantity", leaf::(quantity)), ()))); + } + assert_eq!( + refused(to_raw(&Object((Field("items", &collected), ())))), + "invalid value at `T.items[2].quantity`: Int out of 32-bit range" + ); + // `null` of a nullable `JSON`, and nulls inside a `JSON`, are sent. + assert_eq!( + to_raw(&List(( + leaf::(Value::Null), + (leaf::(serde_json::json!([null])), ()) + ))) + .unwrap() + .get(), + "[null,[null]]" + ); + } } diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs index f5305e3..91e4a6d 100644 --- a/crates/shopify_api/src/graphql/operation.rs +++ b/crates/shopify_api/src/graphql/operation.rs @@ -7,6 +7,7 @@ use serde::ser::{Serialize, SerializeMap, Serializer}; use serde_json::value::RawValue; use serde_json::{Map, Value}; +use super::check::{Invalid, VariableType}; use crate::{ApiVersion, Error, Result}; /// A query or a mutation. @@ -284,38 +285,65 @@ impl Operation { } } - fn set(mut self, name: &str, value: serde_json::Result>) -> Self { + fn set( + mut self, + name: &str, + value: std::result::Result, VariablesFailure>, + ) -> Self { match (&mut self.variables, value) { (Ok(variables), Ok(value)) => match variables.iter_mut().find(|(set, _)| set == name) { Some((_, set)) => *set = value, None => variables.push((name.to_string(), value)), }, - (Ok(_), Err(error)) => { - self.variables = Err(VariablesFailure::of(Error::variables(Some(name), &error))) - } + (Ok(_), Err(failure)) => self.variables = Err(failure), (Err(_), _) => {} } self } + fn set_json(self, name: &str, value: &impl Serialize) -> Self { + let value = serde_json::value::to_raw_value(value) + .map_err(|error| VariablesFailure::of(Error::variables(Some(name), &error))); + self.set(name, value) + } + + fn set_checked(self, name: &str, value: &impl VariableType) -> Self { + match value.check(false) { + Ok(()) => self.set_json(name, value), + Err(invalid) => self.set(name, Err(VariablesFailure::invalid(name, invalid))), + } + } + /// Sets a variable to a value convertible to `T`, the Rust type of its /// GraphQL type. - pub fn variable>(self, name: &str, value: V) -> Self { - self.set( - name, - serde_json::value::to_raw_value(&value.into_variable()), - ) + /// + /// The value is checked as [`VariableType`] says: one that Shopify would + /// not read as written makes the operation fail with + /// [`Error::InvalidValue`] before it is sent. + pub fn variable>(self, name: &str, value: V) -> Self { + self.set_checked(name, &value.into_variable()) } /// Sets a variable to any serializable value, checked by nothing. pub fn json_variable(self, name: &str, value: V) -> Self { - self.set(name, serde_json::value::to_raw_value(&value)) + self.set_json(name, &value) + } + + /// What the `Variables` of a `graphql!` module set a variable with. + #[doc(hidden)] + pub fn __variable(self, name: &str, value: T) -> Self { + self.set_checked(name, &value) } /// What `graphql!` sets a variable written as a literal to. #[doc(hidden)] - pub fn __literal_variable(self, name: &str, value: Box) -> Self { - self.set(name, Ok(value)) + pub fn __literal_variable( + self, + name: &str, + value: std::result::Result, Invalid>, + ) -> Self { + let value = value.map_err(|invalid| VariablesFailure::invalid(name, invalid)); + self.set(name, value) } /// Replaces the variables with the fields of a serializable struct or map. @@ -413,29 +441,45 @@ pub(crate) fn variables_of(variables: impl Serialize) -> Result, +enum VariablesFailure { + Variables { + message: String, + detail: Option, + }, + Invalid { + variable: String, + invalid: Invalid, + }, } impl VariablesFailure { fn of(error: Error) -> Self { match error { - Error::Variables { message, detail } => Self { message, detail }, - other => Self { + Error::Variables { message, detail } => Self::Variables { message, detail }, + other => Self::Variables { message: other.to_string(), detail: None, }, } } + fn invalid(variable: &str, invalid: Invalid) -> Self { + Self::Invalid { + variable: variable.to_string(), + invalid, + } + } + fn to_error(&self) -> Error { - Error::Variables { - message: self.message.clone(), - detail: self.detail.clone(), + match self { + Self::Variables { message, detail } => Error::Variables { + message: message.clone(), + detail: detail.clone(), + }, + Self::Invalid { variable, invalid } => invalid.clone().into_error(variable), } } } @@ -474,7 +518,8 @@ impl std::fmt::Debug for Operation { /// `Option` when the variable is nullable and in `Vec` for lists. The /// implementations then accept the usual Rust spellings of those values: /// `&str` for a string, any integer for an `Int`, a bare value for a nullable -/// variable, a slice for a list. +/// variable, a slice for a list. The value converted is then checked, as +/// [`VariableType`] says. #[diagnostic::on_unimplemented( message = "`{Self}` is not a value for a GraphQL variable of Rust type `{T}`", label = "the variable expects a value convertible to `{T}`" @@ -514,7 +559,7 @@ into_variable!(i64: u8 => |value| value.into(), u16 => |value| value.into(), u32 => |value| value.into(), - // Larger than any GraphQL `Int`: Shopify rejects the saturated value. + // Saturated: out of the range of `Int` all the same, and refused. u64 => |value| i64::try_from(value).unwrap_or(i64::MAX), usize => |value| i64::try_from(value).unwrap_or(i64::MAX), isize => |value| i64::try_from(value).unwrap_or(if value < 0 { i64::MIN } else { i64::MAX }), @@ -710,11 +755,91 @@ mod tests { } #[test] - fn integers_that_do_not_fit_are_saturated() { - let operation = Operation::<()>::new("query { shop { id } }") - .variable::("big", u64::MAX) - .variable::("fits", 7_u64); - assert_eq!(variables(operation), json!({ "big": i64::MAX, "fits": 7 })); + fn values_shopify_would_not_read_as_written_are_refused_before_sending() { + let operation = || Operation::<()>::new("query { shop { id } }"); + let fits = operation() + .variable::("min", i32::MIN) + .variable::("max", i64::from(i32::MAX)) + .variable::("unsigned", u64::from(i32::MAX.unsigned_abs())) + .variable::("ratio", f64::MAX) + .variable::, _>("nullable", Value::Null) + .variable::>, _>("items", vec![Value::Null]) + .variable::("nested", json!({ "a": null })); + assert_eq!( + variables(fits), + json!({ + "min": i32::MIN, + "max": i32::MAX, + "unsigned": i32::MAX, + "ratio": f64::MAX, + "nullable": null, + "items": [null], + "nested": { "a": null }, + }) + ); + + for (operation, shown) in [ + ( + operation().variable::("big", u64::MAX), + "invalid value at `$big`: Int out of 32-bit range", + ), + ( + operation().variable::("first", 2_147_483_648_i64), + "invalid value at `$first`: Int out of 32-bit range", + ), + ( + operation().variable::, _>("last", -2_147_483_649_i64), + "invalid value at `$last`: Int out of 32-bit range", + ), + ( + operation().variable::("ratio", f64::NAN), + "invalid value at `$ratio`: not a finite Float", + ), + ( + operation().variable::, _>("ratio", f32::NEG_INFINITY), + "invalid value at `$ratio`: not a finite Float", + ), + ( + operation().variable::, _>("ratios", [1.0, f64::INFINITY]), + "invalid value at `$ratios[1]`: not a finite Float", + ), + ( + operation().variable::>, _>( + "counts", + vec![Some(1), None, Some(1_i64 << 40)], + ), + "invalid value at `$counts[2]`: Int out of 32-bit range", + ), + ( + operation().variable::("settings", Value::Null), + "invalid value at `$settings`: null for a non-null JSON field", + ), + ( + operation().variable::, _>("settings", vec![json!(1), Value::Null]), + "invalid value at `$settings[1]`: null for a non-null JSON field", + ), + ( + operation().variable::("a name", f64::NAN), + "invalid value at `$[variable]`: not a finite Float", + ), + ( + // The first refusal stays. + operation() + .variable::("first", u32::MAX) + .variable::("ratio", f64::NAN) + .variable::("first", 1), + "invalid value at `$first`: Int out of 32-bit range", + ), + ] { + let error = operation.body().unwrap_err(); + assert_eq!(error.to_string(), shown); + assert!(matches!(error, Error::InvalidValue { detail: None, .. })); + assert_eq!(operation.variables_json().unwrap_err().to_string(), shown); + assert_eq!( + operation.clone().body_json().unwrap_err().to_string(), + shown + ); + } } #[test] diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index 81a2e57..12a9ae7 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -83,8 +83,8 @@ pub use auth::{AssociatedUser, Auth, TokenData, TokenStore}; pub use client::{RetryPolicy, Shopify, ShopifyBuilder, USER_AGENT}; pub use error::{Error, GraphqlErrors, RawBody, Result, SensitiveDetail}; pub use graphql::{ - Cost, GraphqlError, InputObject, IntoVariable, Location, Maybe, Operation, OperationKind, - RawResponse, Response, ThrottleStatus, UserError, + Cost, GraphqlError, InputObject, IntoVariable, InvalidValueReason, Location, Maybe, Operation, + OperationKind, RawResponse, Response, ThrottleStatus, UserError, VariableType, }; pub use pagination::Page; pub use shop::ShopDomain; diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs index 0174835..dbe9439 100644 --- a/crates/shopify_api/tests/literals.rs +++ b/crates/shopify_api/tests/literals.rs @@ -400,6 +400,137 @@ async fn a_nullable_input_variable_takes_null_an_option_or_a_literal() { ); } +/// What Shopify would not read as written: an `Int` beyond 32 bits, a +/// `Float` that is not finite, `null` for a non-null `JSON`. The operation +/// fails before anything is sent, saying where and why, never the value. +#[tokio::test] +async fn values_shopify_would_not_read_as_written_fail_before_anything_is_sent() { + let mock = MockTransport::new(); + let shopify = client(&mock); + let big: i64 = 1 << 40; + let quantities = [1_u64, 2, u64::MAX]; + let nan = f64::NAN; + let weights = [Some(1.5), None, Some(f64::INFINITY)]; + let line_item = input!(DraftOrderLineItemInput { quantity: big }); + let pixel = input!(WebPixelInput { + settings: serde_json::Value::Null + }); + + let errors = [ + shopify + .execute(graphql!("mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", input = { lineItems: [{ quantity: 1 }, { quantity: big }] })) + .await + .unwrap_err(), + shopify + .execute(graphql!("mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", input = { + lineItems: [{ quantity: 1, weight: { unit: KILOGRAMS, value: nan } }], + })) + .await + .unwrap_err(), + shopify + .execute(graphql!("mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", input = { + lineItems: [for quantity in quantities => { quantity: quantity }], + })) + .await + .unwrap_err(), + shopify + .execute(graphql!("mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", input = { + lineItems: [for (i, weight) in weights.iter().enumerate() => { + quantity: i, + weight?: weight.map(|value| input!(WeightInput { unit: GRAMS, value: value })), + }], + })) + .await + .unwrap_err(), + shopify + .execute(graphql!("mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", input = { lineItems: [line_item.clone()] })) + .await + .unwrap_err(), + shopify + .execute(graphql!("mutation($webPixel: WebPixelInput!) { webPixelCreate(webPixel: $webPixel) { userErrors { message } } }", webPixel = pixel.clone())) + .await + .unwrap_err(), + shopify + .execute(graphql!( + "mutation($id: ID!, $discount: DiscountAutomaticBasicInput!) { discountAutomaticBasicUpdate(id: $id, automaticBasicDiscount: $discount) { userErrors { message } } }", + id = "gid://shopify/DiscountAutomaticNode/1", + discount = { customerGets: { value: { percentage: f64::INFINITY }, items: { all: true } } }, + )) + .await + .unwrap_err(), + shopify + .execute(recent_products::Variables { first: big, sort_key: None }) + .await + .unwrap_err(), + shopify + .execute(graphql!( + "query($first: Int!) { products(first: $first) { nodes { id } } }", + first = u64::MAX, + )) + .await + .unwrap_err(), + ]; + let shown: Vec = errors.iter().map(ToString::to_string).collect(); + assert_eq!( + shown, + [ + "invalid value at `$input.lineItems[1].quantity`: Int out of 32-bit range", + "invalid value at `$input.lineItems[0].weight.value`: not a finite Float", + "invalid value at `$input.lineItems[2].quantity`: Int out of 32-bit range", + "invalid value at `$input.lineItems[2].weight.value`: not a finite Float", + "invalid value at `$input.lineItems[0].quantity`: Int out of 32-bit range", + "invalid value at `$webPixel.settings`: null for a non-null JSON field", + "invalid value at `$discount.customerGets.value.percentage`: not a finite Float", + "invalid value at `$first`: Int out of 32-bit range", + "invalid value at `$first`: Int out of 32-bit range", + ] + ); + for error in &errors { + assert!(matches!( + error, + shopify_api::Error::InvalidValue { detail: None, .. } + )); + let debug = format!("{error:?}"); + assert!( + !debug.contains("1099511627776") && !debug.contains("NaN"), + "{debug}" + ); + } + assert!(mock.requests().is_empty()); + + // Serialized on its own, an input object fails the same way. + let error = serde_json::to_string(&line_item).unwrap_err(); + assert_eq!( + error.to_string(), + "invalid value at `DraftOrderLineItemInput.quantity`: Int out of 32-bit range" + ); + assert_eq!( + format!("{pixel:?}"), + "invalid value at `WebPixelInput.settings`: null for a non-null JSON field" + ); +} + +/// The bounds are allowed, and nulls inside `JSON`. +#[test] +fn values_at_the_bounds_are_sent() { + let line_item = input!(DraftOrderLineItemInput { + quantity: i64::from(i32::MAX), + weight: { unit: GRAMS, value: f64::MAX }, + }); + let pixel = input!(WebPixelInput { + settings: json!({ "a": null }) + }); + let discount = input!(DiscountCustomerGetsValueInput { percentage?: Some(f64::MIN_POSITIVE) }); + assert_eq!( + serde_json::to_value((&line_item, &pixel, &discount)).unwrap(), + json!([ + { "quantity": i32::MAX, "weight": { "unit": "GRAMS", "value": f64::MAX } }, + { "settings": { "a": null } }, + { "percentage": f64::MIN_POSITIVE }, + ]) + ); +} + /// Names like the ones the macros generate, or generated before, given to /// the caller's locals, closures, functions, constants and trait methods: /// the values sent are the caller's. diff --git a/crates/shopify_api/tests/ui/wrong_value_type.stderr b/crates/shopify_api/tests/ui/wrong_value_type.stderr index 1669745..de3c286 100644 --- a/crates/shopify_api/tests/ui/wrong_value_type.stderr +++ b/crates/shopify_api/tests/ui/wrong_value_type.stderr @@ -24,6 +24,6 @@ help: `&str` implements trait `IntoVariable` note: required by a bound in `Operation::::variable` --> src/graphql/operation.rs | - | pub fn variable>(self, name: &str, value: V) -> Self { - | ^^^^^^^^^^^^^^^ required by this bound in `Operation::::variable` + | pub fn variable>(self, name: &str, value: V) -> Self { + | ^^^^^^^^^^^^^^^ required by this bound in `Operation::::variable` = note: this error originates in the macro `into_variable` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs index 8ad64b1..1a67fce 100644 --- a/crates/shopify_api_graphql/src/codegen.rs +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -310,7 +310,7 @@ pub fn variables_types( pub #ident: #ty, }); setters.push(quote! { - let operation = operation.json_variable(#key, variables.#ident); + let operation = operation.__variable(#key, variables.#ident); }); } else { // `wrap` of a nullable type is already an `Option`. @@ -323,7 +323,8 @@ pub fn variables_types( }); setters.push(quote! { let operation = match variables.#ident { - ::core::option::Option::Some(value) => operation.json_variable(#key, value), + // In `Some`: the value of a nullable variable may be `null`. + value @ ::core::option::Option::Some(_) => operation.__variable(#key, value), ::core::option::Option::None => operation, }; }); diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index 6111f3c..f60c0e7 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -204,14 +204,15 @@ impl<'a> Literals<'a> { let ty = &variable.ty; let site = Site::Variable(variable.name.clone()); let scalar = matches!(self.schema.get(ty.name()), Some(TypeDef::Scalar)); - let converted = |value: Expr| VariableValue::Converted { - ty: variable_type(variable, &self.krate) - .expect("a variable of a scalar or an enum has a Rust type"), - value, + let rust_type = variable_type(variable, &self.krate); + let convert = |value: Expr| { + rust_type + .clone() + .map(|ty| VariableValue::Converted { ty, value }) }; - match value { - Value::Rust(expr) if scalar => return Ok(converted(expr.clone())), - Value::Ident(ident) if scalar => return Ok(converted(ident_expr(ident))), + let converted = match value { + Value::Rust(expr) if scalar => convert(expr.clone()), + Value::Ident(ident) if scalar => convert(ident_expr(ident)), Value::List(List { items, rust: Some(rust), @@ -221,13 +222,16 @@ impl<'a> Literals<'a> { .iter() .all(|item| matches!(item, Value::Rust(_) | Value::Ident(_))) => { - return Ok(converted(rust.clone())); + convert(rust.clone()) } Value::Raw { keyword, value } => { self.enum_only(ty, *keyword, &site)?; - return Ok(converted(value.clone())); + convert(value.clone()) } - _ => {} + _ => None, + }; + if let Some(converted) = converted { + return Ok(converted); } let code = self.value(value, ty, &site, Place::Variable)?; let krate = &self.krate; @@ -274,7 +278,7 @@ impl<'a> Literals<'a> { let krate = &self.krate; let id = input_object_id(name); Ok(quote_spanned! {span=> - #krate::InputObject::<#id>::__new(#name, &#code) + #krate::InputObject::<#id>::__new(#name, #krate::__private::literal::to_raw(&#code)) }) } @@ -367,13 +371,14 @@ impl<'a> Literals<'a> { }; // Each item is written in its turn of the loop, so that it may // borrow what the loop gives. - let push = quote!(::std::vec::Vec::push(&mut #items, #krate::__private::literal::to_raw(&#value));); + let push = + quote!(#krate::__private::literal::Collected::push(&mut #items, &#value);); let body = match filter { Some(filter) => quote!(if #filter { #push }), None => push, }; Ok(quote! {{ - let mut #items = ::std::vec::Vec::new(); + let mut #items = #krate::__private::literal::Collected::new(); for #pattern in #iterable { #body } #items }}) @@ -551,11 +556,12 @@ impl<'a> Literals<'a> { impl #bound for ::core::option::Option {} impl #bound for #krate::Maybe {} }); + let kind = self.kind(&definition.ty); let checks = checks( &items, quote! { - fn optional>(self, value: V) -> #krate::Maybe { - #krate::__private::literal::IntoMaybe::into_maybe(value) + fn optional>(self, value: V) -> #krate::Maybe<#krate::__private::literal::Leaf> { + #krate::__private::literal::optional(#krate::__private::literal::IntoMaybe::into_maybe(value)) } }, ); @@ -587,11 +593,13 @@ impl<'a> Literals<'a> { } let mut items = Vec::new(); let bound = self.expect(ty, place, site, &mut items); + let krate = &self.krate; + let kind = self.kind(ty); let checks = checks( &items, quote! { - fn check(self, value: V) -> V { - value + fn check(self, value: V) -> #krate::__private::literal::Leaf { + #krate::__private::literal::leaf(value) } }, ); @@ -795,6 +803,20 @@ impl<'a> Literals<'a> { } } + /// What a Rust expression of type `ty` is checked for when it is built: + /// the `Int`, `Float` or non-null `JSON` its innermost type is. + fn kind(&self, ty: &TypeRef) -> TokenStream { + let krate = &self.krate; + let (name, non_null) = innermost(ty); + let kind = match (self.schema.get(name), Scalar::of(name)) { + (Some(TypeDef::Scalar), Scalar::Int) => quote!(Int), + (Some(TypeDef::Scalar), Scalar::Float) => quote!(Float), + (Some(TypeDef::Scalar), Scalar::Json) if non_null => quote!(Json), + _ => quote!(Plain), + }; + quote!(#krate::__private::literal::#kind) + } + /// The innermost type of `ty` is an input object. fn holds_input(&self, ty: &TypeRef) -> bool { matches!(self.schema.get(ty.name()), Some(TypeDef::Input { .. })) @@ -927,6 +949,18 @@ fn scalar_types(scalar: Scalar, krate: &TokenStream) -> Vec { } } +/// The innermost named type of `ty`, and whether it is non-null. +fn innermost(ty: &TypeRef) -> (&str, bool) { + match ty { + TypeRef::Named(name) => (name, false), + TypeRef::NonNull(inner) => match &**inner { + TypeRef::Named(name) => (name, true), + other => innermost(other), + }, + TypeRef::List(item) => innermost(item), + } +} + /// The receiver of a check: a value of a type declared, with what its /// method needs, in a block that no expression of the caller's is in. By /// value, so that no trait method of the same name wins over the method. diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index 821e0e5..d56955d 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -122,7 +122,7 @@ fn an_object_is_sent_field_by_field_in_its_order() { let id = input_object_id("ProductUpdateInput"); assert!( code.starts_with(&format!( - ":: shopify_api :: InputObject :: < {id}u64 > :: __new (\"ProductUpdateInput\" , & :: shopify_api :: __private :: literal :: Object ((:: shopify_api :: __private :: literal :: Field (\"id\" , ({{" + ":: shopify_api :: InputObject :: < {id}u64 > :: __new (\"ProductUpdateInput\" , :: shopify_api :: __private :: literal :: to_raw (& :: shopify_api :: __private :: literal :: Object ((:: shopify_api :: __private :: literal :: Field (\"id\" , ({{" )), "{code}" ); @@ -467,3 +467,48 @@ fn input_object_ids_differ_for_every_input_object_of_the_schema() { } assert!(seen.len() > 500); } + +/// Each Rust expression is checked, when it is built, for the scalar its +/// innermost type is: an `Int`, a `Float`, a non-null `JSON`, with or +/// without `?:`. +#[test] +fn each_expression_is_checked_for_its_scalar() { + let schema = Schema::from_json( + r#"{"format": 1, "apiVersion": "2026-10", "query": "Q", "types": { + "String": "s", "Int": "s", "Float": "s", "Boolean": "s", "JSON": "s", + "T": {"i": {"i": "Int!", "f": "[Float]", "j": "JSON!", "jd": "JSON!=", "jl": "[JSON!]", "jn": "JSON", "s": "String"}}, + "Q": {"o": {"f": {"echo": ["String", {"input": "T!"}]}}} + }}"#, + ) + .unwrap(); + let mut literals = Literals::new(&schema, quote!(::shopify_api)); + let code = literals + .input_object( + "T", + Span::call_site(), + &object(vec![ + ("i", rust("a")), + ("f", rust("b")), + ("j", rust("c")), + ("jd?", rust("d")), + ("jl", rust("e")), + ("jn", rust("f")), + ("s", rust("g")), + ]), + ) + .unwrap() + .to_string(); + let marker = "literal :: Leaf < "; + let kinds: Vec<&str> = code + .match_indices(marker) + .map(|(at, _)| { + let rest = &code[at + marker.len()..]; + let kind = &rest[rest.find("literal :: ").unwrap() + "literal :: ".len()..]; + &kind[..kind.find(' ').unwrap()] + }) + .collect(); + assert_eq!( + kinds, + ["Int", "Float", "Json", "Json", "Json", "Plain", "Plain"] + ); +} From ef9ad4802963e1561857777314fd49defc82c802 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:21:15 +0200 Subject: [PATCH 057/135] feat(graphql): refuse integer literals outside of Int at compile time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An integer literal where an `Int` is expected, outside of its 32 bits, is now a compile error at the literal: a field, a `?:` value, an item, a variable, written alone, negated, in `Some(…)`, in parentheses, or in `[…]` or `vec![…]`. Suffixes, underscores and radixes are read. Values computed at run time are refused when the operation is built. Co-Authored-By: Claude Opus 5.5 --- .../tests/ui/literal_int_out_of_range.rs | 7 ++ .../tests/ui/literal_int_out_of_range.stderr | 13 ++ crates/shopify_api_graphql/src/literal.rs | 111 ++++++++++++++++++ crates/shopify_api_graphql/tests/literal.rs | 98 ++++++++++++++++ 4 files changed, 229 insertions(+) create mode 100644 crates/shopify_api/tests/ui/literal_int_out_of_range.rs create mode 100644 crates/shopify_api/tests/ui/literal_int_out_of_range.stderr diff --git a/crates/shopify_api/tests/ui/literal_int_out_of_range.rs b/crates/shopify_api/tests/ui/literal_int_out_of_range.rs new file mode 100644 index 0000000..3940d7a --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_int_out_of_range.rs @@ -0,0 +1,7 @@ +fn main() { + let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: 2_147_483_648_i64 }); + let _ = shopify_api::graphql!( + "query($first: Int!) { products(first: $first) { nodes { id } } }", + first = -2_147_483_649, + ); +} diff --git a/crates/shopify_api/tests/ui/literal_int_out_of_range.stderr b/crates/shopify_api/tests/ui/literal_int_out_of_range.stderr new file mode 100644 index 0000000..fd01a4c --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_int_out_of_range.stderr @@ -0,0 +1,13 @@ +error: The integer is outside the range of `Int`, a 32-bit integer, given for `quantity` of `DraftOrderLineItemInput` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_int_out_of_range.rs:2:69 + | +2 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: 2_147_483_648_i64 }); + | ^^^^^^^^^^^^^^^^^ + +error: The integer is outside the range of `Int`, a 32-bit integer, given for `$first` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_int_out_of_range.rs:5:18 + | +5 | first = -2_147_483_649, + | ^^^^^^^^^^^^^ diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index f60c0e7..201dbbf 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -204,6 +204,15 @@ impl<'a> Literals<'a> { let ty = &variable.ty; let site = Site::Variable(variable.name.clone()); let scalar = matches!(self.schema.get(ty.name()), Some(TypeDef::Scalar)); + if scalar { + match value { + Value::Rust(expr) => self.int_literals(&expr.tokens, ty, &site)?, + Value::List(List { + rust: Some(rust), .. + }) => self.int_literals(&rust.tokens, ty, &site)?, + _ => {} + } + } let rust_type = variable_type(variable, &self.krate); let convert = |value: Expr| { rust_type @@ -519,6 +528,7 @@ impl<'a> Literals<'a> { ); } + self.int_literals(&expr.tokens, &definition.ty, site)?; let mut items = Vec::new(); let value_bound = self.expect(&definition.ty, Place::Field, site, &mut items); let n = self.next(); @@ -591,6 +601,7 @@ impl<'a> Literals<'a> { }; return error(expr.span, message); } + self.int_literals(&expr.tokens, ty, site)?; let mut items = Vec::new(); let bound = self.expect(ty, place, site, &mut items); let krate = &self.krate; @@ -817,6 +828,31 @@ impl<'a> Literals<'a> { quote!(#krate::__private::literal::#kind) } + /// Refuses an integer literal outside of the 32 bits of `Int`, where + /// the innermost type of `ty` is `Int`: written alone, negated, in + /// `Some(…)`, in parentheses, or as an item of `[…]` or `vec![…]`. + fn int_literals(&self, tokens: &TokenStream, ty: &TypeRef, site: &Site) -> Result<(), Error> { + if !matches!(self.schema.get(ty.name()), Some(TypeDef::Scalar)) + || Scalar::of(ty.name()) != Scalar::Int + { + return Ok(()); + } + let mut found = Vec::new(); + int_literals(tokens, &mut found); + match found + .into_iter() + .find(|(value, _)| i32::try_from(*value).is_err()) + { + Some((_, span)) => error( + span, + format!( + "The integer is outside the range of `Int`, a 32-bit integer, given for {site}" + ), + ), + None => Ok(()), + } + } + /// The innermost type of `ty` is an input object. fn holds_input(&self, ty: &TypeRef) -> bool { matches!(self.schema.get(ty.name()), Some(TypeDef::Input { .. })) @@ -949,6 +985,81 @@ fn scalar_types(scalar: Scalar, krate: &TokenStream) -> Vec { } } +/// The integer literals of `tokens` in the forms +/// [`Literals::int_literals`] reads, and their spans; one beyond `i128` is +/// `i128::MAX`. +fn int_literals(tokens: &TokenStream, found: &mut Vec<(i128, Span)>) { + let trees: Vec = tokens.clone().into_iter().collect(); + match trees.as_slice() { + [TokenTree::Literal(literal)] => { + if let Some(value) = integer(&literal.to_string()) { + found.push((value, literal.span())); + } + } + [TokenTree::Punct(minus), TokenTree::Literal(literal)] if minus.as_char() == '-' => { + if let Some(value) = integer(&literal.to_string()) { + found.push((value.saturating_neg(), literal.span())); + } + } + [TokenTree::Group(group)] => match group.delimiter() { + Delimiter::Parenthesis | Delimiter::None => int_literals(&group.stream(), found), + Delimiter::Bracket => items(&group.stream(), found), + Delimiter::Brace => {} + }, + [TokenTree::Ident(some), TokenTree::Group(group)] + if some == "Some" && group.delimiter() == Delimiter::Parenthesis => + { + int_literals(&group.stream(), found); + } + [ + TokenTree::Ident(vec), + TokenTree::Punct(bang), + TokenTree::Group(group), + ] if vec == "vec" && bang.as_char() == '!' && group.delimiter() == Delimiter::Bracket => { + items(&group.stream(), found); + } + _ => {} + } + + fn items(tokens: &TokenStream, found: &mut Vec<(i128, Span)>) { + let mut item = TokenStream::new(); + for tree in tokens.clone() { + match &tree { + TokenTree::Punct(comma) if comma.as_char() == ',' => { + int_literals(&std::mem::take(&mut item), found); + } + _ => item.extend([tree]), + } + } + int_literals(&item, found); + } +} + +/// The value of the text of an integer literal: `2_147_483_648_i64`, +/// `0x8000_0000`, `0b1`; `None` for any other literal. +fn integer(text: &str) -> Option { + const SUFFIXES: [&str; 12] = [ + "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize", + ]; + let (radix, digits) = [(16, "0x"), (8, "0o"), (2, "0b")] + .into_iter() + .find_map(|(radix, prefix)| Some((radix, text.strip_prefix(prefix)?))) + .unwrap_or((10, text)); + let digits = SUFFIXES + .iter() + .find_map(|suffix| digits.strip_suffix(suffix)) + .unwrap_or(digits); + let digits: String = digits.chars().filter(|&digit| digit != '_').collect(); + if digits.is_empty() || !digits.chars().all(|digit| digit.is_digit(radix)) { + return None; + } + Some( + u128::from_str_radix(&digits, radix).map_or(i128::MAX, |value| { + i128::try_from(value).unwrap_or(i128::MAX) + }), + ) +} + /// The innermost named type of `ty`, and whether it is non-null. fn innermost(ty: &TypeRef) -> (&str, bool) { match ty { diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index d56955d..03820bb 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -512,3 +512,101 @@ fn each_expression_is_checked_for_its_scalar() { ["Int", "Float", "Json", "Json", "Json", "Plain", "Plain"] ); } + +/// An integer literal outside of the 32 bits of `Int` is refused where an +/// `Int` is expected: a field, a `?:` value, an item, a variable. +#[test] +fn integer_literals_outside_of_int_are_refused() { + let refused = |fields: Vec<(&str, Value)>| refusal("DraftOrderLineItemInput", fields); + for (text, site) in [ + ( + "2_147_483_648_i64", + "`quantity` of `DraftOrderLineItemInput`", + ), + ("-2147483649", "`quantity` of `DraftOrderLineItemInput`"), + ("0x8000_0000", "`quantity` of `DraftOrderLineItemInput`"), + ("(3000000000)", "`quantity` of `DraftOrderLineItemInput`"), + ( + "340282366920938463463374607431768211456", + "`quantity` of `DraftOrderLineItemInput`", + ), + ] { + assert_eq!( + refused(vec![("quantity", rust(text))]), + format!( + "The integer is outside the range of `Int`, a 32-bit integer, given for {site}" + ), + "{text}" + ); + } + let message = |site: &str| { + format!("The integer is outside the range of `Int`, a 32-bit integer, given for {site}") + }; + assert_eq!( + refused(vec![ + ("quantity", rust("1")), + ("grams?", rust("Some(3_000_000_000)")) + ]), + message("`grams` of `DraftOrderLineItemInput`") + ); + assert_eq!( + refusal( + "DraftOrderInput", + vec![( + "lineItems", + list(vec![Value::Object(object(vec![( + "quantity", + rust("-2_147_483_649") + )]))]) + )] + ), + message("`quantity` of `DraftOrderLineItemInput`") + ); + let first = "query($first: Int!) { products(first: $first) { nodes { id } } }"; + assert_eq!( + variable(first, rust("4_294_967_296_u64")).unwrap_err(), + message("`$first`") + ); + let schema = Schema::from_json( + r#"{"format": 1, "apiVersion": "2026-10", "query": "Q", "types": { + "Int": "s", "String": "s", + "T": {"i": {"l": "[Int!]", "m": "[[Int]]"}}, + "Q": {"o": {"f": {"echo": ["String", {"input": "T!"}]}}} + }}"#, + ) + .unwrap(); + for (field, value) in [ + ("l", rust("vec![1, 2_147_483_648]")), + ("l", list(vec![rust("1"), rust("2_147_483_648")])), + ("m", rust("[[Some(1)], [Some(2_147_483_648)]]")), + ] { + let error = Literals::new(&schema, quote!(::shopify_api)) + .input_object("T", Span::call_site(), &object(vec![(field, value)])) + .unwrap_err(); + assert!( + error + .message + .starts_with("The integer is outside the range of `Int`"), + "{}", + error.message + ); + } + // At the bounds, and computed: checked when the value is built. + assert!( + input( + "DraftOrderLineItemInput", + vec![ + ("quantity", rust("-2_147_483_648")), + ("grams?", rust("Some(1 << 40)")) + ] + ) + .is_ok() + ); + assert!( + input( + "DraftOrderLineItemInput", + vec![("quantity", rust("0x7fff_ffff_i64"))] + ) + .is_ok() + ); +} From a3f145748def90bfe427dbeaa984fdbbcb253729 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:23:09 +0200 Subject: [PATCH 058/135] fix(graphql): read variables back as deep as they were written `variables_json()` and `body()` read back the JSON of the variables with serde_json's limit of 128 levels, so a deep `json_variable` that worked before now failed. The readback has no limit (serde_json's `unbounded_depth`): the value it was written from was as deep. A test checks that modules and variables of scalars compile under `#![no_implicit_prelude]`. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/Cargo.toml | 2 +- crates/shopify_api/src/graphql/operation.rs | 37 ++++++++++++++++--- .../shopify_api/tests/no_implicit_prelude.rs | 32 ++++++++++++++++ 3 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 crates/shopify_api/tests/no_implicit_prelude.rs diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index 954f585..c76b87d 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -41,7 +41,7 @@ chrono.workspace = true futures-core.workspace = true reqwest = { workspace = true, optional = true } serde.workspace = true -serde_json = { workspace = true, features = ["raw_value"] } +serde_json = { workspace = true, features = ["raw_value", "unbounded_depth"] } serde_urlencoded.workspace = true # `rt`: a token renewal runs in its own task, so a caller that gives up does not cancel it. tokio = { workspace = true, features = ["rt", "sync", "time"] } diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs index 91e4a6d..7fc3441 100644 --- a/crates/shopify_api/src/graphql/operation.rs +++ b/crates/shopify_api/src/graphql/operation.rs @@ -372,17 +372,20 @@ impl Operation { .map_err(|failure| failure.to_error())?; variables .iter() - .map(|(name, value)| match serde_json::from_str(value.get()) { - Ok(value) => Ok((name.clone(), value)), - Err(error) => Err(Error::variables(Some(name), &error)), - }) + .map( + |(name, value)| match read_back(serde_json::Deserializer::from_str(value.get())) { + Ok(value) => Ok((name.clone(), value)), + Err(error) => Err(Error::variables(Some(name), &error)), + }, + ) .collect() } /// The body Shopify receives: `query`, `variables` and `operationName`, /// read back from the JSON it is sent as. pub fn body(&self) -> Result { - serde_json::from_slice(&self.body_json()?).map_err(|error| Error::variables(None, &error)) + read_back(serde_json::Deserializer::from_slice(&self.body_json()?)) + .map_err(|error| Error::variables(None, &error)) } /// The body as it is sent. @@ -400,6 +403,17 @@ impl Operation { } } +/// Reads back JSON this crate wrote, as deep as it was written: no limit, +/// since the value it was written from was as deep. +fn read_back<'de, R: serde_json::de::Read<'de>>( + mut deserializer: serde_json::Deserializer, +) -> serde_json::Result { + deserializer.disable_recursion_limit(); + let value = serde::Deserialize::deserialize(&mut deserializer)?; + deserializer.end()?; + Ok(value) +} + struct Body<'a> { query: &'a str, variables: &'a [(String, Box)], @@ -842,6 +856,19 @@ mod tests { } } + /// As deep as the value it was written from: past serde_json's limit of + /// 128 for a text it did not write. + #[test] + fn variables_read_back_as_deep_as_they_were_written() { + let mut deep = json!(1); + for _ in 0..400 { + deep = json!([deep]); + } + let operation = Operation::<()>::new("query { shop { id } }").json_variable("deep", &deep); + assert_eq!(operation.variables_json().unwrap()["deep"], deep); + assert_eq!(operation.body().unwrap()["variables"]["deep"], deep); + } + #[test] fn variables_can_come_from_a_struct() { #[derive(serde::Serialize)] diff --git a/crates/shopify_api/tests/no_implicit_prelude.rs b/crates/shopify_api/tests/no_implicit_prelude.rs new file mode 100644 index 0000000..51b56d3 --- /dev/null +++ b/crates/shopify_api/tests/no_implicit_prelude.rs @@ -0,0 +1,32 @@ +//! The code `graphql!` writes for modules and for variables of scalars names +//! everything by its full path: it compiles without the prelude. +#![no_implicit_prelude] + +extern crate shopify_api; +extern crate std; + +shopify_api::graphql! { + mod products = "query Products($first: Int!, $query: String) { products(first: $first, query: $query) { nodes { id title } } }" +} + +#[test] +fn modules_and_scalar_variables_compile_without_the_prelude() { + let variables = products::Variables { + first: 2, + query: ::std::option::Option::None, + }; + let operation = products::operation(variables); + ::std::assert_eq!( + ::std::string::ToString::to_string(&operation.body().unwrap()["variables"]), + r#"{"first":2}"# + ); + let inline = shopify_api::graphql!( + "query($first: Int!, $query: String) { products(first: $first, query: $query) { nodes { id } } }", + first = 3, + query = "title:shirt", + ); + ::std::assert_eq!( + ::std::string::ToString::to_string(&inline.body().unwrap()["variables"]), + r#"{"first":3,"query":"title:shirt"}"# + ); +} From 79c868cb5a3863e14c46f200cf44d7699c4b9f8a Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:59:12 +0200 Subject: [PATCH 059/135] perf(graphql): one method per literal, constants written in place An inline literal cost a function and a trait for each Rust expression in it, and a value checked when it is built needs more. Now: - a constant of the type of its place (`"text"`, `12`, `-1.5`, `true`) is written in place, with nothing to check; - the Rust expressions of a literal are the arguments of one generated method, which builds and serializes the value. Its parameters shadow functions of their names, imported from `__private`, so that no constant of the caller's turns one into a pattern; - the check of a scalar place is one impl over the types of the scalar, `#[diagnostic::do_not_recommend]` keeping the message of the place. The `Option` given to a scalar field is refused with that message and a note that says what to write; - the traits are named after the crate being compiled, so that rustc does not point at the same name in a dependency. Warm `cargo check` of 150 operations, medians against 298319f: inline literals of constants 2.27 s -> 2.14 s, of variables 2.29 s -> 2.47 s, 150 modules 4.18 s -> 2.24 s. An array of more than 32 items is now accepted for a list. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/graphql/check.rs | 117 ++++- crates/shopify_api/src/graphql/literal.rs | 52 ++- crates/shopify_api/tests/literals.rs | 116 ++++- ...literal_maybe_non_null_with_default.stderr | 13 +- .../tests/ui/literal_option_in_field.stderr | 24 +- .../tests/ui/literal_wrong_input_type.stderr | 19 +- .../tests/ui/literal_wrong_scalar.rs | 5 + .../tests/ui/literal_wrong_scalar.stderr | 70 +++ crates/shopify_api_graphql/src/literal.rs | 435 ++++++++++++------ crates/shopify_api_graphql/tests/literal.rs | 73 ++- 10 files changed, 712 insertions(+), 212 deletions(-) create mode 100644 crates/shopify_api/tests/ui/literal_wrong_scalar.rs create mode 100644 crates/shopify_api/tests/ui/literal_wrong_scalar.stderr diff --git a/crates/shopify_api/src/graphql/check.rs b/crates/shopify_api/src/graphql/check.rs index 7854119..be15c20 100644 --- a/crates/shopify_api/src/graphql/check.rs +++ b/crates/shopify_api/src/graphql/check.rs @@ -5,8 +5,9 @@ //! [`Error::InvalidValue`] before anything is sent. use std::borrow::Cow; +use std::marker::PhantomData; -use serde::Serialize; +use serde::{Serialize, Serializer}; use serde_json::Value; use crate::error::{SensitiveDetail, is_graphql_name}; @@ -220,34 +221,73 @@ impl sealed::Sealed for Vec { } /// The value of a Rust expression in a literal of `graphql!` or `input!`, -/// checked for the scalar `K` it stands for: [`Int`], [`Float`], [`Json`] -/// (non-null) or [`Plain`] (anything else). Not a public API. +/// checked for the kind `K` of the place it stands in, and written. Not a +/// public API. pub trait Validate { fn validate(&self) -> Result<(), Invalid>; + /// Serializes the value: an array of any length as a list, which serde + /// does past 32 items only for slices. + fn write(&self, serializer: S) -> Result; } +/// The Rust types of a value of the scalar `K`, lists and `Option` aside: +/// what the check of a place of that scalar accepts. `Site` is a type of +/// the generated code: with it, that no `Option` is accepted is known, and +/// the check may also have an impl for `Option`. Not a public API. +pub trait Accepts: Validate {} + +/// A value written by [`Validate::write`]. +pub struct Written<'a, V, K>(pub &'a V, PhantomData K>); + +impl<'a, V, K> Written<'a, V, K> { + pub fn new(value: &'a V) -> Self { + Self(value, PhantomData) + } +} + +impl, K> Serialize for Written<'_, V, K> { + fn serialize(&self, serializer: S) -> Result { + self.0.write(serializer) + } +} + +/// The kinds of places: the scalars, `JSON` split by whether `null` is +/// refused at its top, and input objects. #[derive(Debug)] pub enum Int {} #[derive(Debug)] pub enum Float {} +#[derive(Debug)] +pub enum Text {} +#[derive(Debug)] +pub enum Boolean {} /// A non-null `JSON`. #[derive(Debug)] pub enum Json {} +/// A nullable `JSON`. +#[derive(Debug)] +pub enum MaybeJson {} #[derive(Debug)] -pub enum Plain {} +pub enum Input {} -macro_rules! validate { +macro_rules! scalar { ($kind:ty: $($ty:ty => |$value:ident| $check:expr),+ $(,)?) => {$( impl Validate<$kind> for $ty { fn validate(&self) -> Result<(), Invalid> { let $value = self; $check } + + fn write(&self, serializer: S) -> Result { + self.serialize(serializer) + } } + + impl Accepts<$kind, Site> for $ty {} )+}; } -validate!(Int: +scalar!(Int: i8 => |_value| Ok(()), i16 => |_value| Ok(()), i32 => |_value| Ok(()), @@ -259,36 +299,46 @@ validate!(Int: u64 => |value| int(i32::try_from(*value).is_ok()), usize => |value| int(i32::try_from(*value).is_ok()), ); -validate!(Float: +scalar!(Float: f32 => |value| float(f64::from(*value)), f64 => |value| float(*value), i32 => |_value| Ok(()), u32 => |_value| Ok(()), ); -validate!(Json: - Value => |value| json(value), - &Value => |value| json(value), -); -validate!(Plain: +scalar!(Text: String => |_value| Ok(()), &str => |_value| Ok(()), &String => |_value| Ok(()), Cow<'_, str> => |_value| Ok(()), - bool => |_value| Ok(()), +); +scalar!(Boolean: bool => |_value| Ok(())); +scalar!(Json: + Value => |value| json(value), + &Value => |value| json(value), +); +scalar!(MaybeJson: Value => |_value| Ok(()), &Value => |_value| Ok(()), ); -impl Validate for InputObject { +impl Validate for InputObject { fn validate(&self) -> Result<(), Invalid> { self.invalid() } + + fn write(&self, serializer: S) -> Result { + self.serialize(serializer) + } } -impl Validate for &InputObject { +impl Validate for &InputObject { fn validate(&self) -> Result<(), Invalid> { self.invalid() } + + fn write(&self, serializer: S) -> Result { + self.serialize(serializer) + } } impl> Validate for Option { @@ -298,28 +348,51 @@ impl> Validate for Option { None => Ok(()), } } + + fn write(&self, serializer: S) -> Result { + match self { + Some(value) => value.write(serializer), + None => serializer.serialize_none(), + } + } +} + +impl, const N: usize> Validate for [V; N] { + fn validate(&self) -> Result<(), Invalid> { + self.as_slice().validate() + } + + fn write(&self, serializer: S) -> Result { + self.as_slice().write(serializer) + } } impl> Validate for Vec { fn validate(&self) -> Result<(), Invalid> { - items(self, V::validate) + self.as_slice().validate() + } + + fn write(&self, serializer: S) -> Result { + self.as_slice().write(serializer) } } impl> Validate for &Vec { fn validate(&self) -> Result<(), Invalid> { - items(*self, V::validate) + self.as_slice().validate() + } + + fn write(&self, serializer: S) -> Result { + self.as_slice().write(serializer) } } impl> Validate for &[V] { fn validate(&self) -> Result<(), Invalid> { - items(*self, V::validate) + items(self.iter(), V::validate) } -} -impl, const N: usize> Validate for [V; N] { - fn validate(&self) -> Result<(), Invalid> { - items(self, V::validate) + fn write(&self, serializer: S) -> Result { + serializer.collect_seq(self.iter().map(Written::::new)) } } diff --git a/crates/shopify_api/src/graphql/literal.rs b/crates/shopify_api/src/graphql/literal.rs index 36488ce..3f3eefa 100644 --- a/crates/shopify_api/src/graphql/literal.rs +++ b/crates/shopify_api/src/graphql/literal.rs @@ -12,7 +12,9 @@ use std::marker::PhantomData; use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer}; use serde_json::value::RawValue; -pub use super::check::{Float, Int, Invalid, Json, Plain, Validate}; +pub use super::check::{ + Accepts, Boolean, Float, Input, Int, Invalid, Json, MaybeJson, Text, Validate, +}; use crate::Maybe; /// The JSON of a value, or why it is refused. @@ -69,9 +71,9 @@ impl, K> Check for Leaf { } } -impl Serialize for Leaf { +impl, K> Serialize for Leaf { fn serialize(&self, serializer: S) -> Result { - self.0.serialize(serializer) + self.0.write(serializer) } } @@ -92,11 +94,11 @@ impl Collected { } } - pub fn push(&mut self, value: &(impl Check + Serialize)) { + pub fn push(&mut self, value: Result, Invalid>) { if self.invalid.is_some() { return; } - match to_raw(value) { + match value { Ok(item) => self.items.push(item), Err(invalid) => self.invalid = Some(invalid.index(self.items.len())), } @@ -118,6 +120,21 @@ impl Serialize for Collected { } } +/// Functions named like the parameters of the method the macros generate, +/// imported where it is declared: a parameter may shadow a function, so no +/// constant of the caller's of the same name turns it into a pattern. +pub mod names { + macro_rules! names { + ($($name:ident)*) => {$( + pub fn $name() {} + )*}; + } + + names!( + value0 value1 value2 value3 value4 value5 value6 value7 value8 value9 value10 value11 value12 value13 value14 value15 value16 value17 value18 value19 value20 value21 value22 value23 value24 value25 value26 value27 value28 value29 value30 value31 value32 value33 value34 value35 value36 value37 value38 value39 value40 value41 value42 value43 value44 value45 value46 value47 value48 value49 value50 value51 value52 value53 value54 value55 value56 value57 value58 value59 value60 value61 value62 value63 + ); +} + #[derive(Debug)] pub struct Object(pub F); @@ -304,19 +321,23 @@ pub fn raw_option(value: impl RawOption) -> Maybe { value.into_maybe() } -/// The value of `field?: value`: `None` leaves the field out. -pub trait IntoMaybe { - fn into_maybe(self) -> Maybe; +/// The value of `field?: value`, checked as a `K`: `None` leaves the field +/// out. +pub trait OptionalValue { + type Value: Validate; + fn into_maybe(self) -> Maybe; } -impl IntoMaybe for Option { - fn into_maybe(self) -> Maybe { +impl> OptionalValue for Option { + type Value = V; + fn into_maybe(self) -> Maybe { option(self) } } -impl IntoMaybe for Maybe { - fn into_maybe(self) -> Maybe { +impl> OptionalValue for Maybe { + type Value = V; + fn into_maybe(self) -> Maybe { self } } @@ -390,7 +411,10 @@ mod tests { ); let mut collected = Collected::new(); for quantity in [1_usize, 2, 1 << 40, 3, usize::MAX] { - collected.push(&Object((Field("quantity", leaf::(quantity)), ()))); + collected.push(to_raw(&Object(( + Field("quantity", leaf::(quantity)), + (), + )))); } assert_eq!( refused(to_raw(&Object((Field("items", &collected), ())))), @@ -399,7 +423,7 @@ mod tests { // `null` of a nullable `JSON`, and nulls inside a `JSON`, are sent. assert_eq!( to_raw(&List(( - leaf::(Value::Null), + leaf::(Value::Null), (leaf::(serde_json::json!([null])), ()) ))) .unwrap() diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs index dbe9439..44773bc 100644 --- a/crates/shopify_api/tests/literals.rs +++ b/crates/shopify_api/tests/literals.rs @@ -521,6 +521,21 @@ fn values_at_the_bounds_are_sent() { settings: json!({ "a": null }) }); let discount = input!(DiscountCustomerGetsValueInput { percentage?: Some(f64::MIN_POSITIVE) }); + let constants = input!(DraftOrderLineItemInput { + quantity: -2_147_483_648, + title: "t", + requiresShipping: true, + weight: { unit: GRAMS, value: 2 }, + }); + assert_eq!( + serde_json::to_value(&constants).unwrap(), + json!({ "quantity": i32::MIN, "title": "t", "requiresShipping": true, "weight": { "unit": "GRAMS", "value": 2 } }) + ); + let tags = input!(ProductUpdateInput { tags: ["t"; 40] }); + assert_eq!( + serde_json::to_value(&tags).unwrap()["tags"], + json!(vec!["t"; 40]) + ); assert_eq!( serde_json::to_value((&line_item, &pixel, &discount)).unwrap(), json!([ @@ -550,6 +565,9 @@ mod hygiene { Some("captured") } fn push(self, _: &str) {} + fn build(self, _: A, _: B) -> &'static str { + "captured" + } fn variable(self, _: &str, _: V) -> Self { self } @@ -573,6 +591,9 @@ mod hygiene { let __shopify_api_variable_0 = "local"; let check = |text: &str| format!("closure:{text}"); let Checks = "local"; + let literal = "local"; + let value0 = |text: &str| format!("closure:{text}"); + let V1 = "local"; let value = input!(ProductUpdateInput { title: __shopify_api_check3("a"), vendor: __shopify_api_check1("b"), @@ -580,7 +601,8 @@ mod hygiene { productType: __shopify_api_checks, descriptionHtml: __shopify_api_variable_0, templateSuffix?: __shopify_api_optional1("d"), - tags: [for tag in &__shopify_api_items => Checks.to_string() + tag], + tags: [for tag in &__shopify_api_items => Checks.to_string() + tag + literal + V1], + seo: { title: value0("e"), description: literal }, }); assert_eq!( json(&value), @@ -591,7 +613,8 @@ mod hygiene { "productType": "local", "descriptionHtml": "local", "templateSuffix": "closure:d", - "tags": ["locallocal"], + "tags": ["locallocallocallocal"], + "seo": { "title": "closure:e", "description": "local" }, }) ); @@ -621,6 +644,13 @@ mod hygiene { const Checks: &str = "const"; const checks: &str = "const"; const items: &str = "const"; + const literal: &str = "const"; + const value0: &str = "const"; + const V1: &str = "const"; + const value69: &str = "const"; + fn leaf(text: &str) -> String { + format!("fn:{text}") + } static __shopify_api_optional1: &str = "static"; fn __shopify_api_check2(text: &str) -> String { format!("fn:{text}") @@ -632,6 +662,86 @@ mod hygiene { text.map(|text| format!("fn:{text}")) } + /// More values than the names `literal::names` has. + #[test] + fn seventy_values() { + let value = input!(ProductUpdateInput { + tags: [ + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1 + ] + }); + assert_eq!(json(&value)["tags"], json!(vec!["const"; 70])); + } + #[test] fn functions_constants_and_statics() { let value = input!(ProductUpdateInput { @@ -642,6 +752,7 @@ mod hygiene { descriptionHtml: Checks, templateSuffix?: optional(Some(__shopify_api_optional1)), tags: [for tag in __shopify_api_items => check(tag)], + seo: { title: leaf(literal), description: value0.to_string() + V1 }, }); assert_eq!( json(&value), @@ -653,6 +764,7 @@ mod hygiene { "descriptionHtml": "const", "templateSuffix": "fn:static", "tags": ["fn:const"], + "seo": { "title": "fn:const", "description": "constconst" }, }) ); let operation = graphql!( diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr index 6d660f5..a130e07 100644 --- a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -2,22 +2,25 @@ error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[Inven --> tests/ui/literal_maybe_non_null_with_default.rs:6:63 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); - | ^^^^^^^^^^ an `Option`: `None` leaves the field out + | --------------------------------------------------^^^^^^^^^^--- + | | | + | | an `Option`: `None` leaves the field out + | required by a bound introduced by this call | - = help: the trait `__ShopifyApiNoNull4` is not implemented for `Vec>` + = help: the trait `__ShopifyApiNoNull4_c23fa168` is not implemented for `Vec>` help: this trait has no implementations, consider adding one --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required for `Maybe>>` to implement `__ShopifyApiOptional4>>` +note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c23fa168` --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required by a bound in `main::Checks::optional` +note: required by a bound in `Checks::build` --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::optional` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` = note: this error originates in the macro `input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr index 90530dc..9f7c335 100644 --- a/crates/shopify_api/tests/ui/literal_option_in_field.stderr +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -1,23 +1,17 @@ -error[E0277]: `vendor` of `ProductUpdateInput` takes a `String`, not an `Option`: write `vendor?: value` to leave the field out when it is `None`, or `vendor: null` to send `null` +error[E0277]: `vendor` of `ProductUpdateInput` expects a `String`, not `Option` --> tests/ui/literal_option_in_field.rs:3:93 | 3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); - | ^^^^^^ `vendor: None` would send `null`, which clears the field + | ^^^^^^ + | | + | `Option` doesn't satisfy the trait bound + | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiNoOption4` is not implemented for `String` -help: this trait has no implementations, consider adding one + = help: the trait `__ShopifyApiExpect1_c2385b33` is not implemented for `Option` + = note: `vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null` +note: required by a bound in `Checks::build` --> tests/ui/literal_option_in_field.rs:3:13 | 3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required for `Option` to implement `__ShopifyApiExpect3` - --> tests/ui/literal_option_in_field.rs:3:13 - | -3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required by a bound in `main::Checks::check` - --> tests/ui/literal_option_in_field.rs:3:13 - | -3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::check` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr index e9c630c..c0e960e 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -1,11 +1,16 @@ error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` --> tests/ui/literal_wrong_input_type.rs:5:22 | -5 | metafields = seo, - | ^^^ build it with `input!(MetafieldsSetInput { … })` +3 | let _ = shopify_api::graphql!( + | _____________- +4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", +5 | | metafields = seo, + | | ^^^ build it with `input!(MetafieldsSetInput { … })` +6 | | ); + | |_____- required by a bound introduced by this call | - = help: the trait `__ShopifyApiExpect2` is not implemented for `InputObject<2493993284262097346>` -help: the following other types implement trait `__ShopifyApiExpect2` + = help: the trait `__ShopifyApiExpect2_c2384416` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2_c2384416` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -17,7 +22,7 @@ help: the following other types implement trait `__ShopifyApiExpect2` | | | | |_____`&InputObject<960560859991546817>` | `InputObject<960560859991546817>` -note: required for `Vec>` to implement `main::__ShopifyApiExpect1` +note: required for `Vec>` to implement `__ShopifyApiExpect1_c2384416` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -26,7 +31,7 @@ note: required for `Vec>` to implement `main::_ 5 | | metafields = seo, 6 | | ); | |_____^ -note: required by a bound in `main::Checks::check` +note: required by a bound in `Checks::build` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -34,5 +39,5 @@ note: required by a bound in `main::Checks::check` 4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", 5 | | metafields = seo, 6 | | ); - | |_____^ required by this bound in `Checks::check` + | |_____^ required by this bound in `Checks::build` = note: this error originates in the macro `shopify_api::graphql` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.rs b/crates/shopify_api/tests/ui/literal_wrong_scalar.rs new file mode 100644 index 0000000..bef69c7 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.rs @@ -0,0 +1,5 @@ +fn main() { + let count = 2_u8; + let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + let _ = shopify_api::input!(WeightInput { unit: GRAMS, value: 2_u64 }); +} diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr new file mode 100644 index 0000000..bdec6bf --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr @@ -0,0 +1,70 @@ +error[E0277]: `quantity` of `DraftOrderLineItemInput` expects an `Int`, not `&str` + --> tests/ui/literal_wrong_scalar.rs:3:69 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^^^ + | | + | `&'static str` doesn't satisfy the trait bound + | any integer type + | + = help: the trait `main::__ShopifyApiExpect1_c2384be1` is not implemented for `&str` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_wrong_scalar.rs:3:13 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `title` of `DraftOrderLineItemInput` expects a `String`, not `u8` + --> tests/ui/literal_wrong_scalar.rs:3:81 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^^^^^ + | | + | `u8` doesn't satisfy the trait bound + | `String`, `&str`, `&String` or `Cow` + | + = help: the trait `__ShopifyApiExpect3_c2384be1` is not implemented for `u8` + = note: `title?: value` takes an `Option`, `None` leaving the field out; `title: null` sends `null` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_wrong_scalar.rs:3:13 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `requiresShipping` of `DraftOrderLineItemInput` expects a `Boolean`, not `{integer}` + --> tests/ui/literal_wrong_scalar.rs:3:106 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^ + | | + | `{integer}` doesn't satisfy the trait bound + | `bool` + | + = help: the trait `__ShopifyApiExpect5_c2384be1` is not implemented for `{integer}` + = note: `requiresShipping?: value` takes an `Option`, `None` leaving the field out; `requiresShipping: null` sends `null` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_wrong_scalar.rs:3:13 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `value` of `WeightInput` expects a `Float`, not `u64` + --> tests/ui/literal_wrong_scalar.rs:4:67 + | +4 | let _ = shopify_api::input!(WeightInput { unit: GRAMS, value: 2_u64 }); + | ^^^^^ + | | + | `u64` doesn't satisfy the trait bound + | `f64`, `f32`, `i32` or `u32` + | + = help: the trait `main::__ShopifyApiExpect1_c2384be1` is not implemented for `u64` + = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c2384be1`, but not `main::__ShopifyApiExpect1_c2384be1` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_wrong_scalar.rs:4:13 + | +4 | let _ = shopify_api::input!(WeightInput { unit: GRAMS, value: 2_u64 }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index 201dbbf..f21903f 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -158,15 +158,21 @@ enum Place { /// Checks values against a schema and writes their code. /// /// No name the code declares is in scope where a Rust expression of a value -/// is evaluated, so that none captures or shadows a name of the caller's: -/// each expression is checked by the method of a type declared in a block -/// of its own, the receiver of the call, and the code declares no local -/// that a constant of the caller's could match. +/// is evaluated, so that none captures or shadows a name of the caller's. +/// The Rust expressions of a value are the arguments of one method, which +/// builds the value; the method, and the traits that check each argument, +/// are declared in a block of their own, the receiver of the call. A +/// constant (`"text"`, `12`, `true`) is written in place, with nothing to +/// check. The code declares no local that a constant of the caller's could +/// match. pub struct Literals<'a> { schema: &'a Schema, krate: TokenStream, items: Vec, count: usize, + /// Of the names of the traits, from the crate being compiled: rustc + /// points at a trait of the same name in another crate otherwise. + suffix: u32, } impl fmt::Debug for Literals<'_> { @@ -187,6 +193,7 @@ impl<'a> Literals<'a> { krate, items: Vec::new(), count: 0, + suffix: crate_suffix(), } } @@ -242,11 +249,9 @@ impl<'a> Literals<'a> { if let Some(converted) = converted { return Ok(converted); } - let code = self.value(value, ty, &site, Place::Variable)?; - let krate = &self.krate; - Ok(VariableValue::Literal( - quote!(#krate::__private::literal::to_raw(&#code)), - )) + let mut build = Build::default(); + let body = self.value(value, ty, &site, Place::Variable, &mut build)?; + Ok(VariableValue::Literal(build.finish(body, &self.krate))) } /// `input!(name { … })`: an `InputObject` of the input object `name`. @@ -283,21 +288,25 @@ impl<'a> Literals<'a> { ); } }; - let code = self.object(name, fields, object)?; + let mut build = Build::default(); + let body = self.object(name, fields, object, &mut build)?; + let json = build.finish(body, &self.krate); let krate = &self.krate; let id = input_object_id(name); Ok(quote_spanned! {span=> - #krate::InputObject::<#id>::__new(#name, #krate::__private::literal::to_raw(&#code)) + #krate::InputObject::<#id>::__new(#name, #json) }) } - /// The code of a value of type `ty`: an expression of a serializable value. + /// The code that builds a value of type `ty` from the arguments it adds + /// to `build`. fn value( &mut self, value: &Value, ty: &TypeRef, site: &Site, place: Place, + build: &mut Build, ) -> Result { let krate = self.krate.clone(); let inner = ty.nullable(); @@ -313,17 +322,18 @@ impl<'a> Literals<'a> { } Value::Raw { keyword, value } => { self.enum_only(ty, *keyword, site)?; - let tokens = &value.tokens; - Ok(quote_spanned!(value.span=> #krate::__private::literal::raw(#tokens))) + let tokens = argument(value); + let arg = quote_spanned!(value.span=> #krate::__private::literal::raw(#tokens)); + Ok(build.argument(None, quote!(::std::string::String), arg)) } Value::Ident(ident) => match self.enum_values(inner) { Some((name, values, deprecated)) => { self.enum_value(ident, name, values, deprecated, site) } - None => self.expression(&ident_expr(ident), ty, site, place), + None => self.expression(&ident_expr(ident), ty, site, place, build), }, Value::Object(object) => match self.input_fields(inner) { - Some((name, fields)) => self.object(name, fields, object), + Some((name, fields)) => self.object(name, fields, object, build), None => error( object.span, format!("{site} expects {}, not an object", self.what(ty)), @@ -334,15 +344,15 @@ impl<'a> Literals<'a> { let site = Site::Item(Box::new(site.clone())); let mut items = Vec::new(); for value in &list.items { - items.push(self.value(value, item, &site, Place::Item)?); + items.push(self.value(value, item, &site, Place::Item, build)?); } let nested = items .iter() .rev() .fold(quote!(()), |rest, item| quote!((#item, #rest))); - Ok(quote!(#krate::__private::literal::List(#nested))) + Ok(quote!(literal::List(#nested))) } - (_, Some(rust)) => self.expression(rust, ty, site, place), + (_, Some(rust)) => self.expression(rust, ty, site, place, build), (_, None) => error( list.span, format!("{site} expects {}, not a list", self.what(ty)), @@ -356,7 +366,9 @@ impl<'a> Literals<'a> { ); }; let site = Site::Item(Box::new(site.clone())); - let value = self.value(&comprehension.item, item, &site, Place::Item)?; + let mut each = Build::default(); + let value = self.value(&comprehension.item, item, &site, Place::Item, &mut each)?; + let value = each.finish(value, &krate); let For { pattern, binding, @@ -381,18 +393,19 @@ impl<'a> Literals<'a> { // Each item is written in its turn of the loop, so that it may // borrow what the loop gives. let push = - quote!(#krate::__private::literal::Collected::push(&mut #items, &#value);); + quote!(#krate::__private::literal::Collected::push(&mut #items, #value);); let body = match filter { Some(filter) => quote!(if #filter { #push }), None => push, }; - Ok(quote! {{ + let list = quote! {{ let mut #items = #krate::__private::literal::Collected::new(); for #pattern in #iterable { #body } #items - }}) + }}; + Ok(build.argument(None, quote!(#krate::__private::literal::Collected), list)) } - Value::Rust(expr) => self.expression(expr, ty, site, place), + Value::Rust(expr) => self.expression(expr, ty, site, place, build), } } @@ -402,8 +415,8 @@ impl<'a> Literals<'a> { name: &str, definitions: &BTreeMap, object: &Object, + build: &mut Build, ) -> Result { - let krate = self.krate.clone(); let mut given: Vec<&str> = Vec::new(); let mut fields = Vec::new(); for field in &object.fields { @@ -446,12 +459,13 @@ impl<'a> Literals<'a> { ), ); } - let value = self.optional(field, definition, &site)?; - quote!(#krate::__private::literal::Optional(#key, #value)) + let value = self.optional(field, definition, &site, build)?; + quote!(literal::Optional(#key, #value)) } None => { - let value = self.value(&field.value, &definition.ty, &site, Place::Field)?; - quote!(#krate::__private::literal::Field(#key, #value)) + let value = + self.value(&field.value, &definition.ty, &site, Place::Field, build)?; + quote!(literal::Field(#key, #value)) } }; fields.push(code); @@ -479,7 +493,7 @@ impl<'a> Literals<'a> { .iter() .rev() .fold(quote!(()), |rest, field| quote!((#field, #rest))); - Ok(quote!(#krate::__private::literal::Object(#nested))) + Ok(quote!(literal::Object(#nested))) } /// `field?: value`, the field being optional: `Maybe` of the value. @@ -488,6 +502,7 @@ impl<'a> Literals<'a> { field: &Field, definition: &InputValue, site: &Site, + build: &mut Build, ) -> Result { let krate = self.krate.clone(); let key = &field.name; @@ -496,15 +511,15 @@ impl<'a> Literals<'a> { let expr = match &field.value { Value::Raw { keyword, value } => { self.enum_only(&definition.ty, *keyword, site)?; - let tokens = &value.tokens; + let tokens = argument(value); let convert = if null_refused { quote!(raw_option) } else { quote!(raw_optional) }; - return Ok( - quote_spanned!(value.span=> #krate::__private::literal::#convert(#tokens)), - ); + let arg = + quote_spanned!(value.span=> #krate::__private::literal::#convert(#tokens)); + return Ok(build.argument(None, quote!(#krate::Maybe<::std::string::String>), arg)); } Value::Rust(expr) => expr.clone(), Value::Ident(ident) => ident_expr(ident), @@ -529,18 +544,18 @@ impl<'a> Literals<'a> { } self.int_literals(&expr.tokens, &definition.ty, site)?; - let mut items = Vec::new(); - let value_bound = self.expect(&definition.ty, Place::Field, site, &mut items); + let kind = self.kind(&definition.ty); + let value_bound = self.expect(&definition.ty, Place::Field, site, &kind, build); let n = self.next(); - let bound = format_ident!("__ShopifyApiOptional{n}"); + let bound = self.name("Optional", n); let what = escape(&self.what(&definition.ty)); let (message, label, maybe_bound) = if null_refused { - let no_null = format_ident!("__ShopifyApiNoNull{n}"); + let no_null = self.name("NoNull", n); let refusal = escape(&format!( "{site} is non-null (`{}`): `{key}?:` takes an `Option`, not a `Maybe`, whose `Null` it refuses", definition.ty )); - items.push(quote! { + build.items.push(quote! { #[diagnostic::on_unimplemented(message = #refusal, label = "an `Option`: `None` leaves the field out")] trait #no_null {} }); @@ -559,24 +574,24 @@ impl<'a> Literals<'a> { quote!(#value_bound), ) }; - // `IntoMaybe` as a supertrait: one refusal, which names the field. - items.push(quote! { + // `OptionalValue` as a supertrait: one refusal, which names the field. + build.items.push(quote! { #[diagnostic::on_unimplemented(message = #message, label = #label)] - trait #bound: #krate::__private::literal::IntoMaybe {} - impl #bound for ::core::option::Option {} - impl #bound for #krate::Maybe {} + trait #bound: literal::OptionalValue<#kind> {} + impl #bound for ::core::option::Option {} + impl #bound for #krate::Maybe {} }); - let kind = self.kind(&definition.ty); - let checks = checks( - &items, - quote! { - fn optional>(self, value: V) -> #krate::Maybe<#krate::__private::literal::Leaf> { - #krate::__private::literal::optional(#krate::__private::literal::IntoMaybe::into_maybe(value)) - } - }, + let generic = format_ident!("V{n}"); + let value = build.argument( + Some(quote!(#generic: #bound)), + quote!(#generic), + argument(&expr), ); - let tokens = argument(&expr); - Ok(quote_spanned!(expr.span=> #checks.optional(#tokens))) + Ok(quote! { + literal::optional::<#kind, _>( + literal::OptionalValue::<#kind>::into_maybe(#value) + ) + }) } /// A Rust expression for a value of type `ty`, checked by a trait. @@ -586,6 +601,7 @@ impl<'a> Literals<'a> { ty: &TypeRef, site: &Site, place: Place, + build: &mut Build, ) -> Result { if self.is_enum(ty) { let name = ty.name(); @@ -602,20 +618,62 @@ impl<'a> Literals<'a> { return error(expr.span, message); } self.int_literals(&expr.tokens, ty, site)?; - let mut items = Vec::new(); - let bound = self.expect(ty, place, site, &mut items); - let krate = &self.krate; let kind = self.kind(ty); - let checks = checks( - &items, - quote! { - fn check(self, value: V) -> #krate::__private::literal::Leaf { - #krate::__private::literal::leaf(value) - } - }, + if let Some(constant) = self.constant(expr, ty) { + return Ok(constant); + } + let bound = self.expect(ty, place, site, &kind, build); + let generic = format_ident!("V{}", self.next()); + let value = build.argument( + Some(quote!(#generic: #bound)), + quote!(#generic), + argument(expr), ); - let tokens = argument(expr); - Ok(quote_spanned!(expr.span=> #checks.check(#tokens))) + Ok(quote!(literal::leaf::<#kind, _>(#value))) + } + + /// A literal that has the type `ty` whatever its context, written in + /// place: a string for a string scalar, an integer for an `Int` (checked + /// already) or a `Float`, a float for a `Float`, `true` or `false`. + fn constant(&self, expr: &Expr, ty: &TypeRef) -> Option { + let TypeRef::Named(name) = ty.nullable() else { + return None; + }; + if !matches!(self.schema.get(name), Some(TypeDef::Scalar)) { + return None; + } + let trees: Vec = expr.tokens.clone().into_iter().collect(); + let literal = match trees.as_slice() { + [TokenTree::Ident(ident)] if ident == "true" || ident == "false" => { + return (Scalar::of(name) == Scalar::Boolean).then(|| expr.tokens.clone()); + } + [TokenTree::Literal(literal)] => literal.to_string(), + [TokenTree::Punct(minus), TokenTree::Literal(literal)] if minus.as_char() == '-' => { + literal.to_string() + } + _ => return None, + }; + let tokens = &expr.tokens; + match (Scalar::of(name), number(&literal)) { + (Scalar::String, _) + if literal.starts_with('"') + || literal.starts_with("r\"") + || literal.starts_with("r#") => + { + (!trees.iter().any(|tree| matches!(tree, TokenTree::Punct(_)))) + .then(|| tokens.clone()) + } + (Scalar::Int, Some(Number::Int(suffix))) + if suffix.is_empty() || INT_TYPES.contains(&suffix) => + { + Some(quote!(literal::leaf::(#tokens))) + } + ( + Scalar::Float, + Some(Number::Int("" | "i32" | "u32") | Number::Float("" | "f32" | "f64")), + ) => Some(quote!(literal::leaf::(#tokens))), + _ => None, + } } /// The trait a Rust expression of type `ty` must implement at `place`, @@ -625,18 +683,21 @@ impl<'a> Literals<'a> { ty: &TypeRef, place: Place, site: &Site, - items: &mut Vec, + kind: &TokenStream, + build: &mut Build, ) -> Ident { - let bound = format_ident!("__ShopifyApiExpect{}", self.next()); + let n = self.next(); + let bound = self.name("Expect", n); let krate = self.krate.clone(); let what = self.what(ty); let mut label = accepted(self.schema, ty.nullable()); let mut impls = Vec::new(); + let mut note = None; let inner = ty.nullable(); if !ty.is_non_null() && place != Place::Field { label.push_str(", or an `Option` of it, `None` sending `null`"); let non_null = TypeRef::NonNull(Box::new(inner.clone())); - let value = self.expect(&non_null, place, site, items); + let value = self.expect(&non_null, place, site, kind, build); impls.push(quote!(impl #bound for V {})); impls.push(quote!(impl #bound for ::core::option::Option {})); } else { @@ -646,7 +707,8 @@ impl<'a> Literals<'a> { item, Place::Item, &Site::Item(Box::new(site.clone())), - items, + kind, + build, ); impls.push(quote! { impl #bound for ::std::vec::Vec {} @@ -663,16 +725,21 @@ impl<'a> Literals<'a> { impl<'a> #bound for &'a #krate::InputObject<#id> {} }); } - _ => { - for ty in scalar_types(Scalar::of(name), &krate) { - impls.push(quote!(impl<'a> #bound for #ty {})); - } - } + // One impl for the types of the scalar: the refusal is this + // trait's, which names the place. + _ => impls.push(quote! { + #[diagnostic::do_not_recommend] + impl> #bound for V {} + }), }, TypeRef::NonNull(_) => unreachable!("`nullable` removes the `!`"), } if place == Place::Field { - impls.push(self.no_option(&bound, ty, site)); + if self.is_scalar(inner) { + note = self.option_note(ty, site); + } else { + impls.push(self.no_option(&bound, ty, site, kind)); + } } } // The type of an `InputObject` is a hash: the message names the @@ -688,19 +755,48 @@ impl<'a> Literals<'a> { escape(&what) ); let label = escape(&label); - items.push(quote! { - #[diagnostic::on_unimplemented(message = #message, label = #label)] - trait #bound {} + let note = note.map(|note: String| { + let note = escape(¬e); + quote!(, note = #note) + }); + // `Validate` as a supertrait: what a value is checked for when it is + // built follows from its type being accepted. + build.items.push(quote! { + #[diagnostic::on_unimplemented(message = #message, label = #label #note)] + trait #bound: literal::Validate<#kind> {} #(#impls)* }); bound } + /// What to write for an `Option` in a nullable field of a scalar, whose + /// check takes the types of the scalar only: shown with any refusal. + fn option_note(&self, ty: &TypeRef, site: &Site) -> Option { + let Site::Field { name, .. } = site else { + return None; + }; + (!ty.is_non_null()).then(|| { + format!( + "`{name}?: value` takes an `Option`, `None` leaving the field out; `{name}: null` sends `null`" + ) + }) + } + + fn is_scalar(&self, ty: &TypeRef) -> bool { + matches!(ty, TypeRef::Named(name) if matches!(self.schema.get(name), Some(TypeDef::Scalar))) + } + /// Refuses an `Option` in a field, saying what to write instead: sending /// `null` for `None` would clear the field. - fn no_option(&mut self, bound: &Ident, ty: &TypeRef, site: &Site) -> TokenStream { + fn no_option( + &mut self, + bound: &Ident, + ty: &TypeRef, + site: &Site, + kind: &TokenStream, + ) -> TokenStream { let n = self.next(); - let no_option = format_ident!("__ShopifyApiNoOption{n}"); + let no_option = self.name("NoOption", n); let Site::Field { name, .. } = site else { unreachable!("a field has a field site") }; @@ -721,7 +817,7 @@ impl<'a> Literals<'a> { let (message, label) = (escape(&message), escape(&label)); quote! { #[diagnostic::on_unimplemented(message = #message, label = #label)] - trait #no_option {} + trait #no_option: literal::Validate<#kind> {} impl #bound for ::core::option::Option {} } } @@ -817,15 +913,17 @@ impl<'a> Literals<'a> { /// What a Rust expression of type `ty` is checked for when it is built: /// the `Int`, `Float` or non-null `JSON` its innermost type is. fn kind(&self, ty: &TypeRef) -> TokenStream { - let krate = &self.krate; let (name, non_null) = innermost(ty); let kind = match (self.schema.get(name), Scalar::of(name)) { (Some(TypeDef::Scalar), Scalar::Int) => quote!(Int), (Some(TypeDef::Scalar), Scalar::Float) => quote!(Float), + (Some(TypeDef::Scalar), Scalar::Boolean) => quote!(Boolean), (Some(TypeDef::Scalar), Scalar::Json) if non_null => quote!(Json), - _ => quote!(Plain), + (Some(TypeDef::Scalar), Scalar::Json) => quote!(MaybeJson), + (Some(TypeDef::Scalar), _) => quote!(Text), + _ => quote!(Input), }; - quote!(#krate::__private::literal::#kind) + quote!(literal::#kind) } /// Refuses an integer literal outside of the 32 bits of `Int`, where @@ -915,12 +1013,24 @@ impl<'a> Literals<'a> { } } + fn name(&self, what: &str, n: usize) -> Ident { + format_ident!("__ShopifyApi{what}{n}_{:08x}", self.suffix) + } + fn next(&mut self) -> usize { self.count += 1; self.count } } +/// A hash of the name of the crate being compiled, which cargo gives the +/// macros. +fn crate_suffix() -> u32 { + let name = std::env::var("CARGO_CRATE_NAME").unwrap_or_default(); + let hash = input_object_id(&name); + (hash ^ (hash >> 32)) as u32 +} + fn literal_after_question(key: &str) -> String { format!( "`{key}?:` takes a Rust expression, an `Option` or a `shopify_api::Maybe` whose `None` leaves the field out; write `{key}: …` for this value" @@ -951,40 +1061,6 @@ fn accepted(schema: &Schema, ty: &TypeRef) -> String { } } -/// The Rust types of a scalar, as `IntoVariable` accepts them; they may -/// borrow for `'a`. -fn scalar_types(scalar: Scalar, krate: &TokenStream) -> Vec { - match scalar { - Scalar::String => vec![ - quote!(::std::string::String), - quote!(&'a ::core::primitive::str), - quote!(&'a ::std::string::String), - quote!(::std::borrow::Cow<'a, ::core::primitive::str>), - ], - Scalar::Int => [ - "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "usize", "isize", - ] - .iter() - .map(|name| { - let ident = Ident::new(name, Span::call_site()); - quote!(::core::primitive::#ident) - }) - .collect(), - Scalar::Float => ["f32", "f64", "i32", "u32"] - .iter() - .map(|name| { - let ident = Ident::new(name, Span::call_site()); - quote!(::core::primitive::#ident) - }) - .collect(), - Scalar::Boolean => vec![quote!(::core::primitive::bool)], - Scalar::Json => vec![ - quote!(#krate::__private::serde_json::Value), - quote!(&'a #krate::__private::serde_json::Value), - ], - } -} - /// The integer literals of `tokens` in the forms /// [`Literals::int_literals`] reads, and their spans; one beyond `i128` is /// `i128::MAX`. @@ -1072,20 +1148,115 @@ fn innermost(ty: &TypeRef) -> (&str, bool) { } } -/// The receiver of a check: a value of a type declared, with what its -/// method needs, in a block that no expression of the caller's is in. By -/// value, so that no trait method of the same name wins over the method. -fn checks(items: &[TokenStream], method: TokenStream) -> TokenStream { - quote! { - ({ - #(#items)* - struct Checks; - impl Checks { - #method - } - Checks - }) +/// The Rust expressions of a value, which are the arguments of the method +/// that builds it, and the traits that check them. +#[derive(Default)] +struct Build { + items: Vec, + generics: Vec, + params: Vec, + args: Vec, +} + +impl Build { + /// Takes `arg` as an argument of type `ty`: the name the code that + /// builds the value refers to it by. + fn argument( + &mut self, + generic: Option, + ty: TokenStream, + arg: TokenStream, + ) -> TokenStream { + let name = format_ident!("value{}", self.params.len()); + self.generics.extend(generic); + self.params.push(quote!(#name: #ty)); + self.args.push(arg); + quote!(#name) } + + /// The code of the JSON of the value, or of why it is refused: a + /// `Result, Invalid>`, a type that does not depend on the + /// arguments, so that a refused argument is reported once, at it. + fn finish(self, body: TokenStream, krate: &TokenStream) -> TokenStream { + let Self { + items, + generics, + params, + args, + } = self; + let json = quote!(literal::to_raw(&#body)); + // `literal`, in a block that no expression of the caller's is in. + let path = quote!(#[allow(unused_imports)] use #krate::__private::literal;); + if args.is_empty() { + return quote!({ #path #json }); + } + // The parameters shadow functions of these names, and so no + // constant: `literal::names` has the first ones. + let names = (NAMES..params.len()).map(|n| { + let name = format_ident!("value{n}"); + quote!(#[allow(dead_code)] fn #name() {}) + }); + quote! { + ({ + #path + #[allow(unused_imports)] + use #krate::__private::literal::names::*; + #(#names)* + #(#items)* + struct Checks; + impl Checks { + #[allow(clippy::too_many_arguments)] + fn build<#(#generics),*>(self, #(#params),*) -> ::core::result::Result< + ::std::boxed::Box<#krate::__private::serde_json::value::RawValue>, + literal::Invalid, + > { + #json + } + } + Checks + }) + .build(#(#args),*) + } + } +} + +/// How many names of parameters `literal::names` has. +const NAMES: usize = 64; + +const INT_TYPES: [&str; 10] = [ + "i8", "i16", "i32", "i64", "isize", "u8", "u16", "u32", "u64", "usize", +]; + +/// A number literal and its suffix. +enum Number<'a> { + Int(&'a str), + Float(&'a str), +} + +/// The kind of the number literal `text`, if it is one. +fn number(text: &str) -> Option> { + if !text.starts_with(|first: char| first.is_ascii_digit()) { + return None; + } + if integer(text).is_some() { + let suffix = INT_TYPES + .iter() + .chain(&["i128", "u128"]) + .find(|suffix| text.ends_with(*suffix)) + .copied() + .unwrap_or(""); + return Some(Number::Int(suffix)); + } + let (digits, suffix) = ["f32", "f64"] + .iter() + .find_map(|suffix| Some((text.strip_suffix(suffix)?, *suffix))) + .unwrap_or((text, "")); + digits + .chars() + .all(|character| { + character.is_ascii_digit() || matches!(character, '.' | '_' | 'e' | 'E' | '+' | '-') + }) + .then_some(Number::Float(suffix)) } /// An expression of the caller's as an argument, in parentheses of the diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index 03820bb..a3cdcb8 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -122,10 +122,12 @@ fn an_object_is_sent_field_by_field_in_its_order() { let id = input_object_id("ProductUpdateInput"); assert!( code.starts_with(&format!( - ":: shopify_api :: InputObject :: < {id}u64 > :: __new (\"ProductUpdateInput\" , :: shopify_api :: __private :: literal :: to_raw (& :: shopify_api :: __private :: literal :: Object ((:: shopify_api :: __private :: literal :: Field (\"id\" , ({{" + ":: shopify_api :: InputObject :: < {id}u64 > :: __new (\"ProductUpdateInput\" , ({{" )), "{code}" ); + // The items of `[for … => …]` are built in the loop, an argument: after + // the fields of the object. let keys: Vec<&str> = code .match_indices("literal :: Field (\"") .chain(code.match_indices("literal :: Optional (\"")) @@ -144,9 +146,9 @@ fn an_object_is_sent_field_by_field_in_its_order() { "seo", "title", "metafields", + "tags", "key", "type", - "tags", "vendor" ] ); @@ -168,8 +170,10 @@ fn an_object_is_sent_field_by_field_in_its_order() { items.contains("message = \"`vendor?:` takes an `Option` or a `shopify_api::Maybe` of a `String`, not `{Self}`\""), "{items}" ); + // The check of a scalar field takes the types of the scalar, not an + // `Option`, and says what to write for one. assert!( - items.contains("message = \"`vendor` of `ProductUpdateInput` takes a `String`, not an `Option`: write `vendor?: value` to leave the field out when it is `None`, or `vendor: null` to send `null`\""), + items.contains("note = \"`vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null`\""), "{items}" ); } @@ -316,10 +320,10 @@ fn enum_values_are_checked_and_raw_is_only_for_enums() { vec![("status", raw("status")), ("id", rust("id"))], ) .unwrap(); + // `raw(…)` is an argument, evaluated where the caller wrote it. + assert!(code.contains("Field (\"status\" , value0)"), "{code}"); assert!( - code.contains( - "Field (\"status\" , :: shopify_api :: __private :: literal :: raw (status))" - ), + code.contains(". build (:: shopify_api :: __private :: literal :: raw ((status)) , (id))"), "{code}" ); } @@ -443,7 +447,7 @@ fn inline_variables_of_scalars_convert_as_before_and_others_are_literals() { panic!("a literal"); }; assert!( - code.to_string().contains("Checks }) . check ((rows))"), + code.to_string().contains("Checks }) . build ((rows))"), "{code}" ); assert_eq!( @@ -498,18 +502,19 @@ fn each_expression_is_checked_for_its_scalar() { ) .unwrap() .to_string(); - let marker = "literal :: Leaf < "; - let kinds: Vec<&str> = code - .match_indices(marker) - .map(|(at, _)| { - let rest = &code[at + marker.len()..]; - let kind = &rest[rest.find("literal :: ").unwrap() + "literal :: ".len()..]; - &kind[..kind.find(' ').unwrap()] + let mut kinds: Vec<(usize, &str)> = ["literal :: leaf :: < ", "literal :: optional :: < "] + .iter() + .flat_map(|marker| code.match_indices(marker)) + .map(|(at, marker)| { + let kind = &code[at + marker.len() + "literal :: ".len()..]; + (at, &kind[..kind.find(' ').unwrap()]) }) .collect(); + kinds.sort_unstable(); + let kinds: Vec<&str> = kinds.into_iter().map(|(_, kind)| kind).collect(); assert_eq!( kinds, - ["Int", "Float", "Json", "Json", "Json", "Plain", "Plain"] + ["Int", "Float", "Json", "Json", "Json", "MaybeJson", "Text"] ); } @@ -610,3 +615,41 @@ fn integer_literals_outside_of_int_are_refused() { .is_ok() ); } + +/// A constant of the type of its place is written as it is, with nothing +/// to check; one of another type is checked, and refused by rustc. +#[test] +fn constants_are_written_in_place() { + let (code, _) = input( + "DraftOrderLineItemInput", + vec![ + ("quantity", rust("-12")), + ("title", rust("\"t\"")), + ("requiresShipping", rust("true")), + ( + "weight", + Value::Object(object(vec![ + ("unit", ident("GRAMS")), + ("value", rust("2.5")), + ])), + ), + ], + ) + .unwrap(); + assert!(!code.contains("Checks"), "{code}"); + for (field, value) in [ + ("quantity", "\"12\""), + ("quantity", "12i128"), + ("quantity", "1.5"), + ("title", "12"), + ("title", "b\"t\""), + ("requiresShipping", "1"), + ] { + let mut fields = vec![(field, rust(value))]; + if field != "quantity" { + fields.push(("quantity", rust("1"))); + } + let (code, _) = input("DraftOrderLineItemInput", fields).unwrap(); + assert!(code.contains("Checks"), "{field}: {value}"); + } +} From fd5eecdfd3cca664c43ccdefadd819f24d03f46e Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:01:38 +0200 Subject: [PATCH 060/135] docs: values refused before sending, and what changed for callers README, the reference of `graphql!` and `input!`, MIGRATION and the CHANGELOG say what is refused (a `Float` that is not finite, an `Int` beyond 32 bits, `null` for a non-null `JSON`), when (an integer literal at compile time, any other value when the operation is sent), and what `Error::InvalidValue` shows. MIGRATION adds `.into()` to drop before `execute`, the `VariableType` of `Operation::variable` and the name a `for` pattern binds. The limit of `#![no_implicit_prelude]` is written down, and the test covers literals of constants there. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- MIGRATION.md | 5 +++ README.md | 14 +++++++ crates/shopify_api/docs/graphql.md | 41 ++++++++++++++++++- crates/shopify_api/docs/input.md | 7 ++++ .../shopify_api/tests/no_implicit_prelude.rs | 21 ++++++++-- 6 files changed, 87 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c19f998..710d9bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,10 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: input values written as literals in an inline `graphql!`, checked against the schema at the token: `product = { id: id, status: ACTIVE, descriptionHtml: null, vendor?: vendor, seo: { title: t }, metafields: [for m in &rows if cond => { … }] }`. Field names are the GraphQL ones (`type` included); an unknown or repeated field, a missing required field (each one named), `null` on a non-null type, an unknown enum value (the valid ones listed) and a value of the wrong form are compile errors; deprecated fields and enum values warn. `field?: value` leaves the field out for `None`; an `Option` given to `field: value` does not compile, since `null` would clear the field. `raw(string)` sends an enum value unchecked. Rust expressions are checked by traits whose errors name the GraphQL type. Literals are written straight to JSON, with no `serde_json::Value` in between. - Add: `input!(TypeName { … })` builds an input object ahead of the call, with the same checks, as an `InputObject`: one Rust type per GraphQL name, the same in every module and crate, so that the values of several `input!` go in one `Vec`. - Add: `Maybe` (`Absent`, `Null`, `Value`), for `field?:` when `null` is a choice made at run time. +- Add: values Shopify would not read as written are refused. A `Float` must be finite (NaN and infinity were sent as `null`), an `Int` must fit in 32 bits, a non-null `JSON` must not be `null` at its top. An integer literal out of range is a compile error at the literal. A value known at run time, in a literal, an `input!`, a module's `Variables` or `Operation::variable`, is kept as refused, and the operation fails with `Error::InvalidValue { path, reason, detail }` before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float ``. The message names the place and the reason (`InvalidValueReason`), never the value; a serializer's message is in `sensitive_detail()`. An `InputObject` that is refused fails to serialize on its own. Nothing in the code of the macros panics on a value. +- Add: no name the macros generate is in scope where the values are evaluated: a local, closure, function or constant of yours with the name of a generated item stays yours. - Add: one `graphql! { … }` holds several modules, `;` between them. A module's `Variables` runs as it is, `shopify.execute(module::Variables { … })`, and it names each input object its variables may hold: `pub type MetafieldsSetInput = InputObject<…>`. -- Breaking (against the 1.0 previews): the input structs of modules (`MetafieldsSetInput { owner_id, ..Default::default() }`) are gone, for `input!`, which cannot leave out a required field. `Variables` implements `Default` only when no variable is required, and `PartialEq` only when it holds no input object. An input object variable of an inline `graphql!` takes a literal or values of `input!`, no longer any `Serialize` value such as `json!`. An enum variable takes a bare value (`sortKey = TITLE`) or `raw(string)`, no longer a string. `execute` and `execute_response` take `impl Into>`. `Operation` keeps each variable as the JSON it is sent as: `variables_json` returns the variables read back, by value. +- Breaking (against the 1.0 previews): the input structs of modules (`MetafieldsSetInput { owner_id, ..Default::default() }`) are gone, for `input!`, which cannot leave out a required field. `Variables` implements `Default` only when no variable is required, and `PartialEq` only when it holds no input object. An input object variable of an inline `graphql!` takes a literal or values of `input!`, no longer any `Serialize` value such as `json!`. An enum variable takes a bare value (`sortKey = TITLE`) or `raw(string)`, no longer a string. `execute` and `execute_response` take `impl Into>`, so `execute(variables.into())` no longer infers its type: drop the `.into()`. `Operation` keeps each variable as the JSON it is sent as: `variables_json` returns the variables read back, by value, as deep as they were written. `Operation::variable::` takes a `T` of the sealed `VariableType`, and a `u64` beyond the range of `Int` is refused rather than saturated. The pattern of `[for … => …]` binds a name. - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. - Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. diff --git a/MIGRATION.md b/MIGRATION.md index 568164d..d86ad13 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -55,6 +55,7 @@ to keep that. | `GraphqlErrors(Vec)` | `Graphql(GraphqlErrors { errors, data })` | | `JsonParseError`, `NotWantedJsonFormat`, `NotJson`, `ResponseBroken` | `Decode { path, message, detail }`: a body that is not JSON, or `data` that does not fit its type. `path` and `message` hold no text of the answer (a map key is `[key]`); serde's message is `error.sensitive_detail()` | | Variables that do not serialize | `Variables { message, detail }`: what a `Serialize` implementation wrote is `error.sensitive_detail()`, not the message | +| A `Float` that is NaN or infinite, an `Int` beyond 32 bits, `null` for a non-null `JSON`, sent as they were | `InvalidValue { path, reason, detail }`, before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float `` | | `Authentication(text)` | `Auth { message, detail }`: what the token endpoint wrote is `error.sensitive_detail()` | | `MissingGraphqlData`, `InvalidHeaderValue`, `Other` | Gone | @@ -172,3 +173,7 @@ The input objects of `graphql!` changed before the release. | `shopify.execute(module::operation(module::Variables { … }))` | The same, or `shopify.execute(module::Variables { … })` | | `Variables` always `Default` and `PartialEq` | `Default` when no variable is required, `PartialEq` when it holds no input object | | `Operation::variables_json()` returned `&Map` | It returns the `Map`, read back from the JSON kept for each variable | +| `shopify.execute(module::Variables { … }.into())` | Drop the `.into()`: `execute` takes `impl Into>`, so `.into()` has no single target (E0283) | +| `Operation::variable::` with a `T` of yours | `T` is a `VariableType`: one of the Rust types `graphql!` picks (`String`, `i64`, `f64`, `bool`, `Value`, `InputObject`, in `Option` and `Vec`). `json_variable` takes anything else | +| A `u64` beyond `i64` saturated to `i64::MAX`; NaN and infinity sent as `null`; `null` sent for a non-null `JSON` | Refused: `Error::InvalidValue` when the operation runs, before the request; an integer literal out of the range of `Int` is a compile error | +| `[for _ in … => …]` | `[for _item in … => …]`: the pattern binds a name | diff --git a/README.md b/README.md index 255d5fd..ba79a8e 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,17 @@ shopify.execute(graphql!( A value of another input type is refused, the message naming both GraphQL types: `` an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` ``. +### Values Shopify would not read as written + +A value is checked when it is built, in a literal, an `input!`, a module's +`Variables` or `Operation::variable`: an `Int` must fit in 32 bits, a `Float` +must be finite (JSON has no NaN or infinity, and `null` would clear the +field), and a non-null `JSON` must not be `null` at its top (`null` inside it +is fine). An integer literal out of range is a compile error at the literal. +A value known at run time makes `execute` fail before anything is sent, with +`Error::InvalidValue`, which says where and why, never the value: +`` invalid value at `$input.lineItems[2].quantity`: Int out of 32-bit range ``. + ### Named `graphql! { pub mod name = "…"; … }` names the types, for functions and @@ -194,6 +205,9 @@ type, and `graphql_raw` returns the whole answer, `errors` included. - rustc's own errors, outside those of the macros, show an input object as `InputObject`, `N` a hash of its name. - Enum fields of a module's `Variables` and `raw(…)` are strings nothing checks. +- Under `#![no_implicit_prelude]`, a literal or an `input!` that holds a + Rust expression does not compile: its messages need `#[diagnostic::…]`, + which that attribute hides. Constants, modules and variables of scalars do. The full reference of `graphql!`, with the mapping of every GraphQL type and the rules of literals, is diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 6de791e..b697756 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -127,7 +127,8 @@ variable, so the usual spellings work: | List | A `Vec`, a slice, an array or a `&Vec` of accepted values | Another type is a compile error on the value: `` `&str` is not a value for a -GraphQL variable of Rust type `i64` `` (see [`IntoVariable`]). +GraphQL variable of Rust type `i64` `` (see [`IntoVariable`]). The value is +then checked, as for [input values](#values-shopify-would-not-read-as-written). An enum value is written bare, and checked: `sortKey = TITLE`. A string known at run time goes through `raw(…)`, which nothing checks: @@ -230,9 +231,43 @@ What reads as what, when Rust could read it too: - A lone identifier is an enum value where an enum is expected, and a Rust variable everywhere else. +- The pattern of `[for … in … => …]` binds a name: `[for _item in 0..3 => …]` + rather than `[for _ in 0..3 => …]`. The generated code names the list after + it, which no constant of the caller's can match. + Nothing goes through a `serde_json::Value`: each literal is written straight to the JSON sent, and a value of `input!` holds its JSON already. +# Values Shopify would not read as written + +Every value is checked when it is built (a literal, an `input!`, the +`Variables` of a module, [`Operation::variable`]), for what JSON or GraphQL +would turn into something else: + +| Value | Refused when | Reason shown | +| --- | --- | --- | +| A `Float` | NaN or infinite: JSON writes it `null`, which clears the field | `not a finite Float` | +| An `Int`, of any integer type | Outside of 32 bits, GraphQL's `Int` | `Int out of 32-bit range` | +| A non-null `JSON` | `null` at its top; `null` inside it is sent | `null for a non-null JSON field` | +| Any value | Its `Serialize` fails | `could not serialize` | + +An integer literal out of range is a compile error at the literal: `-1`, +`2_147_483_648_i64`, `0x8000_0000`, `Some(…)` of one, or an item of `[…]` or +`vec![…]`. A value known at run time is kept as refused, and the operation +fails with [`Error::InvalidValue`] when it is sent, or when +[`Operation::body`] or [`Operation::variables_json`] reads it, before any +request. Its `Display` names the place in GraphQL terms and the reason, never +the value: + +```text +invalid value at `$product.metafields[2].value`: not a finite Float +``` + +A serializer's message, which may quote the value, is only in +[`Error::sensitive_detail`]. Shopify's string-encoded scalars, such as +`UnsignedInt64`, are strings, and not checked. An [`InputObject`] that is +refused also fails to serialize on its own, with the same message. + # Named operations A module names the types of an operation: to share it, or to return its @@ -367,3 +402,7 @@ scripts an answer that leaves out a non-null field. - Enum values are checked where they are written; the `String` fields of `Variables` and `raw(…)` are not. - The generated code refers to `::shopify_api`: the dependency cannot be renamed. +- Under `#![no_implicit_prelude]`, a literal or an `input!` that holds a Rust + expression does not compile: its messages are `#[diagnostic::on_unimplemented]`, + whose `diagnostic` namespace that attribute hides. Literals of constants, + modules and variables of scalars compile there. diff --git a/crates/shopify_api/docs/input.md b/crates/shopify_api/docs/input.md index d2a8f5b..8e9d4c2 100644 --- a/crates/shopify_api/docs/input.md +++ b/crates/shopify_api/docs/input.md @@ -49,6 +49,13 @@ message that names both places in GraphQL terms: error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` ``` +A value that Shopify would not read as written, a `Float` that is not +finite, an `Int` beyond 32 bits, `null` for a non-null `JSON`, is kept as +refused: the operation that holds it fails with +[`Error::InvalidValue`](crate::Error::InvalidValue) before it is sent (see +[`graphql!`](crate::graphql!#values-shopify-would-not-read-as-written)). +`input!` needs no `?`. + The fields are checked against the schema of the crate where `input!` is written. A value built in another crate, against another schema or version, has the same Rust type as long as the GraphQL name is the same. diff --git a/crates/shopify_api/tests/no_implicit_prelude.rs b/crates/shopify_api/tests/no_implicit_prelude.rs index 51b56d3..29422e2 100644 --- a/crates/shopify_api/tests/no_implicit_prelude.rs +++ b/crates/shopify_api/tests/no_implicit_prelude.rs @@ -1,5 +1,7 @@ -//! The code `graphql!` writes for modules and for variables of scalars names -//! everything by its full path: it compiles without the prelude. +//! The code `graphql!` and `input!` write for modules, variables of scalars +//! and literals of constants names everything by its full path: it compiles +//! without the prelude. A Rust expression in a literal needs the +//! `diagnostic` namespace, which `no_implicit_prelude` hides. #![no_implicit_prelude] extern crate shopify_api; @@ -10,7 +12,7 @@ shopify_api::graphql! { } #[test] -fn modules_and_scalar_variables_compile_without_the_prelude() { +fn modules_variables_and_constants_compile_without_the_prelude() { let variables = products::Variables { first: 2, query: ::std::option::Option::None, @@ -29,4 +31,17 @@ fn modules_and_scalar_variables_compile_without_the_prelude() { ::std::string::ToString::to_string(&inline.body().unwrap()["variables"]), r#"{"first":3,"query":"title:shirt"}"# ); + let product = shopify_api::input!(ProductUpdateInput { title: "a", status: ACTIVE, tags: ["b"], seo: { title: "s" } }); + let literal = shopify_api::graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + product = { title: "a", status: ACTIVE, descriptionHtml: null }, + ); + ::std::assert_eq!( + ::shopify_api::__private::serde_json::to_string(&product).unwrap(), + r#"{"title":"a","status":"ACTIVE","tags":["b"],"seo":{"title":"s"}}"# + ); + ::std::assert_eq!( + ::std::string::ToString::to_string(&literal.body().unwrap()["variables"]), + r#"{"product":{"descriptionHtml":null,"status":"ACTIVE","title":"a"}}"# + ); } From 175f555c25e780177f3cea9b30644f1728d2b397 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:50:38 +0200 Subject: [PATCH 061/135] fix(graphql): body() and variable_json() give the text sent, parse nothing Reading the JSON back into a Value used one stack frame per level with no recursion limit, so a deep variable crashed a small thread, and it could round an f64 differently from the text sent. body() now returns the exact JSON text execute sends; variable_json(name) replaces variables_json and returns the text of one variable. The unbounded_depth feature is dropped. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- MIGRATION.md | 3 +- crates/shopify_api/Cargo.toml | 2 +- crates/shopify_api/docs/graphql.md | 2 +- crates/shopify_api/src/error.rs | 12 +- crates/shopify_api/src/graphql.rs | 2 +- crates/shopify_api/src/graphql/operation.rs | 106 ++++++++++-------- crates/shopify_api/tests/literals.rs | 12 +- .../shopify_api/tests/no_implicit_prelude.rs | 20 +++- 9 files changed, 96 insertions(+), 65 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 710d9bc..51fb7af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: values Shopify would not read as written are refused. A `Float` must be finite (NaN and infinity were sent as `null`), an `Int` must fit in 32 bits, a non-null `JSON` must not be `null` at its top. An integer literal out of range is a compile error at the literal. A value known at run time, in a literal, an `input!`, a module's `Variables` or `Operation::variable`, is kept as refused, and the operation fails with `Error::InvalidValue { path, reason, detail }` before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float ``. The message names the place and the reason (`InvalidValueReason`), never the value; a serializer's message is in `sensitive_detail()`. An `InputObject` that is refused fails to serialize on its own. Nothing in the code of the macros panics on a value. - Add: no name the macros generate is in scope where the values are evaluated: a local, closure, function or constant of yours with the name of a generated item stays yours. - Add: one `graphql! { … }` holds several modules, `;` between them. A module's `Variables` runs as it is, `shopify.execute(module::Variables { … })`, and it names each input object its variables may hold: `pub type MetafieldsSetInput = InputObject<…>`. -- Breaking (against the 1.0 previews): the input structs of modules (`MetafieldsSetInput { owner_id, ..Default::default() }`) are gone, for `input!`, which cannot leave out a required field. `Variables` implements `Default` only when no variable is required, and `PartialEq` only when it holds no input object. An input object variable of an inline `graphql!` takes a literal or values of `input!`, no longer any `Serialize` value such as `json!`. An enum variable takes a bare value (`sortKey = TITLE`) or `raw(string)`, no longer a string. `execute` and `execute_response` take `impl Into>`, so `execute(variables.into())` no longer infers its type: drop the `.into()`. `Operation` keeps each variable as the JSON it is sent as: `variables_json` returns the variables read back, by value, as deep as they were written. `Operation::variable::` takes a `T` of the sealed `VariableType`, and a `u64` beyond the range of `Int` is refused rather than saturated. The pattern of `[for … => …]` binds a name. +- Breaking (against the 1.0 previews): the input structs of modules (`MetafieldsSetInput { owner_id, ..Default::default() }`) are gone, for `input!`, which cannot leave out a required field. `Variables` implements `Default` only when no variable is required, and `PartialEq` only when it holds no input object. An input object variable of an inline `graphql!` takes a literal or values of `input!`, no longer any `Serialize` value such as `json!`. An enum variable takes a bare value (`sortKey = TITLE`) or `raw(string)`, no longer a string. `execute` and `execute_response` take `impl Into>`, so `execute(variables.into())` no longer infers its type: drop the `.into()`. `Operation` keeps each variable as the JSON it is sent as, and parses nothing back: `body()` returns the exact JSON text `execute` sends, a `String`, no longer a `Value`, and `variable_json(name)` the text of one variable, replacing `variables_json`. `Operation::variable::` takes a `T` of the sealed `VariableType`, and a `u64` beyond the range of `Int` is refused rather than saturated. The pattern of `[for … => …]` binds a name. - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. - Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. diff --git a/MIGRATION.md b/MIGRATION.md index d86ad13..b37d49d 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -172,7 +172,8 @@ The input objects of `graphql!` changed before the release. | One module per `graphql! { … }` | Several, `;` between them | | `shopify.execute(module::operation(module::Variables { … }))` | The same, or `shopify.execute(module::Variables { … })` | | `Variables` always `Default` and `PartialEq` | `Default` when no variable is required, `PartialEq` when it holds no input object | -| `Operation::variables_json()` returned `&Map` | It returns the `Map`, read back from the JSON kept for each variable | +| `Operation::body()` returned a `serde_json::Value` | It returns the exact JSON text `execute` sends, a `String`; parse it yourself for a `Value`, `serde_json::from_str::(&body)` | +| `Operation::variables_json()` returned `&Map` | `Operation::variable_json(name)` returns the JSON text of one variable, `Option<&str>`; nothing is parsed back | | `shopify.execute(module::Variables { … }.into())` | Drop the `.into()`: `execute` takes `impl Into>`, so `.into()` has no single target (E0283) | | `Operation::variable::` with a `T` of yours | `T` is a `VariableType`: one of the Rust types `graphql!` picks (`String`, `i64`, `f64`, `bool`, `Value`, `InputObject`, in `Option` and `Vec`). `json_variable` takes anything else | | A `u64` beyond `i64` saturated to `i64::MAX`; NaN and infinity sent as `null`; `null` sent for a non-null `JSON` | Refused: `Error::InvalidValue` when the operation runs, before the request; an integer literal out of the range of `Int` is a compile error | diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index c76b87d..954f585 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -41,7 +41,7 @@ chrono.workspace = true futures-core.workspace = true reqwest = { workspace = true, optional = true } serde.workspace = true -serde_json = { workspace = true, features = ["raw_value", "unbounded_depth"] } +serde_json = { workspace = true, features = ["raw_value"] } serde_urlencoded.workspace = true # `rt`: a token renewal runs in its own task, so a caller that gives up does not cancel it. tokio = { workspace = true, features = ["rt", "sync", "time"] } diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index b697756..b2da305 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -255,7 +255,7 @@ An integer literal out of range is a compile error at the literal: `-1`, `2_147_483_648_i64`, `0x8000_0000`, `Some(…)` of one, or an item of `[…]` or `vec![…]`. A value known at run time is kept as refused, and the operation fails with [`Error::InvalidValue`] when it is sent, or when -[`Operation::body`] or [`Operation::variables_json`] reads it, before any +[`Operation::body`] or [`Operation::variable_json`] reads it, before any request. Its `Display` names the place in GraphQL terms and the reason, never the value: diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index 6ef734e..6825e1a 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -926,28 +926,28 @@ mod tests { "Variables of an operation", crate::graphql::Operation::::new("query { shop { id } }") .variables(BTreeMap::from([("x", Leaky)])) - .variables_json() + .body() .unwrap_err(), )); errors.push(( "Variables, one", crate::graphql::Operation::::new("query { shop { id } }") .json_variable("x", Leaky) - .variables_json() + .body() .unwrap_err(), )); errors.push(( "Variables, one with an odd name", crate::graphql::Operation::::new("query { shop { id } }") .json_variable(&format!("{TOKEN}\""), Leaky) - .variables_json() + .body() .unwrap_err(), )); errors.push(( "InvalidValue", crate::graphql::Operation::::new("query { shop { id } }") .variable::(&format!("{TOKEN}\""), f64::NAN) - .variables_json() + .body() .unwrap_err(), )); errors.push(( @@ -959,7 +959,7 @@ mod tests { &serde_json::to_value(Leaky).unwrap_err(), )), ) - .variables_json() + .body() .unwrap_err(), )); errors.push(( @@ -1134,7 +1134,7 @@ mod tests { let error = crate::graphql::Operation::::new("query { shop { id } }") .json_variable("input", Leaky) - .variables_json() + .body() .unwrap_err(); assert_eq!( error.to_string(), diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index a862e1e..7cb4dc8 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -59,7 +59,7 @@ impl Shopify { ) -> Result> { let operation = operation.into(); let version = self.version_for(operation.checked_against())?; - let body = operation.body_json()?; + let body = operation.body()?.into_bytes(); let raw = self.send_graphql(version, body, operation.kind()).await?; let (data, extensions) = into_data(raw)?; Ok(Response { diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs index 7fc3441..4f2db67 100644 --- a/crates/shopify_api/src/graphql/operation.rs +++ b/crates/shopify_api/src/graphql/operation.rs @@ -364,32 +364,32 @@ impl Operation { self } - /// The variables, read back from the JSON they are sent as. - pub fn variables_json(&self) -> Result> { + /// The JSON text the variable `name` is sent as, `None` when it is not + /// set; an error when a variable was refused, as + /// [`Shopify::execute`](crate::Shopify::execute) would fail. + /// + /// Nothing is parsed back: to read it as a [`Value`], parse it with the + /// settings you need, such as `serde_json::from_str::(json)`, + /// which refuses a value nested deeper than 128. + pub fn variable_json(&self, name: &str) -> Result> { let variables = self .variables .as_ref() .map_err(|failure| failure.to_error())?; - variables + Ok(variables .iter() - .map( - |(name, value)| match read_back(serde_json::Deserializer::from_str(value.get())) { - Ok(value) => Ok((name.clone(), value)), - Err(error) => Err(Error::variables(Some(name), &error)), - }, - ) - .collect() - } - - /// The body Shopify receives: `query`, `variables` and `operationName`, - /// read back from the JSON it is sent as. - pub fn body(&self) -> Result { - read_back(serde_json::Deserializer::from_slice(&self.body_json()?)) - .map_err(|error| Error::variables(None, &error)) + .find(|(set, _)| set == name) + .map(|(_, value)| value.get())) } - /// The body as it is sent. - pub(crate) fn body_json(&self) -> Result> { + /// The body as the exact JSON text + /// [`Shopify::execute`](crate::Shopify::execute) sends: `query`, + /// `variables` and `operationName`. + /// + /// Nothing is parsed back: to read it as a [`Value`], parse it with the + /// settings you need, such as `serde_json::from_str::(&body)`, + /// which refuses a value nested deeper than 128. + pub fn body(&self) -> Result { let variables = self .variables .as_ref() @@ -399,21 +399,10 @@ impl Operation { variables, name: self.name.as_deref(), }; - serde_json::to_vec(&body).map_err(|error| Error::variables(None, &error)) + serde_json::to_string(&body).map_err(|error| Error::variables(None, &error)) } } -/// Reads back JSON this crate wrote, as deep as it was written: no limit, -/// since the value it was written from was as deep. -fn read_back<'de, R: serde_json::de::Read<'de>>( - mut deserializer: serde_json::Deserializer, -) -> serde_json::Result { - deserializer.disable_recursion_limit(); - let value = serde::Deserialize::deserialize(&mut deserializer)?; - deserializer.end()?; - Ok(value) -} - struct Body<'a> { query: &'a str, variables: &'a [(String, Box)], @@ -652,8 +641,12 @@ mod tests { use super::*; use serde_json::json; + fn body(operation: &Operation) -> Value { + serde_json::from_str(&operation.body().unwrap()).unwrap() + } + fn variables(operation: Operation) -> Value { - Value::Object(operation.variables_json().unwrap()) + body(&operation)["variables"].take() } #[test] @@ -848,25 +841,48 @@ mod tests { let error = operation.body().unwrap_err(); assert_eq!(error.to_string(), shown); assert!(matches!(error, Error::InvalidValue { detail: None, .. })); - assert_eq!(operation.variables_json().unwrap_err().to_string(), shown); assert_eq!( - operation.clone().body_json().unwrap_err().to_string(), + operation.variable_json("first").unwrap_err().to_string(), shown ); } } - /// As deep as the value it was written from: past serde_json's limit of - /// 128 for a text it did not write. + /// The text sent, not parsed back: no depth limit, no stack used per + /// level, no float rounded. #[test] - fn variables_read_back_as_deep_as_they_were_written() { - let mut deep = json!(1); - for _ in 0..400 { - deep = json!([deep]); + fn the_body_and_the_variables_are_the_text_sent() { + let mut value = json!(0); + for _ in 0..250 { + value = json!([value]); } - let operation = Operation::<()>::new("query { shop { id } }").json_variable("deep", &deep); - assert_eq!(operation.variables_json().unwrap()["deep"], deep); - assert_eq!(operation.body().unwrap()["variables"]["deep"], deep); + let deep = format!("{}0{}", "[".repeat(250), "]".repeat(250)); + let float = 2.3318716180463287e-130_f64; + let operation = Operation::<()>::new("query { shop { id } }") + .json_variable("deep", &value) + .variable::("x", float); + let body = std::thread::Builder::new() + .stack_size(256 * 1024) + .spawn(move || operation.body().map(|body| (body, operation))) + .unwrap() + .join() + .unwrap(); + let (body, operation) = body.unwrap(); + assert_eq!( + body, + format!( + r#"{{"query":"query {{ shop {{ id }} }}","variables":{{"deep":{deep},"x":2.3318716180463287e-130}}}}"# + ) + ); + assert_eq!( + operation.variable_json("deep").unwrap(), + Some(deep.as_str()) + ); + assert_eq!( + operation.variable_json("x").unwrap(), + Some("2.3318716180463287e-130") + ); + assert_eq!(operation.variable_json("y").unwrap(), None); } #[test] @@ -928,13 +944,13 @@ mod tests { ); assert_eq!( operation.body().unwrap(), - json!({ "query": "query Shop { shop { id } }", "operationName": "Shop" }) + r#"{"query":"query Shop { shop { id } }","operationName":"Shop"}"# ); assert_eq!(operation.api_version().unwrap(), ApiVersion::V2026_07); let operation = operation.variable::("first", 1); assert_eq!( operation.body().unwrap(), - json!({ "query": "query Shop { shop { id } }", "variables": { "first": 1 }, "operationName": "Shop" }) + r#"{"query":"query Shop { shop { id } }","variables":{"first":1},"operationName":"Shop"}"# ); assert_eq!( Operation::<()>::new("{ shop { id } }") diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs index 44773bc..635eb4d 100644 --- a/crates/shopify_api/tests/literals.rs +++ b/crates/shopify_api/tests/literals.rs @@ -26,6 +26,12 @@ fn sent(mock: &MockTransport) -> String { String::from_utf8(mock.last_request().unwrap().body).unwrap() } +/// The variables of `operation`, parsed from the body it sends. +fn variables(operation: &shopify_api::Operation) -> serde_json::Value { + serde_json::from_str::(&operation.body().unwrap()).unwrap()["variables"] + .take() +} + /// A body of `query` with `variables`, written as `shopify_api` writes it. fn body(query: &str, variables: &str) -> String { format!( @@ -257,7 +263,7 @@ async fn one_vec_of_input_objects_goes_to_an_inline_operation_and_to_a_module() metafields: color_metafields(&rows()), }); assert_eq!( - operation.variables_json().unwrap()["metafields"][1]["compareDigest"], + variables(&operation)["metafields"][1]["compareDigest"], "d3" ); } @@ -625,7 +631,7 @@ mod hygiene { first = __shopify_api_items.len(), ); assert_eq!( - operation.body().unwrap()["variables"], + crate::variables(&operation), json!({ "product": { "title": "closure:e", "tags": ["local"] }, "media": [{ "originalSource": "closure:local", "mediaContentType": "IMAGE", "alt": "local" }], @@ -773,7 +779,7 @@ mod hygiene { first = __shopify_api_items.len(), ); assert_eq!( - operation.body().unwrap()["variables"], + crate::variables(&operation), json!({ "product": { "title": "const", "tags": ["const", "const"] }, "first": 1 }) ); } diff --git a/crates/shopify_api/tests/no_implicit_prelude.rs b/crates/shopify_api/tests/no_implicit_prelude.rs index 29422e2..415d9c1 100644 --- a/crates/shopify_api/tests/no_implicit_prelude.rs +++ b/crates/shopify_api/tests/no_implicit_prelude.rs @@ -19,8 +19,12 @@ fn modules_variables_and_constants_compile_without_the_prelude() { }; let operation = products::operation(variables); ::std::assert_eq!( - ::std::string::ToString::to_string(&operation.body().unwrap()["variables"]), - r#"{"first":2}"# + operation.variable_json("first").unwrap(), + ::std::option::Option::Some("2") + ); + ::std::assert_eq!( + operation.variable_json("query").unwrap(), + ::std::option::Option::None ); let inline = shopify_api::graphql!( "query($first: Int!, $query: String) { products(first: $first, query: $query) { nodes { id } } }", @@ -28,8 +32,12 @@ fn modules_variables_and_constants_compile_without_the_prelude() { query = "title:shirt", ); ::std::assert_eq!( - ::std::string::ToString::to_string(&inline.body().unwrap()["variables"]), - r#"{"first":3,"query":"title:shirt"}"# + inline.variable_json("first").unwrap(), + ::std::option::Option::Some("3") + ); + ::std::assert_eq!( + inline.variable_json("query").unwrap(), + ::std::option::Option::Some(r#""title:shirt""#) ); let product = shopify_api::input!(ProductUpdateInput { title: "a", status: ACTIVE, tags: ["b"], seo: { title: "s" } }); let literal = shopify_api::graphql!( @@ -41,7 +49,7 @@ fn modules_variables_and_constants_compile_without_the_prelude() { r#"{"title":"a","status":"ACTIVE","tags":["b"],"seo":{"title":"s"}}"# ); ::std::assert_eq!( - ::std::string::ToString::to_string(&literal.body().unwrap()["variables"]), - r#"{"product":{"descriptionHtml":null,"status":"ACTIVE","title":"a"}}"# + literal.variable_json("product").unwrap(), + ::std::option::Option::Some(r#"{"title":"a","status":"ACTIVE","descriptionHtml":null}"#) ); } From 1927516a23f7c1a1db17346571b4041a1a3408c6 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:50:38 +0200 Subject: [PATCH 062/135] fix(graphql): a defaulted non-null module variable is never sent as null For `$settings: JSON! = {}`, `Some(Value::Null)` was set as a nullable value and sent as null. `None` still leaves the variable out; the value in `Some` is now checked as non-null, as the inline form does. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/tests/literals.rs | 172 ++++++++++++++++++++++ crates/shopify_api_graphql/src/codegen.rs | 10 +- 2 files changed, 180 insertions(+), 2 deletions(-) diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs index 635eb4d..226e129 100644 --- a/crates/shopify_api/tests/literals.rs +++ b/crates/shopify_api/tests/literals.rs @@ -406,6 +406,178 @@ async fn a_nullable_input_variable_takes_null_an_option_or_a_literal() { ); } +graphql! { + mod defaults = "query Defaults($first: Int! = 10, $query: String! = \"a\", $sortKey: ProductSortKeys! = TITLE) { + products(first: $first, query: $query, sortKey: $sortKey) { nodes { id } } + }"; + mod pixel = "mutation Pixel($settings: JSON! = {}) { webPixelCreate(webPixel: {settings: $settings}) { userErrors { message } } }"; + mod weight = "mutation Weight($id: ID!, $value: Float! = 1.0) { + inventoryItemUpdate(id: $id, input: {measurement: {weight: {value: $value, unit: KILOGRAMS}}}) { userErrors { message } } + }"; + mod draft = "mutation Draft($input: DraftOrderInput! = {}, $items: [DraftOrderLineItemInput!]! = [], $tags: [String!]! = []) { + a: draftOrderCreate(input: $input) { userErrors { message } } + b: draftOrderCreate(input: {lineItems: $items, tags: $tags}) { userErrors { message } } + }"; +} + +/// A non-null variable with a default: `None` leaves it out, for Shopify +/// to use the default; a value is checked as non-null, never sent as `null`. +#[test] +fn a_defaulted_non_null_variable_is_left_out_or_checked_as_non_null() { + use serde_json::Value; + use shopify_api::{Error, InvalidValueReason}; + + let reason = |body: shopify_api::Result| match body { + Err(Error::InvalidValue { reason, .. }) => reason, + other => panic!("not refused: {other:?}"), + }; + let big: i64 = 1 << 31; + let line_item = input!(DraftOrderLineItemInput { quantity: big }); + + // Left out. + let operation = defaults::operation(defaults::Variables::default()); + assert_eq!(operation.variable_json("first").unwrap(), None); + assert_eq!(operation.variable_json("query").unwrap(), None); + assert_eq!(operation.variable_json("sortKey").unwrap(), None); + assert_eq!( + pixel::operation(pixel::Variables::default()) + .variable_json("settings") + .unwrap(), + None + ); + let operation = weight::operation(weight::Variables { + id: "gid://shopify/InventoryItem/1".into(), + value: None, + }); + assert_eq!(operation.variable_json("value").unwrap(), None); + let operation = draft::operation(draft::Variables { + input: None, + items: None, + tags: None, + }); + assert_eq!(variables(&operation), Value::Null); + + // Sent. + let operation = defaults::operation(defaults::Variables { + first: Some(i64::from(i32::MAX)), + query: Some("b".into()), + sort_key: Some("ID".into()), + }); + assert_eq!( + variables(&operation), + json!({ "first": i32::MAX, "query": "b", "sortKey": "ID" }) + ); + let operation = pixel::operation(pixel::Variables { + settings: Some(json!({ "a": null })), + }); + assert_eq!( + operation.variable_json("settings").unwrap(), + Some(r#"{"a":null}"#) + ); + let operation = weight::operation(weight::Variables { + id: "gid://shopify/InventoryItem/1".into(), + value: Some(2.5), + }); + assert_eq!(operation.variable_json("value").unwrap(), Some("2.5")); + let operation = draft::operation(draft::Variables { + input: Some(input!(DraftOrderInput { note: "n" })), + items: Some(vec![input!(DraftOrderLineItemInput { quantity: 1 })]), + tags: Some(vec!["t".into()]), + }); + assert_eq!( + variables(&operation), + json!({ "input": { "note": "n" }, "items": [{ "quantity": 1 }], "tags": ["t"] }) + ); + + // Refused: the module and the inline operation alike. + for (body, expected) in [ + ( + defaults::operation(defaults::Variables { + first: Some(big), + ..Default::default() + }) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ( + graphql!( + "query Defaults($first: Int! = 10, $query: String! = \"a\", $sortKey: ProductSortKeys! = TITLE) { products(first: $first, query: $query, sortKey: $sortKey) { nodes { id } } }", + first = big, + ) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ( + pixel::operation(pixel::Variables { + settings: Some(Value::Null), + }) + .body(), + InvalidValueReason::NullJson, + ), + ( + graphql!( + "mutation Pixel($settings: JSON! = {}) { webPixelCreate(webPixel: {settings: $settings}) { userErrors { message } } }", + settings = Value::Null, + ) + .body(), + InvalidValueReason::NullJson, + ), + ( + weight::operation(weight::Variables { + id: "gid://shopify/InventoryItem/1".into(), + value: Some(f64::NAN), + }) + .body(), + InvalidValueReason::NotFiniteFloat, + ), + ( + graphql!( + "mutation Weight($id: ID!, $value: Float! = 1.0) { inventoryItemUpdate(id: $id, input: {measurement: {weight: {value: $value, unit: KILOGRAMS}}}) { userErrors { message } } }", + id = "gid://shopify/InventoryItem/1", + value = f64::INFINITY, + ) + .body(), + InvalidValueReason::NotFiniteFloat, + ), + ( + draft::operation(draft::Variables { + input: Some(input!(DraftOrderInput { lineItems: [line_item.clone()] })), + items: None, + tags: None, + }) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ( + draft::operation(draft::Variables { + input: None, + items: Some(vec![line_item.clone()]), + tags: None, + }) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ( + graphql!( + "mutation Draft($input: DraftOrderInput! = {}, $items: [DraftOrderLineItemInput!]! = [], $tags: [String!]! = []) { a: draftOrderCreate(input: $input) { userErrors { message } } b: draftOrderCreate(input: {lineItems: $items, tags: $tags}) { userErrors { message } } }", + input = { lineItems: [{ quantity: big }] }, + ) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ( + graphql!( + "mutation Draft($input: DraftOrderInput! = {}, $items: [DraftOrderLineItemInput!]! = [], $tags: [String!]! = []) { a: draftOrderCreate(input: $input) { userErrors { message } } b: draftOrderCreate(input: {lineItems: $items, tags: $tags}) { userErrors { message } } }", + items = [line_item.clone()], + ) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ] { + assert_eq!(reason(body), expected); + } +} + /// What Shopify would not read as written: an `Int` beyond 32 bits, a /// `Float` that is not finite, `null` for a non-null `JSON`. The operation /// fails before anything is sent, saying where and why, never the value. diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs index 1a67fce..2e47a7f 100644 --- a/crates/shopify_api_graphql/src/codegen.rs +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -321,10 +321,16 @@ pub fn variables_types( #[serde(skip_serializing_if = "::core::option::Option::is_none")] pub #ident: #ty, }); + // `None` leaves the variable out. A non-null variable with a + // default takes its value out of the `Some`, checked as non-null. + let value = if variable.ty.is_non_null() { + quote!(::core::option::Option::Some(value)) + } else { + quote!(value @ ::core::option::Option::Some(_)) + }; setters.push(quote! { let operation = match variables.#ident { - // In `Some`: the value of a nullable variable may be `null`. - value @ ::core::option::Option::Some(_) => operation.__variable(#key, value), + #value => operation.__variable(#key, value), ::core::option::Option::None => operation, }; }); From 886638b6057723a603decc79ef80519bbbcc4a52 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:54:02 +0200 Subject: [PATCH 063/135] =?UTF-8?q?fix(macros):=20any=20pattern=20in=20[fo?= =?UTF-8?q?r=20=E2=80=A6=20=3D>=20=E2=80=A6],=20the=20list=20under=20a=20g?= =?UTF-8?q?enerated=20name?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The list was named after a name the pattern binds, found by a guess on capitals: `use Stage::Ready as ready` with `(ready, item)` failed (E0530), `ref Item` was said to bind nothing, and `_` was refused. The list now has a fixed `__shopify_api_` name on a mixed-site span, which no expression of the caller's sees. `Collected` derives `Default` rather than allowing `new_without_default`. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- MIGRATION.md | 1 - crates/shopify_api/docs/graphql.md | 4 -- crates/shopify_api/src/graphql/literal.rs | 12 +---- crates/shopify_api/tests/literals.rs | 33 ++++++++++++ .../tests/ui/literal_for_binds_no_name.rs | 3 -- .../tests/ui/literal_for_binds_no_name.stderr | 6 --- ...literal_maybe_non_null_with_default.stderr | 4 +- .../tests/ui/literal_option_in_field.stderr | 2 +- .../tests/ui/literal_wrong_input_type.stderr | 6 +-- .../tests/ui/literal_wrong_scalar.stderr | 10 ++-- crates/shopify_api_graphql/src/literal.rs | 23 ++------- crates/shopify_api_graphql/tests/literal.rs | 1 - crates/shopify_api_macros/src/value.rs | 50 ------------------- 14 files changed, 52 insertions(+), 105 deletions(-) delete mode 100644 crates/shopify_api/tests/ui/literal_for_binds_no_name.rs delete mode 100644 crates/shopify_api/tests/ui/literal_for_binds_no_name.stderr diff --git a/CHANGELOG.md b/CHANGELOG.md index 51fb7af..5161c4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: values Shopify would not read as written are refused. A `Float` must be finite (NaN and infinity were sent as `null`), an `Int` must fit in 32 bits, a non-null `JSON` must not be `null` at its top. An integer literal out of range is a compile error at the literal. A value known at run time, in a literal, an `input!`, a module's `Variables` or `Operation::variable`, is kept as refused, and the operation fails with `Error::InvalidValue { path, reason, detail }` before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float ``. The message names the place and the reason (`InvalidValueReason`), never the value; a serializer's message is in `sensitive_detail()`. An `InputObject` that is refused fails to serialize on its own. Nothing in the code of the macros panics on a value. - Add: no name the macros generate is in scope where the values are evaluated: a local, closure, function or constant of yours with the name of a generated item stays yours. - Add: one `graphql! { … }` holds several modules, `;` between them. A module's `Variables` runs as it is, `shopify.execute(module::Variables { … })`, and it names each input object its variables may hold: `pub type MetafieldsSetInput = InputObject<…>`. -- Breaking (against the 1.0 previews): the input structs of modules (`MetafieldsSetInput { owner_id, ..Default::default() }`) are gone, for `input!`, which cannot leave out a required field. `Variables` implements `Default` only when no variable is required, and `PartialEq` only when it holds no input object. An input object variable of an inline `graphql!` takes a literal or values of `input!`, no longer any `Serialize` value such as `json!`. An enum variable takes a bare value (`sortKey = TITLE`) or `raw(string)`, no longer a string. `execute` and `execute_response` take `impl Into>`, so `execute(variables.into())` no longer infers its type: drop the `.into()`. `Operation` keeps each variable as the JSON it is sent as, and parses nothing back: `body()` returns the exact JSON text `execute` sends, a `String`, no longer a `Value`, and `variable_json(name)` the text of one variable, replacing `variables_json`. `Operation::variable::` takes a `T` of the sealed `VariableType`, and a `u64` beyond the range of `Int` is refused rather than saturated. The pattern of `[for … => …]` binds a name. +- Breaking (against the 1.0 previews): the input structs of modules (`MetafieldsSetInput { owner_id, ..Default::default() }`) are gone, for `input!`, which cannot leave out a required field. `Variables` implements `Default` only when no variable is required, and `PartialEq` only when it holds no input object. An input object variable of an inline `graphql!` takes a literal or values of `input!`, no longer any `Serialize` value such as `json!`. An enum variable takes a bare value (`sortKey = TITLE`) or `raw(string)`, no longer a string. `execute` and `execute_response` take `impl Into>`, so `execute(variables.into())` no longer infers its type: drop the `.into()`. `Operation` keeps each variable as the JSON it is sent as, and parses nothing back: `body()` returns the exact JSON text `execute` sends, a `String`, no longer a `Value`, and `variable_json(name)` the text of one variable, replacing `variables_json`. `Operation::variable::` takes a `T` of the sealed `VariableType`, and a `u64` beyond the range of `Int` is refused rather than saturated. - Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. - Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. diff --git a/MIGRATION.md b/MIGRATION.md index b37d49d..6271ce6 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -177,4 +177,3 @@ The input objects of `graphql!` changed before the release. | `shopify.execute(module::Variables { … }.into())` | Drop the `.into()`: `execute` takes `impl Into>`, so `.into()` has no single target (E0283) | | `Operation::variable::` with a `T` of yours | `T` is a `VariableType`: one of the Rust types `graphql!` picks (`String`, `i64`, `f64`, `bool`, `Value`, `InputObject`, in `Option` and `Vec`). `json_variable` takes anything else | | A `u64` beyond `i64` saturated to `i64::MAX`; NaN and infinity sent as `null`; `null` sent for a non-null `JSON` | Refused: `Error::InvalidValue` when the operation runs, before the request; an integer literal out of the range of `Int` is a compile error | -| `[for _ in … => …]` | `[for _item in … => …]`: the pattern binds a name | diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index b2da305..77bf37a 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -231,10 +231,6 @@ What reads as what, when Rust could read it too: - A lone identifier is an enum value where an enum is expected, and a Rust variable everywhere else. -- The pattern of `[for … in … => …]` binds a name: `[for _item in 0..3 => …]` - rather than `[for _ in 0..3 => …]`. The generated code names the list after - it, which no constant of the caller's can match. - Nothing goes through a `serde_json::Value`: each literal is written straight to the JSON sent, and a value of `input!` holds its JSON already. diff --git a/crates/shopify_api/src/graphql/literal.rs b/crates/shopify_api/src/graphql/literal.rs index 3f3eefa..d69dc1c 100644 --- a/crates/shopify_api/src/graphql/literal.rs +++ b/crates/shopify_api/src/graphql/literal.rs @@ -79,21 +79,13 @@ impl, K> Serialize for Leaf { /// The items of `[for … => …]`, each written in its turn of the loop, and /// the first that is refused. -#[derive(Debug)] +#[derive(Debug, Default)] pub struct Collected { items: Vec>, invalid: Option, } impl Collected { - #[allow(clippy::new_without_default)] - pub fn new() -> Self { - Self { - items: Vec::new(), - invalid: None, - } - } - pub fn push(&mut self, value: Result, Invalid>) { if self.invalid.is_some() { return; @@ -409,7 +401,7 @@ mod tests { )))), "invalid value at `T.list[1][0]`: not a finite Float" ); - let mut collected = Collected::new(); + let mut collected = Collected::default(); for quantity in [1_usize, 2, 1 << 40, 3, usize::MAX] { collected.push(to_raw(&Object(( Field("quantity", leaf::(quantity)), diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs index 226e129..c24e5df 100644 --- a/crates/shopify_api/tests/literals.rs +++ b/crates/shopify_api/tests/literals.rs @@ -957,6 +957,39 @@ mod hygiene { } } + enum Stage { + Ready, + } + use Stage::Ready as ready; + + /// Any pattern, whatever it binds: nothing, a name that starts with a + /// capital, a unit variant renamed in lower case, a generated name. + #[test] + fn the_pattern_of_a_for_is_the_callers() { + let value = json(input!(ProductUpdateInput { + tags: [for _ in 0..2 => "sale"], + collectionsToJoin: [for (ready, id) in [(ready, "1")] => id], + collectionsToLeave: [for ref Item in [String::from("a")] => Item], + redirectNewHandle: true, + })); + assert_eq!( + value, + json!({ "tags": ["sale", "sale"], "collectionsToJoin": ["1"], "collectionsToLeave": ["a"], "redirectNewHandle": true }) + ); + let value = json(input!(ProductUpdateInput { + tags: [for __shopify_api_collected in [["a", "b"]] => __shopify_api_collected[1]], + })); + assert_eq!(value, json!({ "tags": ["b"] })); + let operation = graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + product = { tags: [for _ in [()] => "x"], metafields: [for Item in ["k"] => { key: Item, value: "v", namespace: "n", type: "single_line_text_field" }] }, + ); + assert_eq!( + crate::variables(&operation), + json!({ "product": { "tags": ["x"], "metafields": [{ "key": "k", "value": "v", "namespace": "n", "type": "single_line_text_field" }] } }) + ); + } + struct Product { title: &'static str, } diff --git a/crates/shopify_api/tests/ui/literal_for_binds_no_name.rs b/crates/shopify_api/tests/ui/literal_for_binds_no_name.rs deleted file mode 100644 index d162b5f..0000000 --- a/crates/shopify_api/tests/ui/literal_for_binds_no_name.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - let _ = shopify_api::input!(ProductUpdateInput { tags: [for _ in 0..3 => "sale"] }); -} diff --git a/crates/shopify_api/tests/ui/literal_for_binds_no_name.stderr b/crates/shopify_api/tests/ui/literal_for_binds_no_name.stderr deleted file mode 100644 index b951a32..0000000 --- a/crates/shopify_api/tests/ui/literal_for_binds_no_name.stderr +++ /dev/null @@ -1,6 +0,0 @@ -error: The pattern of `[for pattern in … => …]` binds no name: name what it gives, as `[for _item in … => …]` - (checked against the Shopify Admin API 2026-10) - --> tests/ui/literal_for_binds_no_name.rs:2:60 - | -2 | let _ = shopify_api::input!(ProductUpdateInput { tags: [for _ in 0..3 => "sale"] }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr index a130e07..5602a79 100644 --- a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -7,13 +7,13 @@ error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[Inven | | an `Option`: `None` leaves the field out | required by a bound introduced by this call | - = help: the trait `__ShopifyApiNoNull4_c23fa168` is not implemented for `Vec>` + = help: the trait `__ShopifyApiNoNull4_c23fa03b` is not implemented for `Vec>` help: this trait has no implementations, consider adding one --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c23fa168` +note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c23fa03b` --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr index 9f7c335..f5204da 100644 --- a/crates/shopify_api/tests/ui/literal_option_in_field.stderr +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -7,7 +7,7 @@ error[E0277]: `vendor` of `ProductUpdateInput` expects a `String`, not `Option` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect1_c2385b33` is not implemented for `Option` + = help: the trait `__ShopifyApiExpect1_c2385860` is not implemented for `Option` = note: `vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null` note: required by a bound in `Checks::build` --> tests/ui/literal_option_in_field.rs:3:13 diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr index c0e960e..9b30a76 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -9,8 +9,8 @@ error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built wit 6 | | ); | |_____- required by a bound introduced by this call | - = help: the trait `__ShopifyApiExpect2_c2384416` is not implemented for `InputObject<2493993284262097346>` -help: the following other types implement trait `__ShopifyApiExpect2_c2384416` + = help: the trait `__ShopifyApiExpect2_c2384e0f` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2_c2384e0f` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -22,7 +22,7 @@ help: the following other types implement trait `__ShopifyApiExpect2_c2384416` | | | | |_____`&InputObject<960560859991546817>` | `InputObject<960560859991546817>` -note: required for `Vec>` to implement `__ShopifyApiExpect1_c2384416` +note: required for `Vec>` to implement `__ShopifyApiExpect1_c2384e0f` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr index bdec6bf..62a071d 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr @@ -7,7 +7,7 @@ error[E0277]: `quantity` of `DraftOrderLineItemInput` expects an `Int`, not `&st | `&'static str` doesn't satisfy the trait bound | any integer type | - = help: the trait `main::__ShopifyApiExpect1_c2384be1` is not implemented for `&str` + = help: the trait `main::__ShopifyApiExpect1_c2384416` is not implemented for `&str` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 | @@ -24,7 +24,7 @@ error[E0277]: `title` of `DraftOrderLineItemInput` expects a `String`, not `u8` | `u8` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect3_c2384be1` is not implemented for `u8` + = help: the trait `__ShopifyApiExpect3_c2384416` is not implemented for `u8` = note: `title?: value` takes an `Option`, `None` leaving the field out; `title: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -42,7 +42,7 @@ error[E0277]: `requiresShipping` of `DraftOrderLineItemInput` expects a `Boolean | `{integer}` doesn't satisfy the trait bound | `bool` | - = help: the trait `__ShopifyApiExpect5_c2384be1` is not implemented for `{integer}` + = help: the trait `__ShopifyApiExpect5_c2384416` is not implemented for `{integer}` = note: `requiresShipping?: value` takes an `Option`, `None` leaving the field out; `requiresShipping: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -60,8 +60,8 @@ error[E0277]: `value` of `WeightInput` expects a `Float`, not `u64` | `u64` doesn't satisfy the trait bound | `f64`, `f32`, `i32` or `u32` | - = help: the trait `main::__ShopifyApiExpect1_c2384be1` is not implemented for `u64` - = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c2384be1`, but not `main::__ShopifyApiExpect1_c2384be1` + = help: the trait `main::__ShopifyApiExpect1_c2384416` is not implemented for `u64` + = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c2384416`, but not `main::__ShopifyApiExpect1_c2384416` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:4:13 | diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index f21903f..b63fc52 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -88,8 +88,6 @@ pub struct For { /// Of the brackets. pub span: Span, pub pattern: TokenStream, - /// A name the pattern binds, if it binds one. - pub binding: Option, pub iterable: TokenStream, pub filter: Option, pub item: Value, @@ -371,25 +369,14 @@ impl<'a> Literals<'a> { let value = each.finish(value, &krate); let For { pattern, - binding, iterable, filter, .. } = &**comprehension; - // The list is a local named after a name the pattern binds: - // the pattern compiles, so no constant of that name is in - // scope. Its mixed-site hygiene keeps the two apart. - let Some(binding) = binding else { - return error( - comprehension.span, - "The pattern of `[for pattern in … => …]` binds no name: name what it gives, as `[for _item in … => …]`", - ); - }; - let name = binding.to_string(); - let items = match name.strip_prefix("r#") { - Some(name) => Ident::new_raw(name, Span::mixed_site()), - None => Ident::new(&name, Span::mixed_site()), - }; + // A generated name may meet a user item only in a compile + // error (a constant in a pattern, E0530), never in a silent + // change of meaning: mixed-site, no user expression sees it. + let items = Ident::new("__shopify_api_collected", Span::mixed_site()); // Each item is written in its turn of the loop, so that it may // borrow what the loop gives. let push = @@ -399,7 +386,7 @@ impl<'a> Literals<'a> { None => push, }; let list = quote! {{ - let mut #items = #krate::__private::literal::Collected::new(); + let mut #items = <#krate::__private::literal::Collected as ::core::default::Default>::default(); for #pattern in #iterable { #body } #items }}; diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index a3cdcb8..238c416 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -106,7 +106,6 @@ fn an_object_is_sent_field_by_field_in_its_order() { Value::For(Box::new(For { span: Span::call_site(), pattern: quote!(m), - binding: Some(Ident::new("m", Span::call_site())), iterable: quote!(&rows), filter: Some(quote!(!m.value.is_empty())), item: Value::Object(object(vec![ diff --git a/crates/shopify_api_macros/src/value.rs b/crates/shopify_api_macros/src/value.rs index 31b4c42..ff0bffd 100644 --- a/crates/shopify_api_macros/src/value.rs +++ b/crates/shopify_api_macros/src/value.rs @@ -154,7 +154,6 @@ fn parse_for(input: ParseStream, span: Span) -> syn::Result { } Ok(Value::For(Box::new(For { span, - binding: binding(&pattern), pattern: pattern.into_token_stream(), iterable: iterable.into_token_stream(), filter, @@ -162,33 +161,6 @@ fn parse_for(input: ParseStream, span: Span) -> syn::Result { }))) } -/// The first name `pattern` binds. A lone identifier that starts with a -/// capital is taken for a constant, a unit struct or a variant. -fn binding(pattern: &syn::Pat) -> Option { - use syn::Pat; - match pattern { - Pat::Ident(pattern) => { - let name = pattern.ident.unraw().to_string(); - if name != "_" && !name.starts_with(|first: char| first.is_uppercase()) { - return Some(pattern.ident.clone()); - } - pattern - .subpat - .as_ref() - .and_then(|(_, pattern)| binding(pattern)) - } - Pat::Or(pattern) => pattern.cases.first().and_then(binding), - Pat::Paren(pattern) => binding(&pattern.pat), - Pat::Reference(pattern) => binding(&pattern.pat), - Pat::Type(pattern) => binding(&pattern.pat), - Pat::Tuple(pattern) => pattern.elems.iter().find_map(binding), - Pat::TupleStruct(pattern) => pattern.elems.iter().find_map(binding), - Pat::Slice(pattern) => pattern.elems.iter().find_map(binding), - Pat::Struct(pattern) => pattern.fields.iter().find_map(|field| binding(&field.pat)), - _ => None, - } -} - fn expr(value: &syn::Expr) -> Expr { Expr { tokens: value.to_token_stream(), @@ -310,28 +282,6 @@ mod tests { } } - #[test] - fn finds_a_name_the_pattern_of_a_for_binds() { - for (pattern, name) in [ - ("m", Some("m")), - ("(i, m)", Some("i")), - ("(_, m)", Some("m")), - ("&Row { id, .. }", Some("id")), - ("Some(x) | None", Some("x")), - ("ref mut r#type", Some("r#type")), - ("whole @ (_, _)", Some("whole")), - ("_", None), - ("(_, Marker)", None), - ("[_, _]", None), - ] { - let Value::For(comprehension) = parse(&format!("[for {pattern} in xs => 1]")) else { - panic!("{pattern}"); - }; - let found = comprehension.binding.map(|ident| ident.to_string()); - assert_eq!(found.as_deref(), name, "{pattern}"); - } - } - #[test] fn says_what_is_wrong_in_an_object() { for (text, message) in [ From 3b2ed70a28c1951079607454cf05dbc736bcd04a Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:54:05 +0200 Subject: [PATCH 064/135] refactor(macros): parameters under generated names, no shadowing functions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The parameters of the generated method were `value0…`, kept from a constant of the caller's by functions of these names imported in its block, plus local functions past 64. They are now `__shopify_api_value…` on mixed-site spans: as for the list of `[for]`, a constant of one of these names could only fail to compile. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/graphql/literal.rs | 15 -------------- crates/shopify_api_graphql/src/literal.rs | 23 +++++++-------------- crates/shopify_api_graphql/tests/literal.rs | 5 ++++- 3 files changed, 12 insertions(+), 31 deletions(-) diff --git a/crates/shopify_api/src/graphql/literal.rs b/crates/shopify_api/src/graphql/literal.rs index d69dc1c..91bb202 100644 --- a/crates/shopify_api/src/graphql/literal.rs +++ b/crates/shopify_api/src/graphql/literal.rs @@ -112,21 +112,6 @@ impl Serialize for Collected { } } -/// Functions named like the parameters of the method the macros generate, -/// imported where it is declared: a parameter may shadow a function, so no -/// constant of the caller's of the same name turns it into a pattern. -pub mod names { - macro_rules! names { - ($($name:ident)*) => {$( - pub fn $name() {} - )*}; - } - - names!( - value0 value1 value2 value3 value4 value5 value6 value7 value8 value9 value10 value11 value12 value13 value14 value15 value16 value17 value18 value19 value20 value21 value22 value23 value24 value25 value26 value27 value28 value29 value30 value31 value32 value33 value34 value35 value36 value37 value38 value39 value40 value41 value42 value43 value44 value45 value46 value47 value48 value49 value50 value51 value52 value53 value54 value55 value56 value57 value58 value59 value60 value61 value62 value63 - ); -} - #[derive(Debug)] pub struct Object(pub F); diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index b63fc52..6f150c4 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -161,8 +161,9 @@ enum Place { /// builds the value; the method, and the traits that check each argument, /// are declared in a block of their own, the receiver of the call. A /// constant (`"text"`, `12`, `true`) is written in place, with nothing to -/// check. The code declares no local that a constant of the caller's could -/// match. +/// check. Its locals and parameters are `__shopify_api_…` names, on +/// mixed-site spans: a constant of the caller's of one of these names could +/// only make the code fail to compile (E0530), never change what it sends. pub struct Literals<'a> { schema: &'a Schema, krate: TokenStream, @@ -1154,7 +1155,11 @@ impl Build { ty: TokenStream, arg: TokenStream, ) -> TokenStream { - let name = format_ident!("value{}", self.params.len()); + let name = format_ident!( + "__shopify_api_value{}", + self.params.len(), + span = Span::mixed_site() + ); self.generics.extend(generic); self.params.push(quote!(#name: #ty)); self.args.push(arg); @@ -1177,18 +1182,9 @@ impl Build { if args.is_empty() { return quote!({ #path #json }); } - // The parameters shadow functions of these names, and so no - // constant: `literal::names` has the first ones. - let names = (NAMES..params.len()).map(|n| { - let name = format_ident!("value{n}"); - quote!(#[allow(dead_code)] fn #name() {}) - }); quote! { ({ #path - #[allow(unused_imports)] - use #krate::__private::literal::names::*; - #(#names)* #(#items)* struct Checks; impl Checks { @@ -1207,9 +1203,6 @@ impl Build { } } -/// How many names of parameters `literal::names` has. -const NAMES: usize = 64; - const INT_TYPES: [&str; 10] = [ "i8", "i16", "i32", "i64", "isize", "u8", "u16", "u32", "u64", "usize", ]; diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index 238c416..832f495 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -320,7 +320,10 @@ fn enum_values_are_checked_and_raw_is_only_for_enums() { ) .unwrap(); // `raw(…)` is an argument, evaluated where the caller wrote it. - assert!(code.contains("Field (\"status\" , value0)"), "{code}"); + assert!( + code.contains("Field (\"status\" , __shopify_api_value0)"), + "{code}" + ); assert!( code.contains(". build (:: shopify_api :: __private :: literal :: raw ((status)) , (id))"), "{code}" From 5651e7789566bbd08c7fd392bab740c15eed1acc Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:56:21 +0200 Subject: [PATCH 065/135] fix(macros): check at compile time only integer literals, not Some or vec! MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The scanner took `Some(…)` and `vec![…]` by their spelling: with `use normalize as Some;`, a call of the caller's function was refused. Only literals, negated, in parentheses or in a list `[…]` are checked when the crate compiles; every other form is checked when the value is built. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 5 +- crates/shopify_api/docs/graphql.md | 12 +++-- crates/shopify_api/tests/literals.rs | 58 +++++++++++++++++++++ crates/shopify_api_graphql/src/literal.rs | 16 ++---- crates/shopify_api_graphql/tests/literal.rs | 32 ++++++++---- 6 files changed, 95 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5161c4c..10e5559 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Add: input values written as literals in an inline `graphql!`, checked against the schema at the token: `product = { id: id, status: ACTIVE, descriptionHtml: null, vendor?: vendor, seo: { title: t }, metafields: [for m in &rows if cond => { … }] }`. Field names are the GraphQL ones (`type` included); an unknown or repeated field, a missing required field (each one named), `null` on a non-null type, an unknown enum value (the valid ones listed) and a value of the wrong form are compile errors; deprecated fields and enum values warn. `field?: value` leaves the field out for `None`; an `Option` given to `field: value` does not compile, since `null` would clear the field. `raw(string)` sends an enum value unchecked. Rust expressions are checked by traits whose errors name the GraphQL type. Literals are written straight to JSON, with no `serde_json::Value` in between. - Add: `input!(TypeName { … })` builds an input object ahead of the call, with the same checks, as an `InputObject`: one Rust type per GraphQL name, the same in every module and crate, so that the values of several `input!` go in one `Vec`. - Add: `Maybe` (`Absent`, `Null`, `Value`), for `field?:` when `null` is a choice made at run time. -- Add: values Shopify would not read as written are refused. A `Float` must be finite (NaN and infinity were sent as `null`), an `Int` must fit in 32 bits, a non-null `JSON` must not be `null` at its top. An integer literal out of range is a compile error at the literal. A value known at run time, in a literal, an `input!`, a module's `Variables` or `Operation::variable`, is kept as refused, and the operation fails with `Error::InvalidValue { path, reason, detail }` before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float ``. The message names the place and the reason (`InvalidValueReason`), never the value; a serializer's message is in `sensitive_detail()`. An `InputObject` that is refused fails to serialize on its own. Nothing in the code of the macros panics on a value. +- Add: values Shopify would not read as written are refused. A `Float` must be finite (NaN and infinity were sent as `null`), an `Int` must fit in 32 bits, a non-null `JSON` must not be `null` at its top. An integer literal out of range, alone, negated, in parentheses or in a list `[…]`, is a compile error at the literal; `Some(…)`, `vec![…]` and other forms are checked at run time. A value known at run time, in a literal, an `input!`, a module's `Variables` or `Operation::variable`, is kept as refused, and the operation fails with `Error::InvalidValue { path, reason, detail }` before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float ``. The message names the place and the reason (`InvalidValueReason`), never the value; a serializer's message is in `sensitive_detail()`. An `InputObject` that is refused fails to serialize on its own. Nothing in the code of the macros panics on a value. - Add: no name the macros generate is in scope where the values are evaluated: a local, closure, function or constant of yours with the name of a generated item stays yours. - Add: one `graphql! { … }` holds several modules, `;` between them. A module's `Variables` runs as it is, `shopify.execute(module::Variables { … })`, and it names each input object its variables may hold: `pub type MetafieldsSetInput = InputObject<…>`. - Breaking (against the 1.0 previews): the input structs of modules (`MetafieldsSetInput { owner_id, ..Default::default() }`) are gone, for `input!`, which cannot leave out a required field. `Variables` implements `Default` only when no variable is required, and `PartialEq` only when it holds no input object. An input object variable of an inline `graphql!` takes a literal or values of `input!`, no longer any `Serialize` value such as `json!`. An enum variable takes a bare value (`sortKey = TITLE`) or `raw(string)`, no longer a string. `execute` and `execute_response` take `impl Into>`, so `execute(variables.into())` no longer infers its type: drop the `.into()`. `Operation` keeps each variable as the JSON it is sent as, and parses nothing back: `body()` returns the exact JSON text `execute` sends, a `String`, no longer a `Value`, and `variable_json(name)` the text of one variable, replacing `variables_json`. `Operation::variable::` takes a `T` of the sealed `VariableType`, and a `u64` beyond the range of `Int` is refused rather than saturated. diff --git a/README.md b/README.md index ba79a8e..c6cb1f7 100644 --- a/README.md +++ b/README.md @@ -152,8 +152,9 @@ A value is checked when it is built, in a literal, an `input!`, a module's `Variables` or `Operation::variable`: an `Int` must fit in 32 bits, a `Float` must be finite (JSON has no NaN or infinity, and `null` would clear the field), and a non-null `JSON` must not be `null` at its top (`null` inside it -is fine). An integer literal out of range is a compile error at the literal. -A value known at run time makes `execute` fail before anything is sent, with +is fine). An integer literal out of range, alone, negated, in parentheses or +in a list `[…]`, is a compile error at the literal; `Some(…)`, `vec![…]` and +any other form are checked at run time. A value known at run time makes `execute` fail before anything is sent, with `Error::InvalidValue`, which says where and why, never the value: `` invalid value at `$input.lineItems[2].quantity`: Int out of 32-bit range ``. diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 77bf37a..968520c 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -247,10 +247,14 @@ would turn into something else: | A non-null `JSON` | `null` at its top; `null` inside it is sent | `null for a non-null JSON field` | | Any value | Its `Serialize` fails | `could not serialize` | -An integer literal out of range is a compile error at the literal: `-1`, -`2_147_483_648_i64`, `0x8000_0000`, `Some(…)` of one, or an item of `[…]` or -`vec![…]`. A value known at run time is kept as refused, and the operation -fails with [`Error::InvalidValue`] when it is sent, or when +An integer literal out of range is a compile error at the literal, where +an `Int` is expected: `2_147_483_648_i64`, `-2147483649`, `0x8000_0000`, +`(3_000_000_000)`, in any base, with `_` and a suffix, negated, in +parentheses, alone or as an item of a list `[…]`. Only these forms are +checked when the crate compiles, since their meaning does not depend on what +a name resolves to. Any other value, `Some(…)`, `vec![…]`, `[x; n]` or a +computed one, is checked when it is built: it is kept as refused, and the +operation fails with [`Error::InvalidValue`] when it is sent, or when [`Operation::body`] or [`Operation::variable_json`] reads it, before any request. Its `Display` names the place in GraphQL terms and the reason, never the value: diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs index c24e5df..66a68bf 100644 --- a/crates/shopify_api/tests/literals.rs +++ b/crates/shopify_api/tests/literals.rs @@ -724,6 +724,64 @@ fn values_at_the_bounds_are_sent() { ); } +/// Only integer literals, negated, in parentheses or in a list `[…]`, are +/// checked when the crate compiles: what `Some(…)` calls depends on what +/// the name resolves to. The other forms are checked when the value is +/// built. +mod int_forms { + use shopify_api::{Error, InvalidValueReason, graphql, input}; + + fn normalize(n: i64) -> i32 { + (n - 2_147_483_648) as i32 + } + use normalize as Some; + + #[test] + fn a_function_named_some_is_the_callers() { + let value = input!(DraftOrderLineItemInput { + quantity: Some(2_147_483_648i64) + }); + assert_eq!( + serde_json::to_value(value).unwrap(), + serde_json::json!({ "quantity": 0 }) + ); + } + + #[test] + fn repeats_vec_and_option_are_checked_when_built() { + let out_of_range = |body: shopify_api::Result| { + matches!( + body, + Err(Error::InvalidValue { + reason: InvalidValueReason::IntOutOfRange, + .. + }) + ) + }; + assert!(out_of_range( + graphql!( + "query($n: Int!) { products(first: $n) { nodes { id } } }", + n = { [2_147_483_648i64; 1][0] } + ) + .body() + )); + assert!(out_of_range( + graphql!( + "query($n: Int) { products(first: $n) { nodes { id } } }", + n = ::core::option::Option::Some(3_000_000_000i64), + ) + .body() + )); + assert!(out_of_range( + graphql!( + "mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", + input = { lineItems: [{ quantity: vec![2_147_483_648i64][0] }] }, + ) + .body() + )); + } +} + /// Names like the ones the macros generate, or generated before, given to /// the caller's locals, closures, functions, constants and trait methods: /// the values sent are the caller's. diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index 6f150c4..e01706c 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -916,7 +916,9 @@ impl<'a> Literals<'a> { /// Refuses an integer literal outside of the 32 bits of `Int`, where /// the innermost type of `ty` is `Int`: written alone, negated, in - /// `Some(…)`, in parentheses, or as an item of `[…]` or `vec![…]`. + /// parentheses, or as an item of a list `[…]`. Only forms whose meaning + /// does not depend on what a name resolves to: `Some(…)` may be a + /// function of the caller's. Any other value is checked when it is built. fn int_literals(&self, tokens: &TokenStream, ty: &TypeRef, site: &Site) -> Result<(), Error> { if !matches!(self.schema.get(ty.name()), Some(TypeDef::Scalar)) || Scalar::of(ty.name()) != Scalar::Int @@ -1070,18 +1072,6 @@ fn int_literals(tokens: &TokenStream, found: &mut Vec<(i128, Span)>) { Delimiter::Bracket => items(&group.stream(), found), Delimiter::Brace => {} }, - [TokenTree::Ident(some), TokenTree::Group(group)] - if some == "Some" && group.delimiter() == Delimiter::Parenthesis => - { - int_literals(&group.stream(), found); - } - [ - TokenTree::Ident(vec), - TokenTree::Punct(bang), - TokenTree::Group(group), - ] if vec == "vec" && bang.as_char() == '!' && group.delimiter() == Delimiter::Bracket => { - items(&group.stream(), found); - } _ => {} } diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index 832f495..9dbab31 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -549,13 +549,6 @@ fn integer_literals_outside_of_int_are_refused() { let message = |site: &str| { format!("The integer is outside the range of `Int`, a 32-bit integer, given for {site}") }; - assert_eq!( - refused(vec![ - ("quantity", rust("1")), - ("grams?", rust("Some(3_000_000_000)")) - ]), - message("`grams` of `DraftOrderLineItemInput`") - ); assert_eq!( refusal( "DraftOrderInput", @@ -583,9 +576,9 @@ fn integer_literals_outside_of_int_are_refused() { ) .unwrap(); for (field, value) in [ - ("l", rust("vec![1, 2_147_483_648]")), + ("l", rust("[1, 2_147_483_648]")), ("l", list(vec![rust("1"), rust("2_147_483_648")])), - ("m", rust("[[Some(1)], [Some(2_147_483_648)]]")), + ("m", rust("[[1], [(-2_147_483_649)]]")), ] { let error = Literals::new(&schema, quote!(::shopify_api)) .input_object("T", Span::call_site(), &object(vec![(field, value)])) @@ -598,7 +591,8 @@ fn integer_literals_outside_of_int_are_refused() { error.message ); } - // At the bounds, and computed: checked when the value is built. + // At the bounds, computed, or in a form whose meaning depends on what a + // name resolves to: checked when the value is built. assert!( input( "DraftOrderLineItemInput", @@ -609,6 +603,24 @@ fn integer_literals_outside_of_int_are_refused() { ) .is_ok() ); + assert!( + input( + "DraftOrderLineItemInput", + vec![ + ("quantity", rust("Some(3_000_000_000)")), + ("grams?", rust("Some(3_000_000_000)")) + ] + ) + .is_ok() + ); + for value in ["vec![2_147_483_648]", "[2_147_483_648; 2]"] { + assert!( + Literals::new(&schema, quote!(::shopify_api)) + .input_object("T", Span::call_site(), &object(vec![("l", rust(value))])) + .is_ok(), + "{value}" + ); + } assert!( input( "DraftOrderLineItemInput", From bed1cb07538a2fd848339ee948e9410c2c18b782 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:59:53 +0200 Subject: [PATCH 066/135] chore: give each #[allow] of the PR its reason The lints still allowed, on structs a test only decodes and in the generated code, now say why. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk.rs | 2 +- crates/shopify_api/src/bulk/rows.rs | 6 +++--- crates/shopify_api/src/decode.rs | 6 +++--- crates/shopify_api/src/error.rs | 4 ++-- crates/shopify_api/src/graphql/response.rs | 4 ++-- crates/shopify_api/src/webhooks.rs | 2 +- crates/shopify_api/tests/bulk_stream.rs | 2 +- crates/shopify_api/tests/literals.rs | 7 ++++++- crates/shopify_api_graphql/src/codegen.rs | 4 ++-- crates/shopify_api_graphql/src/literal.rs | 4 ++-- 10 files changed, 23 insertions(+), 18 deletions(-) diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index bfefd61..963abd9 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -957,7 +957,7 @@ mod tests { assert_eq!(rows[1]["id"], 2); #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Row { id: String, } diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index a54b52f..e1c4dfe 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -676,7 +676,7 @@ mod tests { #[tokio::test] async fn a_decode_error_names_its_line_shows_nothing_of_it_and_the_stream_goes_on() { #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Row { id: u64, } @@ -938,12 +938,12 @@ mod tests { #[tokio::test] async fn groups_read_typed_parents_and_children_and_hide_bad_values() { #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Product { id: String, } #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Variant { id: String, price: u64, diff --git a/crates/shopify_api/src/decode.rs b/crates/shopify_api/src/decode.rs index 7872359..78b83b8 100644 --- a/crates/shopify_api/src/decode.rs +++ b/crates/shopify_api/src/decode.rs @@ -1015,7 +1015,7 @@ mod tests { } #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Order { name: String, lines: Vec, @@ -1023,14 +1023,14 @@ mod tests { } #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Line { quantity: u64, kind: Kind, } #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] enum Kind { Physical, Digital { url: String }, diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index 6825e1a..5a41af6 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -1102,12 +1102,12 @@ mod tests { ..Default::default() }; #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Data { orders: Vec, } #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Order { count: u64, } diff --git a/crates/shopify_api/src/graphql/response.rs b/crates/shopify_api/src/graphql/response.rs index d2ac2f7..15b8f2a 100644 --- a/crates/shopify_api/src/graphql/response.rs +++ b/crates/shopify_api/src/graphql/response.rs @@ -251,12 +251,12 @@ mod tests { #[test] fn decoding_names_the_path_of_the_mismatch() { #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Data { orders: Vec, } #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Order { name: String, } diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs index b9adbc1..b389fc6 100644 --- a/crates/shopify_api/src/webhooks.rs +++ b/crates/shopify_api/src/webhooks.rs @@ -618,7 +618,7 @@ mod tests { } assert_eq!(webhook.payload::().unwrap().name, "#1001"); #[derive(Debug, Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] struct Wrong { name: u32, } diff --git a/crates/shopify_api/tests/bulk_stream.rs b/crates/shopify_api/tests/bulk_stream.rs index eafa1e3..a336bb2 100644 --- a/crates/shopify_api/tests/bulk_stream.rs +++ b/crates/shopify_api/tests/bulk_stream.rs @@ -539,7 +539,7 @@ async fn measure_the_memory_of_a_200_mb_export() { let total = chunk.len() * chunks; #[derive(Deserialize)] - #[allow(dead_code)] + #[allow(dead_code, reason = "decoded for the memory it takes, never read")] struct Row { id: String, title: String, diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs index 66a68bf..040fd11 100644 --- a/crates/shopify_api/tests/literals.rs +++ b/crates/shopify_api/tests/literals.rs @@ -786,7 +786,12 @@ mod int_forms { /// the caller's locals, closures, functions, constants and trait methods: /// the values sent are the caller's. mod hygiene { - #![allow(non_upper_case_globals, non_snake_case, dead_code)] + #![allow( + non_upper_case_globals, + non_snake_case, + dead_code, + reason = "names and items that look like the generated ones" + )] use serde_json::{Value, json}; use shopify_api::{graphql, input}; diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs index 2e47a7f..890e67c 100644 --- a/crates/shopify_api_graphql/src/codegen.rs +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -160,7 +160,7 @@ impl DataTypes<'_> { #[doc = #doc] #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq, #krate::__private::serde::Serialize, #krate::__private::serde::Deserialize)] #[serde(crate = #serde)] - #[allow(dead_code)] + #[allow(dead_code, reason = "the caller may read only some fields")] pub struct #ident { #(#fields)* } @@ -282,7 +282,7 @@ pub fn variables_types( let doc = format!(" The input object `{name}`: build it with `input!({name} {{ … }})`."); quote! { #[doc = #doc] - #[allow(dead_code)] + #[allow(dead_code, reason = "the caller may not name every input object")] pub type #ident = #krate::InputObject<#id>; } }); diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index e01706c..c923cbb 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -1168,7 +1168,7 @@ impl Build { } = self; let json = quote!(literal::to_raw(&#body)); // `literal`, in a block that no expression of the caller's is in. - let path = quote!(#[allow(unused_imports)] use #krate::__private::literal;); + let path = quote!(#[allow(unused_imports, reason = "not every value uses it")] use #krate::__private::literal;); if args.is_empty() { return quote!({ #path #json }); } @@ -1178,7 +1178,7 @@ impl Build { #(#items)* struct Checks; impl Checks { - #[allow(clippy::too_many_arguments)] + #[allow(clippy::too_many_arguments, reason = "one per Rust expression of the value")] fn build<#(#generics),*>(self, #(#params),*) -> ::core::result::Result< ::std::boxed::Box<#krate::__private::serde_json::value::RawValue>, literal::Invalid, From 5080836ec71d3b4ebfdf039f504f1c163dcf2ef5 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:59:53 +0200 Subject: [PATCH 067/135] docs: a wrong input type names the type expected, not the one given rustc shows the type given as `InputObject`, `N` a hash of its name: README and the `input!` docs no longer promise both GraphQL names. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +++-- crates/shopify_api/docs/input.md | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c6cb1f7..405fd25 100644 --- a/README.md +++ b/README.md @@ -143,8 +143,9 @@ shopify.execute(graphql!( )).await?; ``` -A value of another input type is refused, the message naming both GraphQL -types: `` an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` ``. +A value of another input type is refused, the message naming the place and +the GraphQL type it expects: `` an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` ``. +The type given may show only as `InputObject`, `N` a hash of its name. ### Values Shopify would not read as written diff --git a/crates/shopify_api/docs/input.md b/crates/shopify_api/docs/input.md index 8e9d4c2..2fe2fa9 100644 --- a/crates/shopify_api/docs/input.md +++ b/crates/shopify_api/docs/input.md @@ -43,12 +43,14 @@ required field, `?:` for a field that may be left out, enum values bare or `raw(…)`, nested objects and lists, `[for … => …]`. A value of another input type is refused where one is expected, with a -message that names both places in GraphQL terms: +message that names the place and the GraphQL type it expects: ```text error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` ``` +The type given may show only as `InputObject`, `N` a hash of its name. + A value that Shopify would not read as written, a `Float` that is not finite, an `Int` beyond 32 bits, `null` for a non-null `JSON`, is kept as refused: the operation that holds it fails with From 2f33e8ca65eb00a41650a832e3a901d37b982e09 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:25:03 +0200 Subject: [PATCH 068/135] fix(graphql): leave a literal its suffix's type cannot hold to the runtime check Under `allow(overflowing_literals)`, `0xffff_ffff_i32` is `-1`, a valid `Int`, but the compile-time check read 4294967295 and refused it. A suffixed literal whose value its suffix's type cannot hold is now checked when it is built, from the value Rust gives it. Unsuffixed and in-range suffixed literals are still checked at compile time. Also drops an `allow(unused_imports)` that nothing needed. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/docs/graphql.md | 6 ++- crates/shopify_api/tests/literals.rs | 14 +++++ crates/shopify_api_graphql/src/literal.rs | 60 ++++++++++++++++----- crates/shopify_api_graphql/tests/literal.rs | 27 ++++++++++ 4 files changed, 92 insertions(+), 15 deletions(-) diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 968520c..1a390e0 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -252,8 +252,10 @@ an `Int` is expected: `2_147_483_648_i64`, `-2147483649`, `0x8000_0000`, `(3_000_000_000)`, in any base, with `_` and a suffix, negated, in parentheses, alone or as an item of a list `[…]`. Only these forms are checked when the crate compiles, since their meaning does not depend on what -a name resolves to. Any other value, `Some(…)`, `vec![…]`, `[x; n]` or a -computed one, is checked when it is built: it is kept as refused, and the +a name resolves to. Any other value, `Some(…)`, `vec![…]`, `[x; n]`, a +computed one, or a literal its suffix's type cannot hold (under +`allow(overflowing_literals)`, `0xffff_ffff_i32` is `-1`), is checked when +it is built: it is kept as refused, and the operation fails with [`Error::InvalidValue`] when it is sent, or when [`Operation::body`] or [`Operation::variable_json`] reads it, before any request. Its `Display` names the place in GraphQL terms and the reason, never diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs index 040fd11..1202fb9 100644 --- a/crates/shopify_api/tests/literals.rs +++ b/crates/shopify_api/tests/literals.rs @@ -782,6 +782,20 @@ mod int_forms { } } +/// A suffixed literal its type cannot hold is the value the compiler gives +/// it under `allow(overflowing_literals)`, checked when it is built. +#[test] +#[allow(overflowing_literals, reason = "a literal that wraps to `-1`")] +fn a_wrapping_suffixed_literal_is_its_rust_value() { + let value = input!(DraftOrderLineItemInput { + quantity: 0xffff_ffff_i32 + }); + assert_eq!( + serde_json::to_value(value).unwrap(), + json!({ "quantity": -1 }) + ); +} + /// Names like the ones the macros generate, or generated before, given to /// the caller's locals, closures, functions, constants and trait methods: /// the values sent are the caller's. diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index c923cbb..01be0ec 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -1053,18 +1053,18 @@ fn accepted(schema: &Schema, ty: &TypeRef) -> String { /// The integer literals of `tokens` in the forms /// [`Literals::int_literals`] reads, and their spans; one beyond `i128` is -/// `i128::MAX`. +/// `i128::MAX`, and one whose suffix's type cannot hold it is left out. fn int_literals(tokens: &TokenStream, found: &mut Vec<(i128, Span)>) { let trees: Vec = tokens.clone().into_iter().collect(); match trees.as_slice() { [TokenTree::Literal(literal)] => { - if let Some(value) = integer(&literal.to_string()) { + if let Some(value) = int_literal(&literal.to_string(), false) { found.push((value, literal.span())); } } [TokenTree::Punct(minus), TokenTree::Literal(literal)] if minus.as_char() == '-' => { - if let Some(value) = integer(&literal.to_string()) { - found.push((value.saturating_neg(), literal.span())); + if let Some(value) = int_literal(&literal.to_string(), true) { + found.push((value, literal.span())); } } [TokenTree::Group(group)] => match group.delimiter() { @@ -1092,6 +1092,44 @@ fn int_literals(tokens: &TokenStream, found: &mut Vec<(i128, Span)>) { /// The value of the text of an integer literal: `2_147_483_648_i64`, /// `0x8000_0000`, `0b1`; `None` for any other literal. fn integer(text: &str) -> Option { + let (magnitude, _) = integer_parts(text)?; + Some(magnitude.map_or(i128::MAX, |value| { + i128::try_from(value).unwrap_or(i128::MAX) + })) +} + +/// The value of an integer literal, negated or not, when the compiler gives +/// it the value written; `None` when its suffix's type cannot hold it, as +/// `0xffff_ffff_i32`, which `allow(overflowing_literals)` makes `-1`: only +/// the value built from it is known. `isize` and `usize` are taken as 32 +/// bits, the narrowest a target may have. +fn int_literal(text: &str, negated: bool) -> Option { + let (magnitude, suffix) = integer_parts(text)?; + if let Some(suffix) = suffix { + let bits = match &suffix[1..] { + "size" => 32, + bits => bits.parse().ok()?, + }; + let largest = if suffix.starts_with('i') { + (1_u128 << (bits - 1)) - u128::from(!negated) + } else { + u128::MAX >> (128 - bits) + }; + if magnitude? > largest { + return None; + } + } + let value = integer(text)?; + Some(if negated { + value.saturating_neg() + } else { + value + }) +} + +/// The digits of an integer literal as a number, `None` beyond `u128`, and +/// its suffix; `None` for any other literal. +fn integer_parts(text: &str) -> Option<(Option, Option<&'static str>)> { const SUFFIXES: [&str; 12] = [ "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize", ]; @@ -1099,19 +1137,15 @@ fn integer(text: &str) -> Option { .into_iter() .find_map(|(radix, prefix)| Some((radix, text.strip_prefix(prefix)?))) .unwrap_or((10, text)); - let digits = SUFFIXES + let (digits, suffix) = SUFFIXES .iter() - .find_map(|suffix| digits.strip_suffix(suffix)) - .unwrap_or(digits); + .find_map(|suffix| Some((digits.strip_suffix(suffix)?, Some(*suffix)))) + .unwrap_or((digits, None)); let digits: String = digits.chars().filter(|&digit| digit != '_').collect(); if digits.is_empty() || !digits.chars().all(|digit| digit.is_digit(radix)) { return None; } - Some( - u128::from_str_radix(&digits, radix).map_or(i128::MAX, |value| { - i128::try_from(value).unwrap_or(i128::MAX) - }), - ) + Some((u128::from_str_radix(&digits, radix).ok(), suffix)) } /// The innermost named type of `ty`, and whether it is non-null. @@ -1168,7 +1202,7 @@ impl Build { } = self; let json = quote!(literal::to_raw(&#body)); // `literal`, in a block that no expression of the caller's is in. - let path = quote!(#[allow(unused_imports, reason = "not every value uses it")] use #krate::__private::literal;); + let path = quote!(use #krate::__private::literal;); if args.is_empty() { return quote!({ #path #json }); } diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index 9dbab31..c5d0c0e 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -530,6 +530,14 @@ fn integer_literals_outside_of_int_are_refused() { "2_147_483_648_i64", "`quantity` of `DraftOrderLineItemInput`", ), + ( + "2_147_483_648i64", + "`quantity` of `DraftOrderLineItemInput`", + ), + ( + "0x1_0000_0000_i64", + "`quantity` of `DraftOrderLineItemInput`", + ), ("-2147483649", "`quantity` of `DraftOrderLineItemInput`"), ("0x8000_0000", "`quantity` of `DraftOrderLineItemInput`"), ("(3000000000)", "`quantity` of `DraftOrderLineItemInput`"), @@ -628,6 +636,25 @@ fn integer_literals_outside_of_int_are_refused() { ) .is_ok() ); + for text in [ + "0xffff_ffff_i32", + "2_147_483_648_i32", + "-129i8", + "256u8", + "0x1_0000_0000_usize", + ] { + assert!( + input("DraftOrderLineItemInput", vec![("quantity", rust(text))]).is_ok(), + "a literal its suffix's type cannot hold is checked when built: {text}" + ); + } + assert!( + input( + "DraftOrderLineItemInput", + vec![("quantity", rust("-2_147_483_648_i32"))] + ) + .is_ok() + ); } /// A constant of the type of its place is written as it is, with nothing From e5b2e2d72ac3e967ed34d40af8739e44b7256273 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:25:03 +0200 Subject: [PATCH 069/135] test(literals): drop narrating and stale comments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Splits the defaulted-variable test into three named tests in place of `// Left out.`, `// Sent.` and `// Refused: …`, and says why the seventy-values test exists instead of naming the removed `literal::names`. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/tests/literals.rs | 40 +++++++++++++++++----------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs index 1202fb9..6f2058b 100644 --- a/crates/shopify_api/tests/literals.rs +++ b/crates/shopify_api/tests/literals.rs @@ -420,21 +420,12 @@ graphql! { }"; } -/// A non-null variable with a default: `None` leaves it out, for Shopify -/// to use the default; a value is checked as non-null, never sent as `null`. +/// A non-null variable with a default, given `None`, is left out, for +/// Shopify to use the default. #[test] -fn a_defaulted_non_null_variable_is_left_out_or_checked_as_non_null() { +fn a_defaulted_non_null_variable_given_none_is_left_out() { use serde_json::Value; - use shopify_api::{Error, InvalidValueReason}; - let reason = |body: shopify_api::Result| match body { - Err(Error::InvalidValue { reason, .. }) => reason, - other => panic!("not refused: {other:?}"), - }; - let big: i64 = 1 << 31; - let line_item = input!(DraftOrderLineItemInput { quantity: big }); - - // Left out. let operation = defaults::operation(defaults::Variables::default()); assert_eq!(operation.variable_json("first").unwrap(), None); assert_eq!(operation.variable_json("query").unwrap(), None); @@ -456,8 +447,11 @@ fn a_defaulted_non_null_variable_is_left_out_or_checked_as_non_null() { tags: None, }); assert_eq!(variables(&operation), Value::Null); +} - // Sent. +/// A non-null variable with a default, given a value, sends it. +#[test] +fn a_defaulted_non_null_variable_given_a_value_sends_it() { let operation = defaults::operation(defaults::Variables { first: Some(i64::from(i32::MAX)), query: Some("b".into()), @@ -488,8 +482,22 @@ fn a_defaulted_non_null_variable_is_left_out_or_checked_as_non_null() { variables(&operation), json!({ "input": { "note": "n" }, "items": [{ "quantity": 1 }], "tags": ["t"] }) ); +} - // Refused: the module and the inline operation alike. +/// A value given to a non-null variable with a default is checked as +/// non-null, never sent as `null`, by a module and an inline operation +/// alike. +#[test] +fn a_defaulted_non_null_variable_checks_its_value() { + use serde_json::Value; + use shopify_api::{Error, InvalidValueReason}; + + let reason = |body: shopify_api::Result| match body { + Err(Error::InvalidValue { reason, .. }) => reason, + other => panic!("not refused: {other:?}"), + }; + let big: i64 = 1 << 31; + let line_item = input!(DraftOrderLineItemInput { quantity: big }); for (body, expected) in [ ( defaults::operation(defaults::Variables { @@ -917,7 +925,9 @@ mod hygiene { text.map(|text| format!("fn:{text}")) } - /// More values than the names `literal::names` has. + /// Seventy values, each a constant named like a generated one: the + /// macro numbers its own names past any count, and every value sent + /// is the caller's. #[test] fn seventy_values() { let value = input!(ProductUpdateInput { From c0edfcc78011b0b83c897d9ea2112c3b43a7d85e Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:35:20 +0200 Subject: [PATCH 070/135] test(literal): drop two comments the assertions already say Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api_graphql/tests/literal.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index c5d0c0e..94a5344 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -300,7 +300,6 @@ fn enum_values_are_checked_and_raw_is_only_for_enums() { ), "`values` of `CollectionSourceInclusionConditionProductStatusInput` expects a list of values of the enum `ProductStatus`: write them bare, `[ACTIVE, …]`, or `[for value in … => raw(value)]` for strings known at run time" ); - // A long enum is listed in part. let exemptions = refusal( "CompanyLocationInput", vec![ @@ -343,7 +342,6 @@ fn a_value_has_the_form_of_its_type() { refusal("ProductUpdateInput", vec![("title", list(vec![rust("t")]))]), "`title` of `ProductUpdateInput` expects a `String`, not a list" ); - // No single value where a list is expected. assert_eq!( refusal( "ProductUpdateInput", From 8b2563e4cedd14572177193dedc907da95fccd20 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:34:47 +0100 Subject: [PATCH 071/135] fix(graphql): send the crate's own operations to a pinned version unwarned A client pinned to another version than 2026-10 warned, at its first bulk or webhook call, that "an operation" should change the app's Cargo.toml: those operations are the crate's, checked against its own schema, and run on every supported version. They now go to the pinned version silently; the warning stays for the app's operations. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk.rs | 14 ++++--- crates/shopify_api/src/graphql.rs | 17 +++++++- crates/shopify_api/src/graphql/operation.rs | 15 +++++++ crates/shopify_api/src/webhooks.rs | 8 ++-- crates/shopify_api/tests/bulk.rs | 43 +++++++++++++++++++++ 5 files changed, 86 insertions(+), 11 deletions(-) diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 963abd9..58c88ad 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -392,7 +392,7 @@ impl Shopify { group_objects: bool, ) -> Result { let data = self - .execute(run_query::Variables { + .execute_own(run_query::Variables { query: query.to_string(), group_objects, }) @@ -481,7 +481,7 @@ impl Shopify { client_identifier: Option<&str>, ) -> Result { let data = self - .execute(run_mutation::Variables { + .execute_own(run_mutation::Variables { mutation: mutation.to_string(), staged_upload_path: staged_upload_path.to_string(), client_identifier: client_identifier.map(str::to_string), @@ -517,7 +517,7 @@ impl Shopify { I::Item: Serialize, { let data = self - .execute(staged_uploads::Variables { + .execute_own(staged_uploads::Variables { input: vec![input!(StagedUploadInput { filename: "bulk_op_vars.jsonl", mimeType: "text/jsonl", @@ -588,7 +588,9 @@ impl Shopify { /// A bulk operation by ID, `None` when the shop has none of that ID. pub async fn bulk_operation(&self, id: &str) -> Result> { - let data = self.execute(get::Variables { id: id.to_string() }).await?; + let data = self + .execute_own(get::Variables { id: id.to_string() }) + .await?; data.bulk_operation.as_ref().map(operation_of).transpose() } @@ -598,7 +600,7 @@ impl Shopify { filter: BulkOperationsFilter, ) -> Result> { let data = self - .execute(list::Variables { + .execute_own(list::Variables { first: i64::from(filter.first), after: filter.after, query: filter.query, @@ -621,7 +623,7 @@ impl Shopify { /// Asks Shopify to cancel a running bulk operation. pub async fn cancel_bulk_operation(&self, id: &str) -> Result { let data = self - .execute(cancel::Variables { id: id.to_string() }) + .execute_own(cancel::Variables { id: id.to_string() }) .await?; let payload = data .bulk_operation_cancel diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs index 7cb4dc8..da7a1a1 100644 --- a/crates/shopify_api/src/graphql.rs +++ b/crates/shopify_api/src/graphql.rs @@ -58,7 +58,14 @@ impl Shopify { operation: impl Into>, ) -> Result> { let operation = operation.into(); - let version = self.version_for(operation.checked_against())?; + let version = if operation.is_own() { + // Written for the version of the crate's schema, and kept working + // on the versions it supports: a pinned one is not a mistake. + self.pinned_api_version() + .map_or_else(|| self.version_for(operation.checked_against()), Ok)? + } else { + self.version_for(operation.checked_against())? + }; let body = operation.body()?.into_bytes(); let raw = self.send_graphql(version, body, operation.kind()).await?; let (data, extensions) = into_data(raw)?; @@ -68,6 +75,14 @@ impl Shopify { }) } + /// [`Shopify::execute`] for one of this crate's operations. + pub(crate) async fn execute_own( + &self, + operation: impl Into>, + ) -> Result { + self.execute(operation.into().own()).await + } + /// Runs any query or mutation and returns its `data`. Nothing checks the /// text: prefer [`graphql!`](crate::graphql!) for an operation known /// when the crate compiles. diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs index 4f2db67..63746e2 100644 --- a/crates/shopify_api/src/graphql/operation.rs +++ b/crates/shopify_api/src/graphql/operation.rs @@ -213,6 +213,8 @@ pub struct Operation { name: Option>, /// The Admin API version of the schema the operation was checked against. checked_against: Option<&'static str>, + /// One of this crate's operations: it goes to a pinned version unwarned. + own: bool, /// Each variable as the JSON it is sent as, in the order it was set. variables: std::result::Result)>, VariablesFailure>, data: PhantomData D>, @@ -227,6 +229,7 @@ impl Operation { query, name: None, checked_against: None, + own: false, variables: Ok(Vec::new()), data: PhantomData, } @@ -245,6 +248,7 @@ impl Operation { kind, name: name.map(Cow::Borrowed), checked_against: Some(checked_against), + own: false, variables: Ok(Vec::new()), data: PhantomData, } @@ -276,6 +280,16 @@ impl Operation { self.checked_against } + /// Marks one of this crate's operations. + pub(crate) fn own(mut self) -> Self { + self.own = true; + self + } + + pub(crate) fn is_own(&self) -> bool { + self.own + } + /// The Admin API version the operation is sent to when the client pins /// none: the one it was checked against, else [`ApiVersion::DEFAULT`]. pub fn api_version(&self) -> Result { @@ -494,6 +508,7 @@ impl Clone for Operation { kind: self.kind, name: self.name.clone(), checked_against: self.checked_against, + own: self.own, variables: self.variables.clone(), data: PhantomData, } diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs index b389fc6..0396f97 100644 --- a/crates/shopify_api/src/webhooks.rs +++ b/crates/shopify_api/src/webhooks.rs @@ -430,7 +430,7 @@ impl Shopify { pub async fn webhook_subscriptions(&self) -> Result> { let pages = self .paginate( - |after| list::operation(list::Variables { after }), + |after| list::operation(list::Variables { after }).own(), |data| { let connection = data.webhook_subscriptions; crate::Page::new( @@ -449,7 +449,7 @@ impl Shopify { spec: &WebhookSubscriptionSpec, ) -> Result { let data = self - .execute(create::Variables { + .execute_own(create::Variables { topic: spec.topic.clone(), webhook_subscription: subscription_input(spec, false), }) @@ -474,7 +474,7 @@ impl Shopify { pub async fn delete_webhook_subscription(&self, id: &str) -> Result<()> { let data = self - .execute(delete::Variables { id: id.to_string() }) + .execute_own(delete::Variables { id: id.to_string() }) .await?; let payload = data.webhook_subscription_delete.ok_or_else(|| { Error::decode( @@ -494,7 +494,7 @@ impl Shopify { spec: &WebhookSubscriptionSpec, ) -> Result { let data = self - .execute(update::Variables { + .execute_own(update::Variables { id: id.to_string(), webhook_subscription: subscription_input(spec, true), }) diff --git a/crates/shopify_api/tests/bulk.rs b/crates/shopify_api/tests/bulk.rs index 5adb2bb..9e4f3d6 100644 --- a/crates/shopify_api/tests/bulk.rs +++ b/crates/shopify_api/tests/bulk.rs @@ -264,3 +264,46 @@ async fn waiting_gives_up_after_its_timeout() { // 1 + 2 + 4 + 8 + 10 seconds, then the 5 that are left. assert_eq!(mock.requests().len(), 6); } + +/// Counts the warnings of the current thread. +struct Warnings(Arc>>); + +impl tracing::Subscriber for Warnings { + fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool { + *metadata.level() <= tracing::Level::WARN + } + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + fn event(&self, event: &tracing::Event<'_>) { + self.0 + .lock() + .unwrap() + .push(event.metadata().name().to_string()); + } + fn enter(&self, _: &tracing::span::Id) {} + fn exit(&self, _: &tracing::span::Id) {} +} + +/// The crate's operations go to a pinned version, without a warning that +/// would tell the app to change its own schema. +#[tokio::test] +async fn the_operations_of_the_crate_follow_a_pinned_version_unwarned() { + let warnings = Arc::new(Mutex::new(Vec::new())); + let _guard = tracing::subscriber::set_default(Warnings(warnings.clone())); + let mock = MockTransport::new(); + mock.push_data(json!({ "bulkOperation": null })); + let shopify = client(&mock).with_api_version(shopify_api::ApiVersion::V2026_07); + + assert!( + shopify + .bulk_operation("gid://shopify/BulkOperation/1") + .await + .unwrap() + .is_none() + ); + assert!(mock.requests()[0].url.contains("/admin/api/2026-07/")); + assert!(warnings.lock().unwrap().is_empty(), "{warnings:?}"); +} From fae0b9259a64815a83b3385337319e35577f7d99 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:35:06 +0100 Subject: [PATCH 072/135] refactor(transport)!: name the reqwest of the public API after its version `transport::reqwest` and `ReqwestTransport::from_builder` tied the 1.x API to reqwest 0.13: a reqwest 0.14 would have needed a 2.0. Both move to `transport::reqwest_0_13` (`reqwest_0_13::reqwest`, `reqwest_0_13::from_builder`), so that a later reqwest comes as a module of its own next to it. The policy, and the Tokio runtime the client needs, are in the module docs. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/transport.rs | 69 ++++++++++++++++++++--------- 1 file changed, 47 insertions(+), 22 deletions(-) diff --git a/crates/shopify_api/src/transport.rs b/crates/shopify_api/src/transport.rs index 31fc586..4230e32 100644 --- a/crates/shopify_api/src/transport.rs +++ b/crates/shopify_api/src/transport.rs @@ -1,5 +1,17 @@ //! The HTTP layer, behind a trait: [`ReqwestTransport`] by default, a //! [`MockTransport`](crate::testing::MockTransport) in tests, or your own. +//! +//! # reqwest +//! +//! No item of this crate names a type of `reqwest` but those of +//! [`reqwest_0_13`], the module named after the major version it is built +//! with. A later major version of `reqwest` comes as a module of its own, +//! next to it, in a minor release of this crate: `reqwest_0_13` stays, and +//! code that builds a client with it keeps compiling. [`ReqwestTransport::new`] +//! may move to the newer `reqwest` in a minor release. +//! +//! The default transport, and the token renewals, run on Tokio: call the +//! client from a Tokio runtime. use std::fmt; use std::future::Future; @@ -382,10 +394,41 @@ pub trait Transport: Send + Sync + 'static { } } -/// The `reqwest` this crate is built with, for [`ReqwestTransport::from_builder`]. +/// A [`ReqwestTransport`] from a client of `reqwest` 0.13 you configure. +/// +/// ``` +/// use shopify_api::transport::reqwest_0_13::{self, reqwest}; +/// +/// let builder = reqwest::Client::builder().connect_timeout(std::time::Duration::from_secs(3)); +/// let transport = reqwest_0_13::from_builder(builder)?; +/// # Ok::<(), shopify_api::Error>(()) +/// ``` #[cfg(any(feature = "rustls", feature = "native-tls"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))] -pub use reqwest; +pub mod reqwest_0_13 { + use super::ReqwestTransport; + + /// The `reqwest` 0.13 this crate is built with: build the client of + /// [`from_builder`] with it. + pub use reqwest; + + /// A transport from a client you configure: a proxy, other timeouts, + /// other certificates. Redirections are turned off whatever the builder + /// says, as [`Transport`](super::Transport) requires. + pub fn from_builder(builder: reqwest::ClientBuilder) -> Result { + let client = builder + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|error| { + // A proxy's address may hold a password: errors leave it out. + crate::Error::Config(format!( + "the HTTP client does not start: {}", + error.without_url() + )) + })?; + Ok(ReqwestTransport { client }) + } +} /// The default [`Transport`], over `reqwest`: no redirections, a 10-second /// connection timeout and a 60-second request timeout. A streamed answer @@ -400,32 +443,14 @@ pub struct ReqwestTransport { #[cfg(any(feature = "rustls", feature = "native-tls"))] impl ReqwestTransport { + /// To configure the client, see [`reqwest_0_13::from_builder`]. pub fn new() -> Result { - Self::from_builder( + reqwest_0_13::from_builder( reqwest::Client::builder() .connect_timeout(Duration::from_secs(10)) .timeout(Duration::from_secs(60)), ) } - - /// A transport from a client you configure: a proxy, other timeouts, - /// other certificates. Redirections are turned off whatever the builder - /// says, as [`Transport`] requires. - /// - /// Build `builder` with the [`reqwest`] this module re-exports. - pub fn from_builder(builder: reqwest::ClientBuilder) -> Result { - let client = builder - .redirect(reqwest::redirect::Policy::none()) - .build() - .map_err(|error| { - // A proxy's address may hold a password: errors leave it out. - crate::Error::Config(format!( - "the HTTP client does not start: {}", - error.without_url() - )) - })?; - Ok(Self { client }) - } } #[cfg(any(feature = "rustls", feature = "native-tls"))] From 5d28fcde1db2881cce73c29f78934208621208c3 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:35:18 +0100 Subject: [PATCH 073/135] fix(webhooks)!: refuse what the client secret signs that is not a webhook The launch query's `hmac`, the signature of a session token and the `signature` of an app proxy request are HMAC-SHA256 with the client secret, like a webhook: an installer of the app could re-encode one as `X-Shopify-Hmac-Sha256`, send the signed text as the body, and name any shop and topic in the unsigned headers. `Webhook::verify` and `verify_hmac` now refuse a body that does not start with `{` or `<` (after whitespace): none of those texts can, a JSON array from an app proxy query could. `webhooks::sign` and `ShopifyApp::sign_query`, `sign_app_proxy` and `sign_session_token` move behind the `testing` feature: they are signing oracles. The docs say what the signature covers, and `Webhook::verify_payload_shop` checks that the payload of a destructive topic names the shop of the headers. Also: - headers: values `AsRef<[u8]>`, so `&http::HeaderMap` goes in as it is, and the `shopify-*` names without `X-` are read; an axum handler in the docs; - `Debug` of `Webhook` shows the length of the body, not the body; - `WebhookSubscription::created_at` and `updated_at` are `DateTime`. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/oauth.rs | 6 + crates/shopify_api/src/webhooks.rs | 166 +++++++++++++++++++----- crates/shopify_api/tests/webhooks.rs | 183 +++++++++++++++++++++++++++ 3 files changed, 325 insertions(+), 30 deletions(-) diff --git a/crates/shopify_api/src/oauth.rs b/crates/shopify_api/src/oauth.rs index 3bcfe73..ae08307 100644 --- a/crates/shopify_api/src/oauth.rs +++ b/crates/shopify_api/src/oauth.rs @@ -405,6 +405,8 @@ impl ShopifyApp { } /// The `hmac` Shopify signs a query of Shopify admin with: for tests. + #[cfg(any(test, feature = "testing"))] + #[cfg_attr(docsrs, doc(cfg(feature = "testing")))] pub fn sign_query(&self, query: &str) -> Result { let params = parse_query(query)?; let mut mac = mac(&self.client_secret); @@ -437,6 +439,8 @@ impl ShopifyApp { } /// The `signature` Shopify signs an app proxy request with: for tests. + #[cfg(any(test, feature = "testing"))] + #[cfg_attr(docsrs, doc(cfg(feature = "testing")))] pub fn sign_app_proxy(&self, query: &str) -> Result { let params = parse_query(query)?; let mut mac = mac(&self.client_secret); @@ -531,6 +535,8 @@ impl ShopifyApp { /// A session token signed with the app's secret, as Shopify makes them: /// for tests. `claims` should hold `iss`, `dest`, `aud`, `exp` and `nbf`. + #[cfg(any(test, feature = "testing"))] + #[cfg_attr(docsrs, doc(cfg(feature = "testing")))] pub fn sign_session_token(&self, claims: &Value) -> String { let header = BASE64_URL.encode(br#"{"alg":"HS256","typ":"JWT"}"#); let payload = BASE64_URL.encode(serde_json::to_vec(claims).unwrap_or_default()); diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs index 0396f97..ec29dcc 100644 --- a/crates/shopify_api/src/webhooks.rs +++ b/crates/shopify_api/src/webhooks.rs @@ -12,22 +12,56 @@ //! let order: serde_json::Value = webhook.payload()?; //! println!("order {} on {}", order["name"], webhook.shop()); //! } +//! "app/uninstalled" | "shop/redact" | "customers/redact" => { +//! // Destructive: the shop of the headers is not signed, the payload is. +//! webhook.verify_payload_shop()?; +//! // … delete what the app holds for `webhook.shop()`. +//! } //! other => println!("{other} ignored"), //! } //! # Ok(()) //! # } //! ``` //! +//! With axum, or any framework on the `http` crate, the `HeaderMap` and the +//! raw body go in as they are: +//! +//! ```ignore +//! use axum::body::Bytes; +//! use axum::http::{HeaderMap, StatusCode}; +//! use shopify_api::webhooks::Webhook; +//! +//! async fn webhooks(headers: HeaderMap, body: Bytes) -> StatusCode { +//! let secret = std::env::var("SHOPIFY_API_SECRET").unwrap_or_default(); +//! let Ok(webhook) = Webhook::verify(&headers, body, &secret) else { +//! return StatusCode::UNAUTHORIZED; +//! }; +//! // Answer within 5 seconds: queue the work, then return. +//! tracing::info!("{} from {}", webhook.topic(), webhook.shop()); +//! StatusCode::OK +//! } +//! ``` +//! //! Shopify may deliver a webhook more than once: [`Webhook::event_id`] //! identifies the event across deliveries. //! +//! # What the signature covers +//! //! The signature covers the body only. The headers (the topic, the shop, the //! IDs) are what Shopify sent along, unsigned: a captured body could be -//! replayed with other headers. Check what matters against the body, or -//! against your own records of the shop. +//! replayed with other headers. Before deleting anything on `app/uninstalled`, +//! `shop/redact` or `customers/redact`, check that the payload names the shop +//! of the headers, with [`Webhook::verify_payload_shop`]. +//! +//! The client secret also signs the launch queries of Shopify admin, the app +//! proxy requests and the session tokens, which an installer of the app can +//! read. So that none of them passes for a webhook, only a body that starts +//! with `{` (JSON) or `<` (XML) verifies: a form-encoded query, a JWT or a +//! JSON array never does. use base64::Engine; use base64::engine::general_purpose::STANDARD; +use chrono::{DateTime, Utc}; use hmac::{Hmac, KeyInit, Mac}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; @@ -38,9 +72,12 @@ use shopify_api_macros::{__graphql_internal as graphql, __input_internal as inpu /// Whether `hmac_header` (`X-Shopify-Hmac-Sha256`) is the signature of /// `body` with `secret`, the client secret of the app. Compares in constant time. +/// +/// `false` for a body that is not a JSON object or an XML document, as +/// [`Webhook::verify`] refuses it: see [what the signature covers](self#what-the-signature-covers). pub fn verify_hmac(secret: &str, body: &[u8], hmac_header: &str) -> bool { // Anyone can sign with an empty key: it verifies nothing. - if secret.is_empty() { + if secret.is_empty() || !is_webhook_body(body) { return false; } let Ok(expected) = STANDARD.decode(hmac_header.trim()) else { @@ -53,7 +90,20 @@ pub fn verify_hmac(secret: &str, body: &[u8], hmac_header: &str) -> bool { mac.verify_slice(&expected).is_ok() } +/// Whether `body` starts as a webhook does, with `{` or `<`. The other texts +/// the client secret signs start otherwise: a query with a parameter name, a +/// session token with `eyJ`, and an app proxy request with a name that sorts +/// before `path_prefix`, never `{`, though `[` may. +fn is_webhook_body(body: &[u8]) -> bool { + matches!( + body.iter().find(|byte| !byte.is_ascii_whitespace()), + Some(b'{' | b'<') + ) +} + /// The signature Shopify would send for `body`, base64: for tests. +#[cfg(any(test, feature = "testing"))] +#[cfg_attr(docsrs, doc(cfg(feature = "testing")))] pub fn sign(secret: &str, body: &[u8]) -> String { let mut mac = Hmac::::new_from_slice(secret.as_bytes()).expect("HMAC takes a key of any length"); @@ -62,7 +112,10 @@ pub fn sign(secret: &str, body: &[u8]) -> String { } /// A webhook whose signature was verified. -#[derive(Debug, Clone, PartialEq, Eq)] +/// +/// `Debug` shows the length of the body, not the body: it holds the data of +/// customers. +#[derive(Clone, PartialEq, Eq)] #[non_exhaustive] pub struct Webhook { topic: String, @@ -76,12 +129,34 @@ pub struct Webhook { body: Vec, } +impl std::fmt::Debug for Webhook { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Webhook") + .field("topic", &self.topic) + .field("shop", &self.shop) + .field("webhook_id", &self.webhook_id) + .field("event_id", &self.event_id) + .field("api_version", &self.api_version) + .field("triggered_at", &self.triggered_at) + .field("sub_topic", &self.sub_topic) + .field("name", &self.name) + .field("body", &format_args!("[{} bytes]", self.body.len())) + .finish() + } +} + impl Webhook { /// Verifies a webhook from its headers and raw body, and reads its headers. /// - /// `headers` are name and value pairs, the names in any case. Fails when - /// the signature is missing or does not match, or a header Shopify always + /// `headers` are name and value pairs: an `http::HeaderMap` by + /// reference, or pairs of strings. Names are read in any case, with or + /// without their `X-` (`X-Shopify-Topic` or `shopify-topic`). Fails when + /// the signature is missing or does not match, when the body is neither + /// a JSON object nor an XML document, or when a header Shopify always /// sends is missing. + /// + /// The headers are not signed: see [what the signature covers](self#what-the-signature-covers). pub fn verify( headers: impl IntoIterator, body: impl Into>, @@ -89,7 +164,7 @@ impl Webhook { ) -> Result where K: AsRef, - V: AsRef, + V: AsRef<[u8]>, { Self::verify_with_secrets(headers, body, &[secret]) } @@ -103,36 +178,45 @@ impl Webhook { ) -> Result where K: AsRef, - V: AsRef, + V: AsRef<[u8]>, { + // Lowercase, without `x-`; a value that is not UTF-8 is not Shopify's. let headers: Vec<(String, String)> = headers .into_iter() - .map(|(name, value)| { - ( - name.as_ref().to_ascii_lowercase(), - value.as_ref().to_string(), - ) + .filter_map(|(name, value)| { + let name = name.as_ref().to_ascii_lowercase(); + let name = match name.strip_prefix("x-") { + Some(rest) if rest.starts_with("shopify-") => rest.to_string(), + _ => name, + }; + let value = std::str::from_utf8(value.as_ref()).ok()?.trim().to_string(); + Some((name, value)) }) .collect(); let header = |name: &str| { headers .iter() .find(|(given, _)| given == name) - .map(|(_, value)| value.trim().to_string()) + .map(|(_, value)| value.clone()) }; let required = |name: &'static str| { header(name) - .ok_or_else(|| Error::Verification(format!("the webhook has no `{name}` header"))) + .ok_or_else(|| Error::Verification(format!("the webhook has no `x-{name}` header"))) }; let body = body.into(); - let signature = required("x-shopify-hmac-sha256")?; + let signature = required("shopify-hmac-sha256")?; if secrets.iter().all(|secret| secret.is_empty()) { return Err(Error::Verification( "no secret to verify the webhook with: the client secret of the app is empty" .to_string(), )); } + if !is_webhook_body(&body) { + return Err(Error::Verification( + "the body of the webhook is neither a JSON object nor an XML document".to_string(), + )); + } if !secrets .iter() .any(|secret| verify_hmac(secret, &body, &signature)) @@ -141,22 +225,44 @@ impl Webhook { "the signature of the webhook does not match".to_string(), )); } - let shop = ShopDomain::new(&required("x-shopify-shop-domain")?).map_err(|error| { + let shop = ShopDomain::new(&required("shopify-shop-domain")?).map_err(|error| { Error::Verification(format!("the webhook names an invalid shop: {error}")) })?; Ok(Self { - topic: required("x-shopify-topic")?, + topic: required("shopify-topic")?, shop, - webhook_id: header("x-shopify-webhook-id"), - event_id: header("x-shopify-event-id"), - api_version: header("x-shopify-api-version"), - triggered_at: header("x-shopify-triggered-at"), - sub_topic: header("x-shopify-sub-topic"), - name: header("x-shopify-name"), + webhook_id: header("shopify-webhook-id"), + event_id: header("shopify-event-id"), + api_version: header("shopify-api-version"), + triggered_at: header("shopify-triggered-at"), + sub_topic: header("shopify-sub-topic"), + name: header("shopify-name"), body, }) } + /// Fails unless the JSON payload names [`Webhook::shop`], the shop of the + /// unsigned `X-Shopify-Shop-Domain`, in its `shop_domain` (the compliance + /// topics) or its `myshopify_domain` (`app/uninstalled`). Call it before + /// acting on a destructive topic: `app/uninstalled`, `shop/redact`, + /// `customers/redact`. + pub fn verify_payload_shop(&self) -> Result<()> { + let payload: serde_json::Value = serde_json::from_slice(&self.body).map_err(|_| { + Error::Verification("the payload of the webhook is not JSON".to_string()) + })?; + let named = ["shop_domain", "myshopify_domain"] + .iter() + .filter_map(|field| payload.get(field)?.as_str()) + .any(|shop| ShopDomain::new(shop).is_ok_and(|shop| shop == self.shop)); + if named { + Ok(()) + } else { + Err(Error::Verification( + "the payload of the webhook does not name the shop of its headers".to_string(), + )) + } + } + /// `orders/create`. pub fn topic(&self) -> &str { &self.topic @@ -262,8 +368,8 @@ pub struct WebhookSubscription { pub name: Option, /// The API version of the payloads. pub api_version: String, - pub created_at: String, - pub updated_at: String, + pub created_at: DateTime, + pub updated_at: DateTime, } #[derive(Deserialize)] @@ -277,8 +383,8 @@ struct Wire { include_fields: Vec, metafield_namespaces: Vec, name: Option, - created_at: String, - updated_at: String, + created_at: DateTime, + updated_at: DateTime, api_version: WireVersion, } @@ -685,8 +791,8 @@ mod tests { metafield_namespaces: Vec::new(), name: None, api_version: "2026-10".to_string(), - created_at: String::new(), - updated_at: String::new(), + created_at: DateTime::default(), + updated_at: DateTime::default(), }; assert!(spec.matches(&subscription)); subscription.uri = "https://example.com/other".to_string(); diff --git a/crates/shopify_api/tests/webhooks.rs b/crates/shopify_api/tests/webhooks.rs index 2fad94a..03e1249 100644 --- a/crates/shopify_api/tests/webhooks.rs +++ b/crates/shopify_api/tests/webhooks.rs @@ -126,3 +126,186 @@ async fn a_refused_subscription_returns_the_user_errors() { "webhookSubscriptionCreate refused: webhookSubscription.callbackUrl: Address is invalid" ); } + +mod verification { + use shopify_api::webhooks::{Webhook, sign, verify_hmac}; + + const SECRET: &str = "hush"; + + fn headers(signature: &str, topic: &str, shop: &str) -> Vec<(String, String)> { + vec![ + ("X-Shopify-Hmac-Sha256".into(), signature.into()), + ("X-Shopify-Topic".into(), topic.into()), + ("X-Shopify-Shop-Domain".into(), shop.into()), + ] + } + + fn refusal(signature: &str, body: &[u8]) -> String { + let result = Webhook::verify( + headers(signature, "shop/redact", "victim.myshopify.com"), + body, + SECRET, + ); + assert!(!verify_hmac(SECRET, body, signature)); + result.unwrap_err().to_string() + } + + /// The other texts the client secret signs, which an installer of the + /// app reads, never pass for a webhook. + #[cfg(feature = "oauth")] + mod forgeries { + use base64::Engine; + use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; + use serde_json::json; + use shopify_api::oauth::ShopifyApp; + + use super::*; + + const NOT_A_WEBHOOK: &str = "verification failed: the body of the webhook is neither a JSON object nor an XML document"; + + #[test] + fn the_hmac_of_a_launch_query_is_not_a_webhook_signature() { + let app = ShopifyApp::new("client-id", SECRET); + // Sorted, nothing to escape: the message signed is the query itself. + let query = "host=YWRtaW4&shop=attacker.myshopify.com×tamp=1700000000"; + let hmac = app.sign_query(query).unwrap(); + let signature = STANDARD.encode(hex::decode(hmac).unwrap()); + assert_eq!(refusal(&signature, query.as_bytes()), NOT_A_WEBHOOK); + } + + #[test] + fn the_signature_of_a_session_token_is_not_a_webhook_signature() { + let app = ShopifyApp::new("client-id", SECRET); + let token = app.sign_session_token(&json!({ + "dest": "https://attacker.myshopify.com", + "aud": "client-id", + "exp": 1, + })); + let (signed, signature) = token.rsplit_once('.').unwrap(); + let signature = STANDARD.encode(URL_SAFE_NO_PAD.decode(signature).unwrap()); + assert_eq!(refusal(&signature, signed.as_bytes()), NOT_A_WEBHOOK); + } + + /// The parameters of an app proxy request are the storefront's: a + /// name that sorts first can open a JSON array, never an object. + #[test] + fn an_app_proxy_request_is_not_a_webhook() { + let app = ShopifyApp::new("client-id", SECRET); + let query = "%5B%22=&logged_in_customer_id=&path_prefix=%2Fapps%2Fx\ + &shop=attacker.myshopify.com×tamp=1700000000&z=%22%5D"; + let message = "[\"=logged_in_customer_id=path_prefix=/apps/xshop=attacker.myshopify.comtimestamp=1700000000z=\"]"; + assert!(serde_json::from_str::(message).is_ok()); + let signature = app.sign_app_proxy(query).unwrap(); + let signature = STANDARD.encode(hex::decode(signature).unwrap()); + assert_eq!( + sign(SECRET, message.as_bytes()), + signature, + "the message signed" + ); + assert_eq!(refusal(&signature, message.as_bytes()), NOT_A_WEBHOOK); + } + } + + #[test] + fn only_json_objects_and_xml_verify() { + for body in [ + &b"{\"id\":1}"[..], + b"\n {}", + b"", + ] { + assert!( + Webhook::verify( + headers(&sign(SECRET, body), "orders/create", "a"), + body, + SECRET + ) + .is_ok() + ); + assert!(verify_hmac(SECRET, body, &sign(SECRET, body))); + } + for body in [&b""[..], b" ", b"[1]", b"a=1", b"eyJhbGciOiJIUzI1NiJ9.e30"] { + refusal(&sign(SECRET, body), body); + } + } + + #[test] + fn headers_without_x_and_in_any_case_are_read() { + let body = br#"{"id":1}"#; + let signature = sign(SECRET, body); + let headers = [ + ("shopify-hmac-sha256", signature.as_str()), + ("Shopify-Topic", "orders/create"), + ("SHOPIFY-SHOP-DOMAIN", "a.myshopify.com"), + ("shopify-api-version", "2026-10"), + ("shopify-webhook-id", "w1"), + ]; + let webhook = Webhook::verify(headers, &body[..], SECRET).unwrap(); + assert_eq!(webhook.topic(), "orders/create"); + assert_eq!(webhook.shop().as_str(), "a.myshopify.com"); + assert_eq!(webhook.api_version(), Some("2026-10")); + assert_eq!(webhook.webhook_id(), Some("w1")); + } + + /// axum's and actix's `HeaderMap` is `http`'s, which reqwest re-exports. + #[cfg(feature = "rustls")] + #[test] + fn a_header_map_goes_in_as_it_is() { + use shopify_api::transport::reqwest_0_13::reqwest::header::{HeaderMap, HeaderValue}; + + let body = br#"{"id":1}"#; + let mut map = HeaderMap::new(); + map.insert( + "x-shopify-hmac-sha256", + HeaderValue::from_str(&sign(SECRET, body)).unwrap(), + ); + map.insert("x-shopify-topic", HeaderValue::from_static("orders/create")); + map.insert( + "x-shopify-shop-domain", + HeaderValue::from_static("a.myshopify.com"), + ); + // A value that is not UTF-8 is not Shopify's: ignored. + map.insert("x-other", HeaderValue::from_bytes(&[0xff]).unwrap()); + let webhook = Webhook::verify(&map, body.to_vec(), SECRET).unwrap(); + assert_eq!(webhook.shop().as_str(), "a.myshopify.com"); + } + + #[test] + fn debug_shows_the_length_of_the_body_not_the_body() { + let body = br#"{"email":"ada@example.com"}"#; + let webhook = Webhook::verify( + headers(&sign(SECRET, body), "customers/create", "a"), + &body[..], + SECRET, + ) + .unwrap(); + let shown = format!("{webhook:?}"); + assert!(!shown.contains("ada@example.com"), "{shown}"); + assert!(shown.contains("[27 bytes]"), "{shown}"); + } + + #[test] + fn a_destructive_webhook_checks_the_shop_of_its_payload() { + let verified = |body: &str, shop: &str| { + Webhook::verify( + headers(&sign(SECRET, body.as_bytes()), "shop/redact", shop), + body.as_bytes(), + SECRET, + ) + .unwrap() + .verify_payload_shop() + }; + let redact = r#"{"shop_id":1,"shop_domain":"a.myshopify.com"}"#; + assert!(verified(redact, "a.myshopify.com").is_ok()); + assert_eq!( + verified(redact, "victim.myshopify.com") + .unwrap_err() + .to_string(), + "verification failed: the payload of the webhook does not name the shop of its headers" + ); + let uninstalled = + r#"{"id":1,"domain":"shop.example.com","myshopify_domain":"a.myshopify.com"}"#; + assert!(verified(uninstalled, "a").is_ok()); + assert!(verified(r#"{"id":1}"#, "a").is_err()); + assert!(verified("", "a").is_err()); + } +} From 9110d67b7182df7ece935019f399ce3cac16df6c Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:35:29 +0100 Subject: [PATCH 074/135] fix(oauth)!: verify the session tokens of UI extensions; apps carry a token store - `verify_session_token` reads a `dest` with or without `https://`, as a checkout or customer account UI extension writes it, and requires a whole `.myshopify.com` domain (a bare handle no longer passes). - `SessionToken::user_id` is `subject`: the staff member's ID from Shopify admin, the customer's GID from an extension. - `ShopifyApp::with_token_store`: the clients the app builds save the tokens they renew, so a rotated refresh token is no longer lost. `ShopifyBuilder::shared_token_store` takes a store already shared. - `RequestedToken` is `#[non_exhaustive]`. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/client.rs | 6 +++ crates/shopify_api/src/oauth.rs | 60 ++++++++++++++++++++------- crates/shopify_api/tests/oauth.rs | 69 +++++++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 16 deletions(-) diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index b7de5bb..e74c933 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -386,6 +386,12 @@ impl ShopifyBuilder { self } + /// [`ShopifyBuilder::token_store`], for a store already shared. + pub fn shared_token_store(mut self, store: Arc) -> Self { + self.token_store = Some(store); + self + } + /// How long before it expires a token is renewed: five minutes by default. pub fn refresh_leeway(mut self, leeway: Duration) -> Self { self.refresh_leeway = leeway; diff --git a/crates/shopify_api/src/oauth.rs b/crates/shopify_api/src/oauth.rs index ae08307..67ce43d 100644 --- a/crates/shopify_api/src/oauth.rs +++ b/crates/shopify_api/src/oauth.rs @@ -53,7 +53,9 @@ use sha2::Sha256; use crate::auth::{Encoding, request_token}; use crate::transport::{Transport, default_transport}; -use crate::{Auth, Error, Result, ShopDomain, Shopify, ShopifyBuilder, TokenData, USER_AGENT}; +use crate::{ + Auth, Error, Result, ShopDomain, Shopify, ShopifyBuilder, TokenData, TokenStore, USER_AGENT, +}; /// How far the `timestamp` of a signed query may be from now, as Shopify's libraries allow. const QUERY_TOLERANCE_SECONDS: i64 = 90; @@ -87,6 +89,7 @@ pub struct ShopifyApp { client_id: String, client_secret: String, transport: Option>, + token_store: Option>, user_agent: String, } @@ -95,6 +98,7 @@ impl std::fmt::Debug for ShopifyApp { formatter .debug_struct("ShopifyApp") .field("client_id", &self.client_id) + .field("token_store", &self.token_store.is_some()) .finish_non_exhaustive() } } @@ -178,6 +182,7 @@ impl SignedQuery { /// The token an embedded app asks for with a session token. #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] pub enum RequestedToken { /// A token of the shop that does not expire. Offline, @@ -193,7 +198,7 @@ pub enum RequestedToken { #[derive(Clone, PartialEq)] pub struct SessionToken { shop: ShopDomain, - user_id: Option, + subject: Option, session_id: Option, expires_at: DateTime, claims: Value, @@ -205,7 +210,7 @@ impl std::fmt::Debug for SessionToken { formatter .debug_struct("SessionToken") .field("shop", &self.shop) - .field("user_id", &self.user_id) + .field("subject", &self.subject) .field("session_id", &self.session_id) .field("expires_at", &self.expires_at) .finish_non_exhaustive() @@ -218,9 +223,11 @@ impl SessionToken { &self.shop } - /// The staff member, `sub`. - pub fn user_id(&self) -> Option<&str> { - self.user_id.as_deref() + /// `sub`: the ID of the staff member for a token of Shopify admin + /// (`42`), the GID of the customer for a token of a checkout or customer + /// account UI extension (`gid://shopify/Customer/1`), when one is logged in. + pub fn subject(&self) -> Option<&str> { + self.subject.as_deref() } /// The session, `sid`. @@ -250,6 +257,7 @@ impl ShopifyApp { client_secret: client_secret.into(), // Without one, the requests that need it fail with `NoTransport`. transport: default_transport().ok(), + token_store: None, user_agent: USER_AGENT.to_string(), } } @@ -261,6 +269,14 @@ impl ShopifyApp { self } + /// Saves the tokens that the clients it builds obtain or renew: the + /// refresh token of an expiring token changes at each renewal. The store + /// is told the shop of each token. + pub fn with_token_store(mut self, store: impl TokenStore) -> Self { + self.token_store = Some(Arc::new(store)); + self + } + pub fn with_user_agent(mut self, user_agent: impl Into) -> Self { self.user_agent = user_agent.into(); self @@ -286,17 +302,22 @@ impl ShopifyApp { // ─── Clients ───────────────────────────────────────────────────── - /// A builder of a client of `shop` that uses the app's transport. + /// A builder of a client of `shop` that uses the app's transport and + /// token store. pub fn builder(&self, shop: &ShopDomain) -> ShopifyBuilder { - let builder = Shopify::builder(shop).user_agent(&self.user_agent); - match &self.transport { - Some(transport) => builder.shared_transport(transport.clone()), - None => builder, + let mut builder = Shopify::builder(shop).user_agent(&self.user_agent); + if let Some(transport) = &self.transport { + builder = builder.shared_transport(transport.clone()); } + if let Some(store) = &self.token_store { + builder = builder.shared_token_store(store.clone()); + } + builder } /// A client of `shop` with a token the app obtained: renewed with its - /// refresh token when it has one, used as it is otherwise. + /// refresh token when it has one, used as it is otherwise. The renewed + /// tokens go to the app's [token store](Self::with_token_store). pub fn client(&self, shop: &ShopDomain, token: TokenData) -> Result { let auth = if token.refresh_token.is_some() { Auth::expiring_token(&self.client_id, &self.client_secret, token) @@ -453,6 +474,10 @@ impl ShopifyApp { /// Verifies a session token from the app's frontend (the bearer of its /// requests): signed by the app's secret with HS256, issued for the app, /// within its dates, from a shop. + /// + /// The tokens of Shopify admin and of UI extensions both verify: the + /// `dest` of an extension's token is the shop's domain without `https://`, + /// and it may have no `iss`. pub fn verify_session_token(&self, token: &str) -> Result { self.verify_session_token_at(token, Utc::now()) } @@ -509,8 +534,11 @@ impl ShopifyApp { .get("dest") .and_then(Value::as_str) .ok_or_else(|| invalid("the session token has no `dest`"))?; - let shop = destination - .strip_prefix("https://") + // `https://shop.myshopify.com` from Shopify admin, `shop.myshopify.com` from an extension. + let host = destination.strip_prefix("https://").unwrap_or(destination); + let shop = Some(host) + // A whole domain: a bare handle is not what Shopify writes. + .filter(|host| host.to_ascii_lowercase().ends_with(".myshopify.com")) .and_then(|host| ShopDomain::new(host).ok()) .ok_or_else(|| invalid("the `dest` of the session token is not a shop"))?; let issuer = claims.get("iss").and_then(Value::as_str); @@ -521,7 +549,7 @@ impl ShopifyApp { } let text = |name: &str| claims.get(name).and_then(Value::as_str).map(str::to_string); Ok(SessionToken { - user_id: text("sub"), + subject: text("sub"), session_id: text("sid"), expires_at: Utc .timestamp_opt(expires, 0) @@ -820,7 +848,7 @@ mod tests { .verify_session_token_at(&format!("Bearer {token}"), at(now)) .unwrap(); assert_eq!(session.shop().as_str(), "my-shop.myshopify.com"); - assert_eq!(session.user_id(), Some("42")); + assert_eq!(session.subject(), Some("42")); assert_eq!(session.expires_at(), at(now + 60)); assert_eq!(session.as_str(), token); diff --git a/crates/shopify_api/tests/oauth.rs b/crates/shopify_api/tests/oauth.rs index bec5b7f..341415d 100644 --- a/crates/shopify_api/tests/oauth.rs +++ b/crates/shopify_api/tests/oauth.rs @@ -125,3 +125,72 @@ async fn an_online_token_names_its_staff_member() { assert_eq!(user.first_name.as_deref(), Some("Ada")); assert_eq!(user.account_owner, Some(true)); } + +#[test] +fn a_checkout_extension_session_token_verifies() { + let app = ShopifyApp::new("client-id", "client-secret"); + let now = now(); + // As a checkout UI extension sends it: `dest` without `https://`, no `iss`, a customer. + let bearer = app.sign_session_token(&json!({ + "dest": "store-name.myshopify.com", + "aud": "client-id", + "exp": now + 60, + "nbf": now, + "iat": now, + "jti": "6c992878-dbaf-48d1-bb9d-6d9b59814fd1", + "sub": "gid://shopify/Customer/1", + })); + let session = app.verify_session_token(&bearer).unwrap(); + assert_eq!(session.shop().as_str(), "store-name.myshopify.com"); + assert_eq!(session.subject(), Some("gid://shopify/Customer/1")); + + // A bare handle, or another host, is still not a shop. + for dest in ["store-name", "store-name.example.com", "https://store-name"] { + let bearer = + app.sign_session_token(&json!({ "dest": dest, "aud": "client-id", "exp": now + 60 })); + assert!(app.verify_session_token(&bearer).is_err(), "{dest}"); + } +} + +#[derive(Default, Clone)] +struct Saved(std::sync::Arc>>); + +impl shopify_api::TokenStore for Saved { + fn save<'a>( + &'a self, + shop: &'a shopify_api::ShopDomain, + token: &'a shopify_api::TokenData, + ) -> shopify_api::transport::BoxFuture<'a, Result<(), Box>> + { + Box::pin(async move { + self.0 + .lock() + .unwrap() + .push((shop.to_string(), token.clone())); + Ok(()) + }) + } +} + +#[tokio::test] +async fn the_clients_of_an_app_save_their_renewed_tokens() { + let mock = MockTransport::new(); + mock.push_json( + json!({ "access_token": "shpat_2", "expires_in": 3600, "refresh_token": "shprt_2" }), + ); + mock.push_data(json!({ "shop": { "name": "My shop" } })); + let saved = Saved::default(); + let app = app(&mock).with_token_store(saved.clone()); + + let mut token = shopify_api::TokenData::new("shpat_1"); + token.expires_at = Some(chrono::Utc::now()); + token.refresh_token = Some("shprt_1".to_string()); + let shop = shopify_api::ShopDomain::new("my-shop").unwrap(); + let shopify = app.client(&shop, token).unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + + let saved = saved.0.lock().unwrap(); + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].0, "my-shop.myshopify.com"); + assert_eq!(saved[0].1.refresh_token.as_deref(), Some("shprt_2")); +} From 78ed6035d6c2a7edf506824cd17040c88a0837a1 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:35:39 +0100 Subject: [PATCH 075/135] fix(auth)!: send nothing until a renewed token is saved; keep the refresh token - A `TokenStore::save` that failed was never tried again: the store kept the refresh token Shopify had already rotated, and a restart could not refresh. The client now holds its lock through the save, and every call tries a failed save again first, failing with `Error::TokenStore` while it fails: no request goes out with a token that is not stored. - A refresh answer without `refresh_token` keeps the current refresh token and its expiry, instead of dropping them. - `TokenData::expires_within` takes a `std::time::Duration`, like `ShopifyBuilder::refresh_leeway`. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/auth.rs | 131 ++++++++++++++++++++----------- crates/shopify_api/src/client.rs | 7 +- crates/shopify_api/tests/auth.rs | 91 ++++++++++++++++++++- 3 files changed, 177 insertions(+), 52 deletions(-) diff --git a/crates/shopify_api/src/auth.rs b/crates/shopify_api/src/auth.rs index a0dbe9e..f84048f 100644 --- a/crates/shopify_api/src/auth.rs +++ b/crates/shopify_api/src/auth.rs @@ -166,13 +166,15 @@ impl TokenData { } /// The access token expires within `leeway`, or has expired. - pub fn expires_within(&self, leeway: chrono::Duration) -> bool { - self.expires_at - .is_some_and(|expires_at| match Utc::now().checked_add_signed(leeway) { - Some(limit) => expires_at <= limit, - // A leeway beyond the calendar: everything expires within it. - None => true, - }) + pub fn expires_within(&self, leeway: Duration) -> bool { + let limit = chrono::Duration::from_std(leeway) + .ok() + .and_then(|leeway| Utc::now().checked_add_signed(leeway)); + self.expires_at.is_some_and(|expires_at| match limit { + Some(limit) => expires_at <= limit, + // A leeway beyond the calendar: everything expires within it. + None => true, + }) } /// The refresh token is still valid, as far as is known. @@ -238,6 +240,11 @@ pub struct AssociatedUser { /// reuses them. An expiring offline token comes with a new refresh token /// each time: without a store, a restart is left with one that no longer works. /// +/// Until a renewed token is saved, the client sends nothing with it: the +/// request that renewed it, and every request after, first try the save +/// again, and fail with [`Error::TokenStore`] while it fails. A token +/// Shopify rotated is so never used before it is stored. +/// /// Saves run one at a time, in the order of the renewals, in a task of their /// own: a request that is cancelled does not cancel its save. A store must /// not call the client whose token it saves. @@ -409,17 +416,19 @@ pub(crate) struct Endpoint { /// refresh token Shopify rotated is never lost halfway. pub(crate) struct Tokens { kind: Arc, + /// Held through a renewal and its save: saves run in the order of the + /// renewals, and nothing reads a token that is not saved yet. state: Arc>, - /// Saves run in the order of the renewals, outside the lock of the state. - saves: Arc>, store: Option>, - leeway: chrono::Duration, + leeway: Duration, } struct State { token: Option, /// When the last renewal failed, and why. failure: Option<(Instant, String)>, + /// The token was renewed, and the store has not saved it yet. + unsaved: bool, } impl State { @@ -427,7 +436,7 @@ impl State { fn valid(&self) -> Option { self.token .as_ref() - .filter(|token| !token.expires_within(chrono::Duration::zero())) + .filter(|token| !token.expires_within(Duration::ZERO)) .map(|token| token.access_token.clone()) } @@ -440,19 +449,36 @@ impl State { } impl Tokens { - pub fn new(auth: Auth, store: Option>, leeway: chrono::Duration) -> Self { + pub fn new(auth: Auth, store: Option>, leeway: Duration) -> Self { Self { kind: Arc::new(auth.kind), state: Arc::new(Mutex::new(State { token: auth.token, failure: None, + unsaved: false, })), - saves: Arc::new(Mutex::new(())), store, leeway, } } + /// The state, once the token it holds is saved: a save that failed is + /// tried again first, in a task of its own. + async fn saved_state(&self, endpoint: &Arc) -> Result> { + let mut state = self.state.clone().lock_owned().await; + if !state.unsaved { + return Ok(state); + } + let store = self.store.clone(); + let endpoint = endpoint.clone(); + tokio::spawn(async move { + save(store.as_deref(), &endpoint.shop, &mut state).await?; + Ok(state) + }) + .await + .map_err(stopped)? + } + /// The token to send, obtained or renewed first when it is missing or /// about to expire. /// @@ -460,7 +486,7 @@ impl Tokens { /// yet is still sent, and the renewal is not tried again for /// [`RENEWAL_BACKOFF`]. pub async fn get(&self, endpoint: &Arc) -> Result { - let state = self.state.clone().lock_owned().await; + let state = self.saved_state(endpoint).await?; let still_valid = state.valid(); if let Some(token) = state.token.as_ref() { let renewable = !matches!(*self.kind, Kind::Static); @@ -502,7 +528,7 @@ impl Tokens { if matches!(*self.kind, Kind::Static) { return Ok(None); } - let state = self.state.clone().lock_owned().await; + let state = self.saved_state(endpoint).await?; if let Some(token) = state.token.as_ref() && token.access_token != rejected { @@ -519,8 +545,8 @@ impl Tokens { self.state.lock().await.token.clone() } - /// Obtains a new token in a task of its own, which keeps the lock of the - /// state until the token is in it, and saves it in the order of the renewals. + /// Obtains a new token and saves it, in a task of its own that keeps the + /// lock of the state throughout. async fn renew_locked( &self, mut state: OwnedMutexGuard, @@ -537,7 +563,6 @@ impl Tokens { let kind = self.kind.clone(); let endpoint = endpoint.clone(); let store = self.store.clone(); - let saves = self.saves.clone(); let renewal = tokio::spawn(async move { let token = match obtain(&kind, &state, &endpoint).await { Ok(token) => token, @@ -547,29 +572,35 @@ impl Tokens { } }; let access_token = token.access_token.clone(); - state.token = Some(token.clone()); + state.token = Some(token); state.failure = None; - let turn = saves.lock_owned().await; - drop(state); - let saved = match &store { - Some(store) => store - .save(&endpoint.shop, &token) - .await - .map_err(Error::TokenStore), - None => Ok(()), - }; - drop(turn); - saved.map(|()| access_token) + state.unsaved = true; + save(store.as_deref(), &endpoint.shop, &mut state).await?; + Ok(access_token) }); - renewal.await.map_err(|stopped| { - // A panic's message is not this crate's to show. - Error::auth(if stopped.is_panic() { - "the renewal of the token panicked" - } else { - "the renewal of the token was cancelled" - }) - })? + renewal.await.map_err(stopped)? + } +} + +/// Saves the token of `state` when it is not saved yet. +async fn save(store: Option<&dyn TokenStore>, shop: &ShopDomain, state: &mut State) -> Result<()> { + if let (Some(store), Some(token)) = (store, state.token.as_ref()) + && state.unsaved + { + store.save(shop, token).await.map_err(Error::TokenStore)?; } + state.unsaved = false; + Ok(()) +} + +/// The error of a renewal or a save whose task did not end. +fn stopped(error: tokio::task::JoinError) -> Error { + // A panic's message is not this crate's to show. + Error::auth(if error.is_panic() { + "the renewal of the token panicked" + } else { + "the renewal of the token was cancelled" + }) } /// An OAuth error code (RFC 6749, 5.2, and Shopify's) as an error shows it. @@ -618,10 +649,8 @@ async fn obtain(kind: &Kind, state: &State, endpoint: &Endpoint) -> Result { - let refresh_token = state - .token - .as_ref() - .filter(|token| token.can_refresh()) + let current = state.token.as_ref().filter(|token| token.can_refresh()); + let refresh_token = current .and_then(|token| token.refresh_token.clone()) .ok_or_else(|| { Error::auth(format!( @@ -636,14 +665,21 @@ async fn obtain(kind: &Kind, state: &State, endpoint: &Endpoint) -> Result Self { self.token_store = Some(Arc::new(store)); self @@ -412,8 +413,6 @@ impl ShopifyBuilder { Some(transport) => transport, None => default_transport()?, }; - let leeway = - chrono::Duration::from_std(self.refresh_leeway).unwrap_or(chrono::Duration::MAX); Ok(Shopify { shared: Arc::new(Shared { endpoint: Arc::new(Endpoint { @@ -421,7 +420,7 @@ impl ShopifyBuilder { shop, user_agent: self.user_agent, }), - tokens: Tokens::new(auth, self.token_store, leeway), + tokens: Tokens::new(auth, self.token_store, self.refresh_leeway), }), pinned: self.api_version, retry: self.retry, diff --git a/crates/shopify_api/tests/auth.rs b/crates/shopify_api/tests/auth.rs index ff8e01b..5bff0df 100644 --- a/crates/shopify_api/tests/auth.rs +++ b/crates/shopify_api/tests/auth.rs @@ -465,5 +465,94 @@ async fn a_token_that_never_expires_in_practice_is_read() { token.expires_at, Some(chrono::DateTime::::MAX_UTC) ); - assert!(!token.expires_within(chrono::Duration::days(365))); + assert!(!token.expires_within(std::time::Duration::from_secs(365 * 86_400))); +} + +/// Fails the first `failures` saves, then saves. +#[derive(Clone)] +struct Flaky { + failures: Arc>, + saved: Saved, +} + +impl TokenStore for Flaky { + fn save<'a>( + &'a self, + shop: &'a ShopDomain, + token: &'a TokenData, + ) -> BoxFuture<'a, Result<(), Box>> { + let mut failures = self.failures.lock().unwrap(); + if *failures > 0 { + *failures -= 1; + return Box::pin(async { Err("the database is down".into()) }); + } + self.saved.save(shop, token) + } +} + +#[tokio::test] +async fn nothing_is_sent_until_a_renewed_token_is_saved() { + let mock = MockTransport::new(); + shopify_like(&mock, 3600, vec![]); + let store = Flaky { + failures: Arc::new(Mutex::new(2)), + saved: Saved::default(), + }; + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + let shopify = builder(&mock) + .auth(Auth::expiring_token("id", "secret", stored)) + .token_store(store.clone()) + .build() + .unwrap(); + + // The renewal works, its save fails: nothing is sent, now or on the next call. + for _ in 0..2 { + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(matches!(error, Error::TokenStore(_)), "{error:?}"); + assert!(mock.graphql_requests().is_empty()); + } + // The save goes through: the token it saved is the one sent. + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(token_requests(&mock).len(), 1, "renewed once"); + let saved = store.saved.0.lock().unwrap(); + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].1.refresh_token.as_deref(), Some("shprt_1")); + assert_eq!( + mock.graphql_requests()[0].access_token.as_deref(), + Some("shpat_1") + ); +} + +#[tokio::test] +async fn a_refresh_without_a_new_refresh_token_keeps_the_current_one() { + let mock = MockTransport::new(); + mock.respond_with(|request: &HttpRequest| { + if request.url == TOKEN_URL { + return Ok(HttpResponse::json( + 200, + &json!({ "access_token": "shpat_new", "expires_in": 3600 }), + )); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + let refresh_expires = chrono::Utc::now() + chrono::Duration::days(30); + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + stored.refresh_token_expires_at = Some(refresh_expires); + let shopify = builder(&mock) + .auth(Auth::expiring_token("id", "secret", stored)) + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + let token = shopify.token().await.unwrap(); + assert_eq!(token.access_token, "shpat_new"); + assert_eq!(token.refresh_token.as_deref(), Some("shprt_old")); + assert_eq!(token.refresh_token_expires_at, Some(refresh_expires)); } From 09065c5fae4163a5c3127d47164419750659db90 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:35:57 +0100 Subject: [PATCH 076/135] fix(bulk)!: serialize statuses as Shopify writes them; errors keep the operation - `BulkOperationStatus` and `BulkOperationType` serialize as `"COMPLETED"`, and `Other(s)` as `s`, and read back what Shopify writes: a stored `BulkOperation` round-trips. Both gain `as_str`. - `Error::Bulk { message, operation }`: an operation that ended without completing is in the error, with its `error_code` and `partial_data_url`. - `Error::Timeout { message, id }`: the ID of the bulk operation waited for, which keeps running, to cancel it. - `BulkOperation::created_at` and `completed_at` are `DateTime`. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk.rs | 202 +++++++++++++++++++++++----- crates/shopify_api/src/bulk/rows.rs | 8 +- crates/shopify_api/src/error.rs | 55 ++++++-- crates/shopify_api/tests/bulk.rs | 18 ++- 4 files changed, 230 insertions(+), 53 deletions(-) diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 58c88ad..553b887 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -46,6 +46,7 @@ use std::time::Duration; +use chrono::{DateTime, Utc}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use tokio::time::Instant; @@ -84,8 +85,9 @@ pub struct BulkOperation { pub status: BulkOperationStatus, /// Why it failed: `ACCESS_DENIED`, `INTERNAL_SERVER_ERROR`, `TIMEOUT`. pub error_code: Option, - pub created_at: String, - pub completed_at: Option, + pub created_at: DateTime, + /// When it completed, failed or was canceled. + pub completed_at: Option>, /// The objects written so far, nested ones included. pub object_count: u64, /// The top-level objects written so far. @@ -121,7 +123,9 @@ impl std::fmt::Debug for BulkOperation { } /// The status of a bulk operation. A status Shopify adds later is `Other`. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +/// +/// It serializes as Shopify writes it: `"COMPLETED"`, and `Other` as its text. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum BulkOperationStatus { Created, @@ -149,6 +153,20 @@ impl BulkOperationStatus { } } + /// As Shopify writes it: `COMPLETED`. + pub fn as_str(&self) -> &str { + match self { + Self::Created => "CREATED", + Self::Running => "RUNNING", + Self::Completed => "COMPLETED", + Self::Canceling => "CANCELING", + Self::Canceled => "CANCELED", + Self::Failed => "FAILED", + Self::Expired => "EXPIRED", + Self::Other(other) => other, + } + } + fn parse(value: &str) -> Self { match value { "CREATED" => Self::Created, @@ -171,7 +189,10 @@ impl BulkOperationStatus { } } -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +/// The type of a bulk operation. A type Shopify adds later is `Other`. +/// +/// It serializes as Shopify writes it: `"QUERY"`, and `Other` as its text. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum BulkOperationType { Query, @@ -180,6 +201,15 @@ pub enum BulkOperationType { } impl BulkOperationType { + /// As Shopify writes it: `QUERY`. + pub fn as_str(&self) -> &str { + match self { + Self::Query => "QUERY", + Self::Mutation => "MUTATION", + Self::Other(other) => other, + } + } + fn parse(value: &str) -> Self { match value { "QUERY" => Self::Query, @@ -189,6 +219,26 @@ impl BulkOperationType { } } +/// Serde as Shopify writes the enum: its text, an unknown one as `Other`. +macro_rules! wire_serde { + ($($type:ty),*) => {$( + impl Serialize for $type { + fn serialize(&self, serializer: S) -> std::result::Result { + serializer.serialize_str(self.as_str()) + } + } + + impl<'de> Deserialize<'de> for $type { + fn deserialize>(deserializer: D) -> std::result::Result { + let text = std::borrow::Cow::::deserialize(deserializer)?; + Ok(Self::parse(&text)) + } + } + )*}; +} + +wire_serde!(BulkOperationStatus, BulkOperationType); + /// The selection every operation of this module makes on `BulkOperation`, /// as Shopify sends it. #[derive(Deserialize)] @@ -199,8 +249,8 @@ struct Wire { kind: String, status: String, error_code: Option, - created_at: String, - completed_at: Option, + created_at: DateTime, + completed_at: Option>, object_count: String, root_object_count: String, file_size: Option, @@ -215,7 +265,7 @@ impl Wire { value .parse::() // The value is not shown: it is the answer's. - .map_err(|_| Error::Bulk(format!("`{field}` is not an unsigned integer"))) + .map_err(|_| bulk_error(format!("`{field}` is not an unsigned integer"))) }; Ok(BulkOperation { object_count: number("objectCount", &self.object_count)?, @@ -238,9 +288,17 @@ impl Wire { } } +/// An [`Error::Bulk`] without an operation. +pub(crate) fn bulk_error(message: impl Into) -> Error { + Error::Bulk { + message: message.into(), + operation: None, + } +} + /// The ID of a bulk operation as an error shows it: a `gid://` of Shopify, /// else nothing of the text. -fn shown_id(id: &str) -> &str { +pub(crate) fn shown_id(id: &str) -> &str { let shown = id .strip_prefix("gid://shopify/BulkOperation/") .is_some_and(|number| { @@ -249,26 +307,50 @@ fn shown_id(id: &str) -> &str { if shown { id } else { "[id not shown]" } } +/// What `Debug` of an [`Error::Bulk`] shows of its operation: what its +/// message shows. +pub(crate) struct ShownOperation<'a>(pub &'a BulkOperation); + +impl std::fmt::Debug for ShownOperation<'_> { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("BulkOperation") + .field("id", &shown_id(&self.0.id)) + .field("status", &self.0.status.shown()) + .field( + "error_code", + &self.0.error_code.as_deref().map(shown_error_code), + ) + .finish_non_exhaustive() + } +} + /// The error of an operation that ended without completing. -pub(crate) fn not_completed(operation: &BulkOperation) -> Error { - Error::Bulk(format!( - "the bulk operation {} ended {}{}", - shown_id(&operation.id), - operation.status.shown(), - operation - .error_code - .as_deref() - .map(|code| format!(" ({})", shown_error_code(code))) - .unwrap_or_default() - )) +pub(crate) fn not_completed(operation: BulkOperation) -> Error { + Error::Bulk { + message: format!( + "the bulk operation {} ended {}{}", + shown_id(&operation.id), + operation.status.shown(), + operation + .error_code + .as_deref() + .map(|code| format!(" ({})", shown_error_code(code))) + .unwrap_or_default() + ), + operation: Some(Box::new(operation)), + } } /// The error of a wait that ran out. pub(crate) fn timed_out(id: &str, timeout: Duration) -> Error { - Error::Timeout(format!( - "the bulk operation {} did not end within {timeout:?}", - shown_id(id) - )) + Error::Timeout { + message: format!( + "the bulk operation {} did not end within {timeout:?}", + shown_id(id) + ), + id: Some(id.to_string()), + } } /// A `BulkOperationErrorCode` as an error shows it. @@ -399,7 +481,7 @@ impl Shopify { .await?; let payload = data .bulk_operation_run_query - .ok_or_else(|| Error::Bulk("bulkOperationRunQuery returned nothing".to_string()))?; + .ok_or_else(|| bulk_error("bulkOperationRunQuery returned nothing".to_string()))?; started( "bulkOperationRunQuery", payload.bulk_operation, @@ -489,7 +571,7 @@ impl Shopify { .await?; let payload = data .bulk_operation_run_mutation - .ok_or_else(|| Error::Bulk("bulkOperationRunMutation returned nothing".to_string()))?; + .ok_or_else(|| bulk_error("bulkOperationRunMutation returned nothing".to_string()))?; started( "bulkOperationRunMutation", payload.bulk_operation, @@ -528,7 +610,7 @@ impl Shopify { .await?; let payload = data .staged_uploads_create - .ok_or_else(|| Error::Bulk("stagedUploadsCreate returned nothing".to_string()))?; + .ok_or_else(|| bulk_error("stagedUploadsCreate returned nothing".to_string()))?; let errors = user_errors(&payload.user_errors)?; if !errors.is_empty() { return Err(Error::UserErrors { @@ -541,10 +623,10 @@ impl Shopify { .into_iter() .flatten() .next() - .ok_or_else(|| Error::Bulk("stagedUploadsCreate returned no target".to_string()))?; + .ok_or_else(|| bulk_error("stagedUploadsCreate returned no target".to_string()))?; let url = target .url - .ok_or_else(|| Error::Bulk("the staged upload target has no address".to_string()))?; + .ok_or_else(|| bulk_error("the staged upload target has no address".to_string()))?; let parameters: Vec<(String, String)> = target .parameters .into_iter() @@ -555,7 +637,7 @@ impl Shopify { .find(|(name, _)| name == "key") .map(|(_, value)| value.clone()) .ok_or_else(|| { - Error::Bulk("the staged upload target has no `key` parameter".to_string()) + bulk_error("the staged upload target has no `key` parameter".to_string()) })?; // The storage server wants the length of the body up front: the @@ -627,7 +709,7 @@ impl Shopify { .await?; let payload = data .bulk_operation_cancel - .ok_or_else(|| Error::Bulk("bulkOperationCancel returned nothing".to_string()))?; + .ok_or_else(|| bulk_error("bulkOperationCancel returned nothing".to_string()))?; started( "bulkOperationCancel", payload.bulk_operation, @@ -653,7 +735,7 @@ impl Shopify { } tokio::time::sleep(wait).await; let operation = self.bulk_operation(id).await?.ok_or_else(|| { - Error::Bulk(format!( + bulk_error(format!( "the bulk operation {} does not exist", shown_id(id) )) @@ -791,7 +873,7 @@ impl Shopify { async fn completed_url(&self, id: &str, options: BulkWaitOptions) -> Result> { let operation = self.wait_for_bulk_operation(id, options).await?; if operation.status != BulkOperationStatus::Completed { - return Err(not_completed(&operation)); + return Err(not_completed(operation)); } Ok(operation.url) } @@ -868,7 +950,7 @@ fn started( return Err(Error::UserErrors { mutation, errors }); } let operation = - operation.ok_or_else(|| Error::Bulk(format!("{mutation} returned no operation")))?; + operation.ok_or_else(|| bulk_error(format!("{mutation} returned no operation")))?; operation_of(&operation) } @@ -929,7 +1011,7 @@ mod tests { kind: BulkOperationType::Query, status: BulkOperationStatus::Completed, error_code: None, - created_at: "2026-10-22T10:00:00Z".to_string(), + created_at: "2026-10-22T10:00:00Z".parse().unwrap(), completed_at: None, object_count: 0, root_object_count: 0, @@ -992,6 +1074,58 @@ mod tests { ); } + #[test] + fn statuses_and_types_serialize_as_shopify_writes_them() { + for (status, text) in [ + (BulkOperationStatus::Completed, "\"COMPLETED\""), + (BulkOperationStatus::Canceling, "\"CANCELING\""), + ( + BulkOperationStatus::Other("PAUSED".to_string()), + "\"PAUSED\"", + ), + ] { + assert_eq!(serde_json::to_string(&status).unwrap(), text); + assert_eq!( + serde_json::from_str::(text).unwrap(), + status + ); + } + for (kind, text) in [ + (BulkOperationType::Mutation, "\"MUTATION\""), + (BulkOperationType::Other("EXPORT".to_string()), "\"EXPORT\""), + ] { + assert_eq!(serde_json::to_string(&kind).unwrap(), text); + assert_eq!( + serde_json::from_str::(text).unwrap(), + kind + ); + } + // A stored operation reads back as it was. + let operation = operation_of(&serde_json::json!({ + "id": "gid://shopify/BulkOperation/1", + "type": "QUERY", + "status": "FAILED", + "errorCode": "TIMEOUT", + "createdAt": "2026-10-22T10:00:00Z", + "completedAt": "2026-10-22T10:05:00Z", + "objectCount": "3", + "rootObjectCount": "1", + "fileSize": null, + "url": null, + "partialDataUrl": null, + "query": "{ shop { id } }", + })) + .unwrap(); + let stored = serde_json::to_value(&operation).unwrap(); + assert_eq!(stored["status"], "FAILED"); + assert_eq!(stored["kind"], "QUERY"); + assert_eq!(stored["created_at"], "2026-10-22T10:00:00Z"); + assert_eq!( + serde_json::from_value::(stored).unwrap(), + operation + ); + } + #[test] fn statuses_say_when_they_end() { assert!(BulkOperationStatus::parse("COMPLETED").is_terminal()); diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index e1c4dfe..2505a53 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -83,7 +83,7 @@ impl Lines { fn too_long(&mut self, line: usize) -> Error { self.finish(); - Error::Bulk(format!( + super::bulk_error(format!( "line {line} of the results is longer than {} bytes", self.max )) @@ -387,7 +387,7 @@ impl BulkGroups { } else { "is a child of neither the top-level object before it nor one of its children: run the query with `groupObjects`" }; - Error::Bulk(format!("line {number} of the results {message}")) + super::bulk_error(format!("line {number} of the results {message}")) } /// [`BulkRows::max_line_length`]. @@ -649,7 +649,7 @@ mod tests { BulkRows::new(Some(chunks(endless)), "https://storage.test/r.jsonl") .max_line_length(1024 * 1024); let error = rows.next_row().await.unwrap().unwrap_err(); - assert!(matches!(error, Error::Bulk(_)), "{error:?}"); + assert!(matches!(error, Error::Bulk { .. }), "{error:?}"); assert!(rows.next_row().await.is_none()); } @@ -886,7 +886,7 @@ mod tests { ] { let groups = all_groups(groups_of(body)).await; assert_eq!(groups.len(), 1, "{body}"); - assert!(matches!(groups[0], Err(Error::Bulk(_))), "{body}"); + assert!(matches!(groups[0], Err(Error::Bulk { .. })), "{body}"); } } diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index 5a41af6..d583372 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -2,6 +2,7 @@ use std::fmt; +use crate::bulk::BulkOperation; use crate::graphql::{Cost, GraphqlError, InvalidValueReason, UserError}; use crate::transport::{HttpResponse, TransportError}; @@ -70,10 +71,7 @@ pub enum Error { /// Not an API version this crate supports. `version` is shown only when /// it is written `YYYY-MM`. #[non_exhaustive] - InvalidApiVersion { - version: String, - reason: String, - }, + InvalidApiVersion { version: String, reason: String }, /// The request did not reach Shopify, or its answer did not arrive. #[non_exhaustive] @@ -178,9 +176,24 @@ pub enum Error { }, /// A bulk operation failed, or its answer misses what was expected. - Bulk(String), + #[non_exhaustive] + Bulk { + message: String, + /// The operation as Shopify last reported it, when it ended without + /// completing: its `error_code`, its `partial_data_url`. `Debug` + /// shows its ID, status and error code as `message` does. + operation: Option>, + }, - Timeout(String), + /// A wait ran out. + #[non_exhaustive] + Timeout { + message: String, + /// The bulk operation waited for, which keeps running: to cancel it + /// with [`Shopify::cancel_bulk_operation`](crate::Shopify::cancel_bulk_operation). + /// `Debug` shows it when it is a `gid://` of Shopify. + id: Option, + }, /// The [`TokenStore`](crate::TokenStore) of the client failed to save a /// renewed token. The client holds the new token all the same. @@ -236,8 +249,8 @@ impl fmt::Display for Error { Self::UserErrors { mutation, errors } => { write!(formatter, "{mutation} refused: {}", UserErrors(errors)) } - Self::Bulk(message) => write!(formatter, "bulk operation: {message}"), - Self::Timeout(message) => write!(formatter, "timed out: {message}"), + Self::Bulk { message, .. } => write!(formatter, "bulk operation: {message}"), + Self::Timeout { message, .. } => write!(formatter, "timed out: {message}"), Self::TokenStore(error) => write!(formatter, "the token store failed: {error}"), Self::NoTransport => formatter.write_str( "no HTTP transport: enable the `rustls` or `native-tls` feature, or set one with `ShopifyBuilder::transport`", @@ -341,8 +354,19 @@ impl fmt::Debug for Error { .field("mutation", mutation) .field("errors", errors) .finish(), - Self::Bulk(message) => formatter.debug_tuple("Bulk").field(message).finish(), - Self::Timeout(message) => formatter.debug_tuple("Timeout").field(message).finish(), + Self::Bulk { message, operation } => formatter + .debug_struct("Bulk") + .field("message", message) + .field( + "operation", + &operation.as_deref().map(crate::bulk::ShownOperation), + ) + .finish(), + Self::Timeout { message, id } => formatter + .debug_struct("Timeout") + .field("message", message) + .field("id", &id.as_deref().map(crate::bulk::shown_id)) + .finish(), Self::TokenStore(error) => formatter.debug_tuple("TokenStore").field(error).finish(), Self::NoTransport => formatter.write_str("NoTransport"), Self::Verification(message) => formatter @@ -914,9 +938,12 @@ mod tests { "query": "{ shop { id } }", })) .unwrap(); - errors.push(("Bulk ended", crate::bulk::not_completed(&operation))); + errors.push(("Bulk ended", crate::bulk::not_completed(operation.clone()))); operation.id = format!("gid://shopify/BulkOperation/{TOKEN}"); - errors.push(("Bulk ended, odd id", crate::bulk::not_completed(&operation))); + errors.push(( + "Bulk ended, odd id", + crate::bulk::not_completed(operation.clone()), + )); errors.push(( "Timeout", crate::bulk::timed_out(TOKEN, std::time::Duration::from_secs(1)), @@ -1070,8 +1097,8 @@ mod tests { Error::InvalidValue { .. } => "InvalidValue", Error::Auth { .. } => "Auth", Error::UserErrors { .. } => "UserErrors", - Error::Bulk(_) => "Bulk", - Error::Timeout(_) => "Timeout", + Error::Bulk { .. } => "Bulk", + Error::Timeout { .. } => "Timeout", Error::TokenStore(_) => "TokenStore", Error::NoTransport => "NoTransport", Error::Verification(_) => "Verification", diff --git a/crates/shopify_api/tests/bulk.rs b/crates/shopify_api/tests/bulk.rs index 9e4f3d6..00415f5 100644 --- a/crates/shopify_api/tests/bulk.rs +++ b/crates/shopify_api/tests/bulk.rs @@ -127,6 +127,7 @@ async fn a_failed_operation_is_an_error() { mock.push_data(json!({ "bulkOperationRunQuery": { "bulkOperation": operation("CREATED", None), "userErrors": [] } })); let mut failed = operation("FAILED", None); failed["errorCode"] = json!("ACCESS_DENIED"); + failed["partialDataUrl"] = json!(RESULTS_URL); mock.push_data(json!({ "bulkOperation": failed })); let shopify = client(&mock); @@ -138,6 +139,17 @@ async fn a_failed_operation_is_an_error() { error.to_string(), "bulk operation: the bulk operation gid://shopify/BulkOperation/1 ended Failed (ACCESS_DENIED)" ); + // The operation stays reachable: what failed, and what was written before. + let Error::Bulk { + operation: Some(operation), + .. + } = error + else { + panic!("{error:?}"); + }; + assert_eq!(operation.status, BulkOperationStatus::Failed); + assert_eq!(operation.error_code.as_deref(), Some("ACCESS_DENIED")); + assert_eq!(operation.partial_data_url.as_deref(), Some(RESULTS_URL)); } #[tokio::test] @@ -260,7 +272,11 @@ async fn waiting_gives_up_after_its_timeout() { ) .await .unwrap_err(); - assert!(matches!(error, Error::Timeout(_)), "{error:?}"); + // The ID, to cancel the operation that keeps running. + let Error::Timeout { id, .. } = &error else { + panic!("{error:?}"); + }; + assert_eq!(id.as_deref(), Some("gid://shopify/BulkOperation/1")); // 1 + 2 + 4 + 8 + 10 seconds, then the 5 that are left. assert_eq!(mock.requests().len(), 6); } From 1feeede8b8a393752b866e331a71840fe4edd3bc Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:36:03 +0100 Subject: [PATCH 077/135] fix(retry): draw the jitter from `RandomState`, not the clock The jitter took the nanoseconds of `SystemTime` modulo 1000: macOS gives microseconds, so it was always 0 there, and every client retried in step. It now comes from the random keys of std's `RandomState`. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/client.rs | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index 74a7431..73440c0 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -289,13 +289,15 @@ impl Default for RetryPolicy { } } -/// A fraction in `[0, 1)`, from the clock: retries need no better randomness. +/// A fraction in `[0, 1)`, from the random keys of std's `RandomState`: retries +/// need no better randomness. Not from the clock: macOS gives microseconds, +/// whose nanoseconds are always zero. fn jitter_fraction() -> f64 { - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|elapsed| elapsed.subsec_nanos()) - .unwrap_or_default(); - f64::from(nanos % 1000) / 1000.0 + use std::hash::BuildHasher; + // Each `RandomState` has keys of its own: hashing nothing is random enough. + let bits = std::collections::hash_map::RandomState::new().hash_one(()); + // The top 53 bits, the precision of an `f64`. + (bits >> 11) as f64 / (1u64 << 53) as f64 } /// Builds a [`Shopify`] client. @@ -451,6 +453,21 @@ mod tests { within(30, 1000, 1000); } + #[test] + fn the_jitter_varies() { + let fractions: Vec = (0..64).map(|_| jitter_fraction()).collect(); + assert!( + fractions + .iter() + .all(|fraction| (0.0..1.0).contains(fraction)) + ); + let mut distinct = fractions.clone(); + distinct.sort_by(f64::total_cmp); + distinct.dedup(); + // 64 draws of 53 bits: a repeat is as likely as a cosmic ray. + assert_eq!(distinct.len(), fractions.len(), "{fractions:?}"); + } + #[test] fn a_throttled_request_waits_for_its_cost() { let retry = RetryPolicy::default(); From eeb082c213fed5526b3d389e48fba1b3ce641495 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:36:03 +0100 Subject: [PATCH 078/135] fix!: leave room to grow in `Cost`, `ThrottleStatus` and `OperationKind` `Cost` and `ThrottleStatus` are no longer `Copy`, so that a field without `Copy` (the per-field costs of the cost debug mode) can come in a minor release. `OperationKind` is `#[non_exhaustive]`. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/client.rs | 5 ++++- crates/shopify_api/src/graphql/operation.rs | 1 + crates/shopify_api/src/graphql/response.rs | 4 ++-- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index 73440c0..1b1591d 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -480,7 +480,10 @@ mod tests { restore_rate: 100.0, }, }; - assert_eq!(retry.throttled(0, Some(cost)), Duration::from_millis(2100)); + assert_eq!( + retry.throttled(0, Some(cost.clone())), + Duration::from_millis(2100) + ); let far = crate::graphql::Cost { requested_query_cost: 20000.0, ..cost diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs index 63746e2..c24fd1d 100644 --- a/crates/shopify_api/src/graphql/operation.rs +++ b/crates/shopify_api/src/graphql/operation.rs @@ -12,6 +12,7 @@ use crate::{ApiVersion, Error, Result}; /// A query or a mutation. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[non_exhaustive] pub enum OperationKind { Query, Mutation, diff --git a/crates/shopify_api/src/graphql/response.rs b/crates/shopify_api/src/graphql/response.rs index 15b8f2a..80c2bb9 100644 --- a/crates/shopify_api/src/graphql/response.rs +++ b/crates/shopify_api/src/graphql/response.rs @@ -86,7 +86,7 @@ pub struct UserError { /// The cost of a query and the state of the shop's rate limit, from /// `extensions.cost`. -#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct Cost { @@ -96,7 +96,7 @@ pub struct Cost { pub throttle_status: ThrottleStatus, } -#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct ThrottleStatus { From db7df51bca458ffdca96b00aa1fb3d39d81e7b15 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:38:18 +0100 Subject: [PATCH 079/135] build: ship the license, build the published crates offline, publish them at once - Each of the three packages includes `LICENSE.txt` (a link to the root's). - `shopify_api` ships `graphql/admin.schema.json` (138 KiB compressed), which its doctests read, and no longer its tests and examples, which need the repository: `cargo test` of the published crate runs offline. - The workspace requires chrono 0.4.39: 0.4.38 failed to build the client (`TimeDelta::MAX`), and nothing older is tested. - `cargo update -p ctutils`: 0.4.6 clears RUSTSEC-2026-0385. - CI runs `cargo package --workspace --locked` and `mise run audit` (cargo audit, cargo deny), and the release `cargo publish --workspace`, so that a failure publishes none of the three. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 21 +++++++++++++++++++++ .github/workflows/publish.yml | 11 +++-------- Cargo.lock | 4 ++-- Cargo.toml | 2 +- crates/shopify_api/Cargo.toml | 9 +++++---- crates/shopify_api/LICENSE.txt | 1 + crates/shopify_api_graphql/Cargo.toml | 2 +- crates/shopify_api_graphql/LICENSE.txt | 1 + crates/shopify_api_macros/Cargo.toml | 2 +- crates/shopify_api_macros/LICENSE.txt | 1 + 10 files changed, 37 insertions(+), 17 deletions(-) create mode 120000 crates/shopify_api/LICENSE.txt create mode 120000 crates/shopify_api_graphql/LICENSE.txt create mode 120000 crates/shopify_api_macros/LICENSE.txt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f6d09cc..dca982e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,8 @@ jobs: - check - features - msrv + - package + - audit steps: - run: exit 0 @@ -53,3 +55,22 @@ jobs: - uses: dtolnay/rust-toolchain@1.88 - uses: Swatinem/rust-cache@v2 - run: cargo check --workspace --all-features --locked + + # What `cargo publish --workspace` uploads: each crate builds from its own + # files, with the license, and nothing that needs the network. + package: + name: cargo package + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: jdx/mise-action@v5 + - uses: Swatinem/rust-cache@v2 + - run: cargo package --workspace --locked + + audit: + name: advisories, licenses, sources + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: jdx/mise-action@v5 + - run: mise run audit diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1d65227..b7421e7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -22,13 +22,8 @@ jobs: steps: - uses: actions/checkout@v7 - uses: jdx/mise-action@v5 - # In dependency order: the schema and checker, the macro, then the client. - - run: cargo publish --locked -p shopify_api_graphql - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} - - run: cargo publish --locked -p shopify_api_macros - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} - - run: cargo publish --locked -p shopify_api + # The three crates at once, in dependency order: when one fails to + # build, none is published. + - run: cargo publish --workspace --locked env: CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} diff --git a/Cargo.lock b/Cargo.lock index b727f34..6149bcd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -304,9 +304,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.3" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a" dependencies = [ "cmov", ] diff --git a/Cargo.toml b/Cargo.toml index 5493d8d..88d2c57 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,7 +22,7 @@ shopify_api_graphql = { path = "crates/shopify_api_graphql", version = "=1.0.0" shopify_api_macros = { path = "crates/shopify_api_macros", version = "=1.0.0" } base64 = "0.23" -chrono = { version = "0.4", default-features = false, features = ["clock", "serde", "std"] } +chrono = { version = "0.4.39", default-features = false, features = ["clock", "serde", "std"] } clap = { version = "4.6", features = ["derive", "env"] } futures-core = { version = "0.3.31", default-features = false } graphql-parser = "0.4" diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index 954f585..e9f8034 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -11,16 +11,17 @@ rust-version.workspace = true license.workspace = true repository.workspace = true authors.workspace = true -# `graphql/admin.schema.json`, the whole Admin schema the tests use, stays -# out: the crate's own operations need only `graphql/internal.schema.json`. +# What `cargo test` of the published crate needs, offline: the sources and +# their doctests, which read the Admin schema of `graphql/`. The tests and the +# examples stay in the repository: they need its other files and toolchain. include = [ "src/**", "docs/**", - "tests/**", - "examples/**", + "graphql/admin.schema.json", "graphql/internal.schema.json", "graphql/operations/**", "Cargo.toml", + "LICENSE.txt", ] # The version of the tests, the examples and `graphql/internal.schema.json`. diff --git a/crates/shopify_api/LICENSE.txt b/crates/shopify_api/LICENSE.txt new file mode 120000 index 0000000..1ef648f --- /dev/null +++ b/crates/shopify_api/LICENSE.txt @@ -0,0 +1 @@ +../../LICENSE.txt \ No newline at end of file diff --git a/crates/shopify_api_graphql/Cargo.toml b/crates/shopify_api_graphql/Cargo.toml index 050d412..152e45f 100644 --- a/crates/shopify_api_graphql/Cargo.toml +++ b/crates/shopify_api_graphql/Cargo.toml @@ -11,7 +11,7 @@ rust-version.workspace = true license.workspace = true repository.workspace = true authors.workspace = true -include = ["src/**", "Cargo.toml", "README.md"] +include = ["src/**", "Cargo.toml", "README.md", "LICENSE.txt"] [dependencies] graphql-parser.workspace = true diff --git a/crates/shopify_api_graphql/LICENSE.txt b/crates/shopify_api_graphql/LICENSE.txt new file mode 120000 index 0000000..1ef648f --- /dev/null +++ b/crates/shopify_api_graphql/LICENSE.txt @@ -0,0 +1 @@ +../../LICENSE.txt \ No newline at end of file diff --git a/crates/shopify_api_macros/Cargo.toml b/crates/shopify_api_macros/Cargo.toml index c6e2681..594ff1d 100644 --- a/crates/shopify_api_macros/Cargo.toml +++ b/crates/shopify_api_macros/Cargo.toml @@ -11,7 +11,7 @@ rust-version.workspace = true license.workspace = true repository.workspace = true authors.workspace = true -include = ["src/**", "Cargo.toml", "README.md"] +include = ["src/**", "Cargo.toml", "README.md", "LICENSE.txt"] [lib] proc-macro = true diff --git a/crates/shopify_api_macros/LICENSE.txt b/crates/shopify_api_macros/LICENSE.txt new file mode 120000 index 0000000..1ef648f --- /dev/null +++ b/crates/shopify_api_macros/LICENSE.txt @@ -0,0 +1 @@ +../../LICENSE.txt \ No newline at end of file From 644572cd656894ac166d0424c710e3351f856a08 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:44:08 +0100 Subject: [PATCH 080/135] docs: the Tokio runtime, the `full` feature, the shop check of destructive webhooks The README and the crate docs say the client needs Tokio, list `full` (every feature but `native-tls`), show `&HeaderMap` and `verify_payload_shop` in the webhook example, and `with_token_store` in the OAuth one. Co-Authored-By: Claude Opus 5.5 --- README.md | 26 ++++++++++++++++++-------- crates/shopify_api/src/lib.rs | 6 +++++- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 405fd25..acec458 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,8 @@ shopify_api = "1" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` -Rust 1.88 or newer. The first build downloads the Admin schema of the latest +Rust 1.88 or newer, and a Tokio runtime: the default transport and the token +renewals run on Tokio. The first build downloads the Admin schema of the latest stable version into `graphql/admin.schema.json`, next to your `Cargo.toml`: commit it. @@ -375,10 +376,18 @@ Feature `webhooks`: ```rust,ignore use shopify_api::webhooks::{Webhook, WebhookSubscriptionSpec}; -// In your HTTP handler, on the raw body. -let webhook = Webhook::verify(headers, body, client_secret)?; -if webhook.topic() == "orders/create" { - let order: MyOrder = webhook.payload()?; +// In your HTTP handler, on the raw body. `headers`: an `&http::HeaderMap` +// (axum, actix, warp), or any (name, value) pairs. +let webhook = Webhook::verify(&headers, body, client_secret)?; +match webhook.topic() { + "orders/create" => { + let order: MyOrder = webhook.payload()?; + } + "app/uninstalled" | "shop/redact" | "customers/redact" => { + // The signature covers the body, not the headers: check the shop. + webhook.verify_payload_shop()?; + } + _ => {} } // Make the shop's subscriptions exactly these. @@ -395,7 +404,8 @@ Feature `oauth`: ```rust,ignore use shopify_api::oauth::{RequestedToken, ShopifyApp}; -let app = ShopifyApp::new(client_id, client_secret); +// The clients it builds save the tokens they renew. +let app = ShopifyApp::new(client_id, client_secret).with_token_store(MyDatabase); // Embedded app: the session token of each request, exchanged for a token. let session = app.verify_session_token(bearer)?; @@ -433,9 +443,9 @@ assert_eq!(mock.graphql_requests()[0].operation_name.as_deref(), Some("Shop")); | `native-tls` | The same over the platform's TLS. | | `webhooks` | Webhook verification, parsing and subscriptions. | | `oauth` | Install links, callbacks, token exchange, session tokens, app proxies. | -| `testing` | `MockTransport`. | +| `testing` | `MockTransport`, and the signing helpers of tests. | | `cli` | The `shopify-api` command. | -| `full` | All of the above. | +| `full` | Every feature but `native-tls`: `webhooks`, `oauth`, `testing`, `cli`, over rustls. | Without `rustls` or `native-tls`, give the client your own `Transport`. diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index 12a9ae7..2c39862 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -49,8 +49,12 @@ //! | `native-tls` | The same over the platform's TLS. | //! | `webhooks` | [`webhooks`]: verification, parsing, subscriptions. | //! | `oauth` | [`oauth`]: install links, callbacks, token exchange, session tokens, app proxies. | -//! | `testing` | [`testing::MockTransport`]. | +//! | `testing` | [`testing::MockTransport`], and the signing helpers of tests. | //! | `cli` | The `shopify-api` command. | +//! | `full` | Every feature but `native-tls`: `webhooks`, `oauth`, `testing`, `cli`, over rustls. | +//! +//! The client runs on Tokio: the default transport, and the token renewals, +//! which run in tasks of their own, need a Tokio runtime. #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] From 3e52b9ec8230dcfcc873c02f4e05b8cdae0fb8bc Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:44:08 +0100 Subject: [PATCH 081/135] docs(migration): cover every break from 0.10, drop the 1.0 previews MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The first sentence no longer says 1.0 keeps everything: what is gone without a replacement is named; a pointer for 0.9 users. - `edit_webhook` never existed in 0.10: the row is now delete-then-add → `update_webhook_subscription(id, &spec)`. - `request_client_credentials_token`, `refresh_token_with_credentials`, `token_url`, the `api_version` field, `ApiVersion::new(String)`, `TryFrom`, `as_str`, the constants, `TokenStoreFuture`, `never_expiring`, `current_token` → `with_token`, a `TokenData` literal, `?` on `serde_json::Error`, `GraphqlResponse`, `parse_jsonl`, the staged upload and connection types, the schema constants, the `graphql` module path, the published dependency features. - `replace_auth` on a reinstall; retries on by default and `RetryPolicy::none()`; `http://` refused; `Value::Null` without `data`; no `operationName` in untyped calls; the token store guarantee. - A complete warp handler in place of `warp_wrapper`, and the library call for a schema of another version than the CLI's. - The section on 1.0 previews, never published, is gone. Co-Authored-By: Claude Opus 5.5 --- MIGRATION.md | 156 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 120 insertions(+), 36 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 6271ce6..68b58a3 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1,8 +1,15 @@ # Upgrading from 0.10 to 1.0 -1.0 keeps what 0.10 did, under new names, and adds operations checked at -compile time. Most code changes in three places: building the client, the -error type, and GraphQL calls. +1.0 does most of what 0.10 did, under new names, and adds operations checked +at compile time. A few things are gone without a replacement in the crate: +the typed webhook payloads and the warp wrapper (a handler is a few lines, +see [Webhooks](#webhooks)), the concurrent bulk helpers, and `utils`. Most +code changes in three places: building the client, the error type, and +GraphQL calls. + +From 0.9 or older (`rest_query` and the REST module): 0.10 removed REST and +moved to GraphQL; see the 0.10.0 entry of [CHANGELOG.md](CHANGELOG.md), then +this guide. ## Building the client @@ -18,24 +25,50 @@ let shopify = Shopify::new("my-shop", Auth::access_token(token))?; | --- | --- | | `ShopifyAuth::AccessToken(token)` | `Auth::access_token(token)` | | `ShopifyAuth::client_credentials(id, secret)` | `Auth::client_credentials(id, secret)` | +| `ShopifyAuth::ClientCredentials { current_token: Some(token), .. }` | `Auth::client_credentials(id, secret).with_token(token)` | | `ShopifyAuth::expiring_offline_token(id, secret, token)` | `Auth::expiring_token(id, secret, token)` | | `ShopifyConfig { api_version, .. }` | `Shopify::builder(shop).api_version(ApiVersion::V2026_07)` | | `ShopifyConfig { token_store, .. }` | `.token_store(store)` | | `ShopifyConfig { token_refresh_leeway, .. }` | `.refresh_leeway(duration)` (a `std::time::Duration`) | | `ShopifyConfig { user_agent, .. }` | `.user_agent(text)` | | `ShopifyConfig { shared_secret, .. }` | Gone: pass the secret to `webhooks::Webhook::verify` | -| `ApiVersion::new("2026-07")` | The same, or `ApiVersion::V2026_07` | -| `shopify.replace_auth(auth)` | Build another client | +| `ApiVersion::new(text)`, from an `impl Into` | `ApiVersion::new(&str)`, `text.parse::()`, or `ApiVersion::V2026_07` | +| `ApiVersion::try_from(string)` (a `String`) | `ApiVersion::try_from(string.as_str())` | +| `version.as_str()` | `version.to_string()` (`Display`) | +| `shopify.api_version` (a public field) | `shopify.api_version()` | +| `DEFAULT_API_VERSION`, `MIN_API_VERSION` | `ApiVersion::DEFAULT` (2026-10), `ApiVersion::MINIMUM` | +| `VERSION` | `USER_AGENT` | +| `shopify.replace_auth(auth)` | Build another client: see below | | `shopify.get_shop()`, `shop_domain()` | `shopify.shop()`, a `ShopDomain` | | `shopify.get_query_url()` | `shopify.graphql_url(version)` | +| `shopify.token_url()` | Gone: the client asks for its tokens itself | +| `shopify.request_client_credentials_token(id, secret)` | `Shopify::new(shop, Auth::client_credentials(id, secret))?`, then `shopify.access_token().await?` (the token, obtained if need be) or `shopify.token().await` (the whole `TokenData`) | +| `shopify.refresh_token_with_credentials(id, secret, refresh)` | `Auth::expiring_token(id, secret, token)`: the client refreshes before expiry and on a `401`, and saves with its `TokenStore` | + +`replace_auth` swapped the token of a client in place. A client's +credentials are now fixed: when a shop reinstalls the app, or its token +changes otherwise, build a new client with the new token, and replace the old +one wherever it is held (its clones keep the old token). `TokenStore::save_token(shop: &str, token: TokenData)` is `TokenStore::save(shop: &ShopDomain, token: &TokenData)`, and returns a boxed -error of yours. `TokenData` has the same fields, and two more for online -tokens; build it with `TokenData::new(token)`. +error of yours; `TokenStoreFuture` is `transport::BoxFuture`. While a save +fails, the client sends nothing: each call tries the save again first, and +fails with `Error::TokenStore`. `TokenData` has the same fields, two more for +online tokens, and reads the JSON 0.10 stored. It is `#[non_exhaustive]`: build +it with `TokenData::new(token)` (0.10's `TokenData::never_expiring`), then set +its fields, instead of a struct literal. `expires_within` takes a +`std::time::Duration`. The shop must now be `` or `.myshopify.com` (with or without -`https://`): 0.10 accepted any text and appended `.myshopify.com`. +`https://`): 0.10 accepted any text, `http://` included, and appended +`.myshopify.com`. An `http://` address is refused. + +**Retries are on by default.** 0.10 returned `Throttled` at the first +throttle. 1.0 retries up to four times: a throttled request waits for what +its cost needs, a `429` for its `Retry-After` (up to five minutes), a query +for a backoff after a `5xx` or a network failure. To keep 0.10's behaviour: +`Shopify::builder(shop).retry(RetryPolicy::none())`. Without a pinned version, an operation of `graphql!` goes to the version its schema was checked against (the `api-version` of your `Cargo.toml`, else the @@ -57,7 +90,12 @@ to keep that. | Variables that do not serialize | `Variables { message, detail }`: what a `Serialize` implementation wrote is `error.sensitive_detail()`, not the message | | A `Float` that is NaN or infinite, an `Int` beyond 32 bits, `null` for a non-null `JSON`, sent as they were | `InvalidValue { path, reason, detail }`, before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float `` | | `Authentication(text)` | `Auth { message, detail }`: what the token endpoint wrote is `error.sensitive_detail()` | -| `MissingGraphqlData`, `InvalidHeaderValue`, `Other` | Gone | +| `MissingGraphqlData` | Gone: an answer without `data` (and without `errors`) gives `Value::Null` to `graphql`; `graphql_as` and `execute` then fail with `Decode` unless the type reads `null` | +| `InvalidHeaderValue`, `Other` | Gone | + +`Error` no longer converts from `reqwest::Error` or `serde_json::Error`: a +`?` on a `serde_json` result in a function that returns +`shopify_api::Result` needs your own error type, or `map_err`. ## GraphQL calls @@ -88,6 +126,15 @@ let data: ShopQuery = shopify.graphql_as("query { shop { name } }", ()).await?; Variables are now anything that serializes to an object, by value or by reference, or `()` for none. +The untyped calls send no `operationName`. To name one, for Shopify's logs: +`shopify.execute(Operation::::new(query).with_name("Name"))`. + +| 0.10 | 1.0 | +| --- | --- | +| `GraphqlResponse` | `RawResponse` (`data` as a `Value`), or `Response` from `execute_response` | +| `GraphqlError` | `GraphqlError`, with `message`, `locations`, `path`, `extensions` and `code()` | +| `shopify_api::graphql::*` (the module) | The module is private: `shopify_api::graphql` is the macro, the types are at the root | + With `graphql!`, an input object is a literal checked against the schema, in place of a `json!` value: @@ -116,20 +163,74 @@ shopify.execute(graphql!( | `Shopify::download_bulk_jsonl(url)` | `shopify.download_bulk_results(url)`, or `bulk_query_rows` for the whole cycle; `download_bulk_results_stream(url)` and `bulk_query_stream` read the rows as they download | | `run_bulk_queries`, `run_bulk_mutations`, `BulkConcurrencyOptions` | Gone: call the single versions in a loop | | `ShopifyBulkOperation`, `ShopifyBulkStatus` | `bulk::BulkOperation`, `bulk::BulkOperationStatus` | - -`object_count`, `root_object_count` and `file_size` are numbers. +| `ShopifyBulkErrorCode` | `BulkOperation::error_code`, a `String` | +| `BulkOperationPayload` | `BulkOperation`, its `userErrors` as `Error::UserErrors` | +| `BulkOperationConnection`, `BulkOperationEdge`, `PageInfo` | `Page` | +| `StagedUploadResource`, `StagedUploadParameter`, `StagedMediaUploadTarget`, `StagedUploadsCreateInput` | Internal: `stage_bulk_variables` does the upload | +| `ShopifyUserError` | `UserError` | +| `parse_jsonl(&str)` | `bulk::parse_jsonl(&[u8])`: `parse_jsonl(text.as_bytes())` | + +`object_count`, `root_object_count` and `file_size` are numbers, and +`created_at` and `completed_at` are `chrono::DateTime`. A failed operation +is an `Error::Bulk` whose `operation` holds it, with its `error_code` and +`partial_data_url`; a wait that ran out is an `Error::Timeout` whose `id` is +the operation's, which keeps running. ## Webhooks The `webhooks` feature verifies and reads webhooks without a web framework, so the `warp-wrapper` feature, `Shopify::warp_wrapper` and the `ShopifyWebhook` -payload structs are gone. In your handler, with the raw body: +payload structs (`Order`, `Customer`, `InventoryItem`, `InventoryLevel`, +`Address`…) are gone: declare the fields you read in a struct of yours. With +warp, what `warp_wrapper` did: ```rust,ignore -let webhook = shopify_api::webhooks::Webhook::verify(headers, body, client_secret)?; -let order: MyOrder = webhook.payload()?; +use bytes::Bytes; +use serde::Deserialize; +use shopify_api::webhooks::Webhook; +use warp::http::{HeaderMap, StatusCode}; +use warp::Filter; + +#[derive(Deserialize)] +struct Order { + id: u64, + name: String, +} + +let secret = std::env::var("SHOPIFY_API_SECRET")?; +let webhooks = warp::path("webhooks") + .and(warp::post()) + .and(warp::header::headers_cloned()) + .and(warp::body::bytes()) + .map(move |headers: HeaderMap, body: Bytes| { + // Checks the signature, and reads the topic, the shop and the IDs. + let Ok(webhook) = Webhook::verify(&headers, body, &secret) else { + return StatusCode::UNAUTHORIZED; + }; + match webhook.topic() { + "orders/create" => match webhook.payload::() { + Ok(order) => println!("{} on {}", order.name, webhook.shop()), + Err(_) => return StatusCode::BAD_REQUEST, + }, + "app/uninstalled" => { + // The shop of the headers is not signed: check the payload's. + if webhook.verify_payload_shop().is_err() { + return StatusCode::UNAUTHORIZED; + } + // … forget the shop. + } + _ => {} + } + StatusCode::OK + }); ``` +With axum, `async fn(headers: HeaderMap, body: Bytes)` takes the same two +values (see the docs of `shopify_api::webhooks`). `Webhook::verify` requires +the `X-Shopify-Topic` and `X-Shopify-Shop-Domain` headers, which Shopify always +sends, and only verifies a JSON object or an XML body; +`webhooks::verify_hmac(secret, body, header)` checks the signature alone. + | 0.10 | 1.0 | | --- | --- | | `shopify.verify_hmac(data, header)` | `webhooks::verify_hmac(secret, data, header)` | @@ -137,7 +238,7 @@ let order: MyOrder = webhook.payload()?; | `add_webhook(address, topic, format)` | `create_webhook_subscription(&WebhookSubscriptionSpec::new(topic, address))` | | `delete_webhook(id)` | `delete_webhook_subscription(id)` | | `webhook_auto_config(vec![(address, topic, format)])` | `sync_webhook_subscriptions(&[WebhookSubscriptionSpec::new(topic, address)])`, which returns what it did | -| `edit_webhook` | Delete and create, or `sync_webhook_subscriptions` | +| `delete_webhook(id)` then `add_webhook(…)`, to change a subscription | `update_webhook_subscription(id, &spec)`, which replaces its options in place | Topics are accepted as `orders/create` or `ORDERS_CREATE`. @@ -147,7 +248,10 @@ Topics are accepted as `orders/create` or `ORDERS_CREATE`. | --- | --- | | `download_public_admin_schema("2026-04")` | `schema::download_public_admin_schema(ApiVersion::V2026_04)` | | `shopify.download_admin_schema()` | The same | +| `SHOPIFY_DEV_ADMIN_SCHEMA_PROXY` | `schema::PUBLIC_ADMIN_SCHEMA_ENDPOINT` | +| `ADMIN_SCHEMA_INTROSPECTION_QUERY` | `schema::INTROSPECTION_QUERY` | | `shopify-api schema download --public --out file` | `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`: `graphql!` downloads it. `shopify-api schema download` refreshes it, `--introspection` for the raw result | +| `shopify-api schema download --api-version 2026-07` | No flag: the command reads the version of the nearest `Cargo.toml`. For another version, or outside a package: `schema::download_public_admin_schema(ApiVersion::new("2026-07")?)` | `graphql!` reads the compact form it downloads, in `graphql/admin.schema.json`. @@ -156,24 +260,4 @@ Topics are accepted as `orders/create` or `ORDERS_CREATE`. - `utils::retry_async` and `retry_sync`: the client retries what can be. - `utils::read_json_tree`: `serde_json::Value::pointer`. - `utils::deserialize_from_value` and `deserialize_from_str`: errors name the path of a mismatch. -- The `debug` and `graphql-client` features, and the `simple_logger` dependency: logs go through `tracing`. - -# Upgrading from a 1.0 preview - -The input objects of `graphql!` changed before the release. - -| 1.0 preview | 1.0 | -| --- | --- | -| `module::MetafieldsSetInput { owner_id: id.to_string(), namespace: Some("custom".into()), ..Default::default() }` | `input!(MetafieldsSetInput { ownerId: id, namespace: "custom", … })`: GraphQL field names, every required field, `?:` for an `Option` | -| `module::MetafieldsSetInput` as a struct | The same name, a type alias of the `InputObject` every `input!(MetafieldsSetInput { … })` builds | -| An inline input object variable given `json!({ … })` or any `Serialize` value | An object literal, `product = { id: id, … }`, or values of `input!`; `json!` goes through `Shopify::graphql` | -| An enum variable given a string, `sortKey = "TITLE"` or `sortKey = key` | `sortKey = TITLE`, checked, or `sortKey = raw(key)` | -| No way to send `null` for an input field | `field: null`, or `field?: Maybe::Null` | -| One module per `graphql! { … }` | Several, `;` between them | -| `shopify.execute(module::operation(module::Variables { … }))` | The same, or `shopify.execute(module::Variables { … })` | -| `Variables` always `Default` and `PartialEq` | `Default` when no variable is required, `PartialEq` when it holds no input object | -| `Operation::body()` returned a `serde_json::Value` | It returns the exact JSON text `execute` sends, a `String`; parse it yourself for a `Value`, `serde_json::from_str::(&body)` | -| `Operation::variables_json()` returned `&Map` | `Operation::variable_json(name)` returns the JSON text of one variable, `Option<&str>`; nothing is parsed back | -| `shopify.execute(module::Variables { … }.into())` | Drop the `.into()`: `execute` takes `impl Into>`, so `.into()` has no single target (E0283) | -| `Operation::variable::` with a `T` of yours | `T` is a `VariableType`: one of the Rust types `graphql!` picks (`String`, `i64`, `f64`, `bool`, `Value`, `InputObject`, in `Option` and `Vec`). `json_variable` takes anything else | -| A `u64` beyond `i64` saturated to `i64::MAX`; NaN and infinity sent as `null`; `null` sent for a non-null `JSON` | Refused: `Error::InvalidValue` when the operation runs, before the request; an integer literal out of the range of `Int` is a compile error | +- The `debug`, `graphql-client` and `warp-wrapper` features, and the `hmac`, `sha2`, `warp` and `graphql_client` features that 0.10 published for its optional dependencies: `webhooks` and `oauth` enable what they need. The `simple_logger` dependency: logs go through `tracing`. From 3e463f4d4d85d49e341bcdf39631e1880daed92f Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:44:08 +0100 Subject: [PATCH 082/135] docs(changelog): say what is new in 1.0 against 0.10, and what this round changed What 0.10 already had (token renewal and `TokenStore`, typed bulk operations, webhook subscriptions and verification, schema download) moves from Added to Changed, with what 1.0 adds to each. The entries against unpublished 1.0 previews are gone, and what they held that matters against 0.10 is under Breaking. The 1.0.0 heading reads Unreleased until the tag. Entries cover the fixes of this round: webhook bodies and headers, the token store guarantee, structured bulk errors, bulk serde, extension session tokens, `reqwest_0_13`, packaging. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 82 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 50 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 10e5559..98202de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,40 +1,58 @@ # Changelog -## 1.0.0 +## 1.0.0 (Unreleased) A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATION.md). -- Add: `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`) or read from a file (`file("…graphql")`). -- Add: input values written as literals in an inline `graphql!`, checked against the schema at the token: `product = { id: id, status: ACTIVE, descriptionHtml: null, vendor?: vendor, seo: { title: t }, metafields: [for m in &rows if cond => { … }] }`. Field names are the GraphQL ones (`type` included); an unknown or repeated field, a missing required field (each one named), `null` on a non-null type, an unknown enum value (the valid ones listed) and a value of the wrong form are compile errors; deprecated fields and enum values warn. `field?: value` leaves the field out for `None`; an `Option` given to `field: value` does not compile, since `null` would clear the field. `raw(string)` sends an enum value unchecked. Rust expressions are checked by traits whose errors name the GraphQL type. Literals are written straight to JSON, with no `serde_json::Value` in between. -- Add: `input!(TypeName { … })` builds an input object ahead of the call, with the same checks, as an `InputObject`: one Rust type per GraphQL name, the same in every module and crate, so that the values of several `input!` go in one `Vec`. -- Add: `Maybe` (`Absent`, `Null`, `Value`), for `field?:` when `null` is a choice made at run time. -- Add: values Shopify would not read as written are refused. A `Float` must be finite (NaN and infinity were sent as `null`), an `Int` must fit in 32 bits, a non-null `JSON` must not be `null` at its top. An integer literal out of range, alone, negated, in parentheses or in a list `[…]`, is a compile error at the literal; `Some(…)`, `vec![…]` and other forms are checked at run time. A value known at run time, in a literal, an `input!`, a module's `Variables` or `Operation::variable`, is kept as refused, and the operation fails with `Error::InvalidValue { path, reason, detail }` before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float ``. The message names the place and the reason (`InvalidValueReason`), never the value; a serializer's message is in `sensitive_detail()`. An `InputObject` that is refused fails to serialize on its own. Nothing in the code of the macros panics on a value. -- Add: no name the macros generate is in scope where the values are evaluated: a local, closure, function or constant of yours with the name of a generated item stays yours. -- Add: one `graphql! { … }` holds several modules, `;` between them. A module's `Variables` runs as it is, `shopify.execute(module::Variables { … })`, and it names each input object its variables may hold: `pub type MetafieldsSetInput = InputObject<…>`. -- Breaking (against the 1.0 previews): the input structs of modules (`MetafieldsSetInput { owner_id, ..Default::default() }`) are gone, for `input!`, which cannot leave out a required field. `Variables` implements `Default` only when no variable is required, and `PartialEq` only when it holds no input object. An input object variable of an inline `graphql!` takes a literal or values of `input!`, no longer any `Serialize` value such as `json!`. An enum variable takes a bare value (`sortKey = TITLE`) or `raw(string)`, no longer a string. `execute` and `execute_response` take `impl Into>`, so `execute(variables.into())` no longer infers its type: drop the `.into()`. `Operation` keeps each variable as the JSON it is sent as, and parses nothing back: `body()` returns the exact JSON text `execute` sends, a `String`, no longer a `Value`, and `variable_json(name)` the text of one variable, replacing `variables_json`. `Operation::variable::` takes a `T` of the sealed `VariableType`, and a `u64` beyond the range of `Int` is refused rather than saturated. -- Add: deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. -- Add: `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. -- Add: no schema ships with the crates. `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. -- Add: `shopify-api check` checks `.graphql` files against the schema. -- Add: retries: a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`. -- Add: tokens are renewed once for all the clones of a client, before they expire and when Shopify refuses one with a `401`. `Auth::expiring_token` with a `TokenStore`. -- Add: `Shopify::paginate`, `Page`. -- Add: bulk operations: `bulk_query_rows`, `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, typed `BulkOperation` and statuses, adaptive polling. -- Add: bulk results read as they download, in memory that follows the line being read rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. -- Add: `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group; so is a child whose parent has no unaliased `id`, which the error names. -- Add: `run_bulk_mutation_iter` and `stage_bulk_variables_iter` take the variables from an iterator; the JSONL is written straight into the body of the upload, in memory once. -- Add: `Transport::send_streaming`, with a default that goes through `send`, and `StreamingResponse`, `BodyStream`. `ReqwestTransport` streams: the timeout of the request bounds the wait for the headers and for each chunk, not the whole body. `MockTransport::push_chunks` and `push_streaming` script a body in chunks. -- Add: `webhooks`: `Webhook::verify` (headers, signature with secret rotation, payload), subscriptions with `sync_webhook_subscriptions`, which updates in place and creates before it deletes. -- Add: `oauth`: `ShopifyApp` with install links, callback and admin launch verification, code exchange, session tokens and token exchange, app proxies. -- Add: `Transport` trait, `ReqwestTransport` (redirections always off, `from_builder` for your own settings), and `testing::MockTransport`, with `testing::client`, which retries without waiting, even for a scripted `Retry-After`. -- Add: token renewals run in a task of their own: a cancelled request does not lose a rotated refresh token. A failed renewal answers the requests waiting for it. -- Add: an error shows nothing of what the crate did not write (`Error` documents the contract): no body, value or map key of an answer, no message of serde or of a `Serialize` implementation, no query string or user of an address. `Error::Http` displays the status, the address, the content type and the length of the body; `Error::raw_http_body` (or the `raw_body: RawBody` field) gives the body. `Error::Decode` displays the kind of mismatch, its line and column, and a path of the type's own field names and indexes, with `[key]` for a map key. `Error::Variables` names the variable that does not serialize. `Error::sensitive_detail` gives serde's message, the `Serialize` implementation's or the token endpoint's, all kept out of `Display` and `Debug` (`SensitiveDetail`). The `Debug` of `GraphqlErrors` counts the entries of partial `data`, and that of `GraphqlError` shows `extensions.code` and counts the other extensions (Shopify echoes an invalid variable's whole value in `extensions.value`). Shopify's own messages in `errors` and `userErrors` are shown as they are. `Error::Http` carries Shopify's `X-Request-Id`. -- Breaking (against the 1.0 previews): `Error::Http` displays no part of the body and has no `body` field any more (it was a redacted 1 KiB preview); it has `content_type`. `Error::Json` is gone: a body that is not JSON is `Error::Decode`. `Error::Decode` has a `detail` field and its path writes a map key `[key]`. `Error::Variables(String)` and `Error::Auth(String)` are `Variables { message, detail }` and `Auth { message, detail }`. `Error` no longer converts from `serde_json::Error`. `InvalidShop` and `InvalidApiVersion` do not display the text given, which may be a token given in the wrong place (`InvalidApiVersion` shows a version written `YYYY-MM`). -- Add: `ShopDomain` refuses anything but `` or `.myshopify.com`. -- Breaking: `Shopify::new(shop, auth)` and `Shopify::builder`; `ShopifyAuth` is `Auth`; `ShopifyConfig` is gone; `ShopifyAPIError` is `Error`. -- Breaking: `graphql` returns `data` as a `Value` and `graphql_as` reads it as a type; `post_graphql` and the `graphql-client` feature are gone. -- Breaking: the warp wrapper, the webhook payload structs, `utils` (`retry_async`, `read_json_tree`) and `graphql_at_path` are gone. -- Breaking: Rust 1.88, edition 2024. +### Added + +- `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`) or read from a file (`file("…graphql")`). +- Input values written as literals in an inline `graphql!`, checked against the schema at the token: `product = { id: id, status: ACTIVE, descriptionHtml: null, vendor?: vendor, seo: { title: t }, metafields: [for m in &rows if cond => { … }] }`. Field names are the GraphQL ones (`type` included); an unknown or repeated field, a missing required field (each one named), `null` on a non-null type, an unknown enum value (the valid ones listed) and a value of the wrong form are compile errors; deprecated fields and enum values warn. `field?: value` leaves the field out for `None`; an `Option` given to `field: value` does not compile, since `null` would clear the field. `raw(string)` sends an enum value unchecked. Rust expressions are checked by traits whose errors name the GraphQL type. Literals are written straight to JSON, with no `serde_json::Value` in between. +- `input!(TypeName { … })` builds an input object ahead of the call, with the same checks, as an `InputObject`: one Rust type per GraphQL name, the same in every module and crate, so that the values of several `input!` go in one `Vec`. +- `Maybe` (`Absent`, `Null`, `Value`), for `field?:` when `null` is a choice made at run time. +- Values Shopify would not read as written are refused. A `Float` must be finite (NaN and infinity were sent as `null`), an `Int` must fit in 32 bits, a non-null `JSON` must not be `null` at its top. An integer literal out of range, alone, negated, in parentheses or in a list `[…]`, is a compile error at the literal; `Some(…)`, `vec![…]` and other forms are checked at run time. A value known at run time, in a literal, an `input!`, a module's `Variables` or `Operation::variable`, is kept as refused, and the operation fails with `Error::InvalidValue { path, reason, detail }` before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float ``. The message names the place and the reason (`InvalidValueReason`), never the value; a serializer's message is in `sensitive_detail()`. An `InputObject` that is refused fails to serialize on its own. Nothing in the code of the macros panics on a value. +- No name the macros generate is in scope where the values are evaluated: a local, closure, function or constant of yours with the name of a generated item stays yours. +- One `graphql! { … }` holds several modules, `;` between them. A module's `Variables` runs as it is, `shopify.execute(module::Variables { … })`, and it names each input object its variables may hold: `pub type MetafieldsSetInput = InputObject<…>`. +- Deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. +- `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. +- `Operation`, what `graphql!` builds, or `Operation::new` for any text: `execute` and `execute_response` take `impl Into>`, a module's `Variables` included. `body()` is the exact JSON text sent, and `variable_json(name)` the text of one variable; `with_name` sets the `operationName`. +- `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. +- `shopify-api check` checks `.graphql` files against the schema. +- Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. The jitter of the backoff is random on every platform. +- `Shopify::paginate`, `Page`. +- Bulk results read as they download, in memory that follows the line being read rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. +- `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group; so is a child whose parent has no unaliased `id`, which the error names. +- `run_bulk_mutation_iter` and `stage_bulk_variables_iter` take the variables from an iterator; the JSONL is written straight into the body of the upload, in memory once. +- `Transport`, the HTTP layer as a trait, with `send_streaming` (a default goes through `send`), `StreamingResponse` and `BodyStream`. The default `ReqwestTransport` never follows a redirection, and streams: the timeout of a request bounds the wait for the headers and for each chunk, not the whole body. A client of your own goes through `transport::reqwest_0_13::from_builder`: reqwest appears in the API only under `transport::reqwest_0_13`, named after its major version, so that a later reqwest comes next to it. The client runs on Tokio. +- `testing::MockTransport` (`push_data`, `push_chunks`, `push_streaming`, `respond_with`…), and `testing::client`, which retries without waiting, even for a scripted `Retry-After`. `testing` also gives the signing helpers: `webhooks::sign`, `ShopifyApp::sign_query`, `sign_app_proxy`, `sign_session_token`. +- `oauth`: `ShopifyApp`, with install links, the verification of callbacks, admin launches and app proxy requests, the code exchange, session tokens and the token exchange. `verify_session_token` takes the tokens of Shopify admin and of checkout and customer account UI extensions (a `dest` without `https://`); `SessionToken::subject` is the staff member's ID or the customer's GID. `ShopifyApp::with_token_store` gives the clients it builds a `TokenStore`. +- An error shows nothing of what the crate did not write (`Error` documents the contract): no body, value or map key of an answer, no message of serde or of a `Serialize` implementation, no query string or user of an address. `Error::Http` displays the status, the address, the content type and the length of the body; `Error::raw_http_body` (or the `raw_body: RawBody` field) gives the body. `Error::Decode` displays the kind of mismatch, its line and column, and a path of the type's own field names and indexes, with `[key]` for a map key. `Error::Variables` names the variable that does not serialize. `Error::sensitive_detail` gives serde's message, the `Serialize` implementation's or the token endpoint's, all kept out of `Display` and `Debug` (`SensitiveDetail`). The `Debug` of `GraphqlErrors` counts the entries of partial `data`, and that of `GraphqlError` shows `extensions.code` and counts the other extensions (Shopify echoes an invalid variable's whole value in `extensions.value`). Shopify's own messages in `errors` and `userErrors` are shown as they are. `Error::Http` carries Shopify's `X-Request-Id`. +- `Error::Bulk { message, operation }` holds the operation that ended without completing, with its `error_code` and `partial_data_url`; `Error::Timeout { message, id }` the ID of the bulk operation waited for, to cancel it. + +### Changed + +- Tokens: 0.10 renewed a token before it expired and saved it with a `TokenStore`. 1.0 also renews when Shopify refuses one with a `401`; one renewal serves every clone of a client and the requests waiting for it; it runs in a task of its own, so a cancelled request does not lose a rotated refresh token; a failed renewal answers the requests waiting for it. Until a renewed token is saved, nothing is sent: each call tries a failed save again first, and fails with `Error::TokenStore`. A refresh answer without a refresh token keeps the current one. `Auth::with_token` starts from a stored token. +- Bulk operations: 0.10 ran, read, listed and waited for them, with typed statuses. 1.0 adds `bulk_query_rows` (the whole cycle), `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, and polling that starts at one second and backs off. `BulkOperation` has numbers for its counts and `DateTime` for its dates; `BulkOperationStatus` and `BulkOperationType` serialize as Shopify writes them (`"COMPLETED"`, an unknown one as its text) and round-trip. +- Webhook subscriptions: 0.10 listed, added, deleted and auto-configured them. 1.0 has `webhook_subscriptions` (every page), `create_`, `update_` (in place, new) and `delete_webhook_subscription`, and `sync_webhook_subscriptions`, which updates in place, creates before it deletes, and returns what it did. `WebhookSubscription` dates are `DateTime`. +- Webhook verification: 0.10 checked the HMAC. `Webhook::verify` also reads the headers (topic, shop, IDs; with or without `X-`, in any case, from any `(name, value)` pairs, `&http::HeaderMap` included), accepts several secrets during a rotation, and refuses a body that is not a JSON object or an XML document: the launch queries, session tokens and app proxy requests the client secret also signs can never pass for a webhook. `Webhook::verify_payload_shop` checks that a destructive webhook names, in its payload, the unsigned shop of its headers. `Debug` of a `Webhook` shows the length of its body, not the body. +- Schema download: `schema::download_public_admin_schema` and `download_admin_schema` take an `ApiVersion`. +- `ShopDomain` refuses anything but `` or `.myshopify.com`, `http://` included; 0.10 appended `.myshopify.com` to any text. +- Without a pinned version, an operation of `graphql!` goes to the version of its schema, and an untyped call to `ApiVersion::DEFAULT`, 2026-10 (0.10: 2026-04). The crate's own operations go to a pinned version without a warning. + +### Breaking + +- `Shopify::new(shop, auth)` and `Shopify::builder`; `ShopifyAuth` is `Auth`; `ShopifyConfig` is gone; `replace_auth`, `token_url`, the public `api_version` field, `request_client_credentials_token` and `refresh_token_with_credentials` are gone (the client asks for its tokens itself). `DEFAULT_API_VERSION`, `MIN_API_VERSION` and `VERSION` are `ApiVersion::DEFAULT`, `ApiVersion::MINIMUM` and `USER_AGENT`; `ApiVersion::new` takes a `&str`. +- `ShopifyAPIError` is `Error`, which no longer converts from `reqwest::Error` or `serde_json::Error`. `MissingGraphqlData` is gone: an answer without `data` gives `Value::Null`. +- `TokenStore::save_token(&str, TokenData)` is `save(&ShopDomain, &TokenData)`; `TokenData` is `#[non_exhaustive]`, built with `TokenData::new`; `expires_within` takes a `std::time::Duration`. +- `graphql` returns `data` as a `Value` and `graphql_as` reads it as a type; `post_graphql` and the `graphql-client` feature are gone; the untyped calls send no `operationName`. +- `GraphqlResponse` is `RawResponse`; the `shopify_api::graphql` module is private (`graphql` is the macro); `parse_jsonl` takes bytes; the staged upload and connection types are internal. +- The warp wrapper, the webhook payload structs, `utils` (`retry_async`, `read_json_tree`) and `graphql_at_path` are gone, as are `run_bulk_queries`, `run_bulk_mutations` and `BulkConcurrencyOptions`, and the features `debug`, `graphql-client`, `warp-wrapper`, `hmac`, `sha2`, `warp` and `graphql_client`. +- Rust 1.88, edition 2024. + +### Packaging + +- The three crates are released together, each requiring the exact version of the others, and published at once (`cargo publish --workspace`). Each package includes the license. `cargo test` of the published `shopify_api` runs offline. +- Security: `Cargo.lock` picks up `ctutils` 0.4.6 for RUSTSEC-2026-0385. chrono 0.4.39 or newer. ## 0.10.1 From f11ad79c8db45e9e9640cf6548fb71b9adf1e242 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:31:20 +0100 Subject: [PATCH 083/135] fix(schema): never change a crate's schema behind its back Without a pinned api-version, the version of a crate is the one of its schema file: a new quarter no longer downloads anything, and a build gives the same result whatever the date. The latest version is taken only when there is no file and no pin. A crate built as a dependency (CARGO_PRIMARY_PACKAGE unset) never downloads nor writes its schema: a missing file, a file of another version than the pinned one, or of an older format is a compile error that names the directory where to run `shopify-api schema download`. A download is tried once per file and version in a compiler process, with a 10 s connect timeout; its failure says what to do and never falls back on another version. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/docs/graphql.md | 53 +- crates/shopify_api/src/bin/shopify-api.rs | 34 +- crates/shopify_api_graphql/src/lib.rs | 6 +- crates/shopify_api_graphql/src/project.rs | 633 +++++++++++++++++++--- crates/shopify_api_graphql/src/schema.rs | 2 +- crates/shopify_api_macros/src/lib.rs | 136 +---- 6 files changed, 622 insertions(+), 242 deletions(-) diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 1a390e0..7fb2950 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -341,37 +341,52 @@ graphql! { # Schema and API version -No schema ships with the crate. On the first build, `graphql!` downloads the -schema of the crate's version from Shopify's public endpoint into -`graphql/admin.schema.json`, and checks every operation of the crate against -it. Later builds read the file, and download again when the version changes. -Commit the file: builds without network access (CI sandboxes, docs.rs) need -it, and so does a published crate. +No schema ships with `shopify_api`. Each crate that uses `graphql!` keeps the +schema of its Admin API version in `graphql/admin.schema.json`, next to its +`Cargo.toml`, and every operation of the crate is checked against it. Commit +the file: builds without network access (CI sandboxes, docs.rs) need it, and +so does a published crate. -The version is the one your `Cargo.toml` declares: +The version is the one your `Cargo.toml` pins: ```toml [package.metadata.shopify_api] api-version = "2026-07" ``` -Without it, it is the latest stable version: Shopify releases one on the first -day of each quarter (`2026-10` on October 1st), and the next build that -recompiles the crate moves to it. A field the new version removed is then a -compile error. When the new version cannot be downloaded (no network, or -Shopify has not published it yet that day), the build keeps the file it has, -else takes the version before. +Without a pin, the version is the one of the schema file: it does not change +when Shopify releases a new one, and a build gives the same result whatever +the date. With no file either, the first build takes the latest stable +version (the one before, on the first day of a quarter when Shopify has not +published it yet). `shopify-api schema download` moves an unpinned crate to +the latest version; pinning one is clearer. + +When it builds a crate cargo was asked to build (a package of the workspace +you build, test or run), `graphql!` downloads the schema from Shopify's +public endpoint when the file is missing, when it holds another version than +the pinned one, or when it is in a format an older `shopify_api` wrote. It +tries once per build: without network access, every operation fails at once +with the reason, and `graphql!` never checks against another version than the +one the operations go to. + +A crate built as a dependency (from crates.io, git, or a path dependency +cargo was not asked to build) never downloads nor writes its schema: it +uses the file it ships. When the file is missing, or does not hold the +version its `Cargo.toml` pins, or is in an older format, the build fails and +names the directory where to run `shopify-api schema download`. The `shopify-api` command (`cargo install shopify_api --features cli`) -downloads the file again on demand: `shopify-api schema download`, or +downloads the file on demand: `shopify-api schema download`, or `shopify-api schema download --shop my-shop` for the schema a shop's token sees. -| Source, in order | | -| --- | --- | -| `SHOPIFY_GRAPHQL_SCHEMA` | Path of a schema file, relative to `Cargo.toml` or absolute. It applies to the packages cargo builds, not to their dependencies, which keep their own schema. | -| `api-version` in `[package.metadata.shopify_api]` | Kept in `graphql/admin.schema.json`, downloaded when the file is missing or holds another version. | -| The latest stable version | Kept there too, the same way. | +| The schema of a crate | Package cargo was asked to build | Dependency | +| --- | --- | --- | +| `SHOPIFY_GRAPHQL_SCHEMA` is set | That file, relative to `Cargo.toml` or absolute, as it is. | Ignored. | +| File present, no pin | The file, never downloaded again. | The file. | +| File present, of the pinned version | The file. | The file. | +| File present, of another version or an older format | Downloaded again. | Compile error. | +| No file | Downloaded: the pinned version, else the latest. | Compile error. | An operation goes to the version of the schema it was checked against: a crate whose schema is 2026-07 calls the 2026-07 endpoint, with nothing to diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index 0f94b6a..9a62b18 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -11,7 +11,7 @@ use std::sync::Arc; use std::time::SystemTime; use shopify_api_graphql::project::{ - configured_api_version, previous_api_version, up_to_date_schema, write_atomically, + configured_api_version, previous_api_version, project_schema, write_atomically, }; use shopify_api_graphql::{ PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, SchemaSource, analyze, latest_api_version, @@ -46,9 +46,11 @@ enum SchemaCommand { /// `graphql!` reads it. /// /// The version is `api-version` in `[package.metadata.shopify_api]` of the - /// nearest package, else the latest stable one. `graphql!` downloads it by - /// itself when the file is missing or holds another version: this command - /// refreshes it, or downloads it through a shop with --shop. + /// nearest package, else the latest stable one: this moves a crate that + /// pins none to the latest version. `graphql!` downloads the file by itself + /// only when it is missing, in an older format, or of another version than + /// the pinned one; this command refreshes it, or downloads it through a + /// shop with --shop. Download(DownloadArgs), } @@ -287,27 +289,11 @@ fn load_schema(path: Option<&Path>) -> Result<(Schema, String), String> { Some(path) => path.to_path_buf(), None => { let named = std::env::var_os(SCHEMA_ENV); - match schema_source( - package_root().as_deref(), - named.as_deref(), - SystemTime::now(), - )? { + match schema_source(package_root().as_deref(), named.as_deref())? { SchemaSource::File(path) => path, - SchemaSource::Version { - path, - version, - latest, - } => { - let schema = up_to_date_schema(&path, &version, latest, |file| { - if !file.is_file() || read(file).is_ok_and(|s| s.api_version != version) { - eprintln!( - "Downloading the Admin schema {version} into {}…", - file.display() - ); - } - read(file) - }) - .map_err(|error| error.to_string())?; + SchemaSource::Project { dir, path, pinned } => { + let schema = + project_schema(&dir, pinned.as_deref(), true, SystemTime::now(), read)?; return Ok((Arc::unwrap_or_clone(schema), path.display().to_string())); } } diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs index 9797c01..52ce95e 100644 --- a/crates/shopify_api_graphql/src/lib.rs +++ b/crates/shopify_api_graphql/src/lib.rs @@ -6,9 +6,9 @@ //! that description into Rust types. [`literal`] checks the values written in //! Rust for input types (`{ title: "x" }`) and writes the code that sends //! them. The `graphql!` and `input!` macros are a thin layer over them. -//! [`project`] finds the API version of a crate (the one its `Cargo.toml` -//! declares, else the latest), and downloads that version's schema (with the -//! `download` feature). No schema is bundled. +//! [`project`] finds the API version and the schema file of a crate, and +//! downloads that version's schema (with the `download` feature). No schema +//! is bundled. #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index 23fce67..9c32504 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -7,10 +7,10 @@ //! api-version = "2026-07" //! ``` //! -//! Without it, the crate follows the latest stable version. Either way, -//! `graphql!` checks the crate's operations against that version's schema, -//! kept in [`PROJECT_SCHEMA_PATH`]: downloaded on the first build, and again -//! when the version changes. +//! Without it, the version is the one of the schema file the crate has, kept +//! in [`PROJECT_SCHEMA_PATH`], and the latest stable one when there is no file +//! yet. `graphql!` checks the crate's operations against that schema: see +//! [`schema_plan`] for when it is downloaded. use std::ffi::OsStr; use std::path::{Path, PathBuf}; @@ -118,27 +118,25 @@ fn api_version_in(manifest: &str) -> Result, String> { pub enum SchemaSource { /// A schema file, used as it is. File(PathBuf), - /// The schema of `version`, kept in `path`: to download when the file is - /// missing or holds another version. - Version { - /// The crate's [`PROJECT_SCHEMA_PATH`]. + /// The crate's [`PROJECT_SCHEMA_PATH`], and the version its `Cargo.toml` + /// declares: see [`schema_plan`]. + Project { + /// The directory of the crate's `Cargo.toml`. + dir: PathBuf, + /// `dir` joined with [`PROJECT_SCHEMA_PATH`]. path: PathBuf, - /// The version its `Cargo.toml` declares, else the latest one. - version: String, - /// No version is declared: `version` is the latest one. - latest: bool, + /// The version its `Cargo.toml` declares. + pinned: Option, }, } -/// The schema `graphql!` uses for the crate in `manifest_dir`, at `now`: +/// The schema `graphql!` uses for the crate in `manifest_dir`: /// /// 1. the file `named` by [`SCHEMA_ENV`]; -/// 2. the version declared in `Cargo.toml`, kept in [`PROJECT_SCHEMA_PATH`]; -/// 3. else the latest version, kept there too. +/// 2. else [`PROJECT_SCHEMA_PATH`], with the version `Cargo.toml` declares. pub fn schema_source( manifest_dir: Option<&Path>, named: Option<&OsStr>, - now: SystemTime, ) -> Result { if let Some(named) = named.filter(|value| !value.is_empty()) { let path = match manifest_dir { @@ -155,14 +153,110 @@ pub fn schema_source( } let dir = manifest_dir .ok_or("no Cargo.toml of a package: the schema of a crate is kept next to it")?; - let declared = configured_api_version(dir)?; - Ok(SchemaSource::Version { + Ok(SchemaSource::Project { path: dir.join(PROJECT_SCHEMA_PATH), - latest: declared.is_none(), - version: declared.unwrap_or_else(|| latest_api_version(now)), + pinned: configured_api_version(dir)?, + dir: dir.to_path_buf(), }) } +/// What a crate's schema file holds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchemaFile { + Missing, + /// A schema of `version` this version of the crate reads. + Usable { + version: String, + }, + /// A file it cannot read: another format, or broken. `reason` names the + /// file; `version` is the one it holds, when it says. + Unusable { + version: Option, + reason: String, + }, +} + +/// What to do with a crate's schema file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchemaPlan { + /// Read it as it is. + Read, + /// Download `version` into it, then read it. + Download { + version: String, + /// No version is pinned and there is no file: `version` is the + /// latest one, which may not be out yet on the first day of a quarter. + latest: bool, + }, + /// Fail the build with this message. + Refuse(String), +} + +/// What to do with the schema file of the crate in `dir`, `file`, when its +/// `Cargo.toml` pins `pinned`. +/// +/// The version of a crate is the one it pins, else the one of its file: a +/// file is never replaced by a newer version on its own, so that a build +/// gives the same result whatever the date. Without either, the crate takes +/// the latest version at `now`. +/// +/// Only the `primary` package, one cargo was asked to build, downloads. A +/// dependency uses the file it ships, and refuses to build when it has none +/// or when it is not the version its `Cargo.toml` pins: its author tested its +/// operations against that file, and the registry copy is not to be written. +pub fn schema_plan( + dir: &Path, + file: &SchemaFile, + pinned: Option<&str>, + primary: bool, + now: SystemTime, +) -> SchemaPlan { + let path = dir.join(PROJECT_SCHEMA_PATH); + let fix = || { + format!( + "Run `shopify-api schema download` in `{}` (`cargo install shopify_api --features cli`), \ + and commit the file. As a dependency, a crate never downloads its schema: it uses the one it ships.", + dir.display() + ) + }; + match (file, pinned) { + (SchemaFile::Usable { .. }, None) => SchemaPlan::Read, + (SchemaFile::Usable { version }, Some(pinned)) if version == pinned => SchemaPlan::Read, + (SchemaFile::Usable { version }, Some(pinned)) if !primary => SchemaPlan::Refuse(format!( + "`{}` holds the Admin API {version}, but `{}` declares {pinned}. {}", + path.display(), + dir.join("Cargo.toml").display(), + fix() + )), + (SchemaFile::Missing, _) if !primary => SchemaPlan::Refuse(format!( + "`{}` is missing: `graphql!` needs the schema of the crate's API version there. {}", + path.display(), + fix() + )), + (SchemaFile::Unusable { reason, .. }, _) if !primary => { + SchemaPlan::Refuse(format!("{reason}. {}", fix())) + } + (_, Some(pinned)) => SchemaPlan::Download { + version: pinned.to_string(), + latest: false, + }, + ( + SchemaFile::Unusable { + version: Some(version), + .. + }, + None, + ) => SchemaPlan::Download { + version: version.clone(), + latest: false, + }, + (_, None) => SchemaPlan::Download { + version: latest_api_version(now), + latest: true, + }, + } +} + /// Shopify's public copy of the Admin schema: a GraphQL endpoint per version /// that answers introspection without a token. pub const PUBLIC_ADMIN_SCHEMA_ENDPOINT: &str = "https://shopify.dev/admin-graphql-direct-proxy"; @@ -247,6 +341,8 @@ pub fn download_public_schema(version: &str) -> Result Result<(), String> { }) } -/// The schema of `version` in `path`, read with `read`: the file when it -/// holds that version, else downloaded into it. +/// The schema of the crate in `dir`, read with `read`, after downloading it +/// when [`schema_plan`] says so. `primary` is whether cargo was asked to +/// build this crate, rather than build it as a dependency. /// -/// For the `latest` version, a failed download falls back on the file as it -/// is, else on the previous version: a new version may not be out yet on its -/// first day, and a build without network keeps the schema it has. +/// A download is tried once per file and version in a process: when it +/// fails, the next operations of the build fail at once with the same error. #[cfg(feature = "download")] #[cfg_attr(docsrs, doc(cfg(feature = "download")))] -pub fn up_to_date_schema>( +pub fn project_schema>( + dir: &Path, + pinned: Option<&str>, + primary: bool, + now: SystemTime, + read: impl Fn(&Path) -> Result, +) -> Result { + obtain_schema(dir, pinned, primary, now, read, |path, version| { + download_schema_file(path, version).map(drop) + }) +} + +/// [`project_schema`], downloading with `download`. +#[cfg(feature = "download")] +fn obtain_schema>( + dir: &Path, + pinned: Option<&str>, + primary: bool, + now: SystemTime, + read: impl Fn(&Path) -> Result, + download: impl Fn(&Path, &str) -> Result<(), DownloadError>, +) -> Result { + let path = dir.join(PROJECT_SCHEMA_PATH); + let (file, current) = if path.is_file() { + match read(&path) { + Ok(schema) => { + let version = schema.as_ref().api_version.clone(); + (SchemaFile::Usable { version }, Some(schema)) + } + Err(reason) => { + let version = stored_api_version(&path); + (SchemaFile::Unusable { version, reason }, None) + } + } + } else { + (SchemaFile::Missing, None) + }; + match schema_plan(dir, &file, pinned, primary, now) { + SchemaPlan::Read => current.map_or_else(|| read(&path), Ok), + SchemaPlan::Refuse(message) => Err(message), + SchemaPlan::Download { version, latest } => { + download_once(&path, &version, latest, download).map_err(|error| { + let which = match (pinned, &file) { + (Some(_), _) => format!("{version}, the version Cargo.toml pins"), + (None, SchemaFile::Missing) => format!( + "the latest Admin API version, {version}: Cargo.toml pins none, and there is no schema file yet" + ), + (None, _) => format!( + "{version}, the version of the schema file, again: this version of shopify_api cannot read it" + ), + }; + download_failure(&error, &path, &which, &version, now) + })?; + read(&path) + } + } +} + +/// The `apiVersion` a schema file names, whatever its format. +#[cfg(feature = "download")] +fn stored_api_version(path: &Path) -> Option { + #[derive(serde::Deserialize)] + struct Header { + #[serde(rename = "apiVersion")] + api_version: String, + } + let json = std::fs::read_to_string(path).ok()?; + let header: Header = serde_json::from_str(&json).ok()?; + Some(header.api_version) +} + +/// Downloads `version` into `path` with `download`, once in the process: the +/// outcome of the first attempt is the outcome of the next ones. +/// +/// For the `latest` version, an [`DownloadError::UnknownVersion`] tries the +/// version before: a new version may not be out on its first day. +#[cfg(feature = "download")] +fn download_once( path: &Path, version: &str, latest: bool, - read: impl Fn(&Path) -> Result, -) -> Result { - let read = |path: &Path| read(path).map_err(DownloadError::Failed); - let current = path.is_file().then(|| read(path).ok()).flatten(); - if let Some(current) = current { - if current.as_ref().api_version == version { - return Ok(current); - } - return match download_schema_file(path, version) { - Ok(_) => read(path), - Err(_) if latest => Ok(current), - Err(error) => Err(error), - }; + download: impl Fn(&Path, &str) -> Result<(), DownloadError>, +) -> Result<(), DownloadError> { + type Attempts = std::collections::BTreeMap<(PathBuf, String), Result<(), DownloadError>>; + static ATTEMPTS: std::sync::Mutex = std::sync::Mutex::new(Attempts::new()); + // Held during the download: the other operations of the build wait for it. + let mut attempts = ATTEMPTS + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let key = (path.to_path_buf(), version.to_string()); + if let Some(outcome) = attempts.get(&key) { + return outcome.clone(); } - let error = match download_schema_file(path, version) { - Ok(_) => return read(path), - Err(error) => error, - }; - let Some(previous) = previous_api_version(version).filter(|_| latest) else { - return Err(error); + let outcome = match download(path, version) { + Err(error @ DownloadError::UnknownVersion { .. }) if latest => { + match previous_api_version(version) { + Some(previous) => download(path, &previous), + None => Err(error), + } + } + outcome => outcome, }; - match download_schema_file(path, &previous) { - Ok(_) => read(path), - // The latest version not being out yet does not explain why the one - // before failed: that failure is the one to fix. - Err(fallback) if matches!(error, DownloadError::UnknownVersion { .. }) => Err(fallback), - Err(_) => Err(error), + attempts.insert(key, outcome.clone()); + outcome +} + +/// What to tell when the schema of `version`, described by `which`, cannot +/// be downloaded into `path` at `now`. +#[cfg(feature = "download")] +fn download_failure( + error: &DownloadError, + path: &Path, + which: &str, + version: &str, + now: SystemTime, +) -> String { + match error { + DownloadError::UnknownVersion { .. } => { + // On the first day of a quarter, its version may not be out yet. + let released = latest_api_version(now); + let suggested = match previous_api_version(version) { + Some(previous) if released.as_str() >= version => previous, + _ => released, + }; + format!( + "{error}: it is not out yet, or its name is wrong. \ + Declare a released version in Cargo.toml:\n\n{}", + metadata_snippet(&suggested) + ) + } + DownloadError::Failed(_) => format!( + "{error}\n`graphql!` needs the schema of {which}, in `{}`. \ + It does not use another version instead: operations go to the version they were checked against. \ + Build once with network access, or run `shopify-api schema download` in the crate's directory, \ + and commit the file.", + path.display() + ), } } @@ -457,62 +659,47 @@ mod tests { } #[test] - fn without_a_declared_version_the_latest_is_used() { - let project = Project::new("latest"); + fn the_source_is_the_crate_file_with_its_pinned_version() { + let project = Project::new("source"); project.manifest(None); - assert_eq!( - schema_source(Some(&project.0), None, day(2027, 2, 3)), - Ok(SchemaSource::Version { - path: project.0.join(PROJECT_SCHEMA_PATH), - version: "2027-01".to_string(), - latest: true, - }) - ); - assert!(schema_source(None, None, day(2027, 2, 3)).is_err()); - } + let unpinned = SchemaSource::Project { + dir: project.0.clone(), + path: project.0.join(PROJECT_SCHEMA_PATH), + pinned: None, + }; + assert_eq!(schema_source(Some(&project.0), None), Ok(unpinned)); + assert!(schema_source(None, None).is_err()); - #[test] - fn a_declared_version_is_used() { - let project = Project::new("declared"); project.manifest(Some("2026-07")); assert_eq!( - schema_source(Some(&project.0), None, day(2027, 2, 3)), - Ok(SchemaSource::Version { + schema_source(Some(&project.0), None), + Ok(SchemaSource::Project { + dir: project.0.clone(), path: project.0.join(PROJECT_SCHEMA_PATH), - version: "2026-07".to_string(), - latest: false, + pinned: Some("2026-07".to_string()), }) ); } #[test] fn the_environment_names_another_file() { - let now = day(2026, 10, 22); let project = Project::new("named"); project.manifest(Some("2026-07")); let other = project.write("schemas/unstable.json", "{}"); assert_eq!( - schema_source( - Some(&project.0), - Some(OsStr::new("schemas/unstable.json")), - now - ), + schema_source(Some(&project.0), Some(OsStr::new("schemas/unstable.json"))), Ok(SchemaSource::File(other.clone())) ); assert_eq!( - schema_source(None, Some(other.as_os_str()), now), + schema_source(None, Some(other.as_os_str())), Ok(SchemaSource::File(other)) ); + assert!(matches!( + schema_source(Some(&project.0), Some(OsStr::new(""))), + Ok(SchemaSource::Project { .. }) + )); assert_eq!( - schema_source(Some(&project.0), Some(OsStr::new("")), now), - Ok(SchemaSource::Version { - path: project.0.join(PROJECT_SCHEMA_PATH), - version: "2026-07".to_string(), - latest: false, - }) - ); - assert_eq!( - schema_source(Some(&project.0), Some(OsStr::new("missing.json")), now), + schema_source(Some(&project.0), Some(OsStr::new("missing.json"))), Err(format!( "SHOPIFY_GRAPHQL_SCHEMA names `{}`, which is not a file", project.0.join("missing.json").display() @@ -520,6 +707,280 @@ mod tests { ); } + fn usable(version: &str) -> SchemaFile { + SchemaFile::Usable { + version: version.to_string(), + } + } + + fn old_format(version: Option<&str>) -> SchemaFile { + SchemaFile::Unusable { + version: version.map(str::to_string), + reason: "`/crate/graphql/admin.schema.json`: Unsupported schema file format 1, \ + this version reads format 2" + .to_string(), + } + } + + fn download(version: &str, latest: bool) -> SchemaPlan { + SchemaPlan::Download { + version: version.to_string(), + latest, + } + } + + #[test] + fn without_a_pin_the_file_is_the_version_whatever_the_date() { + let dir = Path::new("/crate"); + let years_later = day(2031, 5, 6); + for primary in [true, false] { + assert_eq!( + schema_plan(dir, &usable("2026-07"), None, primary, years_later), + SchemaPlan::Read + ); + } + // No file and no pin: the first build of the crate takes the latest. + assert_eq!( + schema_plan(dir, &SchemaFile::Missing, None, true, day(2027, 2, 3)), + download("2027-01", true) + ); + } + + #[test] + fn the_primary_package_downloads_its_pinned_version() { + let dir = Path::new("/crate"); + let now = day(2026, 10, 22); + assert_eq!( + schema_plan(dir, &usable("2026-07"), Some("2026-07"), true, now), + SchemaPlan::Read + ); + assert_eq!( + schema_plan(dir, &usable("2026-07"), Some("2026-10"), true, now), + download("2026-10", false) + ); + assert_eq!( + schema_plan(dir, &SchemaFile::Missing, Some("2026-04"), true, now), + download("2026-04", false) + ); + // A file of an older format is downloaded again, for the same version. + assert_eq!( + schema_plan(dir, &old_format(Some("2026-07")), None, true, now), + download("2026-07", false) + ); + assert_eq!( + schema_plan( + dir, + &old_format(Some("2026-07")), + Some("2026-10"), + true, + now + ), + download("2026-10", false) + ); + assert_eq!( + schema_plan(dir, &old_format(None), None, true, now), + download("2026-10", true) + ); + } + + #[test] + fn a_dependency_never_downloads() { + let dir = Path::new("/registry/deplib-1.0.0"); + let now = day(2026, 10, 22); + let refusal = |file: &SchemaFile, pinned: Option<&str>| match schema_plan( + dir, file, pinned, false, now, + ) { + SchemaPlan::Refuse(message) => { + let fix = "Run `shopify-api schema download` in `/registry/deplib-1.0.0`"; + assert!(message.contains(fix), "{message}"); + message + } + other => panic!("{file:?}, {pinned:?}: {other:?}"), + }; + assert_eq!( + schema_plan(dir, &usable("2026-07"), Some("2026-07"), false, now), + SchemaPlan::Read + ); + let message = refusal(&usable("2026-07"), Some("2026-10")); + assert!( + message.starts_with( + "`/registry/deplib-1.0.0/graphql/admin.schema.json` holds the Admin API 2026-07, \ + but `/registry/deplib-1.0.0/Cargo.toml` declares 2026-10." + ), + "{message}" + ); + for pinned in [None, Some("2026-10")] { + let message = refusal(&SchemaFile::Missing, pinned); + assert!( + message.contains("admin.schema.json` is missing"), + "{message}" + ); + let message = refusal(&old_format(Some("2026-07")), pinned); + assert!( + message.contains("Unsupported schema file format 1"), + "{message}" + ); + } + } + + #[cfg(feature = "download")] + mod obtaining { + use std::cell::RefCell; + use std::sync::Arc; + + use super::*; + use crate::Schema; + + const SCHEMA: &str = r#"{"format":FORMAT,"apiVersion":"VERSION","query":"Q","types":{"Q":{"o":{"f":{"a":"Int"}}},"Int":"s"}}"#; + + fn schema(version: &str) -> String { + SCHEMA + .replace("FORMAT", &crate::schema::FORMAT.to_string()) + .replace("VERSION", version) + } + + fn read(path: &Path) -> Result, String> { + let json = std::fs::read_to_string(path).map_err(|error| error.to_string())?; + Schema::from_json(&json) + .map(Arc::new) + .map_err(|error| error.to_string()) + } + + /// The versions asked for, and what the next downloads do. + struct Network { + asked: RefCell>, + online: bool, + released: &'static [&'static str], + } + + impl Network { + fn new(online: bool, released: &'static [&'static str]) -> Self { + Self { + asked: RefCell::new(Vec::new()), + online, + released, + } + } + + fn download(&self, path: &Path, version: &str) -> Result<(), DownloadError> { + self.asked.borrow_mut().push(version.to_string()); + if !self.online { + return Err(DownloadError::Failed("offline".to_string())); + } + if !self.released.contains(&version) { + return Err(DownloadError::UnknownVersion { + version: version.to_string(), + answer: "HTTP 400".to_string(), + }); + } + write_atomically(path, &schema(version)).map_err(DownloadError::Failed) + } + + fn obtain( + &self, + project: &Project, + primary: bool, + now: SystemTime, + ) -> Result, String> { + let pinned = configured_api_version(&project.0).unwrap(); + obtain_schema( + &project.0, + pinned.as_deref(), + primary, + now, + read, + |path, version| self.download(path, version), + ) + } + } + + #[test] + fn a_dependency_reads_its_file_and_never_writes_it() { + let project = Project::new("dependency"); + project.manifest(None); + let file = project.write(PROJECT_SCHEMA_PATH, &schema("2026-04")); + let network = Network::new(true, &["2026-04", "2026-07", "2026-10"]); + let schema = network.obtain(&project, false, day(2026, 10, 22)).unwrap(); + assert_eq!(schema.api_version, "2026-04"); + + project.manifest(Some("2026-10")); + let error = network + .obtain(&project, false, day(2026, 10, 22)) + .unwrap_err(); + assert!(error.contains("holds the Admin API 2026-04"), "{error}"); + assert!(network.asked.borrow().is_empty()); + assert!(read(&file).unwrap().api_version == "2026-04"); + } + + #[test] + fn a_failed_download_is_tried_once_and_says_what_to_do() { + let project = Project::new("offline"); + project.manifest(Some("2026-10")); + project.write(PROJECT_SCHEMA_PATH, &schema("2026-07")); + let network = Network::new(false, &[]); + for _ in 0..3 { + let error = network + .obtain(&project, true, day(2026, 10, 22)) + .unwrap_err(); + assert!(error.starts_with("offline\n`graphql!` needs the schema of 2026-10, the version Cargo.toml pins"), "{error}"); + assert!( + error.contains("It does not use another version instead"), + "{error}" + ); + } + assert_eq!(*network.asked.borrow(), ["2026-10"]); + } + + #[test] + fn a_version_shopify_does_not_have_is_named_and_a_released_one_suggested() { + let project = Project::new("unknown"); + let network = Network::new(true, &["2026-10"]); + project.manifest(Some("2027-04")); + assert_eq!( + network + .obtain(&project, true, day(2026, 10, 22)) + .unwrap_err(), + "Shopify has no Admin API version 2027-04 (HTTP 400): it is not out yet, \ + or its name is wrong. Declare a released version in Cargo.toml:\n\n\ + [package.metadata.shopify_api]\napi-version = \"2026-10\"" + ); + // On the first day of a quarter, before Shopify releases its version. + project.manifest(Some("2027-01")); + let error = network.obtain(&project, true, day(2027, 1, 1)).unwrap_err(); + assert!(error.ends_with("api-version = \"2026-10\""), "{error}"); + } + + #[test] + fn the_first_build_takes_the_latest_released_version() { + let project = Project::new("first"); + project.manifest(None); + // January 1st, before Shopify releases 2027-01. + let network = Network::new(true, &["2026-10"]); + let schema = network.obtain(&project, true, day(2027, 1, 1)).unwrap(); + assert_eq!(schema.api_version, "2026-10"); + assert_eq!(*network.asked.borrow(), ["2027-01", "2026-10"]); + + // Once 2027-01 is out, the file stays what it is. + let network = Network::new(true, &["2026-10", "2027-01"]); + let schema = network.obtain(&project, true, day(2027, 4, 2)).unwrap(); + assert_eq!(schema.api_version, "2026-10"); + assert!(network.asked.borrow().is_empty()); + } + + #[test] + fn a_file_of_an_older_format_is_downloaded_again_for_its_version() { + let project = Project::new("format"); + project.manifest(None); + let format = format!("\"format\":{}", crate::schema::FORMAT); + let old = schema("2026-07").replacen(&format, "\"format\":0", 1); + project.write(PROJECT_SCHEMA_PATH, &old); + let network = Network::new(true, &["2026-07", "2026-10"]); + let schema = network.obtain(&project, true, day(2026, 10, 22)).unwrap(); + assert_eq!(schema.api_version, "2026-07"); + assert_eq!(*network.asked.borrow(), ["2026-07"]); + } + } + #[test] fn files_are_replaced_in_one_step() { let project = Project::new("atomic"); diff --git a/crates/shopify_api_graphql/src/schema.rs b/crates/shopify_api_graphql/src/schema.rs index 5edfea2..5d41ff5 100644 --- a/crates/shopify_api_graphql/src/schema.rs +++ b/crates/shopify_api_graphql/src/schema.rs @@ -54,7 +54,7 @@ fragment TypeRef on __Type { "; /// The version of the stored form written by [`Schema::to_json`]. -const FORMAT: u32 = 1; +pub(crate) const FORMAT: u32 = 1; /// The reason GraphQL gives when a deprecation has none. const NO_REASON: &str = "No longer supported"; diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 2db5f65..96c79bb 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -13,12 +13,10 @@ use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, quote_spanned}; use shopify_api_graphql::codegen::{DATA_TYPE, data_types, deprecation_warning, variables_types}; use shopify_api_graphql::literal::{self, Literals, Value, VariableValue}; -use shopify_api_graphql::project::{ - DownloadError, metadata_snippet, previous_api_version, up_to_date_schema, -}; +use shopify_api_graphql::project::{metadata_snippet, project_schema}; use shopify_api_graphql::{ - MINIMUM_API_VERSION, Operation, OperationKind, PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, - SchemaSource, Variable, analyze, is_supported_api_version, latest_api_version, schema_source, + MINIMUM_API_VERSION, Operation, OperationKind, SCHEMA_ENV, Schema, SchemaSource, Variable, + analyze, is_supported_api_version, latest_api_version, schema_source, }; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; @@ -246,22 +244,23 @@ impl LoadedSchema { // dependencies, which ship their own schema files. let primary = std::env::var_os("CARGO_PRIMARY_PACKAGE").is_some(); let named = std::env::var_os(SCHEMA_ENV).filter(|_| primary); - let source = schema_source( - manifest_dir().as_deref(), - named.as_deref(), - SystemTime::now(), - )?; - let (path, schema) = match source { + let (path, schema) = match schema_source(manifest_dir().as_deref(), named.as_deref())? { SchemaSource::File(path) => { - let schema = read_schema(&path)?; + let schema = read_schema(&path).map_err(|error| { + format!( + "`{}`, named by {SCHEMA_ENV}: {error}. Download it again with \ + `shopify-api schema download --out `.", + path.display() + ) + })?; (path, schema) } - SchemaSource::Version { - path, - version, - latest, - } => { - let schema = version_schema(&path, &version, latest)?; + SchemaSource::Project { dir, path, pinned } => { + let read = |path: &Path| { + read_schema(path).map_err(|error| format!("`{}`: {error}", path.display())) + }; + let schema = + project_schema(&dir, pinned.as_deref(), primary, SystemTime::now(), read)?; (path, schema) } }; @@ -280,7 +279,8 @@ impl LoadedSchema { /// The schema of `shopify_api`'s own operations. fn internal() -> Result { let path = resolve(manifest_dir().as_deref(), Path::new(INTERNAL_SCHEMA_PATH)); - let schema = read_schema(&path)?; + let schema = + read_schema(&path).map_err(|error| format!("`{}`: {error}", path.display()))?; Ok(Self { schema, path }) } @@ -351,49 +351,8 @@ impl LoadedSchema { } } -/// The schema of `version`: its file when it holds that version, else -/// downloaded into it, once for every operation of the build. -fn version_schema(path: &Path, version: &str, latest: bool) -> Result, String> { - static DOWNLOAD: Mutex<()> = Mutex::new(()); - let _one_at_a_time = DOWNLOAD - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - up_to_date_schema(path, version, latest, read_schema) - .map_err(|error| download_failure(&error, version, latest, SystemTime::now())) -} - -/// What to tell when the schema of `version` cannot be had at `now`. -fn download_failure(error: &DownloadError, version: &str, latest: bool, now: SystemTime) -> String { - match error { - DownloadError::UnknownVersion { .. } => { - // On the first day of a quarter, its version may not be out yet. - let released = latest_api_version(now); - let suggested = match previous_api_version(version) { - Some(previous) if released.as_str() >= version => previous, - _ => released, - }; - format!( - "{error}: it is not out yet, or its name is wrong. \ - Declare a released version in Cargo.toml:\n\n{}", - metadata_snippet(&suggested) - ) - } - DownloadError::Failed(_) => { - let which = if latest { - format!("the latest Admin API version, {version} (Cargo.toml declares none)") - } else { - format!("the Admin API version in Cargo.toml, {version}") - }; - format!( - "{error}\n`graphql!` downloads the schema of {which} into `{PROJECT_SCHEMA_PATH}`: \ - build once with network access and commit the file" - ) - } - } -} - /// Reads a schema file. One compilation expands many operations: each file is -/// parsed once, and again when it changes. +/// parsed once, and again when it changes. The error does not name the file. fn read_schema(file: &Path) -> Result, String> { static CACHE: Mutex> = Mutex::new(None); let modified = std::fs::metadata(file) @@ -408,14 +367,10 @@ fn read_schema(file: &Path) -> Result, String> { { return Ok(schema.clone()); } - let json = std::fs::read_to_string(file) - .map_err(|error| format!("Cannot read the schema `{}`: {error}", file.display()))?; - let schema = Schema::from_json(&json).map(Arc::new).map_err(|error| { - format!( - "`{}`: {error}. Delete it, or run `shopify-api schema download`, to download it again.", - file.display() - ) - })?; + let json = std::fs::read_to_string(file).map_err(|error| format!("cannot read it: {error}"))?; + let schema = Schema::from_json(&json) + .map(Arc::new) + .map_err(|error| error.to_string())?; cache.insert(file.to_path_buf(), (modified, schema.clone())); Ok(schema) } @@ -746,24 +701,15 @@ mod tests { } #[test] - fn a_malformed_schema_file_says_how_to_restore_it() { + fn a_malformed_schema_file_says_why() { let project = Project::new("malformed"); let file = project.write("graphql/admin.schema.json", "{"); let error = read_schema(&file).unwrap_err(); - assert!( - error.starts_with(&format!("`{}`: Invalid schema file: ", file.display())), - "{error}" - ); - assert!( - error.ends_with( - ". Delete it, or run `shopify-api schema download`, to download it again." - ), - "{error}" - ); + assert!(error.starts_with("Invalid schema file: "), "{error}"); let error = read_schema(&project.0.join("absent.json")).unwrap_err(); - assert!(error.starts_with("Cannot read the schema `"), "{error}"); + assert!(error.starts_with("cannot read it: "), "{error}"); } #[test] @@ -857,32 +803,4 @@ mod tests { assert_eq!(error, message, "{source}"); } } - - #[test] - fn a_version_shopify_does_not_have_is_named_and_a_released_one_suggested() { - let day = - |days: u64| SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(days * 86_400); - let (october_22_2026, january_1_2027) = (day(20_748), day(20_819)); - let unknown = |version: &str| DownloadError::UnknownVersion { - version: version.to_string(), - answer: "HTTP 400".to_string(), - }; - - assert_eq!( - download_failure(&unknown("2027-04"), "2027-04", false, october_22_2026), - "Shopify has no Admin API version 2027-04 (HTTP 400): it is not out yet, \ - or its name is wrong. Declare a released version in Cargo.toml:\n\n\ - [package.metadata.shopify_api]\napi-version = \"2026-10\"" - ); - // On the first day of a quarter, before Shopify releases its version. - let error = download_failure(&unknown("2027-01"), "2027-01", false, january_1_2027); - assert!(error.ends_with("api-version = \"2026-10\""), "{error}"); - - let offline = DownloadError::Failed("cannot download".to_string()); - let error = download_failure(&offline, "2026-07", false, october_22_2026); - assert!( - error.ends_with("build once with network access and commit the file"), - "{error}" - ); - } } From d331d6e5fe9afe5b4cf44fef5b3c44ceb5fca0ad Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:34:31 +0100 Subject: [PATCH 084/135] feat(schema): check @oneOf input objects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The introspection query asks for `isOneOf`, and the stored schema keeps it (`"o": true`), in format 2. A file of format 1 is downloaded again by the package being built, and is a compile error in a dependency, as any file that does not fit. A oneOf input object takes exactly one field, `field: value`, whose value is not null: no field, two fields, `field: null` and `field?: …` are refused at the token, in literals, in `input!` and in the text of an operation, where a variable given to its field must be non-null. The test and internal schemas are downloaded again: 37 input objects of 2026-10 are oneOf, ProductSetIdentifiers among them. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/docs/graphql.md | 7 ++ crates/shopify_api/docs/input.md | 3 +- crates/shopify_api/graphql/admin.schema.json | 76 +++++++++---------- .../shopify_api/graphql/internal.schema.json | 2 +- crates/shopify_api/src/schema.rs | 1 + crates/shopify_api/tests/ui/literal_one_of.rs | 9 +++ .../tests/ui/literal_one_of.stderr | 61 +++++++++++++++ .../tests/ui/literal_option_in_field.stderr | 2 +- .../tests/ui/literal_wrong_input_type.stderr | 6 +- .../tests/ui/literal_wrong_scalar.stderr | 10 +-- crates/shopify_api_graphql/src/analyze.rs | 42 +++++++++- crates/shopify_api_graphql/src/codegen.rs | 2 +- crates/shopify_api_graphql/src/literal.rs | 60 ++++++++++++--- crates/shopify_api_graphql/src/restrict.rs | 2 +- crates/shopify_api_graphql/src/schema.rs | 60 ++++++++++++--- crates/shopify_api_graphql/tests/analyze.rs | 31 ++++++++ crates/shopify_api_graphql/tests/literal.rs | 46 ++++++++++- crates/shopify_api_macros/src/lib.rs | 2 +- 18 files changed, 345 insertions(+), 77 deletions(-) create mode 100644 crates/shopify_api/tests/ui/literal_one_of.rs create mode 100644 crates/shopify_api/tests/ui/literal_one_of.stderr diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 7fb2950..6ba2a04 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -192,6 +192,13 @@ object or a list where the type wants another form are compile errors that point at the token. A deprecated field or enum value is a warning that gives Shopify's reason. +A `@oneOf` input object, such as `ProductSetIdentifiers`, takes exactly one +of its fields, written `field: value`, with a value that is not `null`: +`{ handle: "shirt" }`. No field, two fields, `field: null` and `field?: …` +are compile errors at the token, which list the fields to choose from. In +the text of an operation the same holds, and a variable given to such a field +must be non-null (`$handle: String!`). + A field is written one of four ways: | Field | Sends | diff --git a/crates/shopify_api/docs/input.md b/crates/shopify_api/docs/input.md index 2fe2fa9..d744a55 100644 --- a/crates/shopify_api/docs/input.md +++ b/crates/shopify_api/docs/input.md @@ -40,7 +40,8 @@ async fn set_colors(shopify: &Shopify, rows: &[Row]) -> shopify_api::Result<()> compile error, with the closest input object. The fields follow the rules of the [literals of `graphql!`](crate::graphql!#input-values): GraphQL names, every required field, `?:` for a field that may be left out, enum values bare or -`raw(…)`, nested objects and lists, `[for … => …]`. +`raw(…)`, nested objects and lists, `[for … => …]`. A `@oneOf` input object +takes exactly one field, not `null`: `input!(ProductSetIdentifiers { handle: "shirt" })`. A value of another input type is refused where one is expected, with a message that names the place and the GraphQL type it expects: diff --git a/crates/shopify_api/graphql/admin.schema.json b/crates/shopify_api/graphql/admin.schema.json index b571286..4300f96 100644 --- a/crates/shopify_api/graphql/admin.schema.json +++ b/crates/shopify_api/graphql/admin.schema.json @@ -1,4 +1,4 @@ -{"format":1,"apiVersion":"2026-10","query":"QueryRoot","mutation":"Mutation", +{"format":2,"apiVersion":"2026-10","query":"QueryRoot","mutation":"Mutation", "directives":{"idempotent":{"l":["FIELD"],"a":{"key":"String!"}},"include":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}},"skip":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}}},"types":{ "ARN":"s", "AbandonedCheckout":{"o":{"f":{"abandonedCheckoutUrl":"URL!","billingAddress":"MailingAddress","completedAt":"DateTime","createdAt":"DateTime!","customAttributes":"[Attribute!]!","customer":"Customer","defaultCursor":"String!","discountCodes":"[String!]!","id":"ID!","lineItems":["AbandonedCheckoutLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"lineItemsQuantity":"Int!","name":"String!","note":"String!","shippingAddress":"MailingAddress","subtotalPriceSet":"MoneyBag!","taxLines":"[TaxLine!]!","taxesIncluded":"Boolean!","totalDiscountSet":"MoneyBag!","totalDutiesSet":"MoneyBag","totalLineItemsPriceSet":"MoneyBag!","totalPriceSet":"MoneyBag!","totalTaxSet":"MoneyBag","updatedAt":"DateTime!"},"t":["Navigable","Node"],"d":{"lineItemsQuantity":"Use [AbandonedCheckoutLineItem.quantity](https://shopify.dev/api/admin-graphql/unstable/objects/AbandonedCheckoutLineItem#field-quantity) instead."}}}, @@ -435,7 +435,7 @@ "CheckoutAndAccountsConfigurationBrandingExpressCheckoutButtonInput":{"i":{"cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius"}}, "CheckoutAndAccountsConfigurationBrandingExpressCheckoutInput":{"i":{"button":"CheckoutAndAccountsConfigurationBrandingExpressCheckoutButtonInput"}}, "CheckoutAndAccountsConfigurationBrandingFontGroup":{"u":["CheckoutAndAccountsConfigurationBrandingCustomFontGroup","CheckoutAndAccountsConfigurationBrandingShopifyFontGroup"]}, -"CheckoutAndAccountsConfigurationBrandingFontGroupInput":{"i":{"customFontGroup":"CheckoutAndAccountsConfigurationBrandingCustomFontGroupInput","shopifyFontGroup":"CheckoutAndAccountsConfigurationBrandingShopifyFontGroupInput"}}, +"CheckoutAndAccountsConfigurationBrandingFontGroupInput":{"i":{"f":{"customFontGroup":"CheckoutAndAccountsConfigurationBrandingCustomFontGroupInput","shopifyFontGroup":"CheckoutAndAccountsConfigurationBrandingShopifyFontGroupInput"},"o":true}}, "CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy":{"e":["AUTO","BLOCK","SWAP","FALLBACK","OPTIONAL"]}, "CheckoutAndAccountsConfigurationBrandingFontSize":{"o":{"f":{"base":"Float","ratio":"Float"}}}, "CheckoutAndAccountsConfigurationBrandingFontSizeInput":{"i":{"base":"Float","ratio":"Float"}}, @@ -454,7 +454,7 @@ "CheckoutAndAccountsConfigurationBrandingHeadingLevel":{"o":{"f":{"typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyle"}}}, "CheckoutAndAccountsConfigurationBrandingHeadingLevelInput":{"i":{"typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput"}}, "CheckoutAndAccountsConfigurationBrandingImage":{"o":{"f":{"image":"Image"}}}, -"CheckoutAndAccountsConfigurationBrandingImageInput":{"i":{"mediaImageId":"ID"}}, +"CheckoutAndAccountsConfigurationBrandingImageInput":{"i":{"f":{"mediaImageId":"ID"},"o":true}}, "CheckoutAndAccountsConfigurationBrandingImageValue":{"u":["CheckoutAndAccountsConfigurationBrandingImage"]}, "CheckoutAndAccountsConfigurationBrandingInput":{"i":{"components":"CheckoutAndAccountsConfigurationBrandingComponentsInput","designTokens":"CheckoutAndAccountsConfigurationBrandingDesignTokensInput","surfaces":"CheckoutAndAccountsConfigurationBrandingSurfacesInput"}}, "CheckoutAndAccountsConfigurationBrandingLabelPosition":{"e":["INSIDE","OUTSIDE"]}, @@ -686,7 +686,7 @@ "CollectionCreatePayload":{"o":{"f":{"collection":"Collection","userErrors":"[UserError!]!"}}}, "CollectionCreateSourceExclusionInput":{"i":{"conditions":"[CollectionSourceExclusionConditionInput!]=","matchType":"CollectionConditionMatchType","selections":"[CollectionExclusionProductSelectionInput!]="}}, "CollectionCreateSourceInclusionInput":{"i":{"conditions":"[CollectionSourceInclusionConditionInput!]=","matchType":"CollectionConditionMatchType","selections":"[CollectionInclusionProductSelectionInput!]="}}, -"CollectionCreateSourceTargetInput":{"i":{"shareableSource":"CollectionShareableSourceInput","source":"CollectionCreateConditionsSourceInput","subCollections":"CollectionCreateSubCollectionsSourceInput"}}, +"CollectionCreateSourceTargetInput":{"i":{"f":{"shareableSource":"CollectionShareableSourceInput","source":"CollectionCreateConditionsSourceInput","subCollections":"CollectionCreateSubCollectionsSourceInput"},"o":true}}, "CollectionCreateSubCollectionsSourceInput":{"i":{"collectionIds":"[ID!]!","description":"String","title":"String!"}}, "CollectionDeleteInput":{"i":{"id":"ID!"}}, "CollectionDeletePayload":{"o":{"f":{"deletedCollectionId":"ID","shop":"Shop!","userErrors":"[UserError!]!"}}}, @@ -701,7 +701,7 @@ "CollectionExclusionProductSelectionConnection":{"o":{"f":{"edges":"[CollectionExclusionProductSelectionEdge!]!","nodes":"[CollectionExclusionProductSelection!]!","pageInfo":"PageInfo!"}}}, "CollectionExclusionProductSelectionEdge":{"o":{"f":{"cursor":"String!","node":"CollectionExclusionProductSelection!"}}}, "CollectionExclusionProductSelectionInput":{"i":{"productId":"ID!"}}, -"CollectionIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"}}, +"CollectionIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"},"o":true}}, "CollectionInclusionProductSelection":{"o":{"f":{"product":"Product!","variantIds":"[ID!]"}}}, "CollectionInclusionProductSelectionConnection":{"o":{"f":{"edges":"[CollectionInclusionProductSelectionEdge!]!","nodes":"[CollectionInclusionProductSelection!]!","pageInfo":"PageInfo!"}}}, "CollectionInclusionProductSelectionEdge":{"o":{"f":{"cursor":"String!","node":"CollectionInclusionProductSelection!"}}}, @@ -739,7 +739,7 @@ "CollectionSourceExclusionCondition":{"n":{"f":{"id":"ID!"},"t":["CollectionSourceExclusionConditionCollection","CollectionSourceExclusionConditionProductCategory","CollectionSourceExclusionConditionProductTag","CollectionSourceExclusionConditionProductType","CollectionSourceExclusionConditionProductVendor","CollectionSourceExclusionConditionUnknown"]}}, "CollectionSourceExclusionConditionCollection":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","values":"[Collection!]!"},"t":["CollectionSourceExclusionCondition"]}}, "CollectionSourceExclusionConditionCollectionInput":{"i":{"values":"[ID!]!"}}, -"CollectionSourceExclusionConditionInput":{"i":{"collection":"CollectionSourceExclusionConditionCollectionInput","productCategory":"CollectionSourceExclusionConditionProductCategoryInput","productTag":"CollectionSourceExclusionConditionProductTagInput","productType":"CollectionSourceExclusionConditionProductTypeInput","productVendor":"CollectionSourceExclusionConditionProductVendorInput"}}, +"CollectionSourceExclusionConditionInput":{"i":{"f":{"collection":"CollectionSourceExclusionConditionCollectionInput","productCategory":"CollectionSourceExclusionConditionProductCategoryInput","productTag":"CollectionSourceExclusionConditionProductTagInput","productType":"CollectionSourceExclusionConditionProductTypeInput","productVendor":"CollectionSourceExclusionConditionProductVendorInput"},"o":true}}, "CollectionSourceExclusionConditionProductCategory":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductCategoryRelation!","values":"[CollectionSourceExclusionConditionProductCategoryValue!]!"},"t":["CollectionSourceExclusionCondition"]}}, "CollectionSourceExclusionConditionProductCategoryInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductCategoryRelation!","values":"[CollectionSourceExclusionConditionProductCategoryValueInput!]!"}}, "CollectionSourceExclusionConditionProductCategoryRelation":{"e":["EQUALS"]}, @@ -756,14 +756,14 @@ "CollectionSourceExclusionConditionProductVendorRelation":{"e":["EQUALS","CONTAINS"]}, "CollectionSourceExclusionConditionUnknown":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType","relation":"String","values":"[String!]"},"t":["CollectionSourceExclusionCondition"]}}, "CollectionSourceExclusionConditionUpdateCollectionInput":{"i":{"values":"[ID!]!"}}, -"CollectionSourceExclusionConditionUpdateInput":{"i":{"collection":"CollectionSourceExclusionConditionUpdateCollectionInput","productCategory":"CollectionSourceExclusionConditionUpdateProductCategoryInput","productTag":"CollectionSourceExclusionConditionUpdateProductTagInput","productType":"CollectionSourceExclusionConditionUpdateProductTypeInput","productVendor":"CollectionSourceExclusionConditionUpdateProductVendorInput"}}, +"CollectionSourceExclusionConditionUpdateInput":{"i":{"f":{"collection":"CollectionSourceExclusionConditionUpdateCollectionInput","productCategory":"CollectionSourceExclusionConditionUpdateProductCategoryInput","productTag":"CollectionSourceExclusionConditionUpdateProductTagInput","productType":"CollectionSourceExclusionConditionUpdateProductTypeInput","productVendor":"CollectionSourceExclusionConditionUpdateProductVendorInput"},"o":true}}, "CollectionSourceExclusionConditionUpdateProductCategoryInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductCategoryRelation","values":"[CollectionSourceExclusionConditionProductCategoryValueInput!]"}}, "CollectionSourceExclusionConditionUpdateProductTagInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductTagRelation","values":"[String!]"}}, "CollectionSourceExclusionConditionUpdateProductTypeInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductTypeRelation","values":"[String!]"}}, "CollectionSourceExclusionConditionUpdateProductVendorInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductVendorRelation","values":"[String!]"}}, "CollectionSourceInclusion":{"o":{"f":{"conditions":"[CollectionSourceInclusionCondition!]!","matchType":"CollectionConditionMatchType","selections":["CollectionInclusionProductSelectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, "CollectionSourceInclusionCondition":{"n":{"f":{"id":"ID!"},"t":["CollectionSourceInclusionConditionMetafieldBoolean","CollectionSourceInclusionConditionMetafieldDecimal","CollectionSourceInclusionConditionMetafieldInt","CollectionSourceInclusionConditionMetafieldInteger","CollectionSourceInclusionConditionMetafieldMetaobject","CollectionSourceInclusionConditionMetafieldMetaobjectList","CollectionSourceInclusionConditionMetafieldString","CollectionSourceInclusionConditionMetafieldStringList","CollectionSourceInclusionConditionProductCategory","CollectionSourceInclusionConditionProductStatus","CollectionSourceInclusionConditionProductTag","CollectionSourceInclusionConditionProductTitle","CollectionSourceInclusionConditionProductType","CollectionSourceInclusionConditionProductVendor","CollectionSourceInclusionConditionUnknown","CollectionSourceInclusionConditionVariantCompareAtPrice","CollectionSourceInclusionConditionVariantInventory","CollectionSourceInclusionConditionVariantPrice","CollectionSourceInclusionConditionVariantTitle","CollectionSourceInclusionConditionVariantWeight"]}}, -"CollectionSourceInclusionConditionInput":{"i":{"f":{"metafieldBoolean":"CollectionSourceInclusionConditionMetafieldBooleanInput","metafieldDecimal":"CollectionSourceInclusionConditionMetafieldDecimalInput","metafieldInt":"CollectionSourceInclusionConditionMetafieldIntInput","metafieldInteger":"CollectionSourceInclusionConditionMetafieldIntegerInput","metafieldMetaobject":"CollectionSourceInclusionConditionMetafieldMetaobjectInput","metafieldMetaobjectList":"CollectionSourceInclusionConditionMetafieldMetaobjectListInput","metafieldString":"CollectionSourceInclusionConditionMetafieldStringInput","metafieldStringList":"CollectionSourceInclusionConditionMetafieldStringListInput","productCategory":"CollectionSourceInclusionConditionProductCategoryInput","productStatus":"CollectionSourceInclusionConditionProductStatusInput","productTag":"CollectionSourceInclusionConditionProductTagInput","productTitle":"CollectionSourceInclusionConditionProductTitleInput","productType":"CollectionSourceInclusionConditionProductTypeInput","productVendor":"CollectionSourceInclusionConditionProductVendorInput","variantCompareAtPrice":"CollectionSourceInclusionConditionVariantCompareAtPriceInput","variantInventory":"CollectionSourceInclusionConditionVariantInventoryInput","variantPrice":"CollectionSourceInclusionConditionVariantPriceInput","variantTitle":"CollectionSourceInclusionConditionVariantTitleInput","variantWeight":"CollectionSourceInclusionConditionVariantWeightInput"},"d":{"metafieldInteger":"Use `metafieldInt` instead. Integer metafields support values beyond the range of GraphQL's 32-bit `Int`. Removed as of the 2027-01 release."}}}, +"CollectionSourceInclusionConditionInput":{"i":{"f":{"metafieldBoolean":"CollectionSourceInclusionConditionMetafieldBooleanInput","metafieldDecimal":"CollectionSourceInclusionConditionMetafieldDecimalInput","metafieldInt":"CollectionSourceInclusionConditionMetafieldIntInput","metafieldInteger":"CollectionSourceInclusionConditionMetafieldIntegerInput","metafieldMetaobject":"CollectionSourceInclusionConditionMetafieldMetaobjectInput","metafieldMetaobjectList":"CollectionSourceInclusionConditionMetafieldMetaobjectListInput","metafieldString":"CollectionSourceInclusionConditionMetafieldStringInput","metafieldStringList":"CollectionSourceInclusionConditionMetafieldStringListInput","productCategory":"CollectionSourceInclusionConditionProductCategoryInput","productStatus":"CollectionSourceInclusionConditionProductStatusInput","productTag":"CollectionSourceInclusionConditionProductTagInput","productTitle":"CollectionSourceInclusionConditionProductTitleInput","productType":"CollectionSourceInclusionConditionProductTypeInput","productVendor":"CollectionSourceInclusionConditionProductVendorInput","variantCompareAtPrice":"CollectionSourceInclusionConditionVariantCompareAtPriceInput","variantInventory":"CollectionSourceInclusionConditionVariantInventoryInput","variantPrice":"CollectionSourceInclusionConditionVariantPriceInput","variantTitle":"CollectionSourceInclusionConditionVariantTitleInput","variantWeight":"CollectionSourceInclusionConditionVariantWeightInput"},"d":{"metafieldInteger":"Use `metafieldInt` instead. Integer metafields support values beyond the range of GraphQL's 32-bit `Int`. Removed as of the 2027-01 release."},"o":true}}, "CollectionSourceInclusionConditionMetafield":{"n":{"f":{"definition":"MetafieldDefinition!","id":"ID!"},"t":["CollectionSourceInclusionConditionMetafieldBoolean","CollectionSourceInclusionConditionMetafieldDecimal","CollectionSourceInclusionConditionMetafieldInt","CollectionSourceInclusionConditionMetafieldInteger","CollectionSourceInclusionConditionMetafieldMetaobject","CollectionSourceInclusionConditionMetafieldMetaobjectList","CollectionSourceInclusionConditionMetafieldString","CollectionSourceInclusionConditionMetafieldStringList"]}}, "CollectionSourceInclusionConditionMetafieldBoolean":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldBooleanRelation!","value":"Boolean!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, "CollectionSourceInclusionConditionMetafieldBooleanInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldBooleanRelation!","value":"Boolean!"}}, @@ -810,7 +810,7 @@ "CollectionSourceInclusionConditionProductVendorInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductVendorRelation!","values":"[String!]!"}}, "CollectionSourceInclusionConditionProductVendorRelation":{"e":["EQUALS","NOT_EQUALS","STARTS_WITH","ENDS_WITH","CONTAINS","DOES_NOT_CONTAIN"]}, "CollectionSourceInclusionConditionUnknown":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType","relation":"String","values":"[String!]"},"t":["CollectionSourceInclusionCondition"]}}, -"CollectionSourceInclusionConditionUpdateInput":{"i":{"f":{"metafieldBoolean":"CollectionSourceInclusionConditionUpdateMetafieldBooleanInput","metafieldDecimal":"CollectionSourceInclusionConditionUpdateMetafieldDecimalInput","metafieldInt":"CollectionSourceInclusionConditionUpdateMetafieldIntInput","metafieldInteger":"CollectionSourceInclusionConditionUpdateMetafieldIntegerInput","metafieldMetaobject":"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectInput","metafieldMetaobjectList":"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectListInput","metafieldString":"CollectionSourceInclusionConditionUpdateMetafieldStringInput","metafieldStringList":"CollectionSourceInclusionConditionUpdateMetafieldStringListInput","productCategory":"CollectionSourceInclusionConditionUpdateProductCategoryInput","productStatus":"CollectionSourceInclusionConditionUpdateProductStatusInput","productTag":"CollectionSourceInclusionConditionUpdateProductTagInput","productTitle":"CollectionSourceInclusionConditionUpdateProductTitleInput","productType":"CollectionSourceInclusionConditionUpdateProductTypeInput","productVendor":"CollectionSourceInclusionConditionUpdateProductVendorInput","variantCompareAtPrice":"CollectionSourceInclusionConditionUpdateVariantCompareAtPriceInput","variantInventory":"CollectionSourceInclusionConditionUpdateVariantInventoryInput","variantPrice":"CollectionSourceInclusionConditionUpdateVariantPriceInput","variantTitle":"CollectionSourceInclusionConditionUpdateVariantTitleInput","variantWeight":"CollectionSourceInclusionConditionUpdateVariantWeightInput"},"d":{"metafieldInteger":"Use `metafieldInt` instead. Integer metafields support values beyond the range of GraphQL's 32-bit `Int`. Removed as of the 2027-01 release."}}}, +"CollectionSourceInclusionConditionUpdateInput":{"i":{"f":{"metafieldBoolean":"CollectionSourceInclusionConditionUpdateMetafieldBooleanInput","metafieldDecimal":"CollectionSourceInclusionConditionUpdateMetafieldDecimalInput","metafieldInt":"CollectionSourceInclusionConditionUpdateMetafieldIntInput","metafieldInteger":"CollectionSourceInclusionConditionUpdateMetafieldIntegerInput","metafieldMetaobject":"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectInput","metafieldMetaobjectList":"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectListInput","metafieldString":"CollectionSourceInclusionConditionUpdateMetafieldStringInput","metafieldStringList":"CollectionSourceInclusionConditionUpdateMetafieldStringListInput","productCategory":"CollectionSourceInclusionConditionUpdateProductCategoryInput","productStatus":"CollectionSourceInclusionConditionUpdateProductStatusInput","productTag":"CollectionSourceInclusionConditionUpdateProductTagInput","productTitle":"CollectionSourceInclusionConditionUpdateProductTitleInput","productType":"CollectionSourceInclusionConditionUpdateProductTypeInput","productVendor":"CollectionSourceInclusionConditionUpdateProductVendorInput","variantCompareAtPrice":"CollectionSourceInclusionConditionUpdateVariantCompareAtPriceInput","variantInventory":"CollectionSourceInclusionConditionUpdateVariantInventoryInput","variantPrice":"CollectionSourceInclusionConditionUpdateVariantPriceInput","variantTitle":"CollectionSourceInclusionConditionUpdateVariantTitleInput","variantWeight":"CollectionSourceInclusionConditionUpdateVariantWeightInput"},"d":{"metafieldInteger":"Use `metafieldInt` instead. Integer metafields support values beyond the range of GraphQL's 32-bit `Int`. Removed as of the 2027-01 release."},"o":true}}, "CollectionSourceInclusionConditionUpdateMetafieldBooleanInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldBooleanRelation","value":"Boolean"}}, "CollectionSourceInclusionConditionUpdateMetafieldDecimalInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldDecimalRelation","value":"Decimal"}}, "CollectionSourceInclusionConditionUpdateMetafieldIntInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldIntRelation","value":"String"}}, @@ -858,7 +858,7 @@ "CollectionUpdateSourceExclusionInput":{"i":{"conditionsToCreate":"[CollectionSourceExclusionConditionInput!]","conditionsToDelete":"[ID!]","conditionsToUpdate":"[CollectionUpdateSourceExclusionConditionInput!]","matchType":"CollectionConditionMatchType","selectionsToAdd":"[CollectionExclusionProductSelectionInput!]","selectionsToRemove":"[CollectionExclusionProductSelectionInput!]"}}, "CollectionUpdateSourceInclusionConditionInput":{"i":{"condition":"CollectionSourceInclusionConditionUpdateInput!","id":"ID!"}}, "CollectionUpdateSourceInclusionInput":{"i":{"conditionsToCreate":"[CollectionSourceInclusionConditionInput!]","conditionsToDelete":"[ID!]","conditionsToUpdate":"[CollectionUpdateSourceInclusionConditionInput!]","matchType":"CollectionConditionMatchType","selectionsToAdd":"[CollectionInclusionProductSelectionInput!]","selectionsToRemove":"[CollectionInclusionProductSelectionInput!]"}}, -"CollectionUpdateSourceTargetInput":{"i":{"condition":"CollectionUpdateConditionsSourceInput","subCollections":"CollectionUpdateSubCollectionsSourceInput"}}, +"CollectionUpdateSourceTargetInput":{"i":{"f":{"condition":"CollectionUpdateConditionsSourceInput","subCollections":"CollectionUpdateSubCollectionsSourceInput"},"o":true}}, "CollectionUpdateSubCollectionsSourceInput":{"i":{"collectionIds":"[ID!]","description":"String","id":"ID!","title":"String"}}, "Color":"s", "ColumnDataType":{"e":["UNSPECIFIED","MONEY","PERCENT","INTEGER","FLOAT","DECIMAL","STRING","BOOLEAN","TIMESTAMP","MINUTE_TIMESTAMP","HOUR_TIMESTAMP","DAY_TIMESTAMP","WEEK_TIMESTAMP","MONTH_TIMESTAMP","QUARTER_TIMESTAMP","YEAR_TIMESTAMP","DAY_OF_WEEK","HOUR_OF_DAY","IDENTITY","MONTH_OF_YEAR","WEEK_OF_YEAR","SECOND_TIMESTAMP","ARRAY","MILLISECOND_DURATION","SECOND_DURATION","MINUTE_DURATION","HOUR_DURATION","DAY_DURATION","CUMULATIVE","GEO_COORDINATE","ENTITY","COLOR","STRING_IDENTITY","RATING","UNITLESS_SCALAR","MULTIPLIER"]}, @@ -1026,7 +1026,7 @@ "CustomerEmailMarketingConsentUpdateUserErrorCode":{"e":["INVALID","INCLUSION","INTERNAL_ERROR","MISSING_ARGUMENT"]}, "CustomerEmailMarketingState":{"e":["NOT_SUBSCRIBED","PENDING","SUBSCRIBED","UNSUBSCRIBED","REDACTED","INVALID"]}, "CustomerGenerateAccountActivationUrlPayload":{"o":{"f":{"accountActivationUrl":"URL","userErrors":"[UserError!]!"}}}, -"CustomerIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","emailAddress":"String","id":"ID","phoneNumber":"String"}}, +"CustomerIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","emailAddress":"String","id":"ID","phoneNumber":"String"},"o":true}}, "CustomerInput":{"i":{"f":{"addresses":"[MailingAddressInput!]","email":"String","emailMarketingConsent":"CustomerEmailMarketingConsentInput","firstName":"String","id":"ID","lastName":"String","locale":"String","metafields":"[MetafieldInput!]","multipassIdentifier":"String","note":"String","phone":"String","smsMarketingConsent":"CustomerSmsMarketingConsentInput","tags":"[String!]","taxExempt":"Boolean","taxExemptions":"[TaxExemption!]","whatsAppMarketingConsent":"CustomerMarketingConsentInput"},"d":{"addresses":"Use the dedicated address mutations (`customerAddressCreate`, `customerAddressUpdate`, `customerAddressDelete`) instead."}}}, "CustomerJourney":{"o":{"f":{"customerOrderIndex":"Int!","daysToConversion":"Int!","firstVisit":"CustomerVisit!","lastVisit":"CustomerVisit","moments":"[CustomerMoment!]!"}}}, "CustomerJourneySummary":{"o":{"f":{"customerOrderIndex":"Int","daysToConversion":"Int","firstVisit":"CustomerVisit","lastVisit":"CustomerVisit","moments":["CustomerMomentConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"momentsCount":"Count","ready":"Boolean!"}}}, @@ -1101,7 +1101,7 @@ "CustomerSendAccountInviteEmailPayload":{"o":{"f":{"customer":"Customer","userErrors":"[CustomerSendAccountInviteEmailUserError!]!"}}}, "CustomerSendAccountInviteEmailUserError":{"o":{"f":{"code":"CustomerSendAccountInviteEmailUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, "CustomerSendAccountInviteEmailUserErrorCode":{"e":["INVALID"]}, -"CustomerSetIdentifiers":{"i":{"customId":"UniqueMetafieldValueInput","email":"String","id":"ID","phone":"String"}}, +"CustomerSetIdentifiers":{"i":{"f":{"customId":"UniqueMetafieldValueInput","email":"String","id":"ID","phone":"String"},"o":true}}, "CustomerSetInput":{"i":{"f":{"addresses":"[MailingAddressInput!]","email":"String","firstName":"String","id":"ID","lastName":"String","locale":"String","note":"String","phone":"String","tags":"[String!]","taxExempt":"Boolean","taxExemptions":"[TaxExemption!]"},"d":{"addresses":"Use the dedicated address mutations (`customerAddressCreate`, `customerAddressUpdate`, `customerAddressDelete`) instead.","id":"To update a customer use `identifier` argument instead."}}}, "CustomerSetPayload":{"o":{"f":{"customer":"Customer","userErrors":"[CustomerSetUserError!]!"}}}, "CustomerSetUserError":{"o":{"f":{"code":"CustomerSetUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, @@ -1218,10 +1218,10 @@ "DeliveryMethodType":{"e":["SHIPPING","PICK_UP","NONE","RETAIL","LOCAL","PICKUP_POINT"]}, "DeliveryOptionDefinition":{"n":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!"},"t":["DeliveryCarrierCalculatedOptionDefinition","DeliveryFlatRateOptionDefinition","DeliveryValueBasedOptionDefinition","DeliveryWeightBasedOptionDefinition"]}}, "DeliveryOptionDefinitionConnection":{"o":{"f":{"edges":"[DeliveryOptionDefinitionEdge!]!","nodes":"[DeliveryOptionDefinition!]!","pageInfo":"PageInfo!"}}}, -"DeliveryOptionDefinitionCreateInput":{"i":{"carrierCalculated":"DeliveryCarrierCalculatedOptionDefinitionCreateInput","flatRate":"DeliveryFlatRateOptionDefinitionCreateInput","valueBased":"DeliveryValueBasedOptionDefinitionCreateInput","weightBased":"DeliveryWeightBasedOptionDefinitionCreateInput"}}, +"DeliveryOptionDefinitionCreateInput":{"i":{"f":{"carrierCalculated":"DeliveryCarrierCalculatedOptionDefinitionCreateInput","flatRate":"DeliveryFlatRateOptionDefinitionCreateInput","valueBased":"DeliveryValueBasedOptionDefinitionCreateInput","weightBased":"DeliveryWeightBasedOptionDefinitionCreateInput"},"o":true}}, "DeliveryOptionDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryOptionDefinition!"}}}, "DeliveryOptionDefinitionRateGroup":{"n":{"f":{"conditions":"DeliveryRateGroupConditions!","id":"ID!"},"t":["DeliveryCarrierCalculatedRateGroup","DeliveryFlatRateGroup","DeliveryValueBasedRateGroup","DeliveryWeightBasedRateGroup"]}}, -"DeliveryOptionDefinitionUpdateInput":{"i":{"carrierCalculated":"DeliveryCarrierCalculatedOptionDefinitionUpdateInput","flatRate":"DeliveryFlatRateOptionDefinitionUpdateInput","valueBased":"DeliveryValueBasedOptionDefinitionUpdateInput","weightBased":"DeliveryWeightBasedOptionDefinitionUpdateInput"}}, +"DeliveryOptionDefinitionUpdateInput":{"i":{"f":{"carrierCalculated":"DeliveryCarrierCalculatedOptionDefinitionUpdateInput","flatRate":"DeliveryFlatRateOptionDefinitionUpdateInput","valueBased":"DeliveryValueBasedOptionDefinitionUpdateInput","weightBased":"DeliveryWeightBasedOptionDefinitionUpdateInput"},"o":true}}, "DeliveryParticipant":{"o":{"f":{"adaptToNewServicesFlag":"Boolean!","carrierService":"DeliveryCarrierService!","fixedFee":"MoneyV2","id":"ID!","participantServices":"[DeliveryParticipantService!]!","percentageOfRateFee":"Float!"},"t":["Node"]}}, "DeliveryParticipantInput":{"i":{"adaptToNewServices":"Boolean","carrierServiceId":"ID","fixedFee":"MoneyInput","id":"ID","participantServices":"[DeliveryParticipantServiceInput!]","percentageOfRateFee":"Float"}}, "DeliveryParticipantService":{"o":{"f":{"active":"Boolean!","name":"String!"}}}, @@ -1373,7 +1373,7 @@ "DiscountCombinesWith":{"o":{"f":{"orderDiscounts":"Boolean!","productDiscounts":"Boolean!","productDiscountsWithTagsOnSameCartLine":"[String!]","shippingDiscounts":"Boolean!"}}}, "DiscountCombinesWithInput":{"i":{"orderDiscounts":"Boolean=","productDiscounts":"Boolean=","productDiscountsWithTagsOnSameCartLine":"ProductDiscountsWithTagsOnSameCartLineInput","shippingDiscounts":"Boolean="}}, "DiscountContext":{"u":["DiscountBuyerSelectionAll","DiscountContextUnknown","DiscountCustomerSegments","DiscountCustomers","DiscountMarkets"]}, -"DiscountContextInput":{"i":{"all":"DiscountBuyerSelection","customerSegments":"DiscountCustomerSegmentsInput","customers":"DiscountCustomersInput","markets":"DiscountMarketsInput"}}, +"DiscountContextInput":{"i":{"f":{"all":"DiscountBuyerSelection","customerSegments":"DiscountCustomerSegmentsInput","customers":"DiscountCustomersInput","markets":"DiscountMarketsInput"},"o":true}}, "DiscountContextUnknown":{"o":{"f":{"contextType":"String!"}}}, "DiscountCountries":{"o":{"f":{"countries":"[CountryCode!]!","includeRestOfWorld":"Boolean!"},"d":{"includeRestOfWorld":"This field is being retired. Discounts that set `includeRestOfWorld: true` will be converted to an explicit list of countries, and `countries` will then return every country where the discount applies."}}}, "DiscountCountriesInput":{"i":{"f":{"add":"[CountryCode!]","includeRestOfWorld":"Boolean=","remove":"[CountryCode!]"},"d":{"includeRestOfWorld":"This field is being retired. Use `add` to specify each country where the discount should apply."}}}, @@ -1504,7 +1504,7 @@ "EventSubjectType":{"e":["COMPANY_LOCATION","COMPANY","CUSTOMER","DRAFT_ORDER","INVENTORY_TRANSFER","COLLECTION","PRODUCT","PRODUCT_VARIANT","ARTICLE","BLOG","COMMENT","PAGE","DISCOUNT_AUTOMATIC_BXGY","DISCOUNT_AUTOMATIC_NODE","DISCOUNT_CODE_NODE","DISCOUNT_NODE","PRICE_RULE","ORDER","UNKNOWN"]}, "ExchangeLineItem":{"o":{"f":{"id":"ID!","lineItem":"LineItem","lineItems":"[LineItem!]","processableQuantity":"Int!","processedQuantity":"Int!","productId":"ID","quantity":"Int!","title":"String","unprocessedQuantity":"Int!","variantId":"ID","variantSku":"String","variantTitle":"String"},"t":["Node"],"d":{"lineItem":"Use `lineItems` instead."}}}, "ExchangeLineItemAppliedDiscountInput":{"i":{"description":"String","value":"ExchangeLineItemAppliedDiscountValueInput!"}}, -"ExchangeLineItemAppliedDiscountValueInput":{"i":{"amount":"MoneyInput","percentage":"Float"}}, +"ExchangeLineItemAppliedDiscountValueInput":{"i":{"f":{"amount":"MoneyInput","percentage":"Float"},"o":true}}, "ExchangeLineItemConnection":{"o":{"f":{"edges":"[ExchangeLineItemEdge!]!","nodes":"[ExchangeLineItem!]!","pageInfo":"PageInfo!"}}}, "ExchangeLineItemEdge":{"o":{"f":{"cursor":"String!","node":"ExchangeLineItem!"}}}, "ExchangeLineItemInput":{"i":{"appliedDiscount":"ExchangeLineItemAppliedDiscountInput","giftCardCodes":"[String!]","quantity":"Int!","variantId":"ID"}}, @@ -1936,7 +1936,7 @@ "LocationEditPayload":{"o":{"f":{"location":"Location","userErrors":"[LocationEditUserError!]!"}}}, "LocationEditUserError":{"o":{"f":{"code":"LocationEditUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, "LocationEditUserErrorCode":{"e":["TOO_LONG","BLANK","NOT_FOUND","INVALID","TAKEN","INVALID_US_ZIPCODE","GENERIC_ERROR","CANNOT_DISABLE_ONLINE_ORDER_FULFILLMENT","CANNOT_MODIFY_ONLINE_ORDER_FULFILLMENT_FOR_FS_LOCATION","INVALID_TYPE","INVALID_VALUE","APP_NOT_AUTHORIZED","UNSTRUCTURED_RESERVED_NAMESPACE","DISALLOWED_OWNER_TYPE","INCLUSION","PRESENT","TOO_SHORT","CAPABILITY_VIOLATION","INTERNAL_ERROR"]}, -"LocationIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","id":"ID"}}, +"LocationIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","id":"ID"},"o":true}}, "LocationLocalPickupDisablePayload":{"o":{"f":{"locationId":"ID","userErrors":"[DeliveryLocationLocalPickupSettingsError!]!"}}}, "LocationLocalPickupEnablePayload":{"o":{"f":{"localPickupSettings":"DeliveryLocalPickupSettings","userErrors":"[DeliveryLocationLocalPickupSettingsError!]!"}}}, "LocationSnapshot":{"o":{"f":{"address":"LocationAddress!","location":"Location","name":"String!","snapshottedAt":"DateTime!"}}}, @@ -1958,11 +1958,11 @@ "MarketConditionType":{"e":["REGION","LOCATION","COMPANY_LOCATION","CHANNEL"]}, "MarketConditions":{"o":{"f":{"channelsCondition":"ChannelsCondition","companyLocationsCondition":"CompanyLocationsCondition","conditionTypes":"[MarketConditionType!]!","locationsCondition":"LocationsCondition","regionsCondition":"RegionsCondition"}}}, "MarketConditionsChannelsInput":{"i":{"channelIds":"[ID!]"}}, -"MarketConditionsCompanyLocationsInput":{"i":{"applicationLevel":"MarketConditionApplicationType","companyLocationIds":"[ID!]"}}, +"MarketConditionsCompanyLocationsInput":{"i":{"f":{"applicationLevel":"MarketConditionApplicationType","companyLocationIds":"[ID!]"},"o":true}}, "MarketConditionsInput":{"i":{"channelsCondition":"MarketConditionsChannelsInput","companyLocationsCondition":"MarketConditionsCompanyLocationsInput","locationsCondition":"MarketConditionsLocationsInput","regionsCondition":"MarketConditionsRegionsInput"}}, -"MarketConditionsLocationsInput":{"i":{"applicationLevel":"MarketConditionApplicationType","locationIds":"[ID!]"}}, +"MarketConditionsLocationsInput":{"i":{"f":{"applicationLevel":"MarketConditionApplicationType","locationIds":"[ID!]"},"o":true}}, "MarketConditionsRegionInput":{"i":{"countryCode":"CountryCode!","subdivision":"String"}}, -"MarketConditionsRegionsInput":{"i":{"applicationLevel":"MarketConditionApplicationType","regionIds":"[ID!]","regions":"[MarketConditionsRegionInput!]"}}, +"MarketConditionsRegionsInput":{"i":{"f":{"applicationLevel":"MarketConditionApplicationType","regionIds":"[ID!]","regions":"[MarketConditionsRegionInput!]"},"o":true}}, "MarketConditionsUpdateInput":{"i":{"conditionsToAdd":"MarketConditionsInput","conditionsToDelete":"MarketConditionsInput"}}, "MarketConnection":{"o":{"f":{"edges":"[MarketEdge!]!","nodes":"[Market!]!","pageInfo":"PageInfo!"}}}, "MarketCreateInput":{"i":{"f":{"catalogs":"[ID!]","conditions":"MarketConditionsInput","currencySettings":"MarketCurrencySettingsUpdateInput","delivery":"MarketDeliveryConfigurationsCreateInput","discounts":"[ID!]","enabled":"Boolean","handle":"String","makeDuplicateRegionMarketsDraft":"Boolean","makeDuplicateUniqueMarketsDraft":"Boolean","name":"String!","priceInclusions":"MarketPriceInclusionsInput","regions":"[MarketRegionCreateInput!]","returnPolicyProfileId":"ID","status":"MarketStatus","webPresences":"[ID!]"},"d":{"enabled":"Use `status` instead.","makeDuplicateRegionMarketsDraft":"Use `makeDuplicateUniqueMarketsDraft` instead.","regions":"Use `conditions` instead."}}}, @@ -2248,13 +2248,13 @@ "MobilePlatformApplicationConnection":{"o":{"f":{"edges":"[MobilePlatformApplicationEdge!]!","nodes":"[MobilePlatformApplication!]!","pageInfo":"PageInfo!"}}}, "MobilePlatformApplicationCreateAndroidInput":{"i":{"appLinksEnabled":"Boolean!","applicationId":"String","sha256CertFingerprints":"[String!]!"}}, "MobilePlatformApplicationCreateAppleInput":{"i":{"appClipApplicationId":"String","appClipsEnabled":"Boolean","appId":"String","sharedWebCredentialsEnabled":"Boolean!","universalLinksEnabled":"Boolean!"}}, -"MobilePlatformApplicationCreateInput":{"i":{"android":"MobilePlatformApplicationCreateAndroidInput","apple":"MobilePlatformApplicationCreateAppleInput"}}, +"MobilePlatformApplicationCreateInput":{"i":{"f":{"android":"MobilePlatformApplicationCreateAndroidInput","apple":"MobilePlatformApplicationCreateAppleInput"},"o":true}}, "MobilePlatformApplicationCreatePayload":{"o":{"f":{"mobilePlatformApplication":"MobilePlatformApplication","userErrors":"[MobilePlatformApplicationUserError!]!"}}}, "MobilePlatformApplicationDeletePayload":{"o":{"f":{"deletedMobilePlatformApplicationId":"ID","userErrors":"[MobilePlatformApplicationUserError!]!"}}}, "MobilePlatformApplicationEdge":{"o":{"f":{"cursor":"String!","node":"MobilePlatformApplication!"}}}, "MobilePlatformApplicationUpdateAndroidInput":{"i":{"appLinksEnabled":"Boolean","applicationId":"String","sha256CertFingerprints":"[String!]"}}, "MobilePlatformApplicationUpdateAppleInput":{"i":{"appClipApplicationId":"String","appClipsEnabled":"Boolean","appId":"String","sharedWebCredentialsEnabled":"Boolean","universalLinksEnabled":"Boolean"}}, -"MobilePlatformApplicationUpdateInput":{"i":{"android":"MobilePlatformApplicationUpdateAndroidInput","apple":"MobilePlatformApplicationUpdateAppleInput"}}, +"MobilePlatformApplicationUpdateInput":{"i":{"f":{"android":"MobilePlatformApplicationUpdateAndroidInput","apple":"MobilePlatformApplicationUpdateAppleInput"},"o":true}}, "MobilePlatformApplicationUpdatePayload":{"o":{"f":{"mobilePlatformApplication":"MobilePlatformApplication","userErrors":"[MobilePlatformApplicationUserError!]!"}}}, "MobilePlatformApplicationUserError":{"o":{"f":{"code":"MobilePlatformApplicationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, "MobilePlatformApplicationUserErrorCode":{"e":["INVALID","NOT_FOUND","TOO_LONG"]}, @@ -2328,7 +2328,7 @@ "OrderCancelJobResult":{"o":{"f":{"done":"Boolean!","errors":"[OrderCancelUserError!]!","id":"ID!","order":"Order","status":"OrderCancelStatus!"},"t":["JobResult","Node"]}}, "OrderCancelPayload":{"o":{"f":{"job":"Job","jobResult":"OrderCancelJobResult","orderCancelUserErrors":"[OrderCancelUserError!]!","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `orderCancelUserErrors` instead."}}}, "OrderCancelReason":{"e":["CUSTOMER","DECLINED","FRAUD","INVENTORY","STAFF","OTHER"]}, -"OrderCancelRefundMethodInput":{"i":{"originalPaymentMethodsRefund":"Boolean","storeCreditRefund":"OrderCancelStoreCreditRefundInput"}}, +"OrderCancelRefundMethodInput":{"i":{"f":{"originalPaymentMethodsRefund":"Boolean","storeCreditRefund":"OrderCancelStoreCreditRefundInput"},"o":true}}, "OrderCancelStatus":{"e":["STARTED","SUCCEEDED","FAILED"]}, "OrderCancelStoreCreditRefundInput":{"i":{"expiresAt":"DateTime"}}, "OrderCancelUserError":{"o":{"f":{"code":"OrderCancelUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, @@ -2342,7 +2342,7 @@ "OrderCreateAssociateCustomerAttributesInput":{"i":{"email":"String","id":"ID"}}, "OrderCreateCustomAttributeInput":{"i":{"key":"String!","value":"String!"}}, "OrderCreateCustomerAddressInput":{"i":{"address1":"String","address2":"String","city":"String","company":"String","country":"String","firstName":"String","lastName":"String","phone":"String","province":"String","zip":"String"}}, -"OrderCreateCustomerInput":{"i":{"toAssociate":"OrderCreateAssociateCustomerAttributesInput","toUpsert":"OrderCreateUpsertCustomerAttributesInput"}}, +"OrderCreateCustomerInput":{"i":{"f":{"toAssociate":"OrderCreateAssociateCustomerAttributesInput","toUpsert":"OrderCreateUpsertCustomerAttributesInput"},"o":true}}, "OrderCreateDiscountCodeInput":{"i":{"freeShippingDiscountCode":"OrderCreateFreeShippingDiscountCodeAttributesInput","itemFixedDiscountCode":"OrderCreateFixedDiscountCodeAttributesInput","itemPercentageDiscountCode":"OrderCreatePercentageDiscountCodeAttributesInput"}}, "OrderCreateFinancialStatus":{"e":["PENDING","AUTHORIZED","PARTIALLY_PAID","PAID","PARTIALLY_REFUNDED","REFUNDED","VOIDED","EXPIRED"]}, "OrderCreateFixedDiscountCodeAttributesInput":{"i":{"amountSet":"MoneyBagInput","code":"String!"}}, @@ -2411,7 +2411,7 @@ "OrderEditUpdateShippingLinePayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[OrderEditUpdateShippingLineUserError!]!"}}}, "OrderEditUpdateShippingLineUserError":{"o":{"f":{"code":"OrderEditUpdateShippingLineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, "OrderEditUpdateShippingLineUserErrorCode":{"e":["INVALID"]}, -"OrderIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","id":"ID"}}, +"OrderIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","id":"ID"},"o":true}}, "OrderInput":{"i":{"f":{"customAttributes":"[AttributeInput!]","email":"String","id":"ID!","localizationExtensions":"[LocalizationExtensionInput!]","localizedFields":"[LocalizedFieldInput!]","metafields":"[MetafieldInput!]","note":"String","phone":"String","poNumber":"String","shippingAddress":"MailingAddressInput","tags":"[String!]"},"d":{"localizationExtensions":"This field will be removed in a future version. Use `localizedFields` instead."}}}, "OrderInvoiceSendPayload":{"o":{"f":{"order":"Order","userErrors":"[OrderInvoiceSendUserError!]!"}}}, "OrderInvoiceSendUserError":{"o":{"f":{"code":"OrderInvoiceSendUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, @@ -2655,7 +2655,7 @@ "ProductFullSyncPayload":{"o":{"f":{"id":"ID","userErrors":"[ProductFullSyncUserError!]!"}}}, "ProductFullSyncUserError":{"o":{"f":{"code":"ProductFullSyncUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, "ProductFullSyncUserErrorCode":{"e":["INVALID"]}, -"ProductIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"}}, +"ProductIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"},"o":true}}, "ProductImageSortKeys":{"e":["CREATED_AT","ID","POSITION"]}, "ProductInput":{"i":{"f":{"category":"ID","claimOwnership":"ProductClaimOwnershipInput","collectionsToJoin":"[ID!]","collectionsToLeave":"[ID!]","combinedListingRole":"CombinedListingsRole","descriptionHtml":"String","giftCard":"Boolean","giftCardTemplateSuffix":"String","handle":"String","id":"ID","metafields":"[MetafieldInput!]","productOptions":"[OptionCreateInput!]","productPublications":"[ProductPublicationInput!]","productType":"String","publications":"[ProductPublicationInput!]","publishDate":"DateTime","publishOn":"DateTime","published":"Boolean","publishedAt":"DateTime","redirectNewHandle":"Boolean","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","vendor":"String"},"d":{"productPublications":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publications":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publishDate":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publishOn":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","published":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publishedAt":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead."}}}, "ProductJoinSellingPlanGroupsPayload":{"o":{"f":{"product":"Product","userErrors":"[SellingPlanGroupUserError!]!"}}}, @@ -2693,7 +2693,7 @@ "ProductResourceFeedback":{"o":{"f":{"channel":"Channel","feedbackGeneratedAt":"DateTime!","messages":"[String!]!","productId":"ID!","productUpdatedAt":"DateTime!","state":"ResourceFeedbackState!"}}}, "ProductResourceFeedbackInput":{"i":{"channelId":"ID","feedbackGeneratedAt":"DateTime!","messages":"[String!]","productId":"ID!","productUpdatedAt":"DateTime!","state":"ResourceFeedbackState!"}}, "ProductSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineItem":"LineItem!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, -"ProductSetIdentifiers":{"i":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"}}, +"ProductSetIdentifiers":{"i":{"f":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"},"o":true}}, "ProductSetInput":{"i":{"f":{"category":"ID","claimOwnership":"ProductClaimOwnershipInput","collections":"[ID!]","combinedListingRole":"CombinedListingsRole","descriptionHtml":"String","files":"[FileSetInput!]","giftCard":"Boolean","giftCardTemplateSuffix":"String","handle":"String","id":"ID","metafields":"[MetafieldInput!]","productOptions":"[OptionSetInput!]","productType":"String","redirectNewHandle":"Boolean","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","variants":"[ProductVariantSetInput!]","vendor":"String"},"d":{"id":"Use `identifier` instead to get the product's ID"}}}, "ProductSetInventoryInput":{"i":{"locationId":"ID!","name":"String!","quantity":"Int!"}}, "ProductSetOperation":{"o":{"f":{"id":"ID!","product":"Product","status":"ProductOperationStatus!","userErrors":"[ProductSetUserError!]!"},"t":["Node","ProductOperation"]}}, @@ -2705,7 +2705,7 @@ "ProductTaxonomyNode":{"o":{"f":{"fullName":"String!","id":"ID!","isLeaf":"Boolean!","isRoot":"Boolean!","name":"String!"},"t":["Node"]}}, "ProductUnpublishInput":{"i":{"id":"ID!","productPublications":"[ProductPublicationInput!]!"}}, "ProductUnpublishPayload":{"o":{"f":{"product":"Product","shop":"Shop!","userErrors":"[UserError!]!"}}}, -"ProductUpdateIdentifiers":{"i":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"}}, +"ProductUpdateIdentifiers":{"i":{"f":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"},"o":true}}, "ProductUpdateInput":{"i":{"category":"ID","collectionsToJoin":"[ID!]","collectionsToLeave":"[ID!]","deleteConflictingConstrainedMetafields":"Boolean=","descriptionHtml":"String","giftCardTemplateSuffix":"String","handle":"String","id":"ID","metafields":"[MetafieldInput!]","productType":"String","redirectNewHandle":"Boolean","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","vendor":"String"}}, "ProductUpdateMediaPayload":{"o":{"f":{"media":"[Media!]","mediaUserErrors":"[MediaUserError!]!","product":"Product","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `mediaUserErrors` instead."}}}, "ProductUpdatePayload":{"o":{"f":{"product":"Product","userErrors":"[UserError!]!"}}}, @@ -2724,7 +2724,7 @@ "ProductVariantDetachMediaPayload":{"o":{"f":{"product":"Product","productVariants":"[ProductVariant!]","userErrors":"[MediaUserError!]!"}}}, "ProductVariantEdge":{"o":{"f":{"cursor":"String!","node":"ProductVariant!"}}}, "ProductVariantGroupRelationshipInput":{"i":{"id":"ID!","quantity":"Int!"}}, -"ProductVariantIdentifierInput":{"i":{"customId":"UniqueMetafieldValueInput","id":"ID"}}, +"ProductVariantIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","id":"ID"},"o":true}}, "ProductVariantInventoryPolicy":{"e":["DENY","CONTINUE"]}, "ProductVariantJoinSellingPlanGroupsPayload":{"o":{"f":{"productVariant":"ProductVariant","userErrors":"[SellingPlanGroupUserError!]!"}}}, "ProductVariantLeaveSellingPlanGroupsPayload":{"o":{"f":{"productVariant":"ProductVariant","userErrors":"[SellingPlanGroupUserError!]!"}}}, @@ -2819,7 +2819,7 @@ "RefundLineItemInput":{"i":{"lineItemId":"ID!","locationId":"ID","quantity":"Int!","restockType":"RefundLineItemRestockType"}}, "RefundLineItemRestockType":{"e":["RETURN","CANCEL","LEGACY_RESTOCK","NO_RESTOCK"]}, "RefundMethodAllocation":{"e":["ORIGINAL_PAYMENT_METHODS","STORE_CREDIT"]}, -"RefundMethodInput":{"i":{"storeCreditRefund":"StoreCreditRefundInput"}}, +"RefundMethodInput":{"i":{"f":{"storeCreditRefund":"StoreCreditRefundInput"},"o":true}}, "RefundReturnOutcome":{"o":{"f":{"amount":"MoneyBag!","suggestedRefundMethods":"[SuggestedRefundMethod!]!","suggestedTransactions":"[SuggestedOrderTransaction!]!"}}}, "RefundShippingInput":{"i":{"fullRefund":"Boolean=","shippingRefundAmount":"MoneyInput"}}, "RefundShippingLine":{"o":{"f":{"id":"ID!","shippingLine":"ShippingLine!","subtotalAmountSet":"MoneyBag!","taxAmountSet":"MoneyBag!"},"t":["Node"]}}, @@ -2902,7 +2902,7 @@ "ReturnPolicyProfileConnection":{"o":{"f":{"edges":"[ReturnPolicyProfileEdge!]!","nodes":"[ReturnPolicyProfile!]!","pageInfo":"PageInfo!"}}}, "ReturnPolicyProfileEdge":{"o":{"f":{"cursor":"String!","node":"ReturnPolicyProfile!"}}}, "ReturnProcessExchangeLineItemInput":{"i":{"id":"ID!","quantity":"Int!"}}, -"ReturnProcessFinancialTransferInput":{"i":{"issueRefund":"ReturnProcessRefundInput"}}, +"ReturnProcessFinancialTransferInput":{"i":{"f":{"issueRefund":"ReturnProcessRefundInput"},"o":true}}, "ReturnProcessInput":{"i":{"exchangeLineItems":"[ReturnProcessExchangeLineItemInput!]=","financialTransfer":"ReturnProcessFinancialTransferInput","note":"String","notifyCustomer":"Boolean=","refundDuties":"[RefundDutyInput!]=","refundShipping":"RefundShippingInput","returnId":"ID!","returnLineItems":"[ReturnProcessReturnLineItemInput!]=","tipLineId":"ID"}}, "ReturnProcessPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, "ReturnProcessRefundInput":{"i":{"allowOverRefunding":"Boolean=","orderTransactions":"[ReturnRefundOrderTransactionInput!]!","refundMethods":"[RefundMethodInput!]="}}, @@ -3396,7 +3396,7 @@ "SubscriptionContractAtomicCreatePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionDraftUserError!]!"}}}, "SubscriptionContractBase":{"n":{"f":{"app":"App","appAdminUrl":"URL","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryPrice":"MoneyV2!","discounts":["SubscriptionManualDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"groupedLines":["SubscriptionGroupedLineConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"lineCount":"Int!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesCount":"Count","note":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["SubscriptionBillingCycleEditedContract","SubscriptionContract"],"d":{"lineCount":"Use `linesCount` instead."}}}, "SubscriptionContractCalculation":{"u":["SubscriptionContractCalculationFailure","SubscriptionContractCalculationPending","SubscriptionContractCalculationSuccess"]}, -"SubscriptionContractCalculationAnchorInput":{"i":{"monthday":"SubscriptionContractCalculationMonthdayAnchorInput","weekday":"SubscriptionContractCalculationWeekdayAnchorInput","yearday":"SubscriptionContractCalculationYeardayAnchorInput"}}, +"SubscriptionContractCalculationAnchorInput":{"i":{"f":{"monthday":"SubscriptionContractCalculationMonthdayAnchorInput","weekday":"SubscriptionContractCalculationWeekdayAnchorInput","yearday":"SubscriptionContractCalculationYeardayAnchorInput"},"o":true}}, "SubscriptionContractCalculationAppManagedBillingConfigInput":{"i":{"maxCycles":"Int","minCycles":"Int"}}, "SubscriptionContractCalculationAppManagedPricingPolicyInput":{"i":{"basePrice":"MoneyInput!","cyclePriceAdjustments":"[SubscriptionContractCalculationCyclePriceAdjustmentInput!]!"}}, "SubscriptionContractCalculationBillingCycleEditInput":{"i":{"customAttributes":"[AttributeInput!]","deliveryMethod":"SubscriptionContractCalculationDeliveryMethodInput","discountCodes":"[SubscriptionContractCalculationDiscountCodeInput!]!=","lines":"[SubscriptionContractCalculationLineInput!]","manualDiscounts":"[SubscriptionContractCalculationManualDiscountInput!]","note":"String","withMerchandiseCustomizations":"Boolean!"}}, @@ -3407,14 +3407,14 @@ "SubscriptionContractCalculationCommitPayload":{"o":{"f":{"contract":"SubscriptionCommittedContract","userErrors":"[SubscriptionContractCalculationCommitUserError!]!"}}}, "SubscriptionContractCalculationCommitUserError":{"o":{"f":{"code":"SubscriptionContractCalculationCommitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, "SubscriptionContractCalculationCommitUserErrorCode":{"e":["INVALID","NOT_READY_TO_COMMIT","DISCOVERY_CALCULATION_NOT_COMMITTABLE","CALCULATION_NOT_FOUND","STALE_CONTRACT","INVALID_BILLING_DATE","CONTRACT_TERMINATED"]}, -"SubscriptionContractCalculationComponentLineInput":{"i":{"productVariantLine":"SubscriptionContractCalculationProductVariantLineInput"}}, +"SubscriptionContractCalculationComponentLineInput":{"i":{"f":{"productVariantLine":"SubscriptionContractCalculationProductVariantLineInput"},"o":true}}, "SubscriptionContractCalculationContractCreateInput":{"i":{"actor":"SubscriptionActor","appManagedBillingConfig":"SubscriptionContractCalculationAppManagedBillingConfigInput","billingPolicy":"SubscriptionContractCalculationBillingPolicyInput!","currencyCode":"CurrencyCode!","customAttributes":"[AttributeInput!]!=","customerId":"ID!","deliveryMethod":"SubscriptionContractCalculationDeliveryMethodInput!","deliveryPolicy":"SubscriptionContractCalculationDeliveryPolicyInput!","discountCodes":"[SubscriptionContractCalculationDiscountCodeInput!]!=","lines":"[SubscriptionContractCalculationLineInput!]!","manualDiscounts":"[SubscriptionContractCalculationManualDiscountInput!]!","note":"String","paymentMethod":"SubscriptionContractCalculationPaymentMethodInput!","withMerchandiseCustomizations":"Boolean!"}}, "SubscriptionContractCalculationContractUpdateInput":{"i":{"appManagedBillingConfig":"SubscriptionContractCalculationAppManagedBillingConfigInput","billingPolicy":"SubscriptionContractCalculationBillingPolicyInput","customAttributes":"[AttributeInput!]","deliveryMethod":"SubscriptionContractCalculationDeliveryMethodInput","deliveryPolicy":"SubscriptionContractCalculationDeliveryPolicyInput","discountCodes":"[SubscriptionContractCalculationDiscountCodeInput!]!=","lines":"[SubscriptionContractCalculationLineInput!]","manualDiscounts":"[SubscriptionContractCalculationManualDiscountInput!]","note":"String","paymentMethod":"SubscriptionContractCalculationPaymentMethodInput","withMerchandiseCustomizations":"Boolean!"}}, "SubscriptionContractCalculationCustomLineInput":{"i":{"appManagedPricingPolicy":"SubscriptionContractCalculationAppManagedPricingPolicyInput","customAttributes":"[AttributeInput!]!=","discounts":"[SubscriptionContractCalculationLineDiscountInput!]!","id":"ID","originSellingPlanId":"ID","price":"MoneyInput!","quantity":"Int!","requiresShipping":"Boolean!","sellingPlanName":"String","sku":"String","taxable":"Boolean!","title":"String!","variantTitle":"String","weight":"WeightInput"}}, "SubscriptionContractCalculationCustomerPaymentMethodInput":{"i":{"id":"ID!"}}, "SubscriptionContractCalculationCyclePriceAdjustmentInput":{"i":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyValueInput!","afterCycle":"Int!","computedPrice":"MoneyInput!"}}, "SubscriptionContractCalculationDeliveryDiscountInput":{"i":{"id":"ID","recurringCycleLimit":"Int!","title":"String!","value":"SubscriptionContractCalculationDiscountValueInput!"}}, -"SubscriptionContractCalculationDeliveryMethodInput":{"i":{"fetchAvailableDeliveryOptions":"SubscriptionContractCalculationFetchDeliveryOptionsInput","localDelivery":"SubscriptionContractCalculationDeliveryMethodLocalDeliveryInput","none":"Boolean","pickup":"SubscriptionContractCalculationDeliveryMethodPickupInput","shipping":"SubscriptionContractCalculationDeliveryMethodShippingInput"}}, +"SubscriptionContractCalculationDeliveryMethodInput":{"i":{"f":{"fetchAvailableDeliveryOptions":"SubscriptionContractCalculationFetchDeliveryOptionsInput","localDelivery":"SubscriptionContractCalculationDeliveryMethodLocalDeliveryInput","none":"Boolean","pickup":"SubscriptionContractCalculationDeliveryMethodPickupInput","shipping":"SubscriptionContractCalculationDeliveryMethodShippingInput"},"o":true}}, "SubscriptionContractCalculationDeliveryMethodLocalDeliveryInput":{"i":{"address":"MailingAddressInput!","code":"String","deliveryPrice":"MoneyInput!","description":"String","instructions":"String","phone":"String!","presentmentTitle":"String","title":"String"}}, "SubscriptionContractCalculationDeliveryMethodPickupInput":{"i":{"code":"String","deliveryPrice":"MoneyInput!","description":"String","locationId":"ID!","presentmentTitle":"String","title":"String"}}, "SubscriptionContractCalculationDeliveryMethodShippingInput":{"i":{"address":"MailingAddressInput!","carrierServiceId":"ID","code":"String","deliveryPrice":"MoneyInput!","description":"String","presentmentTitle":"String","title":"String"}}, @@ -3424,18 +3424,18 @@ "SubscriptionContractCalculationDiagnosticCode":{"e":["INVALID","MERCHANDISE_NOT_FOUND","DELIVERY_ADDRESS_INVALID","CURRENCY_NOT_SUPPORTED","DELIVERY_NO_LOCATION_SHIPS_TO_ADDRESS","DELIVERY_PICKUP_LOCATION_UNAVAILABLE","PAYMENT_METHOD_NOT_FOUND","CUSTOM_VALIDATION","DELIVERY_METHOD_REQUIRED","DELIVERY_METHOD_UNUSED","CUSTOMER_CONTACT_METHOD_REQUIRED","BUNDLE_REQUIRES_MERCHANDISE_CUSTOMIZATIONS","MERCHANDISE_GIFT_CARD_INVALID","DISCOUNT_CODE_NOT_APPLIED","CALCULATION_TIMEOUT","LINE_PRICE_ADJUSTED_FOR_FULFILLMENTS","PROCESSING_ERROR"]}, "SubscriptionContractCalculationDiscountCodeInput":{"i":{"redeemCode":"String!"}}, "SubscriptionContractCalculationDiscountFixedAmountInput":{"i":{"amount":"MoneyInput!","appliesOnEachItem":"Boolean!"}}, -"SubscriptionContractCalculationDiscountValueInput":{"i":{"fixedAmount":"SubscriptionContractCalculationDiscountFixedAmountInput","percentage":"Int"}}, +"SubscriptionContractCalculationDiscountValueInput":{"i":{"f":{"fixedAmount":"SubscriptionContractCalculationDiscountFixedAmountInput","percentage":"Int"},"o":true}}, "SubscriptionContractCalculationFailure":{"o":{"f":{"errors":"[SubscriptionContractCalculationDiagnostic!]!","id":"ID!"}}}, "SubscriptionContractCalculationFetchDeliveryOptionsInput":{"i":{"address":"MailingAddressInput!","withDeliveryCustomizations":"Boolean="}}, "SubscriptionContractCalculationLineDiscountInput":{"i":{"id":"ID","recurringCycleLimit":"Int!","title":"String!","value":"SubscriptionContractCalculationDiscountValueInput!"}}, -"SubscriptionContractCalculationLineInput":{"i":{"customLine":"SubscriptionContractCalculationCustomLineInput","productVariantLine":"SubscriptionContractCalculationProductVariantLineInput","productVariantParentLine":"SubscriptionContractCalculationProductVariantParentLineInput"}}, +"SubscriptionContractCalculationLineInput":{"i":{"f":{"customLine":"SubscriptionContractCalculationCustomLineInput","productVariantLine":"SubscriptionContractCalculationProductVariantLineInput","productVariantParentLine":"SubscriptionContractCalculationProductVariantParentLineInput"},"o":true}}, "SubscriptionContractCalculationLocalDeliveryOption":{"o":{"f":{"code":"String!","description":"String","phoneRequired":"Boolean!","presentmentTitle":"String","price":"MoneyV2!","title":"String!"}}}, -"SubscriptionContractCalculationManualDiscountInput":{"i":{"deliveryDiscount":"SubscriptionContractCalculationDeliveryDiscountInput","orderDiscount":"SubscriptionContractCalculationOrderDiscountInput"}}, +"SubscriptionContractCalculationManualDiscountInput":{"i":{"f":{"deliveryDiscount":"SubscriptionContractCalculationDeliveryDiscountInput","orderDiscount":"SubscriptionContractCalculationOrderDiscountInput"},"o":true}}, "SubscriptionContractCalculationMonthdayAnchorInput":{"i":{"dayOfMonth":"Int!"}}, "SubscriptionContractCalculationMultipleFulfillmentConfig":{"o":{"f":{"cadence":"SubscriptionContractCalculationCadence!","numberOfFulfillments":"Int!"}}}, "SubscriptionContractCalculationMultipleFulfillmentConfigInput":{"i":{"cadence":"SubscriptionContractCalculationCadenceInput!","numberOfFulfillments":"Int!"}}, "SubscriptionContractCalculationOrderDiscountInput":{"i":{"id":"ID","recurringCycleLimit":"Int!","title":"String!","value":"SubscriptionContractCalculationDiscountValueInput!"}}, -"SubscriptionContractCalculationPaymentMethodInput":{"i":{"customerPaymentMethod":"SubscriptionContractCalculationCustomerPaymentMethodInput","none":"Boolean"}}, +"SubscriptionContractCalculationPaymentMethodInput":{"i":{"f":{"customerPaymentMethod":"SubscriptionContractCalculationCustomerPaymentMethodInput","none":"Boolean"},"o":true}}, "SubscriptionContractCalculationPending":{"o":{"f":{"id":"ID!"}}}, "SubscriptionContractCalculationPickupOption":{"o":{"f":{"code":"String!","description":"String","location":"Location!","phoneRequired":"Boolean!","pickupTime":"String","presentmentTitle":"String","price":"MoneyV2!","title":"String!"}}}, "SubscriptionContractCalculationProductVariantLineInput":{"i":{"appManagedPricingPolicy":"SubscriptionContractCalculationAppManagedPricingPolicyInput","customAttributes":"[AttributeInput!]!=","discounts":"[SubscriptionContractCalculationLineDiscountInput!]!","id":"ID","originSellingPlanId":"ID","priceOverride":"MoneyInput","productVariantId":"ID!","quantity":"Int!","sellingPlanName":"String"}}, diff --git a/crates/shopify_api/graphql/internal.schema.json b/crates/shopify_api/graphql/internal.schema.json index 75adc91..468c7b2 100644 --- a/crates/shopify_api/graphql/internal.schema.json +++ b/crates/shopify_api/graphql/internal.schema.json @@ -1,4 +1,4 @@ -{"format":1,"apiVersion":"2026-10","query":"QueryRoot","mutation":"Mutation", +{"format":2,"apiVersion":"2026-10","query":"QueryRoot","mutation":"Mutation", "directives":{"idempotent":{"l":["FIELD"],"a":{"key":"String!"}},"include":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}},"skip":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}}},"types":{ "ApiVersion":{"o":{"f":{"handle":"String!"}}}, "Boolean":"s", diff --git a/crates/shopify_api/src/schema.rs b/crates/shopify_api/src/schema.rs index ca3a592..2e06be3 100644 --- a/crates/shopify_api/src/schema.rs +++ b/crates/shopify_api/src/schema.rs @@ -32,6 +32,7 @@ query IntrospectionQuery { deprecationReason } inputFields(includeDeprecated: true) { ...InputValue } + isOneOf interfaces { name } enumValues(includeDeprecated: true) { name isDeprecated deprecationReason } possibleTypes { name } diff --git a/crates/shopify_api/tests/ui/literal_one_of.rs b/crates/shopify_api/tests/ui/literal_one_of.rs new file mode 100644 index 0000000..7ede229 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_one_of.rs @@ -0,0 +1,9 @@ +fn main() { + let handle: Option<&str> = Some("shirt"); + let _ = shopify_api::input!(ProductSetIdentifiers { id: "gid://shopify/Product/1", handle: "shirt" }); + let _ = shopify_api::input!(ProductSetIdentifiers {}); + let _ = shopify_api::input!(ProductSetIdentifiers { handle?: handle }); + let _ = shopify_api::input!(ProductSetIdentifiers { handle: null }); + let _ = shopify_api::input!(ProductSetIdentifiers { handle: handle }); + let _ = shopify_api::input!(ProductSetIdentifiers { handle: shopify_api::Maybe::<&str>::Null }); +} diff --git a/crates/shopify_api/tests/ui/literal_one_of.stderr b/crates/shopify_api/tests/ui/literal_one_of.stderr new file mode 100644 index 0000000..cce9aa3 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_one_of.stderr @@ -0,0 +1,61 @@ +error: `ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null: `id` is given already + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_one_of.rs:3:88 + | +3 | let _ = shopify_api::input!(ProductSetIdentifiers { id: "gid://shopify/Product/1", handle: "shirt" }); + | ^^^^^^ + +error: `ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_one_of.rs:4:55 + | +4 | let _ = shopify_api::input!(ProductSetIdentifiers {}); + | ^^ + +error: `ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null: write `handle: …`, not `handle?:` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_one_of.rs:5:63 + | +5 | let _ = shopify_api::input!(ProductSetIdentifiers { handle?: handle }); + | ^ + +error: `ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null: `handle: null` is not one + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_one_of.rs:6:65 + | +6 | let _ = shopify_api::input!(ProductSetIdentifiers { handle: null }); + | ^^^^ + +error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Option<&str>` + --> tests/ui/literal_one_of.rs:7:65 + | +7 | let _ = shopify_api::input!(ProductSetIdentifiers { handle: handle }); + | ^^^^^^ + | | + | `Option<&str>` doesn't satisfy the trait bound + | `String`, `&str`, `&String` or `Cow` + | + = help: the trait `main::__ShopifyApiExpect1_c2385860` is not implemented for `Option<&str>` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_one_of.rs:7:13 + | +7 | let _ = shopify_api::input!(ProductSetIdentifiers { handle: handle }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Maybe<&str>` + --> tests/ui/literal_one_of.rs:8:65 + | +8 | let _ = shopify_api::input!(ProductSetIdentifiers { handle: shopify_api::Maybe::<&str>::Null }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | `Maybe<&str>` doesn't satisfy the trait bound + | `String`, `&str`, `&String` or `Cow` + | + = help: the trait `main::__ShopifyApiExpect1_c2385860` is not implemented for `Maybe<&str>` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_one_of.rs:8:13 + | +8 | let _ = shopify_api::input!(ProductSetIdentifiers { handle: shopify_api::Maybe::<&str>::Null }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr index f5204da..9f7c335 100644 --- a/crates/shopify_api/tests/ui/literal_option_in_field.stderr +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -7,7 +7,7 @@ error[E0277]: `vendor` of `ProductUpdateInput` expects a `String`, not `Option` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect1_c2385860` is not implemented for `Option` + = help: the trait `__ShopifyApiExpect1_c2385b33` is not implemented for `Option` = note: `vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null` note: required by a bound in `Checks::build` --> tests/ui/literal_option_in_field.rs:3:13 diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr index 9b30a76..c0e960e 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -9,8 +9,8 @@ error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built wit 6 | | ); | |_____- required by a bound introduced by this call | - = help: the trait `__ShopifyApiExpect2_c2384e0f` is not implemented for `InputObject<2493993284262097346>` -help: the following other types implement trait `__ShopifyApiExpect2_c2384e0f` + = help: the trait `__ShopifyApiExpect2_c2384416` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2_c2384416` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -22,7 +22,7 @@ help: the following other types implement trait `__ShopifyApiExpect2_c2384e0f` | | | | |_____`&InputObject<960560859991546817>` | `InputObject<960560859991546817>` -note: required for `Vec>` to implement `__ShopifyApiExpect1_c2384e0f` +note: required for `Vec>` to implement `__ShopifyApiExpect1_c2384416` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr index 62a071d..bdec6bf 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr @@ -7,7 +7,7 @@ error[E0277]: `quantity` of `DraftOrderLineItemInput` expects an `Int`, not `&st | `&'static str` doesn't satisfy the trait bound | any integer type | - = help: the trait `main::__ShopifyApiExpect1_c2384416` is not implemented for `&str` + = help: the trait `main::__ShopifyApiExpect1_c2384be1` is not implemented for `&str` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 | @@ -24,7 +24,7 @@ error[E0277]: `title` of `DraftOrderLineItemInput` expects a `String`, not `u8` | `u8` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect3_c2384416` is not implemented for `u8` + = help: the trait `__ShopifyApiExpect3_c2384be1` is not implemented for `u8` = note: `title?: value` takes an `Option`, `None` leaving the field out; `title: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -42,7 +42,7 @@ error[E0277]: `requiresShipping` of `DraftOrderLineItemInput` expects a `Boolean | `{integer}` doesn't satisfy the trait bound | `bool` | - = help: the trait `__ShopifyApiExpect5_c2384416` is not implemented for `{integer}` + = help: the trait `__ShopifyApiExpect5_c2384be1` is not implemented for `{integer}` = note: `requiresShipping?: value` takes an `Option`, `None` leaving the field out; `requiresShipping: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -60,8 +60,8 @@ error[E0277]: `value` of `WeightInput` expects a `Float`, not `u64` | `u64` doesn't satisfy the trait bound | `f64`, `f32`, `i32` or `u32` | - = help: the trait `main::__ShopifyApiExpect1_c2384416` is not implemented for `u64` - = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c2384416`, but not `main::__ShopifyApiExpect1_c2384416` + = help: the trait `main::__ShopifyApiExpect1_c2384be1` is not implemented for `u64` + = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c2384be1`, but not `main::__ShopifyApiExpect1_c2384be1` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:4:13 | diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index 3ed8cb8..a98376b 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -1192,6 +1192,43 @@ impl<'a> Analyzer<'a> { Ok(variable) } + /// The rule of a `@oneOf` input object: exactly one field, whose value is + /// not `null`, nor a variable that may be. + fn check_one_of( + &mut self, + named: &str, + fields: &BTreeMap, + given: &BTreeMap>, + place: &str, + position: Pos, + ) -> Result<()> { + let names: Vec = fields.keys().map(|key| format!("`{key}`")).collect(); + let rule = format!( + "`{named}` is a oneOf input: give exactly one of {}, not null (in {place})", + crate::literal::join(&names, "or") + ); + let mut entries = given.iter(); + let (Some((name, value)), None) = (entries.next(), entries.next()) else { + return error_at(position, rule); + }; + match value { + ast::Value::Null => error_at(position, format!("{rule}: `{name}: null` is not one")), + ast::Value::Variable(variable) => { + let ty = self.variable(variable, position)?.ty.clone(); + if ty.is_non_null() { + return Ok(()); + } + error_at( + position, + format!( + "{rule}: `${variable}` is of type `{ty}`, which may be null; declare it `{ty}!`" + ), + ) + } + _ => Ok(()), + } + } + /// Checks a literal or a variable given where `expected` is wanted. fn check_value( &mut self, @@ -1250,12 +1287,15 @@ impl<'a> Analyzer<'a> { } ast::Value::Object(given) => { let named = inner.name(); - let Some(TypeDef::Input { fields }) = self.schema.get(named) else { + let Some(TypeDef::Input { fields, one_of }) = self.schema.get(named) else { return error_at( position, format!("An object is given for {place}, of type `{}`", expected.ty), ); }; + if *one_of { + self.check_one_of(named, fields, given, place, position)?; + } for (name, value) in given { let Some(field) = fields.get(name) else { return error_at( diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs index 890e67c..33de621 100644 --- a/crates/shopify_api_graphql/src/codegen.rs +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -251,7 +251,7 @@ pub fn deprecation_warning(span: Span, note: &str) -> TokenStream { /// The input objects a value of input type `name` may hold, `name` included. fn reachable_inputs<'a>(schema: &'a Schema, name: &'a str, found: &mut BTreeSet<&'a str>) { - if let Some(TypeDef::Input { fields }) = schema.get(name) + if let Some(TypeDef::Input { fields, .. }) = schema.get(name) && found.insert(name) { for field in fields.values() { diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index 01be0ec..4a11998 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -261,8 +261,8 @@ impl<'a> Literals<'a> { object: &Object, ) -> Result { let schema = self.schema; - let fields = match schema.get(name) { - Some(TypeDef::Input { fields }) => fields, + let (fields, one_of) = match schema.get(name) { + Some(TypeDef::Input { fields, one_of }) => (fields, *one_of), Some(other) => { return error( span, @@ -288,7 +288,7 @@ impl<'a> Literals<'a> { } }; let mut build = Build::default(); - let body = self.object(name, fields, object, &mut build)?; + let body = self.object(name, fields, one_of, object, &mut build)?; let json = build.finish(body, &self.krate); let krate = &self.krate; let id = input_object_id(name); @@ -332,7 +332,7 @@ impl<'a> Literals<'a> { None => self.expression(&ident_expr(ident), ty, site, place, build), }, Value::Object(object) => match self.input_fields(inner) { - Some((name, fields)) => self.object(name, fields, object, build), + Some((name, fields, one_of)) => self.object(name, fields, one_of, object, build), None => error( object.span, format!("{site} expects {}, not an object", self.what(ty)), @@ -397,14 +397,23 @@ impl<'a> Literals<'a> { } } - /// The fields of an object literal, for the input object `name`. + /// The fields of an object literal, for the input object `name`, a + /// `@oneOf` one when `one_of`. fn object( &mut self, name: &str, definitions: &BTreeMap, + one_of: bool, object: &Object, build: &mut Build, ) -> Result { + let one_of_rule = || { + let fields: Vec = definitions.keys().map(|key| format!("`{key}`")).collect(); + format!( + "`{name}` is a oneOf input: give exactly one of {}, not null", + join(&fields, "or") + ) + }; let mut given: Vec<&str> = Vec::new(); let mut fields = Vec::new(); for field in &object.fields { @@ -424,6 +433,23 @@ impl<'a> Literals<'a> { format!("The field `{key}` of `{name}` is given twice"), ); } + if one_of { + if let Some(first) = given.first() { + return error( + field.name_span, + format!("{}: `{first}` is given already", one_of_rule()), + ); + } + if let Some(question) = field.optional { + return error( + question, + format!("{}: write `{key}: …`, not `{key}?:`", one_of_rule()), + ); + } + if let Value::Null(span) = field.value { + return error(span, format!("{}: `{key}: null` is not one", one_of_rule())); + } + } given.push(key); if let Some(reason) = &definition.deprecation { let note = format!( @@ -451,13 +477,21 @@ impl<'a> Literals<'a> { quote!(literal::Optional(#key, #value)) } None => { - let value = - self.value(&field.value, &definition.ty, &site, Place::Field, build)?; + // The field of a oneOf input is nullable in the schema, and + // takes a value that is not null. + let ty = match one_of { + true => TypeRef::NonNull(Box::new(definition.ty.nullable().clone())), + false => definition.ty.clone(), + }; + let value = self.value(&field.value, &ty, &site, Place::Field, build)?; quote!(literal::Field(#key, #value)) } }; fields.push(code); } + if one_of && given.is_empty() { + return error(object.span, one_of_rule()); + } let missing: Vec = definitions .iter() .filter(|(key, definition)| definition.is_required() && !given.contains(&key.as_str())) @@ -884,13 +918,17 @@ impl<'a> Literals<'a> { } } - fn input_fields(&self, ty: &TypeRef) -> Option<(&'a str, &'a BTreeMap)> { + /// The name, the fields and whether it is `@oneOf`, of an input object. + fn input_fields( + &self, + ty: &TypeRef, + ) -> Option<(&'a str, &'a BTreeMap, bool)> { let schema = self.schema; match ty { TypeRef::Named(name) => match schema.get(name) { - Some(TypeDef::Input { fields }) => { + Some(TypeDef::Input { fields, one_of }) => { let (name, _) = schema.types.get_key_value(name)?; - Some((name.as_str(), fields)) + Some((name.as_str(), fields, *one_of)) } _ => None, }, @@ -1289,7 +1327,7 @@ fn unraw(ident: &Ident) -> String { } /// `a`, `a and b`, `a, b and c`. -fn join(items: &[String], last: &str) -> String { +pub(crate) fn join(items: &[String], last: &str) -> String { match items { [] => String::new(), [one] => one.clone(), diff --git a/crates/shopify_api_graphql/src/restrict.rs b/crates/shopify_api_graphql/src/restrict.rs index 5c55af1..88238b5 100644 --- a/crates/shopify_api_graphql/src/restrict.rs +++ b/crates/shopify_api_graphql/src/restrict.rs @@ -181,7 +181,7 @@ impl Used { fields: kept(fields, &mut pending), possible_types: possible_types.clone(), }, - TypeDef::Input { fields } => { + TypeDef::Input { fields, .. } => { pending.extend( fields .values() diff --git a/crates/shopify_api_graphql/src/schema.rs b/crates/shopify_api_graphql/src/schema.rs index 5d41ff5..7b45532 100644 --- a/crates/shopify_api_graphql/src/schema.rs +++ b/crates/shopify_api_graphql/src/schema.rs @@ -12,6 +12,7 @@ use serde_json::Value; /// /// It asks for deprecated fields, arguments, input fields and enum values /// too: an operation may still use them, and `graphql!` warns when it does. +/// `isOneOf` marks the input objects that take exactly one field. pub const INTROSPECTION_QUERY: &str = "\ query IntrospectionQuery { __schema { @@ -28,6 +29,7 @@ query IntrospectionQuery { deprecationReason } inputFields(includeDeprecated: true) { ...InputValue } + isOneOf interfaces { name } enumValues(includeDeprecated: true) { name isDeprecated deprecationReason } possibleTypes { name } @@ -54,7 +56,7 @@ fragment TypeRef on __Type { "; /// The version of the stored form written by [`Schema::to_json`]. -pub(crate) const FORMAT: u32 = 1; +pub(crate) const FORMAT: u32 = 2; /// The reason GraphQL gives when a deprecation has none. const NO_REASON: &str = "No longer supported"; @@ -223,6 +225,9 @@ pub enum TypeDef { }, Input { fields: BTreeMap, + /// A `@oneOf` input object: a value gives exactly one of its fields, + /// not `null`. + one_of: bool, }, } @@ -337,13 +342,17 @@ enum StoredEnum { WithDeprecations { v: Vec, d: Deprecations }, } -/// `{ "id": "ID!" }`, or `{ "f": { … }, "d": { "id": "reason" } }`. +/// `{ "id": "ID!" }`, or `{ "f": { … }, "d": { "id": "reason" } }`, with +/// `"o": true` for a `@oneOf` input object. #[derive(Serialize, Deserialize)] #[serde(untagged)] enum StoredInput { - WithDeprecations { + Detailed { f: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] d: Deprecations, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + o: bool, }, Plain(BTreeMap), } @@ -530,9 +539,11 @@ impl Schema { StoredType::Union(possible_types) => TypeDef::Union { possible_types }, StoredType::Input(StoredInput::Plain(fields)) => TypeDef::Input { fields: load_inputs(&name, fields, &Deprecations::new())?, + one_of: false, }, - StoredType::Input(StoredInput::WithDeprecations { f, d }) => TypeDef::Input { + StoredType::Input(StoredInput::Detailed { f, d, o }) => TypeDef::Input { fields: load_inputs(&name, f, &d)?, + one_of: o, }, }; Ok((name, definition)) @@ -608,7 +619,7 @@ impl Schema { }) } TypeDef::Union { possible_types } => StoredType::Union(possible_types.clone()), - TypeDef::Input { fields } => { + TypeDef::Input { fields, one_of } => { let stored = fields .iter() .map(|(name, value)| (name.clone(), store_input(value))) @@ -619,12 +630,13 @@ impl Schema { Some((name.clone(), value.deprecation.clone()?)) }) .collect(); - StoredType::Input(if deprecated.is_empty() { + StoredType::Input(if deprecated.is_empty() && !one_of { StoredInput::Plain(stored) } else { - StoredInput::WithDeprecations { + StoredInput::Detailed { f: stored, d: deprecated, + o: *one_of, } }) } @@ -749,6 +761,7 @@ impl Schema { }, "INPUT_OBJECT" => TypeDef::Input { fields: introspected_inputs(entry.get("inputFields"))?, + one_of: entry.get("isOneOf").and_then(Value::as_bool) == Some(true), }, other => { return Err(schema_error(format!( @@ -968,6 +981,10 @@ mod tests { "deprecationReason": "Use `notes`.", }, ] }, + { "kind": "INPUT_OBJECT", "name": "OrderKey", "isOneOf": true, "inputFields": [ + { "name": "id", "type": named("SCALAR", "ID"), "defaultValue": null }, + { "name": "name", "type": named("SCALAR", "String"), "defaultValue": null }, + ] }, { "kind": "SCALAR", "name": "ID" }, { "kind": "OBJECT", "name": "__Type", "interfaces": [], "fields": [] }, ], @@ -1005,12 +1022,30 @@ mod tests { Some("No longer supported") ); - let Some(TypeDef::Input { fields }) = schema.get("OrderInput") else { + let Some(TypeDef::Input { fields, one_of }) = schema.get("OrderInput") else { panic!("OrderInput is an input object"); }; assert!(fields["id"].is_required()); assert!(!fields["tags"].is_required()); assert_eq!(fields["note"].deprecation.as_deref(), Some("Use `notes`.")); + assert!(!one_of); + assert_eq!( + schema.get("OrderKey"), + Some(&TypeDef::Input { + fields: [ + ( + "id".to_string(), + InputValue::of(TypeRef::Named("ID".to_string())) + ), + ( + "name".to_string(), + InputValue::of(TypeRef::Named("String".to_string())) + ), + ] + .into(), + one_of: true, + }) + ); assert_eq!(schema.possible_types("Node"), ["Order"]); assert_eq!(schema.possible_types("Resource"), ["Order"]); @@ -1031,7 +1066,10 @@ mod tests { let json = schema.to_json(); assert_eq!(Schema::from_json(&json).unwrap(), schema); - assert!(json.starts_with("{\"format\":1,\"apiVersion\":\"2026-10\",")); + assert!(json.starts_with("{\"format\":2,\"apiVersion\":\"2026-10\",")); + assert!(json.contains( + "\n\"OrderKey\":{\"i\":{\"f\":{\"id\":\"ID\",\"name\":\"String\"},\"o\":true}},\n" + )); // One type per line, in name order. assert!(json.contains( "\n\"Order\":{\"o\":{\"f\":{\"id\":\"ID!\",\"legacyName\":\"String\"},\"t\":[\"Node\"],\"d\":{\"legacyName\":\"No longer supported\"}}},\n" @@ -1125,12 +1163,12 @@ mod tests { assert_eq!( Schema::from_json(r#"{"format":9,"apiVersion":"2026-10","query":"Q","types":{}}"#), Err(SchemaError( - "Unsupported schema file format 9, this version reads format 1".to_string() + "Unsupported schema file format 9, this version reads format 2".to_string() )) ); assert_eq!( Schema::from_json( - r#"{"format":1,"apiVersion":"2026-10","query":"Q","types":{"Q":{"o":{"f":{"a":"[Int"}}}}}"# + r#"{"format":2,"apiVersion":"2026-10","query":"Q","types":{"Q":{"o":{"f":{"a":"[Int"}}}}}"# ), Err(SchemaError("Invalid type \"[Int\" for Q.a".to_string())) ); diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs index 4721219..cae0c2a 100644 --- a/crates/shopify_api_graphql/tests/analyze.rs +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -254,6 +254,37 @@ fn refuses_an_input_field_given_twice() { ); } +#[test] +fn a_one_of_input_takes_exactly_one_field_not_null() { + let rule = "`ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null (in argument `identifier` of `Mutation.productSet`)"; + let operation = |identifier: &str| { + format!( + "mutation($id: ID, $handle: String!) {{ productSet(identifier: {identifier}, input: {{}}) {{ product {{ id }} }} }}" + ) + }; + let refused = |identifier: &str| refusal(&operation(identifier)); + assert!(refused("{}").starts_with(rule), "{}", refused("{}")); + assert!( + refused(r#"{id: "1", handle: "a"}"#).starts_with(rule), + "{}", + refused(r#"{id: "1", handle: "a"}"#) + ); + let null = refused("{id: null}"); + assert!( + null.starts_with(&format!("{rule}: `id: null` is not one")), + "{null}" + ); + let nullable = refused("{id: $id}"); + assert!( + nullable.starts_with(&format!( + "{rule}: `$id` is of type `ID`, which may be null; declare it `ID!`" + )), + "{nullable}" + ); + check(r#"mutation { productSet(identifier: {handle: "a"}, input: {}) { product { id } } }"#); + check(&operation("{handle: $handle}").replace("$id: ID, ", "")); +} + /// Only a default other than `null` lets a nullable variable fill a non-null place. #[test] fn refuses_a_null_default_for_a_non_null_place() { diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index 94a5344..1dfddcf 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -478,7 +478,7 @@ fn input_object_ids_differ_for_every_input_object_of_the_schema() { #[test] fn each_expression_is_checked_for_its_scalar() { let schema = Schema::from_json( - r#"{"format": 1, "apiVersion": "2026-10", "query": "Q", "types": { + r#"{"format": 2, "apiVersion": "2026-10", "query": "Q", "types": { "String": "s", "Int": "s", "Float": "s", "Boolean": "s", "JSON": "s", "T": {"i": {"i": "Int!", "f": "[Float]", "j": "JSON!", "jd": "JSON!=", "jl": "[JSON!]", "jn": "JSON", "s": "String"}}, "Q": {"o": {"f": {"echo": ["String", {"input": "T!"}]}}} @@ -574,7 +574,7 @@ fn integer_literals_outside_of_int_are_refused() { message("`$first`") ); let schema = Schema::from_json( - r#"{"format": 1, "apiVersion": "2026-10", "query": "Q", "types": { + r#"{"format": 2, "apiVersion": "2026-10", "query": "Q", "types": { "Int": "s", "String": "s", "T": {"i": {"l": "[Int!]", "m": "[[Int]]"}}, "Q": {"o": {"f": {"echo": ["String", {"input": "T!"}]}}} @@ -692,3 +692,45 @@ fn constants_are_written_in_place() { assert!(code.contains("Checks"), "{field}: {value}"); } } + +#[test] +fn a_one_of_input_takes_exactly_one_field_not_null() { + let rule = "`ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null"; + let (code, _) = input("ProductSetIdentifiers", vec![("handle", rust("handle"))]).unwrap(); + assert!(code.contains("\"handle\""), "{code}"); + input( + "ProductSetIdentifiers", + vec![("id", rust("\"gid://shopify/Product/1\""))], + ) + .unwrap(); + + assert_eq!(refusal("ProductSetIdentifiers", vec![]), rule); + assert_eq!( + refusal( + "ProductSetIdentifiers", + vec![("id", rust("id")), ("handle", rust("handle"))] + ), + format!("{rule}: `id` is given already") + ); + assert_eq!( + refusal("ProductSetIdentifiers", vec![("handle?", rust("handle"))]), + format!("{rule}: write `handle: …`, not `handle?:`") + ); + assert_eq!( + refusal("ProductSetIdentifiers", vec![("handle", null())]), + format!("{rule}: `handle: null` is not one") + ); + // The value of the field is checked as non-null: no `Option` nor `Maybe`. + let (_, items) = input("ProductSetIdentifiers", vec![("handle", rust("handle"))]).unwrap(); + assert!(!items.contains("or an `Option` of it"), "{items}"); + + // Nested, and as the value of a variable. + let source = "mutation($identifier: ProductSetIdentifiers, $input: ProductSetInput!) { productSet(identifier: $identifier, input: $input) { product { id } } }"; + let two = Value::Object(object(vec![("id", rust("id")), ("handle", rust("h"))])); + assert_eq!( + variable(source, two).unwrap_err(), + format!("{rule}: `id` is given already") + ); + let one = Value::Object(object(vec![("id", rust("id"))])); + variable(source, one).unwrap(); +} diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 96c79bb..e789186 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -648,7 +648,7 @@ pub fn __input_internal(input: proc_macro::TokenStream) -> proc_macro::TokenStre mod tests { use super::*; - const SCHEMA: &str = r#"{"format":1,"apiVersion":"2026-07","query":"QueryRoot","types":{ + const SCHEMA: &str = r#"{"format":2,"apiVersion":"2026-07","query":"QueryRoot","types":{ "QueryRoot":{"o":{"f":{"ping":"String"}}}, "String":"s" }}"#; From 103775975ae2adf2ad0271de698067140e20cdc3 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:34:57 +0100 Subject: [PATCH 085/135] docs(graphql): the traits derived on generated types may grow in 1.x Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/docs/graphql.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 6ba2a04..cccd167 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -105,6 +105,11 @@ for node in data.nodes.iter().flatten() { The types derive `Debug`, `Clone`, `PartialEq`, `Serialize` and `Deserialize`; they serialize under the names of the GraphQL fields. +The generated types, these and the `Variables` of a module, may derive more +traits in a 1.x release (`Default`, `Eq`, `Hash`…). Do not implement standard +or serde traits for them yourself: such an impl would conflict with the +derive then. Convert to your own types for traits of your own choosing. + The types of an inline operation have no name you can write: let inference carry them, convert them to your own types, or use a [module](#named-operations). From 9b60e002eebf02f1eec2e7a3103aca0a85521b41 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:35:29 +0100 Subject: [PATCH 086/135] docs(graphql-crate): hide shopify_api_graphql, with no semver guarantee Its modules, re-exports and items are #[doc(hidden)]: it is an implementation detail of shopify_api_macros and of the shopify-api command, pinned with `=` by shopify_api. Its crate doc, README and description say so, and point to shopify_api. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api_graphql/Cargo.toml | 2 +- crates/shopify_api_graphql/README.md | 13 +++++++----- crates/shopify_api_graphql/src/lib.rs | 30 ++++++++++++++++++++------- 3 files changed, 31 insertions(+), 14 deletions(-) diff --git a/crates/shopify_api_graphql/Cargo.toml b/crates/shopify_api_graphql/Cargo.toml index 152e45f..30ba996 100644 --- a/crates/shopify_api_graphql/Cargo.toml +++ b/crates/shopify_api_graphql/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "shopify_api_graphql" -description = "Checks Shopify Admin GraphQL operations against the schema and generates their Rust types. Used by the `graphql!` macro of `shopify_api`." +description = "Internal to shopify_api, no semver guarantee: checks Shopify Admin GraphQL operations against the schema and generates their Rust types for its `graphql!` macro. Depend on `shopify_api` instead." documentation = "https://docs.rs/shopify_api_graphql" keywords = ["shopify", "graphql", "codegen"] categories = ["development-tools", "api-bindings"] diff --git a/crates/shopify_api_graphql/README.md b/crates/shopify_api_graphql/README.md index 261f109..90f2d2c 100644 --- a/crates/shopify_api_graphql/README.md +++ b/crates/shopify_api_graphql/README.md @@ -5,10 +5,13 @@ The compile-time half of [`shopify_api`](https://crates.io/crates/shopify_api)'s checks an operation against it, generates the Rust types of its variables and of its result, and checks the input values written in Rust. -You do not need to depend on it directly: use `shopify_api::graphql!`. It is a -separate crate so that the macro and the `shopify-api` command line share it. +**It is an implementation detail, with no semver guarantee**: any release may +change its items. `shopify_api` depends on it with an exact `=` version. +Depend on [`shopify_api`](https://crates.io/crates/shopify_api) and use its +`graphql!` and `input!` macros instead. It is a separate crate so that the +macros and the `shopify-api` command line share it. -It bundles no schema: it reads the version a crate declares in -`[package.metadata.shopify_api]` of its `Cargo.toml` (else takes the latest -stable one), downloads that version's schema (`download` feature), and stores +It bundles no schema: it reads the version a crate pins in +`[package.metadata.shopify_api]` of its `Cargo.toml`, else the one of its +schema file, downloads that version's schema (`download` feature), and stores it in a compact form (one line per type, no descriptions). diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs index 52ce95e..bf138b3 100644 --- a/crates/shopify_api_graphql/src/lib.rs +++ b/crates/shopify_api_graphql/src/lib.rs @@ -1,38 +1,52 @@ //! Compile-time support for the typed Shopify Admin GraphQL operations of //! [`shopify_api`](https://docs.rs/shopify_api). //! -//! [`analyze`](fn@analyze) checks an operation against a [`Schema`] and -//! describes the shape of its variables and of its result; [`codegen`] turns -//! that description into Rust types. [`literal`] checks the values written in -//! Rust for input types (`{ title: "x" }`) and writes the code that sends -//! them. The `graphql!` and `input!` macros are a thin layer over them. -//! [`project`] finds the API version and the schema file of a crate, and -//! downloads that version's schema (with the `download` feature). No schema -//! is bundled. +//! **An implementation detail of `shopify_api_macros` and of the +//! `shopify-api` command, with no semver guarantee**: any release may change +//! its items. `shopify_api` depends on it with an exact `=` version. Depend on +//! [`shopify_api`](https://crates.io/crates/shopify_api), whose `graphql!` +//! and `input!` macros use it, not on this crate. +//! +//! `analyze` checks an operation against a `Schema` and describes the shape +//! of its variables and of its result; `codegen` turns that description into +//! Rust types. `literal` checks the values written in Rust for input types +//! (`{ title: "x" }`) and writes the code that sends them. `project` finds +//! the API version and the schema file of a crate, and downloads that +//! version's schema (with the `download` feature). No schema is bundled. #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] +#[doc(hidden)] pub mod analyze; +#[doc(hidden)] pub mod codegen; +#[doc(hidden)] pub mod literal; +#[doc(hidden)] pub mod project; mod restrict; +#[doc(hidden)] pub mod schema; +#[doc(hidden)] pub use analyze::{ Deprecation, Error, FieldBase, Operation, OperationKind, Scalar, SelectedField, Selection, Variable, VariableBase, analyze, }; +#[doc(hidden)] pub use project::{ PROJECT_SCHEMA_PATH, SCHEMA_ENV, SchemaSource, latest_api_version, schema_source, }; +#[doc(hidden)] pub use schema::{Field, INTROSPECTION_QUERY, InputValue, Schema, SchemaError, TypeDef, TypeRef}; /// The oldest Admin API version `shopify_api` calls. +#[doc(hidden)] pub const MINIMUM_API_VERSION: &str = "2026-04"; /// Whether `version` is an Admin API version `shopify_api` calls: a quarterly /// release such as `2026-10`, from [`MINIMUM_API_VERSION`] on, or `unstable`. +#[doc(hidden)] pub fn is_supported_api_version(version: &str) -> bool { if version == "unstable" { return true; From 8c619774fff45376c9669094b65b4cc641789492 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:48:41 +0100 Subject: [PATCH 087/135] fix(webhooks)!: verify JSON webhooks only, and subscribe in JSON only `<` sorts before letters: a parameter named ` --- CHANGELOG.md | 4 +- MIGRATION.md | 9 ++- README.md | 4 ++ crates/shopify_api/src/webhooks.rs | 48 ++++++++-------- crates/shopify_api/tests/webhooks.rs | 84 +++++++++++++++++++++++++--- 5 files changed, 110 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98202de..e4b7619 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,8 +33,8 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Tokens: 0.10 renewed a token before it expired and saved it with a `TokenStore`. 1.0 also renews when Shopify refuses one with a `401`; one renewal serves every clone of a client and the requests waiting for it; it runs in a task of its own, so a cancelled request does not lose a rotated refresh token; a failed renewal answers the requests waiting for it. Until a renewed token is saved, nothing is sent: each call tries a failed save again first, and fails with `Error::TokenStore`. A refresh answer without a refresh token keeps the current one. `Auth::with_token` starts from a stored token. - Bulk operations: 0.10 ran, read, listed and waited for them, with typed statuses. 1.0 adds `bulk_query_rows` (the whole cycle), `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, and polling that starts at one second and backs off. `BulkOperation` has numbers for its counts and `DateTime` for its dates; `BulkOperationStatus` and `BulkOperationType` serialize as Shopify writes them (`"COMPLETED"`, an unknown one as its text) and round-trip. -- Webhook subscriptions: 0.10 listed, added, deleted and auto-configured them. 1.0 has `webhook_subscriptions` (every page), `create_`, `update_` (in place, new) and `delete_webhook_subscription`, and `sync_webhook_subscriptions`, which updates in place, creates before it deletes, and returns what it did. `WebhookSubscription` dates are `DateTime`. -- Webhook verification: 0.10 checked the HMAC. `Webhook::verify` also reads the headers (topic, shop, IDs; with or without `X-`, in any case, from any `(name, value)` pairs, `&http::HeaderMap` included), accepts several secrets during a rotation, and refuses a body that is not a JSON object or an XML document: the launch queries, session tokens and app proxy requests the client secret also signs can never pass for a webhook. `Webhook::verify_payload_shop` checks that a destructive webhook names, in its payload, the unsigned shop of its headers. `Debug` of a `Webhook` shows the length of its body, not the body. +- Webhook subscriptions: 0.10 listed, added, deleted and auto-configured them. 1.0 has `webhook_subscriptions` (every page), `create_`, `update_` (in place, new) and `delete_webhook_subscription`, and `sync_webhook_subscriptions`, which updates in place, creates before it deletes, and returns what it did. `WebhookSubscription` dates are `DateTime`. Subscriptions are JSON only: `WebhookSubscriptionSpec` has no format, and `sync_webhook_subscriptions` updates an XML subscription of a desired topic and address to JSON. +- Webhook verification: 0.10 checked the HMAC. `Webhook::verify` also reads the headers (topic, shop, IDs; with or without `X-`, in any case, from any `(name, value)` pairs, `&http::HeaderMap` included), accepts several secrets during a rotation, and verifies JSON webhooks only, refusing a body that is not a JSON object: the launch queries, session tokens and app proxy requests the client secret also signs, which an app proxy query can make read as XML, can never pass for a webhook. `Webhook::verify_payload_shop` checks that a destructive webhook names, in its payload, the unsigned shop of its headers. `Debug` of a `Webhook` shows the length of its body, not the body. - Schema download: `schema::download_public_admin_schema` and `download_admin_schema` take an `ApiVersion`. - `ShopDomain` refuses anything but `` or `.myshopify.com`, `http://` included; 0.10 appended `.myshopify.com` to any text. - Without a pinned version, an operation of `graphql!` goes to the version of its schema, and an untyped call to `ApiVersion::DEFAULT`, 2026-10 (0.10: 2026-04). The crate's own operations go to a pinned version without a warning. diff --git a/MIGRATION.md b/MIGRATION.md index 68b58a3..5b7ccc9 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -228,16 +228,19 @@ let webhooks = warp::path("webhooks") With axum, `async fn(headers: HeaderMap, body: Bytes)` takes the same two values (see the docs of `shopify_api::webhooks`). `Webhook::verify` requires the `X-Shopify-Topic` and `X-Shopify-Shop-Domain` headers, which Shopify always -sends, and only verifies a JSON object or an XML body; +sends, and only verifies JSON webhooks, whose body is a JSON object: the +client secret also signs texts an installer of the app can read and make look +like XML. `sync_webhook_subscriptions` updates an XML subscription of a +desired topic and address to JSON; `webhooks::verify_hmac(secret, body, header)` checks the signature alone. | 0.10 | 1.0 | | --- | --- | | `shopify.verify_hmac(data, header)` | `webhooks::verify_hmac(secret, data, header)` | | `list_webhooks()` | `webhook_subscriptions()`, every page | -| `add_webhook(address, topic, format)` | `create_webhook_subscription(&WebhookSubscriptionSpec::new(topic, address))` | +| `add_webhook(address, topic, format)` | `create_webhook_subscription(&WebhookSubscriptionSpec::new(topic, address))`, always JSON | | `delete_webhook(id)` | `delete_webhook_subscription(id)` | -| `webhook_auto_config(vec![(address, topic, format)])` | `sync_webhook_subscriptions(&[WebhookSubscriptionSpec::new(topic, address)])`, which returns what it did | +| `webhook_auto_config(vec![(address, topic, format)])` | `sync_webhook_subscriptions(&[WebhookSubscriptionSpec::new(topic, address)])`, always JSON, which returns what it did | | `delete_webhook(id)` then `add_webhook(…)`, to change a subscription | `update_webhook_subscription(id, &spec)`, which replaces its options in place | Topics are accepted as `orders/create` or `ORDERS_CREATE`. diff --git a/README.md b/README.md index acec458..aea9e35 100644 --- a/README.md +++ b/README.md @@ -397,6 +397,10 @@ shopify.sync_webhook_subscriptions(&[ ]).await?; ``` +Only JSON webhooks verify, and the subscriptions the crate creates or syncs +are JSON: the client secret also signs launch queries, app proxy requests and +session tokens, which an installer of the app can read and make look like XML. + ## OAuth and embedded apps Feature `oauth`: diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs index ec29dcc..28ee05e 100644 --- a/crates/shopify_api/src/webhooks.rs +++ b/crates/shopify_api/src/webhooks.rs @@ -55,9 +55,10 @@ //! //! The client secret also signs the launch queries of Shopify admin, the app //! proxy requests and the session tokens, which an installer of the app can -//! read. So that none of them passes for a webhook, only a body that starts -//! with `{` (JSON) or `<` (XML) verifies: a form-encoded query, a JWT or a -//! JSON array never does. +//! read. So that none of them passes for a webhook, only JSON webhooks +//! verify, a body that starts with `{`: a form-encoded query, a JWT or a JSON +//! array never does, while a signed query can be made to read as XML. +//! The subscriptions this crate creates or syncs are JSON. use base64::Engine; use base64::engine::general_purpose::STANDARD; @@ -73,7 +74,7 @@ use shopify_api_macros::{__graphql_internal as graphql, __input_internal as inpu /// Whether `hmac_header` (`X-Shopify-Hmac-Sha256`) is the signature of /// `body` with `secret`, the client secret of the app. Compares in constant time. /// -/// `false` for a body that is not a JSON object or an XML document, as +/// `false` for a body that is not a JSON object, as /// [`Webhook::verify`] refuses it: see [what the signature covers](self#what-the-signature-covers). pub fn verify_hmac(secret: &str, body: &[u8], hmac_header: &str) -> bool { // Anyone can sign with an empty key: it verifies nothing. @@ -90,14 +91,14 @@ pub fn verify_hmac(secret: &str, body: &[u8], hmac_header: &str) -> bool { mac.verify_slice(&expected).is_ok() } -/// Whether `body` starts as a webhook does, with `{` or `<`. The other texts +/// Whether `body` starts as a JSON webhook does, with `{`. The other texts /// the client secret signs start otherwise: a query with a parameter name, a /// session token with `eyJ`, and an app proxy request with a name that sorts -/// before `path_prefix`, never `{`, though `[` may. +/// before `path_prefix`, never `{`, though `[` or `<` (XML) may. fn is_webhook_body(body: &[u8]) -> bool { matches!( body.iter().find(|byte| !byte.is_ascii_whitespace()), - Some(b'{' | b'<') + Some(b'{') ) } @@ -152,9 +153,9 @@ impl Webhook { /// `headers` are name and value pairs: an `http::HeaderMap` by /// reference, or pairs of strings. Names are read in any case, with or /// without their `X-` (`X-Shopify-Topic` or `shopify-topic`). Fails when - /// the signature is missing or does not match, when the body is neither - /// a JSON object nor an XML document, or when a header Shopify always - /// sends is missing. + /// the signature is missing or does not match, when the body is not a + /// JSON object (XML webhooks are refused), or when a header Shopify + /// always sends is missing. /// /// The headers are not signed: see [what the signature covers](self#what-the-signature-covers). pub fn verify( @@ -214,7 +215,8 @@ impl Webhook { } if !is_webhook_body(&body) { return Err(Error::Verification( - "the body of the webhook is neither a JSON object nor an XML document".to_string(), + "the body of the webhook is not a JSON object: only JSON webhooks verify" + .to_string(), )); } if !secrets @@ -343,7 +345,7 @@ fn subscription_input( let list = |values: &Vec| (replace || !values.is_empty()).then(|| values.clone()); input!(WebhookSubscriptionInput { uri: &spec.uri, - format: raw(spec.format.as_deref().unwrap_or("JSON")), + format: raw("JSON"), filter?: spec.filter.as_deref().or(replace.then_some("")), includeFields?: list(&spec.include_fields), metafieldNamespaces?: list(&spec.metafield_namespaces), @@ -360,7 +362,8 @@ pub struct WebhookSubscription { pub topic: String, /// An HTTPS address, a `pubsub://` or an Amazon EventBridge `arn:`. pub uri: String, - /// `JSON` or `XML`. + /// `JSON` or `XML`. Only JSON webhooks verify: [`Shopify::sync_webhook_subscriptions`] + /// updates an XML one of a desired topic and address to JSON. pub format: String, pub filter: Option, pub include_fields: Vec, @@ -419,7 +422,7 @@ fn refused(mutation: &'static str, errors: &impl Serialize) -> Result<()> { } } -/// A webhook subscription to create. +/// A webhook subscription to create, always JSON: only JSON webhooks verify. /// /// ``` /// use shopify_api::webhooks::WebhookSubscriptionSpec; @@ -433,7 +436,6 @@ fn refused(mutation: &'static str, errors: &impl Serialize) -> Result<()> { pub struct WebhookSubscriptionSpec { topic: String, uri: String, - format: Option, filter: Option, include_fields: Vec, metafield_namespaces: Vec, @@ -447,7 +449,6 @@ impl WebhookSubscriptionSpec { Self { topic: topic_enum(topic.as_ref()), uri: uri.into(), - format: None, filter: None, include_fields: Vec::new(), metafield_namespaces: Vec::new(), @@ -455,12 +456,6 @@ impl WebhookSubscriptionSpec { } } - /// `JSON` (the default) or `XML`. - pub fn format(mut self, format: impl AsRef) -> Self { - self.format = Some(format.as_ref().to_ascii_uppercase()); - self - } - /// Only the events that match this search. pub fn filter(mut self, filter: impl Into) -> Self { self.filter = Some(filter.into()); @@ -496,7 +491,8 @@ impl WebhookSubscriptionSpec { &self.uri } - /// Whether `subscription` is this one: same topic, address and options. + /// Whether `subscription` is this one: same topic, address and options, + /// and JSON. pub fn matches(&self, subscription: &WebhookSubscription) -> bool { let sorted = |values: &[String]| { let mut values = values.to_vec(); @@ -505,7 +501,7 @@ impl WebhookSubscriptionSpec { }; subscription.topic == self.topic && subscription.uri == self.uri - && subscription.format == self.format.as_deref().unwrap_or("JSON") + && subscription.format == "JSON" && subscription .filter .as_deref() @@ -626,7 +622,9 @@ impl Shopify { /// Makes the shop's subscriptions exactly `desired`: those that match are /// kept, those of a desired topic and address are updated, the missing /// ones created, then the others deleted. Nothing is deleted before what - /// replaces it exists, so no event is missed in between. + /// replaces it exists, so no event is missed in between. An XML + /// subscription of a desired topic and address is updated to JSON: only + /// JSON webhooks verify. /// /// It deletes every subscription of the app on the shop that `desired` /// does not list, including those another part of the app created. diff --git a/crates/shopify_api/tests/webhooks.rs b/crates/shopify_api/tests/webhooks.rs index 03e1249..019d4b8 100644 --- a/crates/shopify_api/tests/webhooks.rs +++ b/crates/shopify_api/tests/webhooks.rs @@ -105,6 +105,41 @@ async fn sync_keeps_updates_creates_then_deletes() { ); } +/// Only JSON webhooks verify: an XML subscription of a desired topic and +/// address is updated to JSON, not kept. +#[tokio::test] +async fn sync_updates_an_xml_subscription_to_json() { + let mock = MockTransport::new(); + let mut xml = subscription(1, "ORDERS_CREATE", "https://example.com/hooks"); + xml["format"] = json!("XML"); + mock.push_data(json!({ "webhookSubscriptions": { + "nodes": [xml], + "pageInfo": { "hasNextPage": false, "endCursor": null }, + } })); + mock.push_data(json!({ "webhookSubscriptionUpdate": { + "webhookSubscription": subscription(1, "ORDERS_CREATE", "https://example.com/hooks"), + "userErrors": [], + } })); + let shopify = client(&mock); + + let report = shopify + .sync_webhook_subscriptions(&[WebhookSubscriptionSpec::new( + "orders/create", + "https://example.com/hooks", + )]) + .await + .unwrap(); + + assert!(report.kept.is_empty()); + assert_eq!(report.updated[0].format, "JSON"); + let sent = mock.graphql_requests(); + assert_eq!( + sent[1].operation_name.as_deref(), + Some("WebhookSubscriptionUpdate") + ); + assert_eq!(sent[1].variables["webhookSubscription"]["format"], "JSON"); +} + #[tokio::test] async fn a_refused_subscription_returns_the_user_errors() { let mock = MockTransport::new(); @@ -161,7 +196,7 @@ mod verification { use super::*; - const NOT_A_WEBHOOK: &str = "verification failed: the body of the webhook is neither a JSON object nor an XML document"; + const NOT_A_WEBHOOK: &str = "verification failed: the body of the webhook is not a JSON object: only JSON webhooks verify"; #[test] fn the_hmac_of_a_launch_query_is_not_a_webhook_signature() { @@ -204,15 +239,38 @@ mod verification { ); assert_eq!(refusal(&signature, message.as_bytes()), NOT_A_WEBHOOK); } + + /// `<` sorts before letters: a parameter named `"; + let signature = app.sign_app_proxy(query).unwrap(); + let signature = STANDARD.encode(hex::decode(signature).unwrap()); + assert_eq!( + sign(SECRET, message.as_bytes()), + signature, + "the message signed" + ); + assert_eq!(refusal(&signature, message.as_bytes()), NOT_A_WEBHOOK); + + // The same text as the sorted `key=value` pairs of a launch query. + let launch = + "=&shop=attacker.myshopify.com×tamp=1700000000"; + assert_eq!( + refusal(&sign(SECRET, launch.as_bytes()), launch.as_bytes()), + NOT_A_WEBHOOK + ); + } } #[test] - fn only_json_objects_and_xml_verify() { - for body in [ - &b"{\"id\":1}"[..], - b"\n {}", - b"", - ] { + fn only_json_objects_verify() { + for body in [&b"{\"id\":1}"[..], b"\n {}"] { assert!( Webhook::verify( headers(&sign(SECRET, body), "orders/create", "a"), @@ -223,7 +281,15 @@ mod verification { ); assert!(verify_hmac(SECRET, body, &sign(SECRET, body))); } - for body in [&b""[..], b" ", b"[1]", b"a=1", b"eyJhbGciOiJIUzI1NiJ9.e30"] { + for body in [ + &b""[..], + b" ", + b"[1]", + b"a=1", + b"eyJhbGciOiJIUzI1NiJ9.e30", + b"", + b" ", + ] { refusal(&sign(SECRET, body), body); } } @@ -306,6 +372,6 @@ mod verification { r#"{"id":1,"domain":"shop.example.com","myshopify_domain":"a.myshopify.com"}"#; assert!(verified(uninstalled, "a").is_ok()); assert!(verified(r#"{"id":1}"#, "a").is_err()); - assert!(verified("", "a").is_err()); + assert!(verified("{not json", "a").is_err()); } } From 586e90aea1c0c5316dd54671a7b9fddde14a9080 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:49:31 +0100 Subject: [PATCH 088/135] docs: describe how the schema file is chosen since f11ad79 README, CHANGELOG and MIGRATION said an unpinned crate follows the latest stable version and downloads again when it changes. It keeps the version of its schema file, and a dependency never downloads: the three now say so once, as `docs/graphql.md` does. The CHANGELOG lists the `@oneOf` checks. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- MIGRATION.md | 8 ++++---- README.md | 19 ++++++++++--------- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4b7619..26a9d97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,8 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. - `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - `Operation`, what `graphql!` builds, or `Operation::new` for any text: `execute` and `execute_response` take `impl Into>`, a module's `Variables` included. `body()` is the exact JSON text sent, and `variable_json(name)` the text of one variable; `with_name` sets the `operationName`. -- `graphql!` downloads the schema of the crate's version into `graphql/admin.schema.json`: the latest stable version, or the one `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml` pins. It downloads again when the version changes, and operations are sent to the version they were checked against. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. +- No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. The package being built downloads the file when it is missing or does not hold the pinned version, once per build; a dependency never downloads nor writes it, and fails to build when its file is missing or does not fit. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. +- `@oneOf` input objects (`ProductSetIdentifiers`…) are checked at compile time: exactly one field, not `null`. - `shopify-api check` checks `.graphql` files against the schema. - Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. The jitter of the backoff is random on every platform. - `Shopify::paginate`, `Page`. diff --git a/MIGRATION.md b/MIGRATION.md index 5b7ccc9..51fe9d8 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -72,9 +72,9 @@ for a backoff after a `5xx` or a network failure. To keep 0.10's behaviour: Without a pinned version, an operation of `graphql!` goes to the version its schema was checked against (the `api-version` of your `Cargo.toml`, else the -latest), and an untyped call to 2026-10. 0.10 sent -everything to 2026-04 by default: pin it with `.api_version(ApiVersion::V2026_04)` -to keep that. +one of the schema file, else the latest on the first build), and an untyped +call to 2026-10. 0.10 sent everything to 2026-04 by default: pin it with +`.api_version(ApiVersion::V2026_04)` to keep that. ## Errors @@ -253,7 +253,7 @@ Topics are accepted as `orders/create` or `ORDERS_CREATE`. | `shopify.download_admin_schema()` | The same | | `SHOPIFY_DEV_ADMIN_SCHEMA_PROXY` | `schema::PUBLIC_ADMIN_SCHEMA_ENDPOINT` | | `ADMIN_SCHEMA_INTROSPECTION_QUERY` | `schema::INTROSPECTION_QUERY` | -| `shopify-api schema download --public --out file` | `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`: `graphql!` downloads it. `shopify-api schema download` refreshes it, `--introspection` for the raw result | +| `shopify-api schema download --public --out file` | `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`: `graphql!` downloads it when the package is built, never as a dependency. `shopify-api schema download` refreshes it, `--introspection` for the raw result | | `shopify-api schema download --api-version 2026-07` | No flag: the command reads the version of the nearest `Cargo.toml`. For another version, or outside a package: `schema::download_public_admin_schema(ApiVersion::new("2026-07")?)` | `graphql!` reads the compact form it downloads, in `graphql/admin.schema.json`. diff --git a/README.md b/README.md index aea9e35..e82fe1e 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread"] } Rust 1.88 or newer, and a Tokio runtime: the default transport and the token renewals run on Tokio. The first build downloads the Admin schema of the latest stable version into `graphql/admin.schema.json`, next to your `Cargo.toml`: -commit it. +commit it. Later builds keep that version until you change it. ## Operations @@ -219,14 +219,15 @@ the rules of literals, is ## API versions Every operation is checked against a schema, and **sent to the version of that -schema**. No schema ships with the crate: `graphql!` downloads the one of your -version into `graphql/admin.schema.json`, and downloads again when the version -changes. Commit the file, so that builds without network access have it. - -Out of the box, the version is **the latest stable one**: when Shopify -releases a new version (each quarter), the next build that recompiles your -crate moves to it, and a field Shopify removed becomes a compile error. To -stay on one version, declare it in your `Cargo.toml`: +schema**. No schema ships with the crate: the first build downloads the one of +the latest stable version into `graphql/admin.schema.json`, and later builds +keep it, whatever Shopify releases since: a build gives the same result +whatever the date. Commit the file, so that builds without network access +have it. A library that uses `graphql!` must ship it: as a dependency, a +crate never downloads its schema. + +To choose the version, pin it in your `Cargo.toml` (`graphql!` downloads its +schema when the file holds another one): ```toml [package.metadata.shopify_api] From 66d52ec6e7f1119ca1fee5e493a772f2779eb686 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:50:46 +0100 Subject: [PATCH 089/135] fix(cli): say when `shopify-api check` downloads a schema MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `project_schema` takes an `on_download` callback, called with the file and the version before each download. The command prints the "Downloading…" line it lost in f11ad79; `graphql!` shows nothing. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bin/shopify-api.rs | 15 +++++++++++++-- crates/shopify_api_graphql/src/project.rs | 6 +++++- crates/shopify_api_macros/src/lib.rs | 11 +++++++++-- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index 9a62b18..12c1824 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -292,8 +292,19 @@ fn load_schema(path: Option<&Path>) -> Result<(Schema, String), String> { match schema_source(package_root().as_deref(), named.as_deref())? { SchemaSource::File(path) => path, SchemaSource::Project { dir, path, pinned } => { - let schema = - project_schema(&dir, pinned.as_deref(), true, SystemTime::now(), read)?; + let schema = project_schema( + &dir, + pinned.as_deref(), + true, + SystemTime::now(), + read, + |file, version| { + eprintln!( + "Downloading the Admin schema {version} into {}…", + file.display() + ); + }, + )?; return Ok((Arc::unwrap_or_clone(schema), path.display().to_string())); } } diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index 9c32504..f233095 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -402,7 +402,9 @@ pub fn write_atomically(path: &Path, contents: &str) -> Result<(), String> { /// The schema of the crate in `dir`, read with `read`, after downloading it /// when [`schema_plan`] says so. `primary` is whether cargo was asked to -/// build this crate, rather than build it as a dependency. +/// build this crate, rather than build it as a dependency. `on_download` +/// is called with the file and the version before each download, to show +/// progress. /// /// A download is tried once per file and version in a process: when it /// fails, the next operations of the build fail at once with the same error. @@ -414,8 +416,10 @@ pub fn project_schema>( primary: bool, now: SystemTime, read: impl Fn(&Path) -> Result, + on_download: impl Fn(&Path, &str), ) -> Result { obtain_schema(dir, pinned, primary, now, read, |path, version| { + on_download(path, version); download_schema_file(path, version).map(drop) }) } diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index e789186..35fe2b5 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -259,8 +259,15 @@ impl LoadedSchema { let read = |path: &Path| { read_schema(path).map_err(|error| format!("`{}`: {error}", path.display())) }; - let schema = - project_schema(&dir, pinned.as_deref(), primary, SystemTime::now(), read)?; + // A proc macro has no progress to show. + let schema = project_schema( + &dir, + pinned.as_deref(), + primary, + SystemTime::now(), + read, + |_, _| {}, + )?; (path, schema) } }; From 4e6f5371ccdd045fd112da54feea94ee8c3555f8 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:12:52 +0100 Subject: [PATCH 090/135] fix(webhooks)!: verify only bodies whose first byte is `{` A signed app proxy query can start with a visitor's parameter such as `\t{"x":"`, which reads as a JSON object after the tab. Skipping leading whitespace let it verify as a webhook, payload shop check included. No text the client secret signs starts with `{` itself. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- MIGRATION.md | 7 +++--- README.md | 6 +++-- crates/shopify_api/src/webhooks.rs | 35 +++++++++++++++------------- crates/shopify_api/tests/webhooks.rs | 35 ++++++++++++++++++++++++---- 5 files changed, 59 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26a9d97..d2cfb38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,7 +35,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Tokens: 0.10 renewed a token before it expired and saved it with a `TokenStore`. 1.0 also renews when Shopify refuses one with a `401`; one renewal serves every clone of a client and the requests waiting for it; it runs in a task of its own, so a cancelled request does not lose a rotated refresh token; a failed renewal answers the requests waiting for it. Until a renewed token is saved, nothing is sent: each call tries a failed save again first, and fails with `Error::TokenStore`. A refresh answer without a refresh token keeps the current one. `Auth::with_token` starts from a stored token. - Bulk operations: 0.10 ran, read, listed and waited for them, with typed statuses. 1.0 adds `bulk_query_rows` (the whole cycle), `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, and polling that starts at one second and backs off. `BulkOperation` has numbers for its counts and `DateTime` for its dates; `BulkOperationStatus` and `BulkOperationType` serialize as Shopify writes them (`"COMPLETED"`, an unknown one as its text) and round-trip. - Webhook subscriptions: 0.10 listed, added, deleted and auto-configured them. 1.0 has `webhook_subscriptions` (every page), `create_`, `update_` (in place, new) and `delete_webhook_subscription`, and `sync_webhook_subscriptions`, which updates in place, creates before it deletes, and returns what it did. `WebhookSubscription` dates are `DateTime`. Subscriptions are JSON only: `WebhookSubscriptionSpec` has no format, and `sync_webhook_subscriptions` updates an XML subscription of a desired topic and address to JSON. -- Webhook verification: 0.10 checked the HMAC. `Webhook::verify` also reads the headers (topic, shop, IDs; with or without `X-`, in any case, from any `(name, value)` pairs, `&http::HeaderMap` included), accepts several secrets during a rotation, and verifies JSON webhooks only, refusing a body that is not a JSON object: the launch queries, session tokens and app proxy requests the client secret also signs, which an app proxy query can make read as XML, can never pass for a webhook. `Webhook::verify_payload_shop` checks that a destructive webhook names, in its payload, the unsigned shop of its headers. `Debug` of a `Webhook` shows the length of its body, not the body. +- Webhook verification: 0.10 checked the HMAC. `Webhook::verify` also reads the headers (topic, shop, IDs; with or without `X-`, in any case, from any `(name, value)` pairs, `&http::HeaderMap` included), accepts several secrets during a rotation, and verifies JSON webhooks only, refusing a body whose first byte is not `{` (whitespace and a byte order mark before it included): the launch queries, session tokens and app proxy requests the client secret also signs, which an app proxy query can make read as XML, or as JSON after a tab, can never pass for a webhook. `Webhook::verify_payload_shop` checks that a destructive webhook names, in its payload, the unsigned shop of its headers. `Debug` of a `Webhook` shows the length of its body, not the body. - Schema download: `schema::download_public_admin_schema` and `download_admin_schema` take an `ApiVersion`. - `ShopDomain` refuses anything but `` or `.myshopify.com`, `http://` included; 0.10 appended `.myshopify.com` to any text. - Without a pinned version, an operation of `graphql!` goes to the version of its schema, and an untyped call to `ApiVersion::DEFAULT`, 2026-10 (0.10: 2026-04). The crate's own operations go to a pinned version without a warning. diff --git a/MIGRATION.md b/MIGRATION.md index 51fe9d8..151854a 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -228,9 +228,10 @@ let webhooks = warp::path("webhooks") With axum, `async fn(headers: HeaderMap, body: Bytes)` takes the same two values (see the docs of `shopify_api::webhooks`). `Webhook::verify` requires the `X-Shopify-Topic` and `X-Shopify-Shop-Domain` headers, which Shopify always -sends, and only verifies JSON webhooks, whose body is a JSON object: the -client secret also signs texts an installer of the app can read and make look -like XML. `sync_webhook_subscriptions` updates an XML subscription of a +sends, and only verifies JSON webhooks, whose body starts with `{` as its +first byte, with no whitespace or byte order mark before it: the client +secret also signs texts an installer of the app can read and make look like +XML, or like JSON after some whitespace. `sync_webhook_subscriptions` updates an XML subscription of a desired topic and address to JSON; `webhooks::verify_hmac(secret, body, header)` checks the signature alone. diff --git a/README.md b/README.md index e82fe1e..ab6471c 100644 --- a/README.md +++ b/README.md @@ -398,9 +398,11 @@ shopify.sync_webhook_subscriptions(&[ ]).await?; ``` -Only JSON webhooks verify, and the subscriptions the crate creates or syncs +Only JSON webhooks verify, a body whose first byte is `{` (no whitespace or +byte order mark before it), and the subscriptions the crate creates or syncs are JSON: the client secret also signs launch queries, app proxy requests and -session tokens, which an installer of the app can read and make look like XML. +session tokens, which an installer of the app can read and make look like XML, +or like JSON after some whitespace. ## OAuth and embedded apps diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs index 28ee05e..43bd284 100644 --- a/crates/shopify_api/src/webhooks.rs +++ b/crates/shopify_api/src/webhooks.rs @@ -56,9 +56,12 @@ //! The client secret also signs the launch queries of Shopify admin, the app //! proxy requests and the session tokens, which an installer of the app can //! read. So that none of them passes for a webhook, only JSON webhooks -//! verify, a body that starts with `{`: a form-encoded query, a JWT or a JSON -//! array never does, while a signed query can be made to read as XML. -//! The subscriptions this crate creates or syncs are JSON. +//! verify, a body whose first byte is `{`, with nothing before it, not even +//! whitespace or a byte order mark. None of the other texts starts so: each +//! starts with a parameter name that sorts before Shopify's own lowercase +//! names, or with `eyJ` for a session token. A signed query can still be made +//! to read as XML, or as JSON after some whitespace, which is why both are +//! refused. The subscriptions this crate creates or syncs are JSON. use base64::Engine; use base64::engine::general_purpose::STANDARD; @@ -74,7 +77,7 @@ use shopify_api_macros::{__graphql_internal as graphql, __input_internal as inpu /// Whether `hmac_header` (`X-Shopify-Hmac-Sha256`) is the signature of /// `body` with `secret`, the client secret of the app. Compares in constant time. /// -/// `false` for a body that is not a JSON object, as +/// `false` for a body whose first byte is not `{`, as /// [`Webhook::verify`] refuses it: see [what the signature covers](self#what-the-signature-covers). pub fn verify_hmac(secret: &str, body: &[u8], hmac_header: &str) -> bool { // Anyone can sign with an empty key: it verifies nothing. @@ -91,15 +94,15 @@ pub fn verify_hmac(secret: &str, body: &[u8], hmac_header: &str) -> bool { mac.verify_slice(&expected).is_ok() } -/// Whether `body` starts as a JSON webhook does, with `{`. The other texts -/// the client secret signs start otherwise: a query with a parameter name, a -/// session token with `eyJ`, and an app proxy request with a name that sorts -/// before `path_prefix`, never `{`, though `[` or `<` (XML) may. +/// Whether `body` starts as a JSON webhook does, its first byte `{`. The +/// other texts the client secret signs start otherwise: a query with a +/// parameter name, a session token with `eyJ`, and an app proxy request with +/// a name that sorts before Shopify's lowercase ones, so never `{`, though +/// `[`, `<` (XML) or whitespace may. fn is_webhook_body(body: &[u8]) -> bool { - matches!( - body.iter().find(|byte| !byte.is_ascii_whitespace()), - Some(b'{') - ) + // Exactly `{`, nothing skipped: a signed app proxy query can start with + // whitespace then `{`, never with `{`. + body.first() == Some(&b'{') } /// The signature Shopify would send for `body`, base64: for tests. @@ -153,9 +156,9 @@ impl Webhook { /// `headers` are name and value pairs: an `http::HeaderMap` by /// reference, or pairs of strings. Names are read in any case, with or /// without their `X-` (`X-Shopify-Topic` or `shopify-topic`). Fails when - /// the signature is missing or does not match, when the body is not a - /// JSON object (XML webhooks are refused), or when a header Shopify - /// always sends is missing. + /// the signature is missing or does not match, when the first byte of the + /// body is not the `{` of a JSON object (XML webhooks are refused), or + /// when a header Shopify always sends is missing. /// /// The headers are not signed: see [what the signature covers](self#what-the-signature-covers). pub fn verify( @@ -215,7 +218,7 @@ impl Webhook { } if !is_webhook_body(&body) { return Err(Error::Verification( - "the body of the webhook is not a JSON object: only JSON webhooks verify" + "the body of the webhook does not start with `{`: only JSON webhooks verify" .to_string(), )); } diff --git a/crates/shopify_api/tests/webhooks.rs b/crates/shopify_api/tests/webhooks.rs index 019d4b8..3c3d38b 100644 --- a/crates/shopify_api/tests/webhooks.rs +++ b/crates/shopify_api/tests/webhooks.rs @@ -196,7 +196,7 @@ mod verification { use super::*; - const NOT_A_WEBHOOK: &str = "verification failed: the body of the webhook is not a JSON object: only JSON webhooks verify"; + const NOT_A_WEBHOOK: &str = "verification failed: the body of the webhook does not start with `{`: only JSON webhooks verify"; #[test] fn the_hmac_of_a_launch_query_is_not_a_webhook_signature() { @@ -222,7 +222,28 @@ mod verification { } /// The parameters of an app proxy request are the storefront's: a - /// name that sorts first can open a JSON array, never an object. + /// name that sorts first can open a JSON object after a tab, a + /// whitespace `Webhook::verify` does not skip. + #[test] + fn an_app_proxy_request_that_reads_as_json_after_a_tab_is_not_a_webhook() { + let app = ShopifyApp::new("client-id", SECRET); + let query = "%09%7B%22x%22%3A%22=&logged_in_customer_id=&path_prefix=%2Fapps%2Fx\ + &shop=attacker.myshopify.com×tamp=1700000000\ + &z=%22%2C%22shop_domain%22%3A%22victim.myshopify.com%22%7D"; + let message = "\t{\"x\":\"=logged_in_customer_id=path_prefix=/apps/xshop=attacker.myshopify.comtimestamp=1700000000z=\",\"shop_domain\":\"victim.myshopify.com\"}"; + let payload: serde_json::Value = serde_json::from_str(message).unwrap(); + assert_eq!(payload["shop_domain"], "victim.myshopify.com"); + let signature = app.sign_app_proxy(query).unwrap(); + let signature = STANDARD.encode(hex::decode(signature).unwrap()); + assert_eq!( + sign(SECRET, message.as_bytes()), + signature, + "the message signed" + ); + assert_eq!(refusal(&signature, message.as_bytes()), NOT_A_WEBHOOK); + } + + /// Or a JSON array, which is not an object. #[test] fn an_app_proxy_request_is_not_a_webhook() { let app = ShopifyApp::new("client-id", SECRET); @@ -269,8 +290,8 @@ mod verification { } #[test] - fn only_json_objects_verify() { - for body in [&b"{\"id\":1}"[..], b"\n {}"] { + fn only_bodies_that_start_with_a_brace_verify() { + for body in [&b"{\"id\":1}"[..], b"{}", b"{ }\n"] { assert!( Webhook::verify( headers(&sign(SECRET, body), "orders/create", "a"), @@ -289,6 +310,12 @@ mod verification { b"eyJhbGciOiJIUzI1NiJ9.e30", b"", b" ", + // JSON objects, but not first: nothing is skipped before the `{`. + b" {}", + b"\t{}", + b"\n{}", + b"\r\n{}", + b"\xEF\xBB\xBF{}", ] { refusal(&sign(SECRET, body), body); } From afbb74d24ad673a3ac0ddebaa1ec904a69d562d4 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:18:29 +0100 Subject: [PATCH 091/135] fix(macros): choose the schema from where the package is, not from the cargo command SHOPIFY_GRAPHQL_SCHEMA applied only when CARGO_PRIMARY_PACKAGE was set, which cargo does not track: a workspace library built alone with the override kept it when reused by the app, and lost it once rebuilt as a dependency. The override now applies to local packages: no Cargo.toml.orig, no .cargo-checksum.json, not under CARGO_HOME. A packaged, vendored or checked-out package never downloads, so `cargo package` fails for a library that does not ship its schema. CARGO_PRIMARY_PACKAGE still gates downloads of local packages, which only turns success into an error. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- MIGRATION.md | 2 +- README.md | 6 +- crates/shopify_api/docs/graphql.md | 59 ++++--- crates/shopify_api/tests/schema_override.rs | 156 ++++++++++++++++++ crates/shopify_api_graphql/src/project.rs | 167 +++++++++++++++++--- crates/shopify_api_macros/src/lib.rs | 25 ++- 7 files changed, 368 insertions(+), 49 deletions(-) create mode 100644 crates/shopify_api/tests/schema_override.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index d2cfb38..fe4f1c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. - `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - `Operation`, what `graphql!` builds, or `Operation::new` for any text: `execute` and `execute_response` take `impl Into>`, a module's `Variables` included. `body()` is the exact JSON text sent, and `variable_json(name)` the text of one variable; `with_name` sets the `operationName`. -- No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. The package being built downloads the file when it is missing or does not hold the pinned version, once per build; a dependency never downloads nor writes it, and fails to build when its file is missing or does not fit. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. +- No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. A local package (of the workspace, or a path dependency) that cargo was asked to build downloads the file when it is missing or does not hold the pinned version, once per build; any other crate never downloads nor writes it, and fails to build when its file is missing or does not fit, a packaged crate in the verification of `cargo package` included. `SHOPIFY_GRAPHQL_SCHEMA` names another schema file for every local package, and is ignored for the packaged, vendored or checked-out ones: which schema a crate gets depends on where it is, never on the cargo command that built it first. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - `@oneOf` input objects (`ProductSetIdentifiers`…) are checked at compile time: exactly one field, not `null`. - `shopify-api check` checks `.graphql` files against the schema. - Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. The jitter of the backoff is random on every platform. diff --git a/MIGRATION.md b/MIGRATION.md index 151854a..3440e5d 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -254,7 +254,7 @@ Topics are accepted as `orders/create` or `ORDERS_CREATE`. | `shopify.download_admin_schema()` | The same | | `SHOPIFY_DEV_ADMIN_SCHEMA_PROXY` | `schema::PUBLIC_ADMIN_SCHEMA_ENDPOINT` | | `ADMIN_SCHEMA_INTROSPECTION_QUERY` | `schema::INTROSPECTION_QUERY` | -| `shopify-api schema download --public --out file` | `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`: `graphql!` downloads it when the package is built, never as a dependency. `shopify-api schema download` refreshes it, `--introspection` for the raw result | +| `shopify-api schema download --public --out file` | `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`: `graphql!` downloads it when cargo is asked to build the package, never for a dependency, or a packaged crate. `shopify-api schema download` refreshes it, `--introspection` for the raw result | | `shopify-api schema download --api-version 2026-07` | No flag: the command reads the version of the nearest `Cargo.toml`. For another version, or outside a package: `schema::download_public_admin_schema(ApiVersion::new("2026-07")?)` | `graphql!` reads the compact form it downloads, in `graphql/admin.schema.json`. diff --git a/README.md b/README.md index ab6471c..8e5a735 100644 --- a/README.md +++ b/README.md @@ -224,7 +224,11 @@ the latest stable version into `graphql/admin.schema.json`, and later builds keep it, whatever Shopify releases since: a build gives the same result whatever the date. Commit the file, so that builds without network access have it. A library that uses `graphql!` must ship it: as a dependency, a -crate never downloads its schema. +crate never downloads its schema, and `cargo package` fails without it. +`SHOPIFY_GRAPHQL_SCHEMA` names another schema file for your own packages (the +workspace and path dependencies), never for a crate from a registry, git or +a vendor directory. The details are in the +[`graphql!` docs](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html#schema-and-api-version). To choose the version, pin it in your `Cargo.toml` (`graphql!` downloads its schema when the file holds another one): diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index cccd167..6406290 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -373,32 +373,51 @@ version (the one before, on the first day of a quarter when Shopify has not published it yet). `shopify-api schema download` moves an unpinned crate to the latest version; pinning one is clearer. -When it builds a crate cargo was asked to build (a package of the workspace -you build, test or run), `graphql!` downloads the schema from Shopify's -public endpoint when the file is missing, when it holds another version than -the pinned one, or when it is in a format an older `shopify_api` wrote. It -tries once per build: without network access, every operation fails at once -with the reason, and `graphql!` never checks against another version than the -one the operations go to. - -A crate built as a dependency (from crates.io, git, or a path dependency -cargo was not asked to build) never downloads nor writes its schema: it -uses the file it ships. When the file is missing, or does not hold the -version its `Cargo.toml` pins, or is in an older format, the build fails and -names the directory where to run `shopify-api schema download`. +`graphql!` tells local packages, your own source (the packages of the +workspace, and path dependencies inside it or outside), from the others, +copies of a dependency: a crate from crates.io or another registry, a git +dependency, a vendored crate, or the copy `cargo package` verifies. A package +is not local when a `Cargo.toml.orig` sits next to its `Cargo.toml` (cargo +writes one into every packaged crate), when it has a `.cargo-checksum.json` +(vendored), or when it is under `$CARGO_HOME` (`~/.cargo` by default), where +cargo keeps registry sources and git checkouts. The schema a crate is +checked against depends on that only, never on the cargo command: cargo +reuses a compiled crate whatever command built it first. + +`SHOPIFY_GRAPHQL_SCHEMA` names a schema file for local packages, relative to +their `Cargo.toml` or absolute, used as it is. It applies to every local +package, the libraries of the workspace too, and is ignored for the others, +which are always checked against the schema they ship. + +When it builds a local package cargo was asked to build (one of the +workspace you build, test or run), `graphql!` downloads the schema from +Shopify's public endpoint when the file is missing, when it holds another +version than the pinned one, or when it is in a format an older +`shopify_api` wrote. It tries once per build: without network access, every +operation fails at once with the reason, and `graphql!` never checks against +another version than the one the operations go to. + +Any other crate never downloads nor writes its schema: it uses the file it +ships. When the file is missing, or does not hold the version its +`Cargo.toml` pins, or is in an older format, the build fails and names the +directory where to run `shopify-api schema download`. That includes a local +library built only as a dependency of the package cargo was asked to build +(build it alone once, or download its schema), and the verification of +`cargo package`: a library that forgot to ship `graphql/admin.schema.json` +fails there, before it is published. The `shopify-api` command (`cargo install shopify_api --features cli`) downloads the file on demand: `shopify-api schema download`, or `shopify-api schema download --shop my-shop` for the schema a shop's token sees. -| The schema of a crate | Package cargo was asked to build | Dependency | -| --- | --- | --- | -| `SHOPIFY_GRAPHQL_SCHEMA` is set | That file, relative to `Cargo.toml` or absolute, as it is. | Ignored. | -| File present, no pin | The file, never downloaded again. | The file. | -| File present, of the pinned version | The file. | The file. | -| File present, of another version or an older format | Downloaded again. | Compile error. | -| No file | Downloaded: the pinned version, else the latest. | Compile error. | +| The schema of a crate | Local, cargo was asked to build it | Local, built as a dependency | Packaged, vendored or checked out | +| --- | --- | --- | --- | +| `SHOPIFY_GRAPHQL_SCHEMA` is set | That file, relative to `Cargo.toml` or absolute, as it is. | That file. | Ignored. | +| File present, no pin | The file, never downloaded again. | The file. | The file. | +| File present, of the pinned version | The file. | The file. | The file. | +| File present, of another version or an older format | Downloaded again. | Compile error. | Compile error. | +| No file | Downloaded: the pinned version, else the latest. | Compile error. | Compile error. | An operation goes to the version of the schema it was checked against: a crate whose schema is 2026-07 calls the 2026-07 endpoint, with nothing to diff --git a/crates/shopify_api/tests/schema_override.rs b/crates/shopify_api/tests/schema_override.rs new file mode 100644 index 0000000..63046ce --- /dev/null +++ b/crates/shopify_api/tests/schema_override.rs @@ -0,0 +1,156 @@ +//! Which schema `graphql!` takes for a library of the workspace, across cargo +//! commands that share a target directory: cargo reuses a compiled crate +//! whatever command built it, so the schema must not depend on which one did. +//! +//! Builds a small workspace with cargo, offline, in `CARGO_TARGET_TMPDIR`. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::{Mutex, MutexGuard}; + +const SCHEMA_ENV: &str = "SHOPIFY_GRAPHQL_SCHEMA"; + +fn schema(version: &str) -> String { + format!( + r#"{{"format": 2, "apiVersion": "{version}", "query": "Q", "types": {{"Q": {{"o": {{"f": {{"f": "String"}}}}}}, "String": "s"}}}}"# + ) +} + +/// A workspace of `app`, which prints the API version of `library`, a path +/// dependency whose own schema is 2026-04, and `override.json`, of 2026-07. +struct Workspace { + root: PathBuf, + target: PathBuf, + /// The tests share a target directory, where `cargo run` of one would + /// run the binary another just built. + _alone: MutexGuard<'static, ()>, +} + +impl Workspace { + fn new(name: &str) -> Self { + static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); + let alone = ONE_AT_A_TIME + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let tmp = Path::new(env!("CARGO_TARGET_TMPDIR")); + let root = tmp.join(name); + let _ = std::fs::remove_dir_all(&root); + let shopify_api = env!("CARGO_MANIFEST_DIR"); + let write = |path: &str, contents: &str| { + let path = root.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, contents).unwrap(); + }; + write( + "Cargo.toml", + "[workspace]\nresolver = \"3\"\nmembers = [\"app\", \"library\"]\n", + ); + // The versions the workspace of shopify_api locks, all downloaded. + let lock = Path::new(shopify_api).join("../../Cargo.lock"); + write("Cargo.lock", &std::fs::read_to_string(lock).unwrap()); + write( + "app/Cargo.toml", + "[package]\nname = \"probe_app\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ + [dependencies]\nprobe_library = { path = \"../library\" }\n", + ); + write( + "app/src/main.rs", + "fn main() { print!(\"{}\", probe_library::probe::API_VERSION); }\n", + ); + write( + "library/Cargo.toml", + &format!( + "[package]\nname = \"probe_library\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ + [dependencies]\nshopify_api = {{ path = '{shopify_api}', default-features = false }}\n" + ), + ); + write( + "library/src/lib.rs", + "shopify_api::graphql! { pub mod probe = \"{ f }\"; }\n", + ); + write("library/graphql/admin.schema.json", &schema("2026-04")); + write("override.json", &schema("2026-07")); + // Shared by the tests: later runs build only the probes again. + let target = tmp.join("schema_override_target"); + Self { + root, + target, + _alone: alone, + } + } + + fn cargo(&self, args: &[&str], with_override: bool) -> Output { + let mut command = Command::new(std::env::var_os("CARGO").unwrap_or("cargo".into())); + command + .args(args) + .arg("--offline") + .arg("--quiet") + .arg("--manifest-path") + .arg(self.root.join("Cargo.toml")) + .env("CARGO_TARGET_DIR", &self.target) + .env_remove("CARGO_PRIMARY_PACKAGE"); + // Empty is no file: the `[env]` of this repository's cargo config, + // which the probes are under, sets the variable only when it is unset. + let named = match with_override { + true => self.root.join("override.json"), + false => PathBuf::new(), + }; + command.env(SCHEMA_ENV, named); + command.output().unwrap() + } + + fn succeed(&self, args: &[&str], with_override: bool) -> String { + let output = self.cargo(args, with_override); + assert!( + output.status.success(), + "cargo {args:?} failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() + } + + fn app_version(&self, with_override: bool) -> String { + self.succeed(&["run", "-p", "probe_app"], with_override) + } + + fn touch_library(&self) { + let source = self.root.join("library/src/lib.rs"); + let mut text = std::fs::read_to_string(&source).unwrap(); + text.push('\n'); + std::fs::write(source, text).unwrap(); + } +} + +/// A library of the workspace is local: the variable applies to it, whether +/// cargo was asked to build it or only the app, and in any order. +#[test] +fn a_local_library_takes_the_override_whatever_cargo_built_it_first() { + let workspace = Workspace::new("local_library"); + workspace.succeed(&["build", "-p", "probe_library"], true); + assert_eq!(workspace.app_version(true), "2026-07"); + workspace.touch_library(); + assert_eq!(workspace.app_version(true), "2026-07"); + // The variable is tracked: without it, the library is compiled again. + assert_eq!(workspace.app_version(false), "2026-04"); + workspace.succeed(&["build", "-p", "probe_library"], false); + assert_eq!(workspace.app_version(true), "2026-07"); +} + +/// A packaged library (a `Cargo.toml.orig` next to its `Cargo.toml`) keeps +/// its own schema, even when cargo is asked to build it, and never +/// downloads one it lacks. +#[test] +fn a_packaged_library_keeps_its_schema_and_never_downloads() { + let workspace = Workspace::new("packaged_library"); + let library = workspace.root.join("library"); + std::fs::copy(library.join("Cargo.toml"), library.join("Cargo.toml.orig")).unwrap(); + workspace.succeed(&["build", "-p", "probe_library"], true); + assert_eq!(workspace.app_version(true), "2026-04"); + + std::fs::remove_file(library.join("graphql/admin.schema.json")).unwrap(); + let output = workspace.cargo(&["build", "-p", "probe_library"], false); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!output.status.success()); + assert!(stderr.contains("admin.schema.json` is missing"), "{stderr}"); + assert!(!stderr.contains("cannot download"), "{stderr}"); +} diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index f233095..ab4574c 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -23,6 +23,7 @@ pub const PROJECT_SCHEMA_PATH: &str = "graphql/admin.schema.json"; /// The environment variable naming another schema file for `graphql!`, /// relative to the `Cargo.toml` of the crate being compiled, or absolute. +/// It applies to local packages only: see [`schema_rules`]. pub const SCHEMA_ENV: &str = "SHOPIFY_GRAPHQL_SCHEMA"; /// The `[package.metadata]` table `shopify_api` reads. @@ -160,6 +161,66 @@ pub fn schema_source( }) } +/// Whether the package in `dir` is local: the user's own source, in a +/// workspace or a path dependency outside it, rather than a packaged, +/// vendored or checked-out copy of a dependency. +/// +/// A package is not local when its directory holds a `Cargo.toml.orig`, +/// which cargo writes into every packaged crate (registry sources, and the +/// copy `cargo package` verifies), or a `.cargo-checksum.json` (vendored), or +/// when it is under `cargo_home`, where cargo keeps registry sources and git +/// checkouts. +/// +/// It depends on the directory and its files only, which stay the same for a +/// compiled crate: cargo reuses that crate whatever command built it. +pub fn is_local_package(dir: &Path, cargo_home: Option<&Path>) -> bool { + if dir.join("Cargo.toml.orig").exists() || dir.join(".cargo-checksum.json").exists() { + return false; + } + let Some(home) = cargo_home else { + return true; + }; + let canonical = |path: &Path| path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); + !canonical(dir).starts_with(canonical(home)) +} + +/// The directory where cargo keeps registry sources and git checkouts: +/// `$CARGO_HOME`, else `.cargo` in the home directory. +pub fn cargo_home() -> Option { + let non_empty = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty()); + if let Some(home) = non_empty("CARGO_HOME") { + return Some(PathBuf::from(home)); + } + non_empty("HOME") + .or_else(|| non_empty("USERPROFILE")) + .map(|home| PathBuf::from(home).join(".cargo")) +} + +/// What `graphql!` may do for the package being compiled. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SchemaRules { + /// Whether [`SCHEMA_ENV`] applies: to a local package only, so that a + /// dependency is always checked against the schema it ships. + pub override_applies: bool, + /// Whether the schema file may be downloaded, see [`schema_plan`]. + pub may_download: bool, +} + +/// The rules for a package that is `local` ([`is_local_package`]) and, +/// with `primary`, one cargo was asked to build. +/// +/// What is compiled depends on `local` only, an input that is the same for +/// a compiled crate. `primary` is not: cargo reuses a crate built as primary +/// when it is later built as a dependency, and the other way round. It only +/// decides whether a missing or outdated file is downloaded or refused, and +/// a refusal is a compile error, never another schema. +pub fn schema_rules(local: bool, primary: bool) -> SchemaRules { + SchemaRules { + override_applies: local, + may_download: local && primary, + } +} + /// What a crate's schema file holds. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SchemaFile { @@ -200,40 +261,44 @@ pub enum SchemaPlan { /// gives the same result whatever the date. Without either, the crate takes /// the latest version at `now`. /// -/// Only the `primary` package, one cargo was asked to build, downloads. A -/// dependency uses the file it ships, and refuses to build when it has none -/// or when it is not the version its `Cargo.toml` pins: its author tested its -/// operations against that file, and the registry copy is not to be written. +/// Only a package that `may_download` ([`schema_rules`]) downloads: a local +/// one cargo was asked to build. Any other uses the file it ships, and +/// refuses to build when it has none or when it is not the version its +/// `Cargo.toml` pins: its author tested its operations against that file, +/// and a registry, vendored or packaged copy is not to be written. pub fn schema_plan( dir: &Path, file: &SchemaFile, pinned: Option<&str>, - primary: bool, + may_download: bool, now: SystemTime, ) -> SchemaPlan { let path = dir.join(PROJECT_SCHEMA_PATH); let fix = || { format!( "Run `shopify-api schema download` in `{}` (`cargo install shopify_api --features cli`), \ - and commit the file. As a dependency, a crate never downloads its schema: it uses the one it ships.", + and commit the file. A crate downloads its schema only as a local package cargo was asked to build: \ + as a dependency, or packaged, it uses the one it ships.", dir.display() ) }; match (file, pinned) { (SchemaFile::Usable { .. }, None) => SchemaPlan::Read, (SchemaFile::Usable { version }, Some(pinned)) if version == pinned => SchemaPlan::Read, - (SchemaFile::Usable { version }, Some(pinned)) if !primary => SchemaPlan::Refuse(format!( - "`{}` holds the Admin API {version}, but `{}` declares {pinned}. {}", - path.display(), - dir.join("Cargo.toml").display(), - fix() - )), - (SchemaFile::Missing, _) if !primary => SchemaPlan::Refuse(format!( + (SchemaFile::Usable { version }, Some(pinned)) if !may_download => { + SchemaPlan::Refuse(format!( + "`{}` holds the Admin API {version}, but `{}` declares {pinned}. {}", + path.display(), + dir.join("Cargo.toml").display(), + fix() + )) + } + (SchemaFile::Missing, _) if !may_download => SchemaPlan::Refuse(format!( "`{}` is missing: `graphql!` needs the schema of the crate's API version there. {}", path.display(), fix() )), - (SchemaFile::Unusable { reason, .. }, _) if !primary => { + (SchemaFile::Unusable { reason, .. }, _) if !may_download => { SchemaPlan::Refuse(format!("{reason}. {}", fix())) } (_, Some(pinned)) => SchemaPlan::Download { @@ -401,8 +466,7 @@ pub fn write_atomically(path: &Path, contents: &str) -> Result<(), String> { } /// The schema of the crate in `dir`, read with `read`, after downloading it -/// when [`schema_plan`] says so. `primary` is whether cargo was asked to -/// build this crate, rather than build it as a dependency. `on_download` +/// when [`schema_plan`] says so, with `may_download` from [`schema_rules`]. `on_download` /// is called with the file and the version before each download, to show /// progress. /// @@ -413,12 +477,12 @@ pub fn write_atomically(path: &Path, contents: &str) -> Result<(), String> { pub fn project_schema>( dir: &Path, pinned: Option<&str>, - primary: bool, + may_download: bool, now: SystemTime, read: impl Fn(&Path) -> Result, on_download: impl Fn(&Path, &str), ) -> Result { - obtain_schema(dir, pinned, primary, now, read, |path, version| { + obtain_schema(dir, pinned, may_download, now, read, |path, version| { on_download(path, version); download_schema_file(path, version).map(drop) }) @@ -429,7 +493,7 @@ pub fn project_schema>( fn obtain_schema>( dir: &Path, pinned: Option<&str>, - primary: bool, + may_download: bool, now: SystemTime, read: impl Fn(&Path) -> Result, download: impl Fn(&Path, &str) -> Result<(), DownloadError>, @@ -449,7 +513,7 @@ fn obtain_schema>( } else { (SchemaFile::Missing, None) }; - match schema_plan(dir, &file, pinned, primary, now) { + match schema_plan(dir, &file, pinned, may_download, now) { SchemaPlan::Read => current.map_or_else(|| read(&path), Ok), SchemaPlan::Refuse(message) => Err(message), SchemaPlan::Download { version, latest } => { @@ -787,6 +851,69 @@ mod tests { ); } + #[test] + fn a_package_is_local_unless_packaged_vendored_or_under_cargo_home() { + let home = Project::new("cargo-home"); + let checkout = home.write("git/checkouts/lib-1a2b/0c9d/Cargo.toml", ""); + let checkout = checkout.parent().unwrap(); + assert!(!is_local_package(checkout, Some(&home.0))); + // Without a `CARGO_HOME`, only the files tell. + assert!(is_local_package(checkout, None)); + + let workspace = Project::new("local"); + workspace.manifest(None); + assert!(is_local_package(&workspace.0, Some(&home.0))); + assert!(is_local_package(&workspace.0, None)); + // A directory whose name starts as `CARGO_HOME`'s is not under it. + let sibling = PathBuf::from(format!("{}-sibling", home.0.display())); + assert!(is_local_package(&sibling, Some(&home.0))); + + for marker in ["Cargo.toml.orig", ".cargo-checksum.json"] { + let packaged = Project::new(&format!("packaged{marker}")); + packaged.manifest(None); + packaged.write(marker, ""); + assert!(!is_local_package(&packaged.0, Some(&home.0)), "{marker}"); + assert!(!is_local_package(&packaged.0, None), "{marker}"); + } + } + + #[cfg(unix)] + #[test] + fn a_cargo_home_through_a_symbolic_link_is_still_cargo_home() { + let real = Project::new("real-cargo-home"); + let registry = real.write("registry/src/index/lib-1.0.0/Cargo.toml", ""); + let linked = std::env::temp_dir().join(format!( + "shopify-api-graphql-linked-home-{}", + std::process::id() + )); + let _ = std::fs::remove_file(&linked); + std::os::unix::fs::symlink(&real.0, &linked).unwrap(); + assert!(!is_local_package(registry.parent().unwrap(), Some(&linked))); + let _ = std::fs::remove_file(&linked); + } + + #[test] + fn the_override_applies_to_local_packages_and_only_a_primary_one_downloads() { + for primary in [true, false] { + assert_eq!( + schema_rules(true, primary), + SchemaRules { + override_applies: true, + may_download: primary, + } + ); + // Packaged, vendored or checked out: never, even when primary, + // as in the verification of `cargo package`. + assert_eq!( + schema_rules(false, primary), + SchemaRules { + override_applies: false, + may_download: false, + } + ); + } + } + #[test] fn a_dependency_never_downloads() { let dir = Path::new("/registry/deplib-1.0.0"); diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 35fe2b5..6f941c1 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -13,7 +13,9 @@ use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, quote_spanned}; use shopify_api_graphql::codegen::{DATA_TYPE, data_types, deprecation_warning, variables_types}; use shopify_api_graphql::literal::{self, Literals, Value, VariableValue}; -use shopify_api_graphql::project::{metadata_snippet, project_schema}; +use shopify_api_graphql::project::{ + cargo_home, is_local_package, metadata_snippet, project_schema, schema_rules, +}; use shopify_api_graphql::{ MINIMUM_API_VERSION, Operation, OperationKind, SCHEMA_ENV, Schema, SchemaSource, Variable, analyze, is_supported_api_version, latest_api_version, schema_source, @@ -240,11 +242,20 @@ struct LoadedSchema { impl LoadedSchema { /// The schema of the crate being compiled. fn load() -> Result { - // The variable is for the crates being built, not for their - // dependencies, which ship their own schema files. + // What is compiled depends on whether the package is local, which + // is the same for a compiled crate whatever cargo command built it, + // never on `CARGO_PRIMARY_PACKAGE`, which cargo does not track. + let dir = manifest_dir(); + let local = dir + .as_deref() + .is_some_and(|dir| is_local_package(dir, cargo_home().as_deref())); + // Untracked, `primary` may be stale for a reused crate. That is fine + // here: it only decides whether a missing or outdated file is + // downloaded or a compile error, never which schema is used. let primary = std::env::var_os("CARGO_PRIMARY_PACKAGE").is_some(); - let named = std::env::var_os(SCHEMA_ENV).filter(|_| primary); - let (path, schema) = match schema_source(manifest_dir().as_deref(), named.as_deref())? { + let rules = schema_rules(local, primary); + let named = std::env::var_os(SCHEMA_ENV).filter(|_| rules.override_applies); + let (path, schema) = match schema_source(dir.as_deref(), named.as_deref())? { SchemaSource::File(path) => { let schema = read_schema(&path).map_err(|error| { format!( @@ -263,7 +274,7 @@ impl LoadedSchema { let schema = project_schema( &dir, pinned.as_deref(), - primary, + rules.may_download, SystemTime::now(), read, |_, _| {}, @@ -320,6 +331,8 @@ impl LoadedSchema { .collect(); quote! { const _: ::core::option::Option<&str> = ::core::option_env!(#SCHEMA_ENV); + // Whether the package is local depends on it. + const _: ::core::option::Option<&str> = ::core::option_env!("CARGO_HOME"); #(const _: &[u8] = ::core::include_bytes!(#files);)* } } From ba9855e2b689ffbb0eaf6bc052243e43753bb975 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:24:30 +0100 Subject: [PATCH 092/135] test(schema_override): run with one feature set only `mise run check` runs the default and the all-features tests at once, in two processes that share CARGO_TARGET_TMPDIR, where this test rebuilds its cargo projects: the two removed each other's directories on CI. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/Cargo.toml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index e9f8034..212f058 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -93,5 +93,11 @@ required-features = ["rustls"] name = "metafields" required-features = ["rustls"] +# With one feature set only: `mise run check` runs the tests of two at once, +# in two processes, and this test's cargo projects are in one directory. +[[test]] +name = "schema_override" +required-features = ["testing"] + [lints] workspace = true From 8a3cb84cfd8e470eccf9b5509c8376c975ebd62a Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:30:47 +0100 Subject: [PATCH 093/135] docs(migration): say verify_hmac keeps the first-byte rule of Webhook::verify Co-Authored-By: Claude Opus 5.5 --- MIGRATION.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MIGRATION.md b/MIGRATION.md index 3440e5d..58a472e 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -233,7 +233,9 @@ first byte, with no whitespace or byte order mark before it: the client secret also signs texts an installer of the app can read and make look like XML, or like JSON after some whitespace. `sync_webhook_subscriptions` updates an XML subscription of a desired topic and address to JSON; -`webhooks::verify_hmac(secret, body, header)` checks the signature alone. +`webhooks::verify_hmac(secret, body, header)` checks the signature without +reading the headers, and refuses a body whose first byte is not `{`, the same +rule as `Webhook::verify`. | 0.10 | 1.0 | | --- | --- | From 356197bfa25e4ed37ac95cf8ecf26462610c124d Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:30:47 +0100 Subject: [PATCH 094/135] fix(macros): keep git dependencies non-local behind a symlinked cargo cache Compare package and $CARGO_HOME paths both as given and canonical, and treat a package as non-local when it or an ancestor holds cargo's .cargo-ok marker (git checkouts, extracted registry sources). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api/docs/graphql.md | 8 +- crates/shopify_api_graphql/src/project.rs | 96 +++++++++++++++++++++-- 3 files changed, 96 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe4f1c9..3d2d06e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. - `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - `Operation`, what `graphql!` builds, or `Operation::new` for any text: `execute` and `execute_response` take `impl Into>`, a module's `Variables` included. `body()` is the exact JSON text sent, and `variable_json(name)` the text of one variable; `with_name` sets the `operationName`. -- No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. A local package (of the workspace, or a path dependency) that cargo was asked to build downloads the file when it is missing or does not hold the pinned version, once per build; any other crate never downloads nor writes it, and fails to build when its file is missing or does not fit, a packaged crate in the verification of `cargo package` included. `SHOPIFY_GRAPHQL_SCHEMA` names another schema file for every local package, and is ignored for the packaged, vendored or checked-out ones: which schema a crate gets depends on where it is, never on the cargo command that built it first. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. +- No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. A local package (of the workspace, or a path dependency) that cargo was asked to build downloads the file when it is missing or does not hold the pinned version, once per build; any other crate never downloads nor writes it, and fails to build when its file is missing or does not fit, a packaged crate in the verification of `cargo package` included. `SHOPIFY_GRAPHQL_SCHEMA` names another schema file for every local package, and is ignored for the packaged, vendored or checked-out ones (a `Cargo.toml.orig`, a `.cargo-checksum.json` or a `.cargo-ok` in the package directory, a `.cargo-ok` above it, or a path under `$CARGO_HOME`, with or without symbolic links resolved): which schema a crate gets depends on where it is, never on the cargo command that built it first. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - `@oneOf` input objects (`ProductSetIdentifiers`…) are checked at compile time: exactly one field, not `null`. - `shopify-api check` checks `.graphql` files against the schema. - Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. The jitter of the backoff is random on every platform. diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 6406290..370611b 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -379,8 +379,12 @@ copies of a dependency: a crate from crates.io or another registry, a git dependency, a vendored crate, or the copy `cargo package` verifies. A package is not local when a `Cargo.toml.orig` sits next to its `Cargo.toml` (cargo writes one into every packaged crate), when it has a `.cargo-checksum.json` -(vendored), or when it is under `$CARGO_HOME` (`~/.cargo` by default), where -cargo keeps registry sources and git checkouts. The schema a crate is +(vendored), when its directory or one above it holds a `.cargo-ok` (cargo +writes one at the root of every extracted registry source and git checkout), +or when it is under `$CARGO_HOME` (`~/.cargo` by default), where cargo keeps +registry sources and git checkouts. Paths count both as written and with +symbolic links resolved, so a `$CARGO_HOME` or a `git` directory in it that +links elsewhere changes nothing. The schema a crate is checked against depends on that only, never on the cargo command: cargo reuses a compiled crate whatever command built it first. diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index ab4574c..5ba0690 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -165,11 +165,19 @@ pub fn schema_source( /// workspace or a path dependency outside it, rather than a packaged, /// vendored or checked-out copy of a dependency. /// -/// A package is not local when its directory holds a `Cargo.toml.orig`, -/// which cargo writes into every packaged crate (registry sources, and the -/// copy `cargo package` verifies), or a `.cargo-checksum.json` (vendored), or -/// when it is under `cargo_home`, where cargo keeps registry sources and git -/// checkouts. +/// A package is not local when: +/// - its directory holds a `Cargo.toml.orig`, which cargo writes into every +/// packaged crate (registry sources, and the copy `cargo package` +/// verifies), or a `.cargo-checksum.json` (vendored); +/// - its directory or one of its ancestors holds a `.cargo-ok`, which cargo +/// writes at the root of every extracted registry source and of every git +/// checkout, where a git dependency may be a subdirectory; +/// - it is under `cargo_home`, where cargo keeps registry sources and git +/// checkouts. +/// +/// Paths are compared both as given and with symbolic links resolved, so a +/// `$CARGO_HOME`, or a `git` or `registry` directory in it, that links to +/// another disk still counts. /// /// It depends on the directory and its files only, which stay the same for a /// compiled crate: cargo reuses that crate whatever command built it. @@ -177,11 +185,33 @@ pub fn is_local_package(dir: &Path, cargo_home: Option<&Path>) -> bool { if dir.join("Cargo.toml.orig").exists() || dir.join(".cargo-checksum.json").exists() { return false; } + let dirs = both_forms(dir); + let in_cargo_checkout = dirs + .iter() + .any(|dir| dir.ancestors().any(|dir| dir.join(".cargo-ok").exists())); + if in_cargo_checkout { + return false; + } let Some(home) = cargo_home else { return true; }; - let canonical = |path: &Path| path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); - !canonical(dir).starts_with(canonical(home)) + let homes = both_forms(home); + !dirs + .iter() + .any(|dir| homes.iter().any(|home| dir.starts_with(home))) +} + +/// `path` made absolute, and also with symbolic links resolved when it +/// exists. +fn both_forms(path: &Path) -> Vec { + let logical = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()); + let mut forms = vec![logical]; + if let Ok(canonical) = forms[0].canonicalize() + && canonical != forms[0] + { + forms.push(canonical); + } + forms } /// The directory where cargo keeps registry sources and git checkouts: @@ -892,6 +922,58 @@ mod tests { let _ = std::fs::remove_file(&linked); } + #[test] + fn a_package_in_a_cargo_checkout_is_not_local() { + let home = Project::new("marker-home"); + // `.cargo-ok` in the package directory itself, as in a registry source. + let source = Project::new("marker-source"); + source.manifest(None); + source.write(".cargo-ok", "{\"v\":1}"); + assert!(!is_local_package(&source.0, Some(&home.0))); + assert!(!is_local_package(&source.0, None)); + + // A package nested in a git checkout, `.cargo-ok` at its root. + let checkout = Project::new("marker-checkout"); + checkout.write(".cargo-ok", ""); + let nested = checkout.write("crates/lib/Cargo.toml", ""); + let nested = nested.parent().unwrap(); + assert!(!is_local_package(nested, Some(&home.0))); + assert!(!is_local_package(nested, None)); + } + + /// `$CARGO_HOME/` links to a directory outside `$CARGO_HOME`. + #[cfg(unix)] + fn linked_cargo_home(name: &str, linked: &str) -> (Project, Project) { + let home = Project::new(&format!("{name}-home")); + let store = Project::new(&format!("{name}-store")); + let link = home.0.join(linked); + std::fs::create_dir_all(link.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(&store.0, &link).unwrap(); + (home, store) + } + + #[cfg(unix)] + #[test] + fn a_symbolic_link_to_the_git_directory_keeps_its_packages_not_local() { + for (name, linked, below) in [ + ("linked-git", "git", "checkouts/lib-1a2b/0c9d"), + ("linked-checkouts", "git/checkouts", "lib-1a2b/0c9d"), + ] { + let (home, store) = linked_cargo_home(name, linked); + let package = home.0.join(linked).join(below).join("crates/lib"); + store.write(&format!("{below}/crates/lib/Cargo.toml"), ""); + // Without a marker, the path under `$CARGO_HOME` tells. + assert!(!is_local_package(&package, Some(&home.0)), "{name}"); + // With its symbolic links resolved, the path is outside + // `$CARGO_HOME`: the `.cargo-ok` at the checkout root tells. + let resolved = package.canonicalize().unwrap(); + assert!(!resolved.starts_with(home.0.canonicalize().unwrap())); + store.write(&format!("{below}/.cargo-ok"), ""); + assert!(!is_local_package(&package, Some(&home.0)), "{name}"); + assert!(!is_local_package(&resolved, Some(&home.0)), "{name}"); + } + } + #[test] fn the_override_applies_to_local_packages_and_only_a_primary_one_downloads() { for primary in [true, false] { From 34c395525a7aeeb54951e82a6d77487b326910b6 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:50:26 +0100 Subject: [PATCH 095/135] feat(graphql)!: name a package's schema file with `schema` in its manifest Replace `SHOPIFY_GRAPHQL_SCHEMA` with `schema = ""` in `[package.metadata.shopify_api]`, relative to the package's Cargo.toml. It replaces `graphql/admin.schema.json` for that package only and follows the same rules: version from `api-version` or the file, download only when allowed, old format downloaded again or refused. The macro, `shopify-api schema download` and `shopify-api check` read it. Which schema a crate is checked against now depends on its Cargo.toml only. Package locality only gates downloads: a misclassification is a compile error naming the file and the command, never another schema. This repository's tests keep a hook, SHOPIFY_API_INTERNAL_TEST_SCHEMA, set in .cargo/config.toml, which applies to every package. Co-Authored-By: Claude Opus 5.5 --- .cargo/config.toml | 9 +- crates/shopify_api/docs/graphql.md | 96 ++-- crates/shopify_api/src/bin/shopify-api.rs | 74 +-- crates/shopify_api/tests/schema_override.rs | 147 ++++-- crates/shopify_api_graphql/src/lib.rs | 6 +- crates/shopify_api_graphql/src/project.rs | 474 +++++++++++++++----- crates/shopify_api_macros/src/lib.rs | 44 +- 7 files changed, 577 insertions(+), 273 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index ff01aa5..eb4d2e0 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,5 +1,6 @@ -# The schema `graphql!` checks the operations of this workspace against, -# tests and examples: the Admin schema 2026-10, without network access. It -# also reaches the projects `trybuild` compiles for the compile-fail tests. +# Internal to this repository's tests, not part of the API: the schema +# `graphql!` checks every package against, the Admin schema 2026-10, without +# network access. It reaches the projects `trybuild` compiles for the +# compile-fail tests, which have no schema file of their own. [env] -SHOPIFY_GRAPHQL_SCHEMA = { value = "crates/shopify_api/graphql/admin.schema.json", relative = true } +SHOPIFY_API_INTERNAL_TEST_SCHEMA = { value = "crates/shopify_api/graphql/admin.schema.json", relative = true } diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 370611b..e0da785 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -359,13 +359,22 @@ schema of its Admin API version in `graphql/admin.schema.json`, next to its the file: builds without network access (CI sandboxes, docs.rs) need it, and so does a published crate. -The version is the one your `Cargo.toml` pins: +The version is the one your `Cargo.toml` pins, and `schema` names another +file than `graphql/admin.schema.json`, relative to that `Cargo.toml`: ```toml [package.metadata.shopify_api] api-version = "2026-07" +schema = "schemas/admin-2026-07.json" # optional ``` +Both keys belong to the package whose `Cargo.toml` holds them: a dependency +is always checked against the file its own `Cargo.toml` names, whatever yours +says. The file `schema` names follows the same rules as the default one: the +version is the pinned one, else the one of the file; it is downloaded only +where the default one would be; one in an older format is downloaded again, +or is a compile error. Editing either key compiles the crate again. + Without a pin, the version is the one of the schema file: it does not change when Shopify releases a new one, and a build gives the same result whatever the date. With no file either, the first build takes the latest stable @@ -373,55 +382,50 @@ version (the one before, on the first day of a quarter when Shopify has not published it yet). `shopify-api schema download` moves an unpinned crate to the latest version; pinning one is clearer. -`graphql!` tells local packages, your own source (the packages of the -workspace, and path dependencies inside it or outside), from the others, -copies of a dependency: a crate from crates.io or another registry, a git -dependency, a vendored crate, or the copy `cargo package` verifies. A package -is not local when a `Cargo.toml.orig` sits next to its `Cargo.toml` (cargo -writes one into every packaged crate), when it has a `.cargo-checksum.json` -(vendored), when its directory or one above it holds a `.cargo-ok` (cargo -writes one at the root of every extracted registry source and git checkout), -or when it is under `$CARGO_HOME` (`~/.cargo` by default), where cargo keeps -registry sources and git checkouts. Paths count both as written and with -symbolic links resolved, so a `$CARGO_HOME` or a `git` directory in it that -links elsewhere changes nothing. The schema a crate is -checked against depends on that only, never on the cargo command: cargo -reuses a compiled crate whatever command built it first. - -`SHOPIFY_GRAPHQL_SCHEMA` names a schema file for local packages, relative to -their `Cargo.toml` or absolute, used as it is. It applies to every local -package, the libraries of the workspace too, and is ignored for the others, -which are always checked against the schema they ship. - -When it builds a local package cargo was asked to build (one of the -workspace you build, test or run), `graphql!` downloads the schema from -Shopify's public endpoint when the file is missing, when it holds another -version than the pinned one, or when it is in a format an older -`shopify_api` wrote. It tries once per build: without network access, every -operation fails at once with the reason, and `graphql!` never checks against -another version than the one the operations go to. - -Any other crate never downloads nor writes its schema: it uses the file it -ships. When the file is missing, or does not hold the version its -`Cargo.toml` pins, or is in an older format, the build fails and names the -directory where to run `shopify-api schema download`. That includes a local -library built only as a dependency of the package cargo was asked to build -(build it alone once, or download its schema), and the verification of -`cargo package`: a library that forgot to ship `graphql/admin.schema.json` -fails there, before it is published. +Which file a crate is checked against depends on its `Cargo.toml` only. What +happens when that file is missing, holds another version than the pinned +one, or is in a format an older `shopify_api` wrote, depends on two more +things: + +- whether cargo was asked to build the package: one of the workspace you + build, test or run, rather than a dependency of it; +- whether the package is your own source (the packages of the workspace, and + path dependencies inside it or outside), rather than a copy of a + dependency: a crate from crates.io or another registry, a git dependency, + a vendored crate, or the copy `cargo package` verifies. `graphql!` takes a + package for a copy when a `Cargo.toml.orig` sits next to its `Cargo.toml` + (cargo writes one into every packaged crate), when it has a + `.cargo-checksum.json` (vendored), when its directory or one above it + holds a `.cargo-ok` (cargo writes one at the root of every extracted + registry source and git checkout), or when it is under `$CARGO_HOME` + (`~/.cargo` by default), with or without symbolic links resolved. + +When both hold, `graphql!` downloads the file from Shopify's public endpoint. +It tries once per build: without network access, every operation fails at +once with the reason, and `graphql!` never checks against another version +than the one the operations go to. + +Otherwise it never downloads nor writes the file: it uses the one the crate +ships. When that file is missing, or does not fit, the build fails, names the +file, and names the directory where to run `shopify-api schema download`. +That includes a local library built only as a dependency of the package cargo +was asked to build (build it alone once, or download its schema), and the +verification of `cargo package`: a library that forgot to ship its schema +fails there, before it is published. A package taken for a copy by mistake +(below an unrelated `.cargo-ok`, say) fails the same way: never with another +schema. The `shopify-api` command (`cargo install shopify_api --features cli`) -downloads the file on demand: `shopify-api schema download`, or -`shopify-api schema download --shop my-shop` for the schema a shop's token -sees. +downloads the file on demand, where `schema` says: `shopify-api schema +download`, or `shopify-api schema download --shop my-shop` for the schema a +shop's token sees. -| The schema of a crate | Local, cargo was asked to build it | Local, built as a dependency | Packaged, vendored or checked out | +| The schema file of a crate (`schema`, else `graphql/admin.schema.json`) | Your own package, cargo was asked to build it | Your own package, built as a dependency | Packaged, vendored or checked out | | --- | --- | --- | --- | -| `SHOPIFY_GRAPHQL_SCHEMA` is set | That file, relative to `Cargo.toml` or absolute, as it is. | That file. | Ignored. | -| File present, no pin | The file, never downloaded again. | The file. | The file. | -| File present, of the pinned version | The file. | The file. | The file. | -| File present, of another version or an older format | Downloaded again. | Compile error. | Compile error. | -| No file | Downloaded: the pinned version, else the latest. | Compile error. | Compile error. | +| Present, no pin | The file, never downloaded again. | The file. | The file. | +| Present, of the pinned version | The file. | The file. | The file. | +| Present, of another version or an older format | Downloaded again. | Compile error. | Compile error. | +| Missing | Downloaded: the pinned version, else the latest. | Compile error. | Compile error. | An operation goes to the version of the schema it was checked against: a crate whose schema is 2026-07 calls the 2026-07 endpoint, with nothing to diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index 12c1824..0428c79 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -11,12 +11,10 @@ use std::sync::Arc; use std::time::SystemTime; use shopify_api_graphql::project::{ - configured_api_version, previous_api_version, project_schema, write_atomically, -}; -use shopify_api_graphql::{ - PROJECT_SCHEMA_PATH, SCHEMA_ENV, Schema, SchemaSource, analyze, latest_api_version, - schema_source, + API_VERSION_KEY, METADATA_TABLE, SCHEMA_KEY, package_config, previous_api_version, + project_schema, write_atomically, }; +use shopify_api_graphql::{Schema, SchemaSource, analyze, latest_api_version, schema_source}; #[derive(Debug, Parser)] #[command( @@ -57,8 +55,9 @@ enum SchemaCommand { /// `Debug` hides the access token and the client secret. #[derive(Args)] struct DownloadArgs { - /// Where to write it. By default, `graphql/admin.schema.json` next to the - /// nearest `Cargo.toml` of a package, where `graphql!` reads it + /// Where to write it. By default, where `graphql!` reads it for the + /// nearest package: `schema` in `[package.metadata.shopify_api]` of its + /// `Cargo.toml`, else `graphql/admin.schema.json` next to it /// (`graphql/admin.introspection.json` with --introspection). #[arg(long)] out: Option, @@ -132,7 +131,8 @@ async fn download(args: DownloadArgs) -> Result { let root = package_root().ok_or( "no Cargo.toml of a package in this directory or above: run it in the crate's directory", )?; - let declared = configured_api_version(&root)?; + let config = package_config(&root)?; + let declared = config.api_version.clone(); let latest = declared.is_none(); let wanted = declared.unwrap_or_else(|| latest_api_version(SystemTime::now())); if latest { @@ -160,11 +160,11 @@ async fn download(args: DownloadArgs) -> Result { Some(out) => (out.clone(), false), None => { let file = if args.introspection { - "graphql/admin.introspection.json" + root.join("graphql/admin.introspection.json") } else { - PROJECT_SCHEMA_PATH + config.schema_path(&root) }; - (root.join(file), !args.introspection) + (file, !args.introspection) } }; let created = !out.exists(); @@ -199,17 +199,21 @@ async fn download(args: DownloadArgs) -> Result { eprintln!("Wrote {} ({types} types).", out.display()); if project { - if created && let Some(root) = out.parent().and_then(Path::parent) { - touch_sources(root); + if created { + touch_sources(&root); } eprintln!( "`graphql!` checks the operations of this crate against the Admin API {version}, \ and sends them to that version. Commit the file: offline builds need it." ); } else if !args.introspection { + let absolute = std::path::absolute(&out).unwrap_or_else(|_| out.clone()); + let named = absolute.strip_prefix(&root).unwrap_or(&absolute); eprintln!( - "Set {SCHEMA_ENV}={} for `graphql!` to use it.", - out.display() + "For `graphql!` to use it, name it in {}:\n\n\ + [package.metadata.{METADATA_TABLE}]\n{API_VERSION_KEY} = \"{version}\"\n{SCHEMA_KEY} = \"{}\"", + root.join("Cargo.toml").display(), + named.display() ); } Ok(ExitCode::SUCCESS) @@ -287,28 +291,26 @@ fn load_schema(path: Option<&Path>) -> Result<(Schema, String), String> { }; let path = match path { Some(path) => path.to_path_buf(), - None => { - let named = std::env::var_os(SCHEMA_ENV); - match schema_source(package_root().as_deref(), named.as_deref())? { - SchemaSource::File(path) => path, - SchemaSource::Project { dir, path, pinned } => { - let schema = project_schema( - &dir, - pinned.as_deref(), - true, - SystemTime::now(), - read, - |file, version| { - eprintln!( - "Downloading the Admin schema {version} into {}…", - file.display() - ); - }, - )?; - return Ok((Arc::unwrap_or_clone(schema), path.display().to_string())); - } + None => match schema_source(package_root().as_deref(), None)? { + SchemaSource::File(path) => path, + SchemaSource::Project { dir, path, pinned } => { + let schema = project_schema( + &dir, + &path, + pinned.as_deref(), + true, + SystemTime::now(), + read, + |file, version| { + eprintln!( + "Downloading the Admin schema {version} into {}…", + file.display() + ); + }, + )?; + return Ok((Arc::unwrap_or_clone(schema), path.display().to_string())); } - } + }, }; let schema = read(&path)?; Ok((Arc::unwrap_or_clone(schema), path.display().to_string())) diff --git a/crates/shopify_api/tests/schema_override.rs b/crates/shopify_api/tests/schema_override.rs index 63046ce..f65e725 100644 --- a/crates/shopify_api/tests/schema_override.rs +++ b/crates/shopify_api/tests/schema_override.rs @@ -1,6 +1,8 @@ -//! Which schema `graphql!` takes for a library of the workspace, across cargo -//! commands that share a target directory: cargo reuses a compiled crate -//! whatever command built it, so the schema must not depend on which one did. +//! Which schema `graphql!` takes for a library of the workspace, with +//! `schema` in its `[package.metadata.shopify_api]`, across cargo commands +//! that share a target directory: cargo reuses a compiled crate whatever +//! command built it, so the schema must not depend on which one did, nor on +//! where the package is. //! //! Builds a small workspace with cargo, offline, in `CARGO_TARGET_TMPDIR`. @@ -8,7 +10,8 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use std::sync::{Mutex, MutexGuard}; -const SCHEMA_ENV: &str = "SHOPIFY_GRAPHQL_SCHEMA"; +/// Internal to this repository's tests: it would apply to the probes too. +const TEST_SCHEMA_ENV: &str = "SHOPIFY_API_INTERNAL_TEST_SCHEMA"; fn schema(version: &str) -> String { format!( @@ -17,7 +20,8 @@ fn schema(version: &str) -> String { } /// A workspace of `app`, which prints the API version of `library`, a path -/// dependency whose own schema is 2026-04, and `override.json`, of 2026-07. +/// dependency whose default schema file is 2026-04, and `override.json`, of +/// 2026-07, which the `schema` key of `library` may name. struct Workspace { root: PathBuf, target: PathBuf, @@ -57,13 +61,6 @@ impl Workspace { "app/src/main.rs", "fn main() { print!(\"{}\", probe_library::probe::API_VERSION); }\n", ); - write( - "library/Cargo.toml", - &format!( - "[package]\nname = \"probe_library\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ - [dependencies]\nshopify_api = {{ path = '{shopify_api}', default-features = false }}\n" - ), - ); write( "library/src/lib.rs", "shopify_api::graphql! { pub mod probe = \"{ f }\"; }\n", @@ -72,14 +69,32 @@ impl Workspace { write("override.json", &schema("2026-07")); // Shared by the tests: later runs build only the probes again. let target = tmp.join("schema_override_target"); - Self { + let workspace = Self { root, target, _alone: alone, - } + }; + workspace.library_metadata(""); + workspace + } + + /// Writes the `Cargo.toml` of `library`, with these lines in its + /// `[package.metadata.shopify_api]`. + fn library_metadata(&self, lines: &str) { + let shopify_api = env!("CARGO_MANIFEST_DIR"); + let manifest = format!( + "[package]\nname = \"probe_library\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ + [dependencies]\nshopify_api = {{ path = '{shopify_api}', default-features = false }}\n\ + [package.metadata.shopify_api]\n{lines}" + ); + std::fs::write(self.root.join("library/Cargo.toml"), manifest).unwrap(); } - fn cargo(&self, args: &[&str], with_override: bool) -> Output { + fn with_override(&self) { + self.library_metadata("schema = \"../override.json\"\n"); + } + + fn cargo(&self, args: &[&str]) -> Output { let mut command = Command::new(std::env::var_os("CARGO").unwrap_or("cargo".into())); command .args(args) @@ -91,16 +106,12 @@ impl Workspace { .env_remove("CARGO_PRIMARY_PACKAGE"); // Empty is no file: the `[env]` of this repository's cargo config, // which the probes are under, sets the variable only when it is unset. - let named = match with_override { - true => self.root.join("override.json"), - false => PathBuf::new(), - }; - command.env(SCHEMA_ENV, named); + command.env(TEST_SCHEMA_ENV, ""); command.output().unwrap() } - fn succeed(&self, args: &[&str], with_override: bool) -> String { - let output = self.cargo(args, with_override); + fn succeed(&self, args: &[&str]) -> String { + let output = self.cargo(args); assert!( output.status.success(), "cargo {args:?} failed:\n{}", @@ -109,8 +120,15 @@ impl Workspace { String::from_utf8(output.stdout).unwrap() } - fn app_version(&self, with_override: bool) -> String { - self.succeed(&["run", "-p", "probe_app"], with_override) + fn app_version(&self) -> String { + self.succeed(&["run", "-p", "probe_app"]) + } + + fn fail(&self, args: &[&str]) -> String { + let output = self.cargo(args); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + assert!(!output.status.success(), "cargo {args:?} succeeded"); + stderr } fn touch_library(&self) { @@ -121,36 +139,73 @@ impl Workspace { } } -/// A library of the workspace is local: the variable applies to it, whether -/// cargo was asked to build it or only the app, and in any order. +/// The key applies to the library whether cargo was asked to build it or +/// only the app, and in any order. An edit of `Cargo.toml` alone compiles +/// the library again. #[test] -fn a_local_library_takes_the_override_whatever_cargo_built_it_first() { - let workspace = Workspace::new("local_library"); - workspace.succeed(&["build", "-p", "probe_library"], true); - assert_eq!(workspace.app_version(true), "2026-07"); +fn the_key_chooses_the_schema_whatever_cargo_built_first() { + let workspace = Workspace::new("key"); + workspace.with_override(); + workspace.succeed(&["build", "-p", "probe_library"]); + assert_eq!(workspace.app_version(), "2026-07"); workspace.touch_library(); - assert_eq!(workspace.app_version(true), "2026-07"); - // The variable is tracked: without it, the library is compiled again. - assert_eq!(workspace.app_version(false), "2026-04"); - workspace.succeed(&["build", "-p", "probe_library"], false); - assert_eq!(workspace.app_version(true), "2026-07"); + assert_eq!(workspace.app_version(), "2026-07"); + // Without the key: the default file, though the library was built last + // with it, and as the package cargo was asked to build. + workspace.library_metadata(""); + assert_eq!(workspace.app_version(), "2026-04"); + workspace.succeed(&["build", "-p", "probe_library"]); + assert_eq!(workspace.app_version(), "2026-04"); + workspace.with_override(); + assert_eq!(workspace.app_version(), "2026-07"); + + // `api-version` is followed too: a pin the file does not hold is an + // error for a library built as a dependency, which never downloads. + workspace.library_metadata("api-version = \"2026-07\"\nschema = \"../override.json\"\n"); + assert_eq!(workspace.app_version(), "2026-07"); + workspace.library_metadata("api-version = \"2026-10\"\nschema = \"../override.json\"\n"); + let stderr = workspace.fail(&["run", "-p", "probe_app"]); + assert!( + stderr.contains("override.json` holds the Admin API 2026-07"), + "{stderr}" + ); + assert!(stderr.contains("shopify-api schema download"), "{stderr}"); +} + +/// A `.cargo-ok` above the workspace makes its packages look like a cargo +/// checkout. That changes nothing to the schema chosen: only a missing file +/// is then a compile error rather than a download. +#[test] +fn an_unrelated_cargo_ok_above_does_not_change_the_schema() { + let workspace = Workspace::new("cargo_ok_above"); + std::fs::write(workspace.root.join(".cargo-ok"), "not cargo's").unwrap(); + workspace.with_override(); + workspace.succeed(&["build", "-p", "probe_library"]); + assert_eq!(workspace.app_version(), "2026-07"); + workspace.library_metadata(""); + assert_eq!(workspace.app_version(), "2026-04"); + + std::fs::remove_file(workspace.root.join("library/graphql/admin.schema.json")).unwrap(); + let stderr = workspace.fail(&["build", "-p", "probe_library"]); + assert!(stderr.contains("admin.schema.json` is missing"), "{stderr}"); + assert!(stderr.contains("shopify-api schema download"), "{stderr}"); + assert!(!stderr.contains("cannot download"), "{stderr}"); } -/// A packaged library (a `Cargo.toml.orig` next to its `Cargo.toml`) keeps -/// its own schema, even when cargo is asked to build it, and never -/// downloads one it lacks. +/// A packaged library (a `Cargo.toml.orig` next to its `Cargo.toml`) takes +/// the file its key names too, even when cargo is asked to build it, and +/// never downloads one it lacks. #[test] -fn a_packaged_library_keeps_its_schema_and_never_downloads() { +fn a_packaged_library_takes_its_key_and_never_downloads() { let workspace = Workspace::new("packaged_library"); let library = workspace.root.join("library"); + workspace.with_override(); std::fs::copy(library.join("Cargo.toml"), library.join("Cargo.toml.orig")).unwrap(); - workspace.succeed(&["build", "-p", "probe_library"], true); - assert_eq!(workspace.app_version(true), "2026-04"); + workspace.succeed(&["build", "-p", "probe_library"]); + assert_eq!(workspace.app_version(), "2026-07"); - std::fs::remove_file(library.join("graphql/admin.schema.json")).unwrap(); - let output = workspace.cargo(&["build", "-p", "probe_library"], false); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(!output.status.success()); - assert!(stderr.contains("admin.schema.json` is missing"), "{stderr}"); + std::fs::remove_file(workspace.root.join("override.json")).unwrap(); + let stderr = workspace.fail(&["build", "-p", "probe_library"]); + assert!(stderr.contains("override.json` is missing"), "{stderr}"); assert!(!stderr.contains("cannot download"), "{stderr}"); } diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs index bf138b3..08e5ee8 100644 --- a/crates/shopify_api_graphql/src/lib.rs +++ b/crates/shopify_api_graphql/src/lib.rs @@ -13,6 +13,10 @@ //! (`{ title: "x" }`) and writes the code that sends them. `project` finds //! the API version and the schema file of a crate, and downloads that //! version's schema (with the `download` feature). No schema is bundled. +//! +//! `SHOPIFY_API_INTERNAL_TEST_SCHEMA` (`project::TEST_SCHEMA_ENV`) is +//! internal to this repository's tests, not part of the API: a schema file +//! `graphql!` then uses for every package. #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] @@ -35,7 +39,7 @@ pub use analyze::{ }; #[doc(hidden)] pub use project::{ - PROJECT_SCHEMA_PATH, SCHEMA_ENV, SchemaSource, latest_api_version, schema_source, + PROJECT_SCHEMA_PATH, SchemaSource, TEST_SCHEMA_ENV, latest_api_version, schema_source, }; #[doc(hidden)] pub use schema::{Field, INTROSPECTION_QUERY, InputValue, Schema, SchemaError, TypeDef, TypeRef}; diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index 5ba0690..634eae2 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -1,16 +1,21 @@ //! The Admin API version of a crate, and the schema file that goes with it. //! -//! A crate may pin its version in its `Cargo.toml`: +//! A crate may pin its version, and name its schema file, in its `Cargo.toml`: //! //! ```toml //! [package.metadata.shopify_api] //! api-version = "2026-07" +//! schema = "schemas/admin-2026-07.json" //! ``` //! -//! Without it, the version is the one of the schema file the crate has, kept -//! in [`PROJECT_SCHEMA_PATH`], and the latest stable one when there is no file -//! yet. `graphql!` checks the crate's operations against that schema: see -//! [`schema_plan`] for when it is downloaded. +//! Without `schema`, the file is [`PROJECT_SCHEMA_PATH`]. Without +//! `api-version`, the version is the one of that file, and the latest stable +//! one when there is no file yet. `graphql!` checks the crate's operations +//! against that schema: see [`schema_plan`] for when it is downloaded. +//! +//! Both keys belong to the package: which schema a crate is checked against +//! depends on its own `Cargo.toml` and files only, never on where it is, nor +//! on the cargo command that built it. use std::ffi::OsStr; use std::path::{Path, PathBuf}; @@ -21,10 +26,13 @@ use crate::{MINIMUM_API_VERSION, is_supported_api_version}; /// Where a crate keeps the schema of its API version, relative to its `Cargo.toml`. pub const PROJECT_SCHEMA_PATH: &str = "graphql/admin.schema.json"; -/// The environment variable naming another schema file for `graphql!`, -/// relative to the `Cargo.toml` of the crate being compiled, or absolute. -/// It applies to local packages only: see [`schema_rules`]. -pub const SCHEMA_ENV: &str = "SHOPIFY_GRAPHQL_SCHEMA"; +/// Internal to this repository's tests, not part of the API: a schema file +/// `graphql!` uses for every package, relative to the `Cargo.toml` of the +/// crate being compiled, or absolute, as it is. This repository's +/// `.cargo/config.toml` sets it, for the projects `trybuild` compiles, which +/// have no schema file. It applies to every package, with no exception, so +/// that its effect does not depend on where a package is. +pub const TEST_SCHEMA_ENV: &str = "SHOPIFY_API_INTERNAL_TEST_SCHEMA"; /// The `[package.metadata]` table `shopify_api` reads. pub const METADATA_TABLE: &str = "shopify_api"; @@ -32,6 +40,10 @@ pub const METADATA_TABLE: &str = "shopify_api"; /// The key of the API version in [`METADATA_TABLE`]. pub const API_VERSION_KEY: &str = "api-version"; +/// The key of the schema file in [`METADATA_TABLE`], relative to the +/// package's `Cargo.toml`; [`PROJECT_SCHEMA_PATH`] without it. +pub const SCHEMA_KEY: &str = "schema"; + /// The lines to add to a `Cargo.toml` to select `version`. pub fn metadata_snippet(version: &str) -> String { format!("[package.metadata.{METADATA_TABLE}]\n{API_VERSION_KEY} = \"{version}\"") @@ -78,25 +90,77 @@ fn year_and_month(days: u64) -> (u64, u64) { (year, month) } -/// The Admin API version the `Cargo.toml` in `manifest_dir` declares, if any. -pub fn configured_api_version(manifest_dir: &Path) -> Result, String> { +/// What the `[package.metadata.shopify_api]` of a `Cargo.toml` declares. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PackageConfig { + /// [`API_VERSION_KEY`]. + pub api_version: Option, + /// [`SCHEMA_KEY`], as written: relative to the `Cargo.toml`. + pub schema: Option, +} + +impl PackageConfig { + /// The schema file of the package in `dir`: [`SCHEMA_KEY`], else + /// [`PROJECT_SCHEMA_PATH`]. + pub fn schema_path(&self, dir: &Path) -> PathBuf { + dir.join( + self.schema + .as_deref() + .unwrap_or(Path::new(PROJECT_SCHEMA_PATH)), + ) + } +} + +/// What the `Cargo.toml` in `manifest_dir` declares; nothing when there is none. +pub fn package_config(manifest_dir: &Path) -> Result { let manifest = manifest_dir.join("Cargo.toml"); let text = match std::fs::read_to_string(&manifest) { Ok(text) => text, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return Ok(PackageConfig::default()); + } Err(error) => return Err(format!("cannot read `{}`: {error}", manifest.display())), }; - api_version_in(&text).map_err(|error| format!("`{}`: {error}", manifest.display())) + config_in(&text).map_err(|error| format!("`{}`: {error}", manifest.display())) +} + +/// The Admin API version the `Cargo.toml` in `manifest_dir` declares, if any. +pub fn configured_api_version(manifest_dir: &Path) -> Result, String> { + package_config(manifest_dir).map(|config| config.api_version) } -/// The API version a `Cargo.toml` declares, if any. -fn api_version_in(manifest: &str) -> Result, String> { +/// What a `Cargo.toml` declares. +fn config_in(manifest: &str) -> Result { let table: toml::Table = manifest.parse().map_err(|error| format!("{error}"))?; - let value = table + let ours = table .get("package") .and_then(|package| package.get("metadata")) - .and_then(|metadata| metadata.get(METADATA_TABLE)) - .and_then(|ours| ours.get(API_VERSION_KEY)); + .and_then(|metadata| metadata.get(METADATA_TABLE)); + let Some(ours) = ours else { + return Ok(PackageConfig::default()); + }; + Ok(PackageConfig { + api_version: api_version_in(ours.get(API_VERSION_KEY))?, + schema: schema_in(ours.get(SCHEMA_KEY))?, + }) +} + +/// The schema file [`SCHEMA_KEY`] names, if any. +fn schema_in(value: Option<&toml::Value>) -> Result, String> { + let Some(value) = value else { + return Ok(None); + }; + match value.as_str() { + Some(path) if !path.is_empty() => Ok(Some(PathBuf::from(path))), + _ => Err(format!( + "`{SCHEMA_KEY}` in [package.metadata.{METADATA_TABLE}] must be the path of a schema file, \ + relative to Cargo.toml, such as \"graphql/admin.schema.json\"" + )), + } +} + +/// The API version [`API_VERSION_KEY`] declares, if any. +fn api_version_in(value: Option<&toml::Value>) -> Result, String> { let Some(value) = value else { return Ok(None); }; @@ -117,14 +181,14 @@ fn api_version_in(manifest: &str) -> Result, String> { /// Where the schema of a crate comes from. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SchemaSource { - /// A schema file, used as it is. + /// A schema file, used as it is: the one [`TEST_SCHEMA_ENV`] names. File(PathBuf), - /// The crate's [`PROJECT_SCHEMA_PATH`], and the version its `Cargo.toml` + /// The schema file of the crate, and the version its `Cargo.toml` /// declares: see [`schema_plan`]. Project { /// The directory of the crate's `Cargo.toml`. dir: PathBuf, - /// `dir` joined with [`PROJECT_SCHEMA_PATH`]. + /// [`PackageConfig::schema_path`]. path: PathBuf, /// The version its `Cargo.toml` declares. pinned: Option, @@ -133,20 +197,22 @@ pub enum SchemaSource { /// The schema `graphql!` uses for the crate in `manifest_dir`: /// -/// 1. the file `named` by [`SCHEMA_ENV`]; -/// 2. else [`PROJECT_SCHEMA_PATH`], with the version `Cargo.toml` declares. +/// 1. the file `test_schema` names, the value of [`TEST_SCHEMA_ENV`] +/// (internal to this repository's tests); +/// 2. else the one [`SCHEMA_KEY`] names, else [`PROJECT_SCHEMA_PATH`], with +/// the version `Cargo.toml` declares. pub fn schema_source( manifest_dir: Option<&Path>, - named: Option<&OsStr>, + test_schema: Option<&OsStr>, ) -> Result { - if let Some(named) = named.filter(|value| !value.is_empty()) { + if let Some(named) = test_schema.filter(|value| !value.is_empty()) { let path = match manifest_dir { Some(dir) => dir.join(named), None => PathBuf::from(named), }; if !path.is_file() { return Err(format!( - "{SCHEMA_ENV} names `{}`, which is not a file", + "{TEST_SCHEMA_ENV} names `{}`, which is not a file", path.display() )); } @@ -154,16 +220,18 @@ pub fn schema_source( } let dir = manifest_dir .ok_or("no Cargo.toml of a package: the schema of a crate is kept next to it")?; + let config = package_config(dir)?; Ok(SchemaSource::Project { - path: dir.join(PROJECT_SCHEMA_PATH), - pinned: configured_api_version(dir)?, + path: config.schema_path(dir), + pinned: config.api_version, dir: dir.to_path_buf(), }) } /// Whether the package in `dir` is local: the user's own source, in a /// workspace or a path dependency outside it, rather than a packaged, -/// vendored or checked-out copy of a dependency. +/// vendored or checked-out copy of a dependency. It only gates downloads, +/// see [`may_download`]. /// /// A package is not local when: /// - its directory holds a `Cargo.toml.orig`, which cargo writes into every @@ -179,8 +247,12 @@ pub fn schema_source( /// `$CARGO_HOME`, or a `git` or `registry` directory in it, that links to /// another disk still counts. /// -/// It depends on the directory and its files only, which stay the same for a -/// compiled crate: cargo reuses that crate whatever command built it. +/// These are heuristics: an unrelated `.cargo-ok` above a workspace, for +/// one, makes it look not local. That is acceptable because the answer +/// never chooses a schema: it only lets a missing or outdated file be +/// downloaded, or turns that into a compile error that names the file and +/// the command to run. A mistake makes a build fail loudly, never compile +/// against another schema. pub fn is_local_package(dir: &Path, cargo_home: Option<&Path>) -> bool { if dir.join("Cargo.toml.orig").exists() || dir.join(".cargo-checksum.json").exists() { return false; @@ -226,29 +298,16 @@ pub fn cargo_home() -> Option { .map(|home| PathBuf::from(home).join(".cargo")) } -/// What `graphql!` may do for the package being compiled. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct SchemaRules { - /// Whether [`SCHEMA_ENV`] applies: to a local package only, so that a - /// dependency is always checked against the schema it ships. - pub override_applies: bool, - /// Whether the schema file may be downloaded, see [`schema_plan`]. - pub may_download: bool, -} - -/// The rules for a package that is `local` ([`is_local_package`]) and, -/// with `primary`, one cargo was asked to build. +/// Whether `graphql!` may download the schema file of the package in `dir`, +/// one cargo was asked to build when `primary` (`CARGO_PRIMARY_PACKAGE`): +/// only a local one ([`is_local_package`]). /// -/// What is compiled depends on `local` only, an input that is the same for -/// a compiled crate. `primary` is not: cargo reuses a crate built as primary -/// when it is later built as a dependency, and the other way round. It only -/// decides whether a missing or outdated file is downloaded or refused, and -/// a refusal is a compile error, never another schema. -pub fn schema_rules(local: bool, primary: bool) -> SchemaRules { - SchemaRules { - override_applies: local, - may_download: local && primary, - } +/// Neither input is tracked by cargo, and neither needs to be: they decide +/// whether a missing or outdated file is downloaded or a compile error, +/// never which file is read. A compiled crate read the same file whatever +/// they were. +pub fn may_download(dir: &Path, cargo_home: Option<&Path>, primary: bool) -> bool { + primary && is_local_package(dir, cargo_home) } /// What a crate's schema file holds. @@ -283,32 +342,32 @@ pub enum SchemaPlan { Refuse(String), } -/// What to do with the schema file of the crate in `dir`, `file`, when its -/// `Cargo.toml` pins `pinned`. +/// What to do with `file`, the schema file at `path` of the crate in `dir`, +/// when its `Cargo.toml` pins `pinned`. /// /// The version of a crate is the one it pins, else the one of its file: a /// file is never replaced by a newer version on its own, so that a build /// gives the same result whatever the date. Without either, the crate takes /// the latest version at `now`. /// -/// Only a package that `may_download` ([`schema_rules`]) downloads: a local -/// one cargo was asked to build. Any other uses the file it ships, and +/// Only a package that [`may_download`] downloads: a local one cargo was +/// asked to build. Any other uses the file it ships, and /// refuses to build when it has none or when it is not the version its /// `Cargo.toml` pins: its author tested its operations against that file, /// and a registry, vendored or packaged copy is not to be written. pub fn schema_plan( dir: &Path, + path: &Path, file: &SchemaFile, pinned: Option<&str>, may_download: bool, now: SystemTime, ) -> SchemaPlan { - let path = dir.join(PROJECT_SCHEMA_PATH); let fix = || { format!( "Run `shopify-api schema download` in `{}` (`cargo install shopify_api --features cli`), \ and commit the file. A crate downloads its schema only as a local package cargo was asked to build: \ - as a dependency, or packaged, it uses the one it ships.", + as a dependency, packaged, vendored, under $CARGO_HOME or below a `.cargo-ok`, it uses the one it ships.", dir.display() ) }; @@ -495,8 +554,9 @@ pub fn write_atomically(path: &Path, contents: &str) -> Result<(), String> { }) } -/// The schema of the crate in `dir`, read with `read`, after downloading it -/// when [`schema_plan`] says so, with `may_download` from [`schema_rules`]. `on_download` +/// The schema of the crate in `dir`, read from `path` with `read`, after +/// downloading it when [`schema_plan`] says so, with `may_download` from +/// [`may_download()`]. `on_download` /// is called with the file and the version before each download, to show /// progress. /// @@ -506,48 +566,57 @@ pub fn write_atomically(path: &Path, contents: &str) -> Result<(), String> { #[cfg_attr(docsrs, doc(cfg(feature = "download")))] pub fn project_schema>( dir: &Path, + path: &Path, pinned: Option<&str>, may_download: bool, now: SystemTime, read: impl Fn(&Path) -> Result, on_download: impl Fn(&Path, &str), ) -> Result { - obtain_schema(dir, pinned, may_download, now, read, |path, version| { - on_download(path, version); - download_schema_file(path, version).map(drop) - }) + obtain_schema( + dir, + path, + pinned, + may_download, + now, + read, + |path, version| { + on_download(path, version); + download_schema_file(path, version).map(drop) + }, + ) } /// [`project_schema`], downloading with `download`. #[cfg(feature = "download")] fn obtain_schema>( dir: &Path, + path: &Path, pinned: Option<&str>, may_download: bool, now: SystemTime, read: impl Fn(&Path) -> Result, download: impl Fn(&Path, &str) -> Result<(), DownloadError>, ) -> Result { - let path = dir.join(PROJECT_SCHEMA_PATH); let (file, current) = if path.is_file() { - match read(&path) { + match read(path) { Ok(schema) => { let version = schema.as_ref().api_version.clone(); (SchemaFile::Usable { version }, Some(schema)) } Err(reason) => { - let version = stored_api_version(&path); + let version = stored_api_version(path); (SchemaFile::Unusable { version, reason }, None) } } } else { (SchemaFile::Missing, None) }; - match schema_plan(dir, &file, pinned, may_download, now) { - SchemaPlan::Read => current.map_or_else(|| read(&path), Ok), + match schema_plan(dir, path, &file, pinned, may_download, now) { + SchemaPlan::Read => current.map_or_else(|| read(path), Ok), SchemaPlan::Refuse(message) => Err(message), SchemaPlan::Download { version, latest } => { - download_once(&path, &version, latest, download).map_err(|error| { + download_once(path, &version, latest, download).map_err(|error| { let which = match (pinned, &file) { (Some(_), _) => format!("{version}, the version Cargo.toml pins"), (None, SchemaFile::Missing) => format!( @@ -557,9 +626,9 @@ fn obtain_schema>( "{version}, the version of the schema file, again: this version of shopify_api cannot read it" ), }; - download_failure(&error, &path, &which, &version, now) + download_failure(&error, path, &which, &version, now) })?; - read(&path) + read(path) } } } @@ -736,24 +805,44 @@ mod tests { assert_eq!(previous_api_version("2026-05"), None); } + fn version_in(manifest: &str) -> Result, String> { + config_in(manifest).map(|config| config.api_version) + } + #[test] fn the_version_is_read_from_the_package_metadata() { - assert_eq!(api_version_in("[package]\nname = \"app\""), Ok(None)); + assert_eq!(version_in("[package]\nname = \"app\""), Ok(None)); assert_eq!( - api_version_in("[package.metadata.shopify_api]\napi-version = \"2026-07\""), + version_in("[package.metadata.shopify_api]\napi-version = \"2026-07\""), Ok(Some("2026-07".to_string())) ); assert_eq!( - api_version_in("[package.metadata.shopify_api]\napi-version = \"unstable\""), + version_in("[package.metadata.shopify_api]\napi-version = \"unstable\""), Ok(Some("unstable".to_string())) ); - let old = api_version_in("[package.metadata.shopify_api]\napi-version = \"2025-01\"") - .unwrap_err(); + let old = + version_in("[package.metadata.shopify_api]\napi-version = \"2025-01\"").unwrap_err(); assert!(old.contains("is not a version shopify_api calls"), "{old}"); - let number = - api_version_in("[package.metadata.shopify_api]\napi-version = 2026").unwrap_err(); + let number = version_in("[package.metadata.shopify_api]\napi-version = 2026").unwrap_err(); assert!(number.contains("must be a string"), "{number}"); - assert!(api_version_in("[package").is_err()); + assert!(version_in("[package").is_err()); + } + + #[test] + fn the_schema_file_is_read_from_the_package_metadata() { + let schema = |manifest: &str| config_in(manifest).map(|config| config.schema); + assert_eq!(schema("[package]\nname = \"app\""), Ok(None)); + assert_eq!( + schema("[package.metadata.shopify_api]\nschema = \"schemas/admin.json\""), + Ok(Some(PathBuf::from("schemas/admin.json"))) + ); + for wrong in ["schema = 1", "schema = \"\""] { + let error = schema(&format!("[package.metadata.shopify_api]\n{wrong}")).unwrap_err(); + assert!( + error.contains("must be the path of a schema file"), + "{error}" + ); + } } #[test] @@ -780,7 +869,30 @@ mod tests { } #[test] - fn the_environment_names_another_file() { + fn the_manifest_names_another_file_relative_to_it() { + let project = Project::new("key"); + project.write( + "Cargo.toml", + "[package]\nname = \"app\"\n\n[package.metadata.shopify_api]\n\ + api-version = \"2026-07\"\nschema = \"schemas/admin-2026-07.json\"\n", + ); + // The file need not exist: missing, it is downloaded or refused as + // the default one is. + let expected = SchemaSource::Project { + dir: project.0.clone(), + path: project.0.join("schemas/admin-2026-07.json"), + pinned: Some("2026-07".to_string()), + }; + assert_eq!(schema_source(Some(&project.0), None), Ok(expected.clone())); + // An empty test variable is no variable. + assert_eq!( + schema_source(Some(&project.0), Some(OsStr::new(""))), + Ok(expected) + ); + } + + #[test] + fn the_test_variable_names_a_file_for_every_package() { let project = Project::new("named"); project.manifest(Some("2026-07")); let other = project.write("schemas/unstable.json", "{}"); @@ -799,7 +911,7 @@ mod tests { assert_eq!( schema_source(Some(&project.0), Some(OsStr::new("missing.json"))), Err(format!( - "SHOPIFY_GRAPHQL_SCHEMA names `{}`, which is not a file", + "SHOPIFY_API_INTERNAL_TEST_SCHEMA names `{}`, which is not a file", project.0.join("missing.json").display() )) ); @@ -820,6 +932,10 @@ mod tests { } } + fn path(dir: &Path) -> PathBuf { + dir.join(PROJECT_SCHEMA_PATH) + } + fn download(version: &str, latest: bool) -> SchemaPlan { SchemaPlan::Download { version: version.to_string(), @@ -833,13 +949,27 @@ mod tests { let years_later = day(2031, 5, 6); for primary in [true, false] { assert_eq!( - schema_plan(dir, &usable("2026-07"), None, primary, years_later), + schema_plan( + dir, + &path(dir), + &usable("2026-07"), + None, + primary, + years_later + ), SchemaPlan::Read ); } // No file and no pin: the first build of the crate takes the latest. assert_eq!( - schema_plan(dir, &SchemaFile::Missing, None, true, day(2027, 2, 3)), + schema_plan( + dir, + &path(dir), + &SchemaFile::Missing, + None, + true, + day(2027, 2, 3) + ), download("2027-01", true) ); } @@ -849,25 +979,54 @@ mod tests { let dir = Path::new("/crate"); let now = day(2026, 10, 22); assert_eq!( - schema_plan(dir, &usable("2026-07"), Some("2026-07"), true, now), + schema_plan( + dir, + &path(dir), + &usable("2026-07"), + Some("2026-07"), + true, + now + ), SchemaPlan::Read ); assert_eq!( - schema_plan(dir, &usable("2026-07"), Some("2026-10"), true, now), + schema_plan( + dir, + &path(dir), + &usable("2026-07"), + Some("2026-10"), + true, + now + ), download("2026-10", false) ); assert_eq!( - schema_plan(dir, &SchemaFile::Missing, Some("2026-04"), true, now), + schema_plan( + dir, + &path(dir), + &SchemaFile::Missing, + Some("2026-04"), + true, + now + ), download("2026-04", false) ); // A file of an older format is downloaded again, for the same version. assert_eq!( - schema_plan(dir, &old_format(Some("2026-07")), None, true, now), + schema_plan( + dir, + &path(dir), + &old_format(Some("2026-07")), + None, + true, + now + ), download("2026-07", false) ); assert_eq!( schema_plan( dir, + &path(dir), &old_format(Some("2026-07")), Some("2026-10"), true, @@ -876,7 +1035,7 @@ mod tests { download("2026-10", false) ); assert_eq!( - schema_plan(dir, &old_format(None), None, true, now), + schema_plan(dir, &path(dir), &old_format(None), None, true, now), download("2026-10", true) ); } @@ -975,25 +1134,16 @@ mod tests { } #[test] - fn the_override_applies_to_local_packages_and_only_a_primary_one_downloads() { - for primary in [true, false] { - assert_eq!( - schema_rules(true, primary), - SchemaRules { - override_applies: true, - may_download: primary, - } - ); - // Packaged, vendored or checked out: never, even when primary, - // as in the verification of `cargo package`. - assert_eq!( - schema_rules(false, primary), - SchemaRules { - override_applies: false, - may_download: false, - } - ); - } + fn only_a_local_primary_package_downloads() { + let home = Project::new("download-home"); + let local = Project::new("download-local"); + local.manifest(None); + assert!(may_download(&local.0, Some(&home.0), true)); + assert!(!may_download(&local.0, Some(&home.0), false)); + // Packaged: never, even when primary, as in the verification of + // `cargo package`. + local.write("Cargo.toml.orig", ""); + assert!(!may_download(&local.0, Some(&home.0), true)); } #[test] @@ -1001,7 +1151,12 @@ mod tests { let dir = Path::new("/registry/deplib-1.0.0"); let now = day(2026, 10, 22); let refusal = |file: &SchemaFile, pinned: Option<&str>| match schema_plan( - dir, file, pinned, false, now, + dir, + &path(dir), + file, + pinned, + false, + now, ) { SchemaPlan::Refuse(message) => { let fix = "Run `shopify-api schema download` in `/registry/deplib-1.0.0`"; @@ -1011,7 +1166,14 @@ mod tests { other => panic!("{file:?}, {pinned:?}: {other:?}"), }; assert_eq!( - schema_plan(dir, &usable("2026-07"), Some("2026-07"), false, now), + schema_plan( + dir, + &path(dir), + &usable("2026-07"), + Some("2026-07"), + false, + now + ), SchemaPlan::Read ); let message = refusal(&usable("2026-07"), Some("2026-10")); @@ -1095,10 +1257,11 @@ mod tests { primary: bool, now: SystemTime, ) -> Result, String> { - let pinned = configured_api_version(&project.0).unwrap(); + let config = package_config(&project.0).unwrap(); obtain_schema( &project.0, - pinned.as_deref(), + &config.schema_path(&project.0), + config.api_version.as_deref(), primary, now, read, @@ -1125,6 +1288,91 @@ mod tests { assert!(read(&file).unwrap().api_version == "2026-04"); } + /// A package whose `Cargo.toml` names `schemas/admin.json`. + fn with_key(name: &str, version: Option<&str>) -> Project { + let project = Project::new(name); + let pin = version.map_or(String::new(), |version| { + format!("api-version = \"{version}\"\n") + }); + project.write( + "Cargo.toml", + &format!( + "[package]\nname = \"app\"\n\n[package.metadata.shopify_api]\n\ + {pin}schema = \"schemas/admin.json\"\n" + ), + ); + project + } + + #[test] + fn the_file_the_manifest_names_follows_the_rules_of_the_default_one() { + let project = with_key("key-local", None); + // The default file is not read when the key names another. + project.write(PROJECT_SCHEMA_PATH, &schema("2026-04")); + project.write("schemas/admin.json", &schema("2026-07")); + let network = Network::new(true, &["2026-07", "2026-10"]); + let now = day(2026, 10, 22); + assert_eq!( + network.obtain(&project, true, now).unwrap().api_version, + "2026-07" + ); + assert!(network.asked.borrow().is_empty()); + + // Missing: a local primary package downloads it there. + std::fs::remove_file(project.0.join("schemas/admin.json")).unwrap(); + assert_eq!( + network.obtain(&project, true, now).unwrap().api_version, + "2026-10" + ); + assert_eq!(*network.asked.borrow(), ["2026-10"]); + assert_eq!( + read(&project.0.join("schemas/admin.json")) + .unwrap() + .api_version, + "2026-10" + ); + assert_eq!( + read(&project.0.join(PROJECT_SCHEMA_PATH)) + .unwrap() + .api_version, + "2026-04" + ); + } + + #[test] + fn a_dependency_uses_the_file_its_manifest_names_and_never_downloads_it() { + let now = day(2026, 10, 22); + let network = Network::new(true, &["2026-04", "2026-07", "2026-10"]); + let project = with_key("key-dependency", Some("2026-07")); + project.write("schemas/admin.json", &schema("2026-07")); + assert_eq!( + network.obtain(&project, false, now).unwrap().api_version, + "2026-07" + ); + + // Missing: an error that names the file and the command. + std::fs::remove_file(project.0.join("schemas/admin.json")).unwrap(); + let error = network.obtain(&project, false, now).unwrap_err(); + let file = project.0.join("schemas/admin.json"); + assert!( + error.starts_with(&format!("`{}` is missing", file.display())), + "{error}" + ); + assert!( + error.contains(&format!( + "Run `shopify-api schema download` in `{}`", + project.0.display() + )), + "{error}" + ); + + // Of another version than the pinned one: an error too. + project.write("schemas/admin.json", &schema("2026-04")); + let error = network.obtain(&project, false, now).unwrap_err(); + assert!(error.contains("holds the Admin API 2026-04"), "{error}"); + assert!(network.asked.borrow().is_empty()); + } + #[test] fn a_failed_download_is_tried_once_and_says_what_to_do() { let project = Project::new("offline"); diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 6f941c1..621aeff 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -13,11 +13,9 @@ use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, quote_spanned}; use shopify_api_graphql::codegen::{DATA_TYPE, data_types, deprecation_warning, variables_types}; use shopify_api_graphql::literal::{self, Literals, Value, VariableValue}; -use shopify_api_graphql::project::{ - cargo_home, is_local_package, metadata_snippet, project_schema, schema_rules, -}; +use shopify_api_graphql::project::{cargo_home, may_download, metadata_snippet, project_schema}; use shopify_api_graphql::{ - MINIMUM_API_VERSION, Operation, OperationKind, SCHEMA_ENV, Schema, SchemaSource, Variable, + MINIMUM_API_VERSION, Operation, OperationKind, Schema, SchemaSource, TEST_SCHEMA_ENV, Variable, analyze, is_supported_api_version, latest_api_version, schema_source, }; use syn::parse::{Parse, ParseStream}; @@ -242,39 +240,32 @@ struct LoadedSchema { impl LoadedSchema { /// The schema of the crate being compiled. fn load() -> Result { - // What is compiled depends on whether the package is local, which - // is the same for a compiled crate whatever cargo command built it, - // never on `CARGO_PRIMARY_PACKAGE`, which cargo does not track. + // The file read depends on the package's `Cargo.toml` only, and on + // the internal test variable, which applies to every package: both + // are tracked. Where the package is, and whether cargo was asked to + // build it, are not: they only decide whether a missing or outdated + // file is downloaded or a compile error. let dir = manifest_dir(); - let local = dir - .as_deref() - .is_some_and(|dir| is_local_package(dir, cargo_home().as_deref())); - // Untracked, `primary` may be stale for a reused crate. That is fine - // here: it only decides whether a missing or outdated file is - // downloaded or a compile error, never which schema is used. - let primary = std::env::var_os("CARGO_PRIMARY_PACKAGE").is_some(); - let rules = schema_rules(local, primary); - let named = std::env::var_os(SCHEMA_ENV).filter(|_| rules.override_applies); - let (path, schema) = match schema_source(dir.as_deref(), named.as_deref())? { + let test_schema = std::env::var_os(TEST_SCHEMA_ENV); + let (path, schema) = match schema_source(dir.as_deref(), test_schema.as_deref())? { SchemaSource::File(path) => { let schema = read_schema(&path).map_err(|error| { - format!( - "`{}`, named by {SCHEMA_ENV}: {error}. Download it again with \ - `shopify-api schema download --out `.", - path.display() - ) + format!("`{}`, named by {TEST_SCHEMA_ENV}: {error}", path.display()) })?; (path, schema) } SchemaSource::Project { dir, path, pinned } => { + let primary = std::env::var_os("CARGO_PRIMARY_PACKAGE").is_some(); + let may_download = may_download(&dir, cargo_home().as_deref(), primary); let read = |path: &Path| { read_schema(path).map_err(|error| format!("`{}`: {error}", path.display())) }; // A proc macro has no progress to show. let schema = project_schema( &dir, + &path, pinned.as_deref(), - rules.may_download, + may_download, SystemTime::now(), read, |_, _| {}, @@ -313,7 +304,8 @@ impl LoadedSchema { let mut tracked = TRACKED .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - // The manifest declares the API version, the schema file holds it. + // The manifest declares the API version and names the schema file, + // which holds the schema. let manifest = manifest_dir().map(|dir| dir.join("Cargo.toml")); let files = [manifest, Some(self.path.clone())] .into_iter() @@ -330,9 +322,7 @@ impl LoadedSchema { .map(|path| path.to_string_lossy().to_string()) .collect(); quote! { - const _: ::core::option::Option<&str> = ::core::option_env!(#SCHEMA_ENV); - // Whether the package is local depends on it. - const _: ::core::option::Option<&str> = ::core::option_env!("CARGO_HOME"); + const _: ::core::option::Option<&str> = ::core::option_env!(#TEST_SCHEMA_ENV); #(const _: &[u8] = ::core::include_bytes!(#files);)* } } From 568be3801555b9870895ee77c3e81085ba00b81c Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:50:26 +0100 Subject: [PATCH 096/135] docs: describe the `schema` key and what package locality decides Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- MIGRATION.md | 5 +++-- README.md | 5 ++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d2d06e..41632bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,8 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. - `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - `Operation`, what `graphql!` builds, or `Operation::new` for any text: `execute` and `execute_response` take `impl Into>`, a module's `Variables` included. `body()` is the exact JSON text sent, and `variable_json(name)` the text of one variable; `with_name` sets the `operationName`. -- No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. A local package (of the workspace, or a path dependency) that cargo was asked to build downloads the file when it is missing or does not hold the pinned version, once per build; any other crate never downloads nor writes it, and fails to build when its file is missing or does not fit, a packaged crate in the verification of `cargo package` included. `SHOPIFY_GRAPHQL_SCHEMA` names another schema file for every local package, and is ignored for the packaged, vendored or checked-out ones (a `Cargo.toml.orig`, a `.cargo-checksum.json` or a `.cargo-ok` in the package directory, a `.cargo-ok` above it, or a path under `$CARGO_HOME`, with or without symbolic links resolved): which schema a crate gets depends on where it is, never on the cargo command that built it first. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. +- No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. A local package (of the workspace, or a path dependency) that cargo was asked to build downloads the file when it is missing or does not hold the pinned version, once per build; any other crate never downloads nor writes it, and fails to build when its file is missing or does not fit, a packaged crate in the verification of `cargo package` included. A packaged, vendored or checked-out crate (a `Cargo.toml.orig`, a `.cargo-checksum.json` or a `.cargo-ok` in the package directory, a `.cargo-ok` above it, or a path under `$CARGO_HOME`, with or without symbolic links resolved) never downloads: where a crate is decides only between a download and a compile error, never which schema it gets. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. +- `schema = ""` in `[package.metadata.shopify_api]` names another schema file than `graphql/admin.schema.json`, relative to the package's `Cargo.toml`, for that package only: a dependency keeps the one its own `Cargo.toml` names. The file follows the rules of the default one (version, download, older format), `shopify-api schema download` and `shopify-api check` use it, and an edit of the key compiles the crate again. - `@oneOf` input objects (`ProductSetIdentifiers`…) are checked at compile time: exactly one field, not `null`. - `shopify-api check` checks `.graphql` files against the schema. - Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. The jitter of the backoff is random on every platform. diff --git a/MIGRATION.md b/MIGRATION.md index 58a472e..61ff770 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -256,10 +256,11 @@ Topics are accepted as `orders/create` or `ORDERS_CREATE`. | `shopify.download_admin_schema()` | The same | | `SHOPIFY_DEV_ADMIN_SCHEMA_PROXY` | `schema::PUBLIC_ADMIN_SCHEMA_ENDPOINT` | | `ADMIN_SCHEMA_INTROSPECTION_QUERY` | `schema::INTROSPECTION_QUERY` | -| `shopify-api schema download --public --out file` | `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`: `graphql!` downloads it when cargo is asked to build the package, never for a dependency, or a packaged crate. `shopify-api schema download` refreshes it, `--introspection` for the raw result | +| `shopify-api schema download --public --out file` | `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`: `graphql!` downloads it when cargo is asked to build the package, never for a dependency, or a packaged crate. `shopify-api schema download` refreshes it, `--introspection` for the raw result. `schema = "file"` next to `api-version` names another file than `graphql/admin.schema.json` | | `shopify-api schema download --api-version 2026-07` | No flag: the command reads the version of the nearest `Cargo.toml`. For another version, or outside a package: `schema::download_public_admin_schema(ApiVersion::new("2026-07")?)` | -`graphql!` reads the compact form it downloads, in `graphql/admin.schema.json`. +`graphql!` reads the compact form it downloads, in `graphql/admin.schema.json`, +or in the file `schema = "…"` names in `[package.metadata.shopify_api]`. ## Removed diff --git a/README.md b/README.md index 8e5a735..3a94bc9 100644 --- a/README.md +++ b/README.md @@ -225,9 +225,8 @@ keep it, whatever Shopify releases since: a build gives the same result whatever the date. Commit the file, so that builds without network access have it. A library that uses `graphql!` must ship it: as a dependency, a crate never downloads its schema, and `cargo package` fails without it. -`SHOPIFY_GRAPHQL_SCHEMA` names another schema file for your own packages (the -workspace and path dependencies), never for a crate from a registry, git or -a vendor directory. The details are in the +`schema = "…"` in `[package.metadata.shopify_api]` names another schema file +for that package, relative to its `Cargo.toml`. The details are in the [`graphql!` docs](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html#schema-and-api-version). To choose the version, pin it in your `Cargo.toml` (`graphql!` downloads its From d6b6981bcbcc943887e6db995cb9c4f5632c71dd Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:08:27 +0100 Subject: [PATCH 097/135] fix(graphql)!: refuse a `schema` path outside the package `cargo package` ships only the package's files, so a schema named by an absolute path or one that climbs out with `..` was missing, or another one, once the crate was packaged. The check is lexical: a symbolic link inside the package may point elsewhere, since cargo ships its content. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 2 +- crates/shopify_api/docs/graphql.md | 5 + crates/shopify_api/tests/schema_override.rs | 40 ++++++- crates/shopify_api_graphql/src/project.rs | 118 +++++++++++++++++++- 5 files changed, 155 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41632bb..f19c301 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - `Operation`, what `graphql!` builds, or `Operation::new` for any text: `execute` and `execute_response` take `impl Into>`, a module's `Variables` included. `body()` is the exact JSON text sent, and `variable_json(name)` the text of one variable; `with_name` sets the `operationName`. - No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. A local package (of the workspace, or a path dependency) that cargo was asked to build downloads the file when it is missing or does not hold the pinned version, once per build; any other crate never downloads nor writes it, and fails to build when its file is missing or does not fit, a packaged crate in the verification of `cargo package` included. A packaged, vendored or checked-out crate (a `Cargo.toml.orig`, a `.cargo-checksum.json` or a `.cargo-ok` in the package directory, a `.cargo-ok` above it, or a path under `$CARGO_HOME`, with or without symbolic links resolved) never downloads: where a crate is decides only between a download and a compile error, never which schema it gets. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. -- `schema = ""` in `[package.metadata.shopify_api]` names another schema file than `graphql/admin.schema.json`, relative to the package's `Cargo.toml`, for that package only: a dependency keeps the one its own `Cargo.toml` names. The file follows the rules of the default one (version, download, older format), `shopify-api schema download` and `shopify-api check` use it, and an edit of the key compiles the crate again. +- `schema = ""` in `[package.metadata.shopify_api]` names another schema file than `graphql/admin.schema.json`, relative to the package's `Cargo.toml`, for that package only. It must name a file inside the package, which `cargo package` ships: an absolute path, or one that climbs out with `..`, is an error (a symbolic link inside the package may point elsewhere). A dependency keeps the one its own `Cargo.toml` names: a dependency keeps the one its own `Cargo.toml` names. The file follows the rules of the default one (version, download, older format), `shopify-api schema download` and `shopify-api check` use it, and an edit of the key compiles the crate again. - `@oneOf` input objects (`ProductSetIdentifiers`…) are checked at compile time: exactly one field, not `null`. - `shopify-api check` checks `.graphql` files against the schema. - Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. The jitter of the backoff is random on every platform. diff --git a/README.md b/README.md index 3a94bc9..f856a75 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,7 @@ whatever the date. Commit the file, so that builds without network access have it. A library that uses `graphql!` must ship it: as a dependency, a crate never downloads its schema, and `cargo package` fails without it. `schema = "…"` in `[package.metadata.shopify_api]` names another schema file -for that package, relative to its `Cargo.toml`. The details are in the +for that package, relative to its `Cargo.toml` and inside the package. The details are in the [`graphql!` docs](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html#schema-and-api-version). To choose the version, pin it in your `Cargo.toml` (`graphql!` downloads its diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index e0da785..560725d 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -368,6 +368,11 @@ api-version = "2026-07" schema = "schemas/admin-2026-07.json" # optional ``` +The file `schema` names must be inside the package, so that `cargo package` +ships it: an absolute path, or one that climbs above `Cargo.toml` with `..`, +is a compile error. A symbolic link inside the package may point elsewhere: +`cargo package` ships the content of the file it links to. + Both keys belong to the package whose `Cargo.toml` holds them: a dependency is always checked against the file its own `Cargo.toml` names, whatever yours says. The file `schema` names follows the same rules as the default one: the diff --git a/crates/shopify_api/tests/schema_override.rs b/crates/shopify_api/tests/schema_override.rs index f65e725..2e47a58 100644 --- a/crates/shopify_api/tests/schema_override.rs +++ b/crates/shopify_api/tests/schema_override.rs @@ -20,8 +20,10 @@ fn schema(version: &str) -> String { } /// A workspace of `app`, which prints the API version of `library`, a path -/// dependency whose default schema file is 2026-04, and `override.json`, of -/// 2026-07, which the `schema` key of `library` may name. +/// dependency whose default schema file is 2026-04, and +/// `schemas/override.json` in it, of 2026-07, which the `schema` key of +/// `library` may name. An `override.json` outside the library, of 2026-07 +/// too, is one it may not name. struct Workspace { root: PathBuf, target: PathBuf, @@ -66,6 +68,7 @@ impl Workspace { "shopify_api::graphql! { pub mod probe = \"{ f }\"; }\n", ); write("library/graphql/admin.schema.json", &schema("2026-04")); + write("library/schemas/override.json", &schema("2026-07")); write("override.json", &schema("2026-07")); // Shared by the tests: later runs build only the probes again. let target = tmp.join("schema_override_target"); @@ -91,7 +94,7 @@ impl Workspace { } fn with_override(&self) { - self.library_metadata("schema = \"../override.json\"\n"); + self.library_metadata("schema = \"schemas/override.json\"\n"); } fn cargo(&self, args: &[&str]) -> Output { @@ -161,9 +164,9 @@ fn the_key_chooses_the_schema_whatever_cargo_built_first() { // `api-version` is followed too: a pin the file does not hold is an // error for a library built as a dependency, which never downloads. - workspace.library_metadata("api-version = \"2026-07\"\nschema = \"../override.json\"\n"); + workspace.library_metadata("api-version = \"2026-07\"\nschema = \"schemas/override.json\"\n"); assert_eq!(workspace.app_version(), "2026-07"); - workspace.library_metadata("api-version = \"2026-10\"\nschema = \"../override.json\"\n"); + workspace.library_metadata("api-version = \"2026-10\"\nschema = \"schemas/override.json\"\n"); let stderr = workspace.fail(&["run", "-p", "probe_app"]); assert!( stderr.contains("override.json` holds the Admin API 2026-07"), @@ -204,8 +207,33 @@ fn a_packaged_library_takes_its_key_and_never_downloads() { workspace.succeed(&["build", "-p", "probe_library"]); assert_eq!(workspace.app_version(), "2026-07"); - std::fs::remove_file(workspace.root.join("override.json")).unwrap(); + std::fs::remove_file(library.join("schemas/override.json")).unwrap(); let stderr = workspace.fail(&["build", "-p", "probe_library"]); assert!(stderr.contains("override.json` is missing"), "{stderr}"); assert!(!stderr.contains("cannot download"), "{stderr}"); } + +/// A file outside the package is refused, though it exists: `cargo package` +/// would not ship it, and the packaged crate would look for it elsewhere. +#[test] +fn a_schema_outside_the_package_is_a_compile_error() { + let workspace = Workspace::new("outside"); + let absolute = workspace.root.join("override.json"); + // A literal string, as `library_metadata` writes the path of shopify_api. + let absolute = format!("'{}'", absolute.display()); + for path in [ + "\"../override.json\"", + "\"schemas/../../override.json\"", + &absolute, + ] { + workspace.library_metadata(&format!("schema = {path}\n")); + let stderr = workspace.fail(&["build", "-p", "probe_library"]); + assert!( + stderr.contains("must name a file inside the package"), + "{stderr}" + ); + assert!(stderr.contains("`cargo package` ships"), "{stderr}"); + } + workspace.library_metadata("schema = \"schemas/../schemas/override.json\"\n"); + assert_eq!(workspace.app_version(), "2026-07"); +} diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index 634eae2..da643ff 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -8,7 +8,9 @@ //! schema = "schemas/admin-2026-07.json" //! ``` //! -//! Without `schema`, the file is [`PROJECT_SCHEMA_PATH`]. Without +//! `schema` must name a file inside the package, which `cargo package` +//! ships: see [`inside_package`]. Without it, the file is +//! [`PROJECT_SCHEMA_PATH`]. Without //! `api-version`, the version is the one of that file, and the latest stable //! one when there is no file yet. `graphql!` checks the crate's operations //! against that schema: see [`schema_plan`] for when it is downloaded. @@ -41,7 +43,8 @@ pub const METADATA_TABLE: &str = "shopify_api"; pub const API_VERSION_KEY: &str = "api-version"; /// The key of the schema file in [`METADATA_TABLE`], relative to the -/// package's `Cargo.toml`; [`PROJECT_SCHEMA_PATH`] without it. +/// package's `Cargo.toml` and inside the package ([`inside_package`]); +/// [`PROJECT_SCHEMA_PATH`] without it. pub const SCHEMA_KEY: &str = "schema"; /// The lines to add to a `Cargo.toml` to select `version`. @@ -95,7 +98,8 @@ fn year_and_month(days: u64) -> (u64, u64) { pub struct PackageConfig { /// [`API_VERSION_KEY`]. pub api_version: Option, - /// [`SCHEMA_KEY`], as written: relative to the `Cargo.toml`. + /// [`SCHEMA_KEY`], relative to the `Cargo.toml`, normalized by + /// [`inside_package`]. pub schema: Option, } @@ -151,7 +155,7 @@ fn schema_in(value: Option<&toml::Value>) -> Result, String> { return Ok(None); }; match value.as_str() { - Some(path) if !path.is_empty() => Ok(Some(PathBuf::from(path))), + Some(path) if !path.is_empty() => inside_package(Path::new(path)).map(Some), _ => Err(format!( "`{SCHEMA_KEY}` in [package.metadata.{METADATA_TABLE}] must be the path of a schema file, \ relative to Cargo.toml, such as \"graphql/admin.schema.json\"" @@ -159,6 +163,46 @@ fn schema_in(value: Option<&toml::Value>) -> Result, String> { } } +/// `path`, relative to a package's `Cargo.toml`, normalized, when it names a +/// file inside the package: `cargo package` ships only the package's files, +/// so a packaged crate would look for any other file at another place, and +/// fail, or find another schema there. +/// +/// The check is lexical: `.` and `a/..` are removed, and the path must not +/// be absolute, have a root or a drive, nor climb above the package. A +/// symbolic link inside the package that points outside it is accepted, on +/// purpose: `cargo package` ships the content of a linked file. The path is +/// returned normalized, so that the file opened is the one checked, even +/// when `a` in `a/..` is a link to a directory. +pub fn inside_package(path: &Path) -> Result { + use std::path::Component; + let outside = || { + format!( + "`{SCHEMA_KEY} = \"{}\"` in [package.metadata.{METADATA_TABLE}] must name a file inside the package, \ + relative to its Cargo.toml, such as \"graphql/admin.schema.json\": \ + `cargo package` ships only the package's files", + path.display() + ) + }; + let mut normal = PathBuf::new(); + for component in path.components() { + match component { + Component::Prefix(_) | Component::RootDir => return Err(outside()), + Component::CurDir => {} + Component::ParentDir => { + if !normal.pop() { + return Err(outside()); + } + } + Component::Normal(name) => normal.push(name), + } + } + if normal.as_os_str().is_empty() { + return Err(outside()); + } + Ok(normal) +} + /// The API version [`API_VERSION_KEY`] declares, if any. fn api_version_in(value: Option<&toml::Value>) -> Result, String> { let Some(value) = value else { @@ -845,6 +889,72 @@ mod tests { } } + #[test] + fn the_schema_file_must_be_inside_the_package() { + let schema = |path: &str| { + config_in(&format!( + "[package.metadata.shopify_api]\nschema = {}", + toml::Value::from(path) + )) + .map(|config| config.schema) + }; + let absolute = std::env::temp_dir().join("admin.schema.json"); + for outside in [ + absolute.to_str().unwrap(), + "/admin.schema.json", + "../x.json", + "a/../../x.json", + "./..", + ".", + "a/..", + ] { + let error = schema(outside).unwrap_err(); + assert!( + error.contains("must name a file inside the package"), + "{error}" + ); + assert!(error.contains("`cargo package` ships"), "{error}"); + } + #[cfg(windows)] + for outside in [ + "C:\\x.json", + "C:x.json", + "\\\\server\\share\\x.json", + "\\x.json", + ] { + assert!(schema(outside).is_err(), "{outside}"); + } + for (inside, normal) in [ + ("a/../x.json", "x.json"), + ("./graphql/x.json", "graphql/x.json"), + ("schemas/../schemas/admin.json", "schemas/admin.json"), + ] { + assert_eq!(schema(inside), Ok(Some(PathBuf::from(normal))), "{inside}"); + } + } + + #[cfg(unix)] + #[test] + fn a_link_inside_the_package_may_point_outside_it() { + let project = Project::new("link"); + let outside = Project::new("link-target"); + let target = outside.write("admin.schema.json", "{}"); + std::fs::create_dir_all(project.0.join("schemas")).unwrap(); + std::os::unix::fs::symlink(&target, project.0.join("schemas/admin.json")).unwrap(); + project.write( + "Cargo.toml", + "[package]\nname = \"app\"\n\n[package.metadata.shopify_api]\nschema = \"schemas/admin.json\"\n", + ); + assert_eq!( + schema_source(Some(&project.0), None), + Ok(SchemaSource::Project { + dir: project.0.clone(), + path: project.0.join("schemas/admin.json"), + pinned: None, + }) + ); + } + #[test] fn the_source_is_the_crate_file_with_its_pinned_version() { let project = Project::new("source"); From fd5ed131ebd286e310112e1497eb47b8e5d6ec62 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:08:27 +0100 Subject: [PATCH 098/135] fix(cli): write the `schema` path of the printed snippet as a TOML string A quote or a backslash in the file name broke the snippet. The path is written with `/` separators, and an --out file outside the package gets a note that `graphql!` cannot use it instead of a snippet. Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 2 +- crates/shopify_api/src/bin/shopify-api.rs | 28 +++++++++------- crates/shopify_api_graphql/src/project.rs | 39 +++++++++++++++++++++++ 3 files changed, 57 insertions(+), 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 88d2c57..d32e0da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ sha2 = "0.11" syn = { version = "3", features = ["full"] } tokio = { version = "1", default-features = false } tracing = { version = "0.1", default-features = false, features = ["std"] } -toml = { version = "1", default-features = false, features = ["std", "parse", "serde"] } +toml = { version = "1", default-features = false, features = ["std", "parse", "serde", "display"] } trybuild = "1" ureq = "3.4" diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index 0428c79..c3f7b41 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -1,6 +1,6 @@ -//! `shopify-api`: downloads the Shopify Admin schema of a crate's API version -//! (the one its `Cargo.toml` declares, else the latest), and checks -//! `.graphql` files against it. +//! `shopify-api`: downloads the Shopify Admin schema of the version a crate's +//! `Cargo.toml` pins, else of the latest version, and checks `.graphql` files +//! against a schema. use std::path::{Path, PathBuf}; use std::process::ExitCode; @@ -11,8 +11,8 @@ use std::sync::Arc; use std::time::SystemTime; use shopify_api_graphql::project::{ - API_VERSION_KEY, METADATA_TABLE, SCHEMA_KEY, package_config, previous_api_version, - project_schema, write_atomically, + inside_package, package_config, previous_api_version, project_schema, schema_snippet, + write_atomically, }; use shopify_api_graphql::{Schema, SchemaSource, analyze, latest_api_version, schema_source}; @@ -209,12 +209,18 @@ async fn download(args: DownloadArgs) -> Result { } else if !args.introspection { let absolute = std::path::absolute(&out).unwrap_or_else(|_| out.clone()); let named = absolute.strip_prefix(&root).unwrap_or(&absolute); - eprintln!( - "For `graphql!` to use it, name it in {}:\n\n\ - [package.metadata.{METADATA_TABLE}]\n{API_VERSION_KEY} = \"{version}\"\n{SCHEMA_KEY} = \"{}\"", - root.join("Cargo.toml").display(), - named.display() - ); + match inside_package(named) { + Ok(named) => eprintln!( + "For `graphql!` to use it, name it in {}:\n\n{}", + root.join("Cargo.toml").display(), + schema_snippet(&version.to_string(), &named) + ), + Err(_) => eprintln!( + "`graphql!` cannot use it: it is outside the package of {}, \ + and `cargo package` ships only the package's files.", + root.join("Cargo.toml").display() + ), + } } Ok(ExitCode::SUCCESS) } diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index da643ff..56b889e 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -52,6 +52,22 @@ pub fn metadata_snippet(version: &str) -> String { format!("[package.metadata.{METADATA_TABLE}]\n{API_VERSION_KEY} = \"{version}\"") } +/// The lines to add to a `Cargo.toml` to select `version` and the schema +/// file at `path`, relative to it: `path` is written with `/` separators, as +/// a TOML string, so that any file name reads back as it is. +pub fn schema_snippet(version: &str, path: &Path) -> String { + let path = path + .components() + .map(|component| component.as_os_str().to_string_lossy()) + .collect::>() + .join("/"); + format!( + "{}\n{SCHEMA_KEY} = {}", + metadata_snippet(version), + toml::Value::from(path) + ) +} + /// The newest stable Admin API version at `now`: Shopify releases one on the /// first day of each quarter, named after it (`2026-10` on October 1st). pub fn latest_api_version(now: SystemTime) -> String { @@ -889,6 +905,29 @@ mod tests { } } + #[test] + fn the_schema_snippet_reads_back_as_the_path() { + let mut names = vec!["schemas/a\"b.json", "schemas/tab\t'q'.json", "admin.json"]; + // A backslash is a separator on Windows, and part of a name elsewhere. + if cfg!(unix) { + names.push("schemas/a\\b.json"); + } + for name in names { + let snippet = schema_snippet("2026-07", Path::new(name)); + let config = config_in(&format!("[package]\nname = \"app\"\n\n{snippet}\n")); + assert_eq!( + config, + Ok(PackageConfig { + api_version: Some("2026-07".to_string()), + schema: Some(PathBuf::from(name)), + }), + "{snippet}" + ); + } + let nested: PathBuf = ["schemas", "admin.json"].iter().collect(); + assert!(schema_snippet("2026-07", &nested).ends_with("schema = \"schemas/admin.json\"")); + } + #[test] fn the_schema_file_must_be_inside_the_package() { let schema = |path: &str| { From 8424c720adfdd7bf76eb201e8aa390b54827228b Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:08:27 +0100 Subject: [PATCH 099/135] docs: say an unpinned crate keeps the version of its schema file Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/schema.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/shopify_api/src/schema.rs b/crates/shopify_api/src/schema.rs index 2e06be3..262b2fd 100644 --- a/crates/shopify_api/src/schema.rs +++ b/crates/shopify_api/src/schema.rs @@ -1,9 +1,11 @@ //! Downloading Shopify's Admin GraphQL schema, as an introspection result. //! -//! [`graphql!`](crate::graphql!) checks operations against the schema of -//! the version a crate declares in its `Cargo.toml`, else of the latest -//! version, and downloads it by itself. These functions return the raw -//! introspection result, for other tools. +//! [`graphql!`](crate::graphql!) checks operations against a crate's schema +//! file, of the version its `Cargo.toml` pins, else of the version that file +//! holds, else, when there is no file yet, of the latest version. It +//! downloads that file only in some cases, see +//! [the schema rules](crate::graphql!#schema-and-api-version). These +//! functions return the raw introspection result, for other tools. use serde_json::{Value, json}; From 076c748e457908d2c784db9d2b5d0de1dabb796f Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:25:50 +0100 Subject: [PATCH 100/135] fix(graphql)!: read the `schema` path as a portable relative path On Windows, `./D:/schema.json` passed the check: `D:` was a plain component in the walk, then became a drive prefix when pushed alone, and the result left the package. `schemas/D:/x.json`, `a/../D:/x.json` and `./D:../x.json` did the same. The `schema` value is now read with `/` separators on every system, and a segment holding `:` or `\` is refused everywhere: a published crate may be built on any system. The normalized path is checked again with `std::path`: only plain components, as many as the names. `shopify-api schema download --out` prints the note instead of a snippet when the file's path is not such a value. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 2 +- crates/shopify_api/docs/graphql.md | 3 +- crates/shopify_api/src/bin/shopify-api.rs | 88 +++++++++++++++++-- crates/shopify_api/tests/schema_override.rs | 1 + crates/shopify_api_graphql/src/project.rs | 96 ++++++++++++++------- 6 files changed, 153 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f19c301..83ffe39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - `Operation`, what `graphql!` builds, or `Operation::new` for any text: `execute` and `execute_response` take `impl Into>`, a module's `Variables` included. `body()` is the exact JSON text sent, and `variable_json(name)` the text of one variable; `with_name` sets the `operationName`. - No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. A local package (of the workspace, or a path dependency) that cargo was asked to build downloads the file when it is missing or does not hold the pinned version, once per build; any other crate never downloads nor writes it, and fails to build when its file is missing or does not fit, a packaged crate in the verification of `cargo package` included. A packaged, vendored or checked-out crate (a `Cargo.toml.orig`, a `.cargo-checksum.json` or a `.cargo-ok` in the package directory, a `.cargo-ok` above it, or a path under `$CARGO_HOME`, with or without symbolic links resolved) never downloads: where a crate is decides only between a download and a compile error, never which schema it gets. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. -- `schema = ""` in `[package.metadata.shopify_api]` names another schema file than `graphql/admin.schema.json`, relative to the package's `Cargo.toml`, for that package only. It must name a file inside the package, which `cargo package` ships: an absolute path, or one that climbs out with `..`, is an error (a symbolic link inside the package may point elsewhere). A dependency keeps the one its own `Cargo.toml` names: a dependency keeps the one its own `Cargo.toml` names. The file follows the rules of the default one (version, download, older format), `shopify-api schema download` and `shopify-api check` use it, and an edit of the key compiles the crate again. +- `schema = ""` in `[package.metadata.shopify_api]` names another schema file than `graphql/admin.schema.json`, relative to the package's `Cargo.toml`, for that package only. It must name a file inside the package, which `cargo package` ships: a relative path with `/`, inside the package, without `:` or `\`; an absolute path, or one that climbs out with `..`, is an error (a symbolic link inside the package may point elsewhere). A dependency keeps the one its own `Cargo.toml` names. The file follows the rules of the default one (version, download, older format), `shopify-api schema download` and `shopify-api check` use it, and an edit of the key compiles the crate again. - `@oneOf` input objects (`ProductSetIdentifiers`…) are checked at compile time: exactly one field, not `null`. - `shopify-api check` checks `.graphql` files against the schema. - Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. The jitter of the backoff is random on every platform. diff --git a/README.md b/README.md index f856a75..3673e77 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,7 @@ whatever the date. Commit the file, so that builds without network access have it. A library that uses `graphql!` must ship it: as a dependency, a crate never downloads its schema, and `cargo package` fails without it. `schema = "…"` in `[package.metadata.shopify_api]` names another schema file -for that package, relative to its `Cargo.toml` and inside the package. The details are in the +for that package, relative to its `Cargo.toml`: a relative path with `/`, inside the package, without `:` or `\`. The details are in the [`graphql!` docs](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html#schema-and-api-version). To choose the version, pin it in your `Cargo.toml` (`graphql!` downloads its diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 560725d..5dc59b8 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -370,7 +370,8 @@ schema = "schemas/admin-2026-07.json" # optional The file `schema` names must be inside the package, so that `cargo package` ships it: an absolute path, or one that climbs above `Cargo.toml` with `..`, -is a compile error. A symbolic link inside the package may point elsewhere: +is a compile error. It is a relative path with `/`, inside the package, +without `:` or `\`. A symbolic link inside the package may point elsewhere: `cargo package` ships the content of the file it links to. Both keys belong to the package whose `Cargo.toml` holds them: a dependency diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index c3f7b41..90571a2 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -207,16 +207,15 @@ async fn download(args: DownloadArgs) -> Result { and sends them to that version. Commit the file: offline builds need it." ); } else if !args.introspection { - let absolute = std::path::absolute(&out).unwrap_or_else(|_| out.clone()); - let named = absolute.strip_prefix(&root).unwrap_or(&absolute); - match inside_package(named) { - Ok(named) => eprintln!( + match schema_key(&root, &out) { + Some(named) => eprintln!( "For `graphql!` to use it, name it in {}:\n\n{}", root.join("Cargo.toml").display(), schema_snippet(&version.to_string(), &named) ), - Err(_) => eprintln!( - "`graphql!` cannot use it: it is outside the package of {}, \ + None => eprintln!( + "`graphql!` cannot use it: `schema` in {} names a file inside the package, \ + as a relative path with `/` separators and no `:` or `\\`, \ and `cargo package` ships only the package's files.", root.join("Cargo.toml").display() ), @@ -225,6 +224,25 @@ async fn download(args: DownloadArgs) -> Result { Ok(ExitCode::SUCCESS) } +/// The `schema` value that names `out`, a file just written, for the +/// package in `root`, if any: a path [`inside_package`] accepts. +fn schema_key(root: &Path, out: &Path) -> Option { + use std::path::Component; + let absolute = std::path::absolute(out).ok()?; + let named = absolute.strip_prefix(root).ok()?; + let value = named + .components() + .map(|component| match component { + Component::Normal(name) => name.to_str(), + Component::CurDir => Some("."), + Component::ParentDir => Some(".."), + Component::Prefix(_) | Component::RootDir => None, + }) + .collect::>>()? + .join("/"); + inside_package(&value).ok() +} + /// The introspection result for `version`, from Shopify's public endpoint or /// through the shop of `args`. async fn fetch(args: &DownloadArgs, version: ApiVersion) -> Result { @@ -379,3 +397,61 @@ fn check(args: CheckArgs) -> Result { ExitCode::SUCCESS }) } + +#[cfg(test)] +mod tests { + use super::*; + + /// An empty directory, canonical, removed when the test ends. + struct Dir(PathBuf); + + impl Dir { + fn new(name: &str) -> Self { + let dir = + std::env::temp_dir().join(format!("shopify-api-cli-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir.canonicalize().unwrap()) + } + + fn write(&self, path: &str) -> PathBuf { + let file = self.0.join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, "{}").unwrap(); + file + } + } + + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn the_key_names_the_file_written() { + let package = Dir::new("key"); + let out = package.write("schemas/admin.json"); + assert_eq!( + schema_key(&package.0, &out), + Some(PathBuf::from("schemas/admin.json")) + ); + package.write("x.json"); + assert_eq!( + schema_key(&package.0, &package.0.join("schemas/../x.json")), + Some(PathBuf::from("x.json")) + ); + let outside = Dir::new("key-outside"); + assert_eq!(schema_key(&package.0, &outside.write("x.json")), None); + } + + #[cfg(unix)] + #[test] + fn a_name_that_is_not_a_portable_key_has_none() { + let package = Dir::new("key-portable"); + for name in ["schemas/a\\b.json", "schemas/D:x.json"] { + let out = package.write(name); + assert_eq!(schema_key(&package.0, &out), None, "{name}"); + } + } +} diff --git a/crates/shopify_api/tests/schema_override.rs b/crates/shopify_api/tests/schema_override.rs index 2e47a58..82840d3 100644 --- a/crates/shopify_api/tests/schema_override.rs +++ b/crates/shopify_api/tests/schema_override.rs @@ -224,6 +224,7 @@ fn a_schema_outside_the_package_is_a_compile_error() { for path in [ "\"../override.json\"", "\"schemas/../../override.json\"", + "\"./D:/override.json\"", &absolute, ] { workspace.library_metadata(&format!("schema = {path}\n")); diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index 56b889e..364b456 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -171,7 +171,7 @@ fn schema_in(value: Option<&toml::Value>) -> Result, String> { return Ok(None); }; match value.as_str() { - Some(path) if !path.is_empty() => inside_package(Path::new(path)).map(Some), + Some(path) if !path.is_empty() => inside_package(path).map(Some), _ => Err(format!( "`{SCHEMA_KEY}` in [package.metadata.{METADATA_TABLE}] must be the path of a schema file, \ relative to Cargo.toml, such as \"graphql/admin.schema.json\"" @@ -184,37 +184,55 @@ fn schema_in(value: Option<&toml::Value>) -> Result, String> { /// so a packaged crate would look for any other file at another place, and /// fail, or find another schema there. /// -/// The check is lexical: `.` and `a/..` are removed, and the path must not -/// be absolute, have a root or a drive, nor climb above the package. A -/// symbolic link inside the package that points outside it is accepted, on -/// purpose: `cargo package` ships the content of a linked file. The path is -/// returned normalized, so that the file opened is the one checked, even -/// when `a` in `a/..` is a link to a directory. -pub fn inside_package(path: &Path) -> Result { +/// `path` is portable, since a published crate may be built on any system: +/// it is read with `/` separators, and no segment may hold a `:` or a `\`, +/// a drive or a separator on Windows and part of a name elsewhere. +/// +/// The check is lexical: `.`, empty segments and `a/..` are removed, and the +/// path must not be absolute, nor climb above the package. A symbolic link +/// inside the package that points outside it is accepted, on purpose: +/// `cargo package` ships the content of a linked file. The path is returned +/// normalized, so that the file opened is the one checked, even when `a` in +/// `a/..` is a link to a directory; on every system, it holds only the +/// names checked, as plain components: no drive, root, `.` nor `..`. +pub fn inside_package(path: &str) -> Result { use std::path::Component; - let outside = || { + let refused = || { format!( - "`{SCHEMA_KEY} = \"{}\"` in [package.metadata.{METADATA_TABLE}] must name a file inside the package, \ - relative to its Cargo.toml, such as \"graphql/admin.schema.json\": \ - `cargo package` ships only the package's files", - path.display() + "`{SCHEMA_KEY} = {}` in [package.metadata.{METADATA_TABLE}] must name a file inside the package, \ + as a relative path with `/` separators and no `:` or `\\`, such as \"graphql/admin.schema.json\": \ + `cargo package` ships only the package's files, and a published crate may be built on any system", + toml::Value::from(path) ) }; - let mut normal = PathBuf::new(); - for component in path.components() { - match component { - Component::Prefix(_) | Component::RootDir => return Err(outside()), - Component::CurDir => {} - Component::ParentDir => { - if !normal.pop() { - return Err(outside()); + if path.starts_with('/') { + return Err(refused()); + } + let mut names = Vec::new(); + for segment in path.split('/') { + if segment.contains([':', '\\']) { + return Err(refused()); + } + match segment { + "" | "." => {} + ".." => { + if names.pop().is_none() { + return Err(refused()); } } - Component::Normal(name) => normal.push(name), + name => names.push(name), } } - if normal.as_os_str().is_empty() { - return Err(outside()); + if names.is_empty() { + return Err(refused()); + } + let normal: PathBuf = names.iter().collect(); + // What this system makes of the names: each one a plain component. + let plain = normal + .components() + .eq(names.iter().map(|name| Component::Normal(OsStr::new(name)))); + if !plain { + return Err(refused()); } Ok(normal) } @@ -907,12 +925,9 @@ mod tests { #[test] fn the_schema_snippet_reads_back_as_the_path() { - let mut names = vec!["schemas/a\"b.json", "schemas/tab\t'q'.json", "admin.json"]; - // A backslash is a separator on Windows, and part of a name elsewhere. - if cfg!(unix) { - names.push("schemas/a\\b.json"); - } - for name in names { + // A backslash is not a `schema` value: `shopify-api` prints a note + // instead of a snippet for such a name. + for name in ["schemas/a\"b.json", "schemas/tab\t'q'.json", "admin.json"] { let snippet = schema_snippet("2026-07", Path::new(name)); let config = config_in(&format!("[package]\nname = \"app\"\n\n{snippet}\n")); assert_eq!( @@ -952,8 +967,27 @@ mod tests { error.contains("must name a file inside the package"), "{error}" ); + assert!( + error.contains("relative path with `/` separators and no `:` or `\\`"), + "{error}" + ); assert!(error.contains("`cargo package` ships"), "{error}"); } + // Not portable, so refused on every system: a drive on Windows, even + // in the middle of the path, and a separator there. + for outside in [ + "./D:/schema.json", + "schemas/D:/schema.json", + "a/../D:/schema.json", + "./D:../schema.json", + "C:x.json", + "a\\b.json", + "schemas\\admin.json", + "a:b/x.json", + ] { + let error = schema(outside).unwrap_err(); + assert!(error.contains("no `:` or `\\`"), "{outside}: {error}"); + } #[cfg(windows)] for outside in [ "C:\\x.json", @@ -967,6 +1001,8 @@ mod tests { ("a/../x.json", "x.json"), ("./graphql/x.json", "graphql/x.json"), ("schemas/../schemas/admin.json", "schemas/admin.json"), + ("schemas//admin.json", "schemas/admin.json"), + ("schemas/admin.json/", "schemas/admin.json"), ] { assert_eq!(schema(inside), Ok(Some(PathBuf::from(normal))), "{inside}"); } From 7988697a24dbbcb5dcf5849aa27d1b0ddd7f1d87 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:25:50 +0100 Subject: [PATCH 101/135] fix(cli): print the `--out` snippet only when it names the file written `--out a/../x.json`, with `a` a link to a directory elsewhere, writes `elsewhere/x.json`, but the snippet said `schema = "x.json"`, another file. The snippet is now printed only when the canonical path of the written file is the one of the normalized path in the package; otherwise the note is. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bin/shopify-api.rs | 33 +++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index 90571a2..3bc4671 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -225,7 +225,9 @@ async fn download(args: DownloadArgs) -> Result { } /// The `schema` value that names `out`, a file just written, for the -/// package in `root`, if any: a path [`inside_package`] accepts. +/// package in `root`, if any: a path [`inside_package`] accepts, that leads +/// to that same file. `a/../x.json` is normalized to `x.json`, which is +/// another file when `a` links to a directory elsewhere. fn schema_key(root: &Path, out: &Path) -> Option { use std::path::Component; let absolute = std::path::absolute(out).ok()?; @@ -240,7 +242,10 @@ fn schema_key(root: &Path, out: &Path) -> Option { }) .collect::>>()? .join("/"); - inside_package(&value).ok() + let normal = inside_package(&value).ok()?; + let written = out.canonicalize().ok()?; + let named = root.join(&normal).canonicalize().ok()?; + (named == written).then_some(normal) } /// The introspection result for `version`, from Shopify's public endpoint or @@ -454,4 +459,28 @@ mod tests { assert_eq!(schema_key(&package.0, &out), None, "{name}"); } } + + #[cfg(unix)] + #[test] + fn a_link_followed_by_dot_dot_names_another_file() { + let package = Dir::new("key-link"); + let outside = Dir::new("key-link-outside"); + std::fs::create_dir_all(outside.0.join("dir")).unwrap(); + std::os::unix::fs::symlink(outside.0.join("dir"), package.0.join("a")).unwrap(); + // Written through the link, `a/../x.json` is `outside/x.json`. + let out = package.0.join("a/../x.json"); + std::fs::write(&out, "{}").unwrap(); + assert!(outside.0.join("x.json").is_file()); + assert_eq!(schema_key(&package.0, &out), None); + // Even when the package has an `x.json` of its own. + package.write("x.json"); + assert_eq!(schema_key(&package.0, &out), None); + // A link inside the package to a file elsewhere is followed by both. + std::os::unix::fs::symlink(outside.0.join("x.json"), package.0.join("linked.json")) + .unwrap(); + assert_eq!( + schema_key(&package.0, &package.0.join("linked.json")), + Some(PathBuf::from("linked.json")) + ); + } } From 4cf5c332f572f40c2e9d7ae1bdb42ff7461d39dc Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:27:29 +0100 Subject: [PATCH 102/135] ci: run the tests of the path rules on Windows Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dca982e..c33fdd5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,6 +24,7 @@ jobs: - msrv - package - audit + - windows steps: - run: exit 0 @@ -74,3 +75,15 @@ jobs: - uses: actions/checkout@v7 - uses: jdx/mise-action@v5 - run: mise run audit + + # Paths read from `Cargo.toml` follow other rules on Windows (drive + # prefixes, `\`): the tests of those rules run there too. + windows: + name: paths on Windows + runs-on: windows-latest + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - run: cargo test -p shopify_api_graphql --lib --locked + - run: cargo test -p shopify_api --features cli --bin shopify-api --locked From 71dd6d483e79516247e8d0d12f83435837396b99 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:30:04 +0100 Subject: [PATCH 103/135] test(schema): expect the paths of a refusal as the platform writes them On Windows, joining a path writes `\` before `graphql/admin.schema.json`. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api_graphql/src/project.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index 364b456..c8fbae0 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -1362,13 +1362,13 @@ mod tests { SchemaPlan::Read ); let message = refusal(&usable("2026-07"), Some("2026-10")); - assert!( - message.starts_with( - "`/registry/deplib-1.0.0/graphql/admin.schema.json` holds the Admin API 2026-07, \ - but `/registry/deplib-1.0.0/Cargo.toml` declares 2026-10." - ), - "{message}" + // Paths as the platform writes them: `\` before `graphql` on Windows. + let expected = format!( + "`{}` holds the Admin API 2026-07, but `{}` declares 2026-10.", + path(dir).display(), + dir.join("Cargo.toml").display() ); + assert!(message.starts_with(&expected), "{message}"); for pinned in [None, Some("2026-10")] { let message = refusal(&SchemaFile::Missing, pinned); assert!( From 70de42981d6c7e162729b43045f4fc602369b53a Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:43:52 +0100 Subject: [PATCH 104/135] fix(graphql)!: refuse `schema` names Windows reads as another file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Windows drops a final `.` or space (`x.json.` opens `x.json`), refuses `<>"|?*` and control characters, and opens a device for `CON`, `NUL`, `COM1`… whatever the extension: the same `schema` value could name another file there than on Unix. Every name of the path must now be portable, even one a later `..` removes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 2 +- crates/shopify_api/docs/graphql.md | 6 +- crates/shopify_api/src/bin/shopify-api.rs | 7 +- crates/shopify_api_graphql/src/project.rs | 93 +++++++++++++++++++---- 5 files changed, 88 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83ffe39..1c61404 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. - `Operation`, what `graphql!` builds, or `Operation::new` for any text: `execute` and `execute_response` take `impl Into>`, a module's `Variables` included. `body()` is the exact JSON text sent, and `variable_json(name)` the text of one variable; `with_name` sets the `operationName`. - No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. A local package (of the workspace, or a path dependency) that cargo was asked to build downloads the file when it is missing or does not hold the pinned version, once per build; any other crate never downloads nor writes it, and fails to build when its file is missing or does not fit, a packaged crate in the verification of `cargo package` included. A packaged, vendored or checked-out crate (a `Cargo.toml.orig`, a `.cargo-checksum.json` or a `.cargo-ok` in the package directory, a `.cargo-ok` above it, or a path under `$CARGO_HOME`, with or without symbolic links resolved) never downloads: where a crate is decides only between a download and a compile error, never which schema it gets. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. -- `schema = ""` in `[package.metadata.shopify_api]` names another schema file than `graphql/admin.schema.json`, relative to the package's `Cargo.toml`, for that package only. It must name a file inside the package, which `cargo package` ships: a relative path with `/`, inside the package, without `:` or `\`; an absolute path, or one that climbs out with `..`, is an error (a symbolic link inside the package may point elsewhere). A dependency keeps the one its own `Cargo.toml` names. The file follows the rules of the default one (version, download, older format), `shopify-api schema download` and `shopify-api check` use it, and an edit of the key compiles the crate again. +- `schema = ""` in `[package.metadata.shopify_api]` names another schema file than `graphql/admin.schema.json`, relative to the package's `Cargo.toml`, for that package only. It must name a file inside the package, which `cargo package` ships: a relative path with `/` and portable names (no `:`, `\`, `<>"|?*` or control character, no name ending in `.` or a space, no device name such as `CON`); an absolute path, or one that climbs out with `..`, is an error (a symbolic link inside the package may point elsewhere). A dependency keeps the one its own `Cargo.toml` names. The file follows the rules of the default one (version, download, older format), `shopify-api schema download` and `shopify-api check` use it, and an edit of the key compiles the crate again. - `@oneOf` input objects (`ProductSetIdentifiers`…) are checked at compile time: exactly one field, not `null`. - `shopify-api check` checks `.graphql` files against the schema. - Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. The jitter of the backoff is random on every platform. diff --git a/README.md b/README.md index 3673e77..9a93220 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,7 @@ whatever the date. Commit the file, so that builds without network access have it. A library that uses `graphql!` must ship it: as a dependency, a crate never downloads its schema, and `cargo package` fails without it. `schema = "…"` in `[package.metadata.shopify_api]` names another schema file -for that package, relative to its `Cargo.toml`: a relative path with `/`, inside the package, without `:` or `\`. The details are in the +for that package, relative to its `Cargo.toml`: a relative path with `/` and portable names (no `:`, `\`, `<>"|?*` or control character, no name ending in `.` or a space, no device name such as `CON`). The details are in the [`graphql!` docs](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html#schema-and-api-version). To choose the version, pin it in your `Cargo.toml` (`graphql!` downloads its diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 5dc59b8..d1ecfe7 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -370,8 +370,10 @@ schema = "schemas/admin-2026-07.json" # optional The file `schema` names must be inside the package, so that `cargo package` ships it: an absolute path, or one that climbs above `Cargo.toml` with `..`, -is a compile error. It is a relative path with `/`, inside the package, -without `:` or `\`. A symbolic link inside the package may point elsewhere: +is a compile error. It is a relative path with `/` and portable names: no +`:`, `\`, `<>"|?*` or control character, no name ending in `.` or a space, +and no device name such as `CON`, which Windows would read as another file +or a device. A symbolic link inside the package may point elsewhere: `cargo package` ships the content of the file it links to. Both keys belong to the package whose `Cargo.toml` holds them: a dependency diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index 3bc4671..bcd2340 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -11,8 +11,8 @@ use std::sync::Arc; use std::time::SystemTime; use shopify_api_graphql::project::{ - inside_package, package_config, previous_api_version, project_schema, schema_snippet, - write_atomically, + PORTABLE_PATH, inside_package, package_config, previous_api_version, project_schema, + schema_snippet, write_atomically, }; use shopify_api_graphql::{Schema, SchemaSource, analyze, latest_api_version, schema_source}; @@ -215,8 +215,7 @@ async fn download(args: DownloadArgs) -> Result { ), None => eprintln!( "`graphql!` cannot use it: `schema` in {} names a file inside the package, \ - as a relative path with `/` separators and no `:` or `\\`, \ - and `cargo package` ships only the package's files.", + as {PORTABLE_PATH}, and `cargo package` ships only the package's files.", root.join("Cargo.toml").display() ), } diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index c8fbae0..f8d984f 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -179,14 +179,42 @@ fn schema_in(value: Option<&toml::Value>) -> Result, String> { } } +/// What [`inside_package`] accepts, for the messages that refuse a path. +pub const PORTABLE_PATH: &str = "a relative path with `/` separators and portable names: \ + no `:`, `\\`, `<`, `>`, `\"`, `|`, `?`, `*` or control character, no name ending in `.` or a space, \ + and no device name such as `CON` or `NUL`"; + +/// A name that means the same file on every system. Windows reads `:` and +/// `\` as a drive and a separator, drops a final `.` or space (`x.json.` +/// opens `x.json`), refuses `<>"|?*` and control characters, and opens a +/// device for `CON`, `NUL`, `COM1`… whatever the extension. +fn portable_name(name: &str) -> bool { + if name.ends_with(['.', ' ']) + || name + .chars() + .any(|c| c.is_control() || r#":\<>"|?*"#.contains(c)) + { + return false; + } + let stem = name.split('.').next().unwrap_or(name).trim_end_matches(' '); + let stem = stem.to_ascii_uppercase(); + let numbered = |prefix: &str| { + stem.strip_prefix(prefix).is_some_and(|number| { + matches!(number, "¹" | "²" | "³") + || (number.len() == 1 && number.bytes().all(|byte| byte.is_ascii_digit())) + }) + }; + !(["CON", "PRN", "AUX", "NUL"].contains(&stem.as_str()) || numbered("COM") || numbered("LPT")) +} + /// `path`, relative to a package's `Cargo.toml`, normalized, when it names a /// file inside the package: `cargo package` ships only the package's files, /// so a packaged crate would look for any other file at another place, and /// fail, or find another schema there. /// /// `path` is portable, since a published crate may be built on any system: -/// it is read with `/` separators, and no segment may hold a `:` or a `\`, -/// a drive or a separator on Windows and part of a name elsewhere. +/// it is read with `/` separators, and each name must mean the same file +/// everywhere ([`PORTABLE_PATH`]). /// /// The check is lexical: `.`, empty segments and `a/..` are removed, and the /// path must not be absolute, nor climb above the package. A symbolic link @@ -200,7 +228,7 @@ pub fn inside_package(path: &str) -> Result { let refused = || { format!( "`{SCHEMA_KEY} = {}` in [package.metadata.{METADATA_TABLE}] must name a file inside the package, \ - as a relative path with `/` separators and no `:` or `\\`, such as \"graphql/admin.schema.json\": \ + as {PORTABLE_PATH}, such as \"graphql/admin.schema.json\": \ `cargo package` ships only the package's files, and a published crate may be built on any system", toml::Value::from(path) ) @@ -210,9 +238,6 @@ pub fn inside_package(path: &str) -> Result { } let mut names = Vec::new(); for segment in path.split('/') { - if segment.contains([':', '\\']) { - return Err(refused()); - } match segment { "" | "." => {} ".." => { @@ -220,6 +245,8 @@ pub fn inside_package(path: &str) -> Result { return Err(refused()); } } + // Checked even when a later `..` removes it. + name if !portable_name(name) => return Err(refused()), name => names.push(name), } } @@ -925,9 +952,16 @@ mod tests { #[test] fn the_schema_snippet_reads_back_as_the_path() { - // A backslash is not a `schema` value: `shopify-api` prints a note - // instead of a snippet for such a name. - for name in ["schemas/a\"b.json", "schemas/tab\t'q'.json", "admin.json"] { + // Names `schema` accepts that TOML must still quote. `\\`, `"` and + // control characters are not portable names: `shopify-api` prints a + // note instead of a snippet for them. + for name in [ + "schemas/it's.json", + "schemas/a#b=c.json", + "schemas/[x] y.json", + "schémas/é.json", + "admin.json", + ] { let snippet = schema_snippet("2026-07", Path::new(name)); let config = config_in(&format!("[package]\nname = \"app\"\n\n{snippet}\n")); assert_eq!( @@ -967,10 +1001,7 @@ mod tests { error.contains("must name a file inside the package"), "{error}" ); - assert!( - error.contains("relative path with `/` separators and no `:` or `\\`"), - "{error}" - ); + assert!(error.contains(PORTABLE_PATH), "{error}"); assert!(error.contains("`cargo package` ships"), "{error}"); } // Not portable, so refused on every system: a drive on Windows, even @@ -986,7 +1017,36 @@ mod tests { "a:b/x.json", ] { let error = schema(outside).unwrap_err(); - assert!(error.contains("no `:` or `\\`"), "{outside}: {error}"); + assert!(error.contains(PORTABLE_PATH), "{outside}: {error}"); + } + // Names Windows reads as another file, or as a device: refused on + // every system too, even when a later `..` removes them. + for alias in [ + "schema.json.", + "schema.json ", + "schemas./admin.json", + "schemas /admin.json", + "x.json./../y.json", + "xy.json", + "x\"y.json", + "x|y.json", + "x?.json", + "x*.json", + "x\ty.json", + "x\u{7f}y.json", + "CON", + "con.json", + "Nul.schema.json", + "AUX .json", + "schemas/PRN/x.json", + "COM1.json", + "lpt9", + "COM\u{b9}.json", + "CON/../x.json", + ] { + let error = schema(alias).unwrap_err(); + assert!(error.contains(PORTABLE_PATH), "{alias:?}: {error}"); } #[cfg(windows)] for outside in [ @@ -1003,6 +1063,11 @@ mod tests { ("schemas/../schemas/admin.json", "schemas/admin.json"), ("schemas//admin.json", "schemas/admin.json"), ("schemas/admin.json/", "schemas/admin.json"), + ("console.json", "console.json"), + ("con-schema.json", "con-schema.json"), + ("COM10.json", "COM10.json"), + (".hidden/admin.json", ".hidden/admin.json"), + ("admin.schema.json", "admin.schema.json"), ] { assert_eq!(schema(inside), Ok(Some(PathBuf::from(normal))), "{inside}"); } From e2b2ae043bf8b10743829fd2af58f75ad36e6d04 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:53:25 +0100 Subject: [PATCH 105/135] fix(graphql): refuse the console devices `CONIN$` and `CONOUT$` as `schema` names Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api_graphql/src/project.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index f8d984f..619bb92 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -187,7 +187,7 @@ pub const PORTABLE_PATH: &str = "a relative path with `/` separators and portabl /// A name that means the same file on every system. Windows reads `:` and /// `\` as a drive and a separator, drops a final `.` or space (`x.json.` /// opens `x.json`), refuses `<>"|?*` and control characters, and opens a -/// device for `CON`, `NUL`, `COM1`… whatever the extension. +/// device for `CON`, `NUL`, `COM1`, `CONIN$`… whatever the extension. fn portable_name(name: &str) -> bool { if name.ends_with(['.', ' ']) || name @@ -204,7 +204,9 @@ fn portable_name(name: &str) -> bool { || (number.len() == 1 && number.bytes().all(|byte| byte.is_ascii_digit())) }) }; - !(["CON", "PRN", "AUX", "NUL"].contains(&stem.as_str()) || numbered("COM") || numbered("LPT")) + !(["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"].contains(&stem.as_str()) + || numbered("COM") + || numbered("LPT")) } /// `path`, relative to a package's `Cargo.toml`, normalized, when it names a @@ -1044,6 +1046,10 @@ mod tests { "lpt9", "COM\u{b9}.json", "CON/../x.json", + "conin$.json", + "CONOUT$", + "ConOut$ .json", + "CONIN$/../x.json", ] { let error = schema(alias).unwrap_err(); assert!(error.contains(PORTABLE_PATH), "{alias:?}: {error}"); From d04e0ad3f119430ac718a29351363c996953fa5f Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:13:08 +0100 Subject: [PATCH 106/135] feat(graphql): check bulk operations against Shopify's bulk rules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `analyze_bulk_query` checks a query as Shopify documents bulk queries for API 2026-10: one top-level connection, five connections at most, nested two levels deep at most, each selected as `edges { node { … } }`, without pagination arguments, of `Node` objects, an unaliased `id` on every node with nested connections, and no two connections of one node that may return the same type. `check_bulk_mutation` checks one mutation field, not a bulk operation itself, with one connection at most. It describes what runs the query: its text without variable definitions, argument lists that hold a variable set apart, `__typename` on the nodes of connections that share a parent, the item types with each connection made a `Vec` of its nodes, and where each line of the results goes. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api_graphql/src/analyze.rs | 4 + crates/shopify_api_graphql/src/bulk.rs | 1289 +++++++++++++++++++++ crates/shopify_api_graphql/src/codegen.rs | 66 +- crates/shopify_api_graphql/src/lib.rs | 2 + crates/shopify_api_graphql/tests/bulk.rs | 262 +++++ 5 files changed, 1616 insertions(+), 7 deletions(-) create mode 100644 crates/shopify_api_graphql/src/bulk.rs create mode 100644 crates/shopify_api_graphql/tests/bulk.rs diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index a98376b..78c80b8 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -151,6 +151,9 @@ pub struct SelectedField { /// always apply, or under `@include` / `@skip`. pub conditional: bool, pub base: FieldBase, + /// A connection of a bulk query, read as the list of its nodes: absent + /// from the line of its parent, filled from the lines that follow. + pub connection: bool, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -663,6 +666,7 @@ impl<'a> Analyzer<'a> { ty: field.ty, conditional: field.conditional, base, + connection: false, }); } diff --git a/crates/shopify_api_graphql/src/bulk.rs b/crates/shopify_api_graphql/src/bulk.rs new file mode 100644 index 0000000..f9bb8a7 --- /dev/null +++ b/crates/shopify_api_graphql/src/bulk.rs @@ -0,0 +1,1289 @@ +//! Bulk operations: Shopify's rules for the query of +//! `bulkOperationRunQuery` and the mutation of `bulkOperationRunMutation`, +//! checked on top of [`analyze`](crate::analyze()), and what a typed bulk +//! query needs at run time: the text it sends, and where each line of its +//! results goes. +//! +//! The rules follow Shopify's guide for API 2026-10 +//! (). Where it +//! is silent, what it does not show is refused: +//! +//! - one top-level field, a connection, not `node` or `nodes`; +//! - at most five connections, nested at most two levels below it; +//! - each connection selected as `edges { node { … } }` and nothing else: +//! no `nodes`, `cursor`, `pageInfo`, and no `first`, `last`, `after` or +//! `before`, which Shopify ignores; +//! - the nodes of a connection implement `Node`; +//! - a nested connection written in the `node { … }` of its parent, not in +//! a fragment or under another field; +//! - an object with nested connections selects `id`, without an alias; +//! - two connections of one object that may return the same type are +//! refused: their lines could not be told apart. +//! +//! A bulk query takes no variables. Its variables are written into its text +//! as GraphQL literals at run time: the text is kept as [`Part`]s, with the +//! argument lists that hold a variable apart. + +use std::collections::{BTreeMap, BTreeSet}; + +use graphql_parser::Pos; +use graphql_parser::query as ast; +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote}; + +use crate::analyze::{Error, FieldBase, Operation, OperationKind, SelectedField, Selection}; +use crate::codegen::{field_idents, item_types}; +use crate::schema::{Field, Schema, TypeDef, TypeRef}; + +type Document<'a> = ast::Document<'a, String>; +type SelectionSet<'a> = ast::SelectionSet<'a, String>; +type Value<'a> = ast::Value<'a, String>; +type Fragments<'a> = BTreeMap<&'a str, &'a ast::FragmentDefinition<'a, String>>; + +/// The most connections a bulk query may have, its top-level one included. +pub const MAX_CONNECTIONS: usize = 5; +/// How many levels of connections a bulk query may nest below its top-level one. +pub const MAX_DEPTH: usize = 2; + +/// The name of the type generated for each top-level object of a bulk query. +pub const ITEM_TYPE: &str = "Item"; + +/// Arguments Shopify ignores in a bulk query: it reads every object. +const PAGINATION: [&str; 4] = ["first", "last", "after", "before"]; + +fn error_at(position: Pos, message: impl Into) -> Result { + Err(Error { + message: message.into(), + position: Some((position.line, position.column)), + }) +} + +fn error(message: impl Into) -> Result { + Err(Error { + message: message.into(), + position: None, + }) +} + +/// A checked bulk query. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct BulkQuery { + /// The selection on the nodes of the top-level connection, each nested + /// connection made a list of its nodes ([`SelectedField::connection`]). + pub item: Selection, + /// The nested connections of the top-level nodes, in the order of their + /// fields in [`BulkQuery::item`]. + pub connections: Vec, + /// The text sent, variables apart. + pub parts: Vec, + /// The default value of each variable that has one, as GraphQL text. + pub defaults: BTreeMap, +} + +/// A nested connection, and where its lines go. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Connection { + /// Its response key. + pub key: String, + /// The object types its nodes may be, which their `__typename` names. + pub types: Vec, + /// The connections of its nodes. + pub connections: Vec, +} + +/// A piece of the text of a bulk query. +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub enum Part { + Text(String), + /// `(name: value, …)` where a value holds a variable. An argument whose + /// variable has no value and no default is left out, and the + /// parentheses with the last one. + Arguments(Vec), +} + +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub struct Argument { + pub name: String, + pub value: ValuePart, +} + +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub enum ValuePart { + /// A constant, as GraphQL text. + Text(String), + Variable(String), + List(Vec), + /// An input object: a field whose variable has no value is left out. + Object(Vec), +} + +/// The object types a value of `name` may be, sorted. +fn concrete_types(schema: &Schema, name: &str) -> Vec { + let mut types: Vec = schema + .possible_types(name) + .into_iter() + .map(str::to_string) + .collect(); + types.sort(); + types.dedup(); + types +} + +fn fields_of<'s>(schema: &'s Schema, name: &str) -> Option<&'s BTreeMap> { + match schema.get(name) { + Some(TypeDef::Object { fields, .. } | TypeDef::Interface { fields, .. }) => Some(fields), + _ => None, + } +} + +/// The node type of a connection type: an object with `edges { node }` +/// and `pageInfo`, as Shopify's connections are. +pub fn connection_node<'s>(schema: &'s Schema, name: &str) -> Option<&'s str> { + let Some(TypeDef::Object { fields, .. }) = schema.get(name) else { + return None; + }; + if !fields.contains_key("pageInfo") { + return None; + } + let edge = fields.get("edges")?.ty.name(); + let Some(TypeDef::Object { fields: edge, .. }) = schema.get(edge) else { + return None; + }; + Some(edge.get("node")?.ty.name()) +} + +/// Every value of `name` implements `Node`. +fn implements_node(schema: &Schema, name: &str) -> bool { + let types = schema.possible_types(name); + !types.is_empty() + && types.iter().all(|ty| { + matches!(schema.get(ty), Some(TypeDef::Object { interfaces, .. }) if interfaces.iter().any(|interface| interface == "Node")) + }) +} + +fn parse(source: &str) -> Result, Error> { + // `analyze` read it first: a failure here is not expected. + graphql_parser::parse_query(source).or_else(|_| error("Invalid GraphQL")) +} + +/// The operation and the fragments of a document `analyze` accepted. +fn parts_of<'a>( + document: &'a Document<'a>, +) -> (&'a ast::OperationDefinition<'a, String>, Fragments<'a>) { + let mut operation = None; + let mut fragments = BTreeMap::new(); + for definition in &document.definitions { + match definition { + ast::Definition::Operation(found) => operation = Some(found), + ast::Definition::Fragment(fragment) => { + fragments.insert(fragment.name.as_str(), fragment); + } + } + } + ( + operation.expect("`analyze` accepted one operation"), + fragments, + ) +} + +fn selection_set<'a>(operation: &'a ast::OperationDefinition<'a, String>) -> &'a SelectionSet<'a> { + match operation { + ast::OperationDefinition::SelectionSet(set) => set, + ast::OperationDefinition::Query(query) => &query.selection_set, + ast::OperationDefinition::Mutation(mutation) => &mutation.selection_set, + ast::OperationDefinition::Subscription(subscription) => &subscription.selection_set, + } +} + +fn set_position(set: &SelectionSet<'_>) -> Pos { + set.span.0 +} + +fn item_position(item: &ast::Selection<'_, String>) -> Pos { + match item { + ast::Selection::Field(field) => field.position, + ast::Selection::InlineFragment(fragment) => fragment.position, + ast::Selection::FragmentSpread(spread) => spread.position, + } +} + +/// The only field of a top-level selection, or an error that says why. +fn top_level_field<'a>( + set: &'a SelectionSet<'a>, + what: &str, +) -> Result<&'a ast::Field<'a, String>, Error> { + match set.items.as_slice() { + [ast::Selection::Field(field)] => Ok(field), + [_, second, ..] => error_at( + item_position(second), + format!("A bulk {what} selects one top-level field: Shopify runs one per operation"), + ), + [other] => error_at( + item_position(other), + format!("A bulk {what} selects one top-level field, not a fragment"), + ), + [] => error_at( + set_position(set), + format!("A bulk {what} selects one top-level field"), + ), + } +} + +/// Checks the bulk rules of a query `analyze` accepted, and describes +/// what runs it. +pub fn analyze_bulk_query( + schema: &Schema, + source: &str, + operation: &Operation, +) -> Result { + if operation.kind != OperationKind::Query { + return error("A bulk query is a query"); + } + let document = parse(source)?; + let (definition, fragments) = parts_of(&document); + let mut checker = Checker { + schema, + fragments: &fragments, + count: 0, + typename: BTreeSet::new(), + }; + checker.variables(definition)?; + + let top = top_level_field(selection_set(definition), "query")?; + if top.name == "node" || top.name == "nodes" { + return error_at( + top.position, + format!( + "`{}` cannot be the top-level field of a bulk query: select a connection, such as `products`", + top.name + ), + ); + } + let ty = fields_of(schema, &schema.query) + .and_then(|fields| fields.get(&top.name)) + .map(|field| field.ty.clone()) + .ok_or_else(|| Error { + message: format!("The query root has no field `{}`", top.name), + position: Some((top.position.line, top.position.column)), + })?; + if connection_node(schema, ty.name()).is_none() || matches!(ty.nullable(), TypeRef::List(_)) { + return error_at( + top.position, + format!( + "The top-level field of a bulk query is a connection: `{}` is `{ty}`. Run it as an ordinary query, or select a connection such as `products`", + top.name + ), + ); + } + let top_connection = checker.connection(top, &schema.query, 0)?; + + let data_field = operation + .data + .fields + .first() + .expect("the selection is not empty"); + let item = item_selection(schema, connection_nodes(data_field)); + + let mut printer = Printer { + typename: &checker.typename, + parts: Vec::new(), + text: String::new(), + }; + printer.operation(definition); + for fragment in fragments.values() { + printer.text.push(' '); + printer.fragment(fragment); + } + let parts = printer.finish(); + + let mut defaults = BTreeMap::new(); + if let ast::OperationDefinition::Query(query) = definition { + for variable in &query.variable_definitions { + if let Some(default) = &variable.default_value { + defaults.insert(variable.name.clone(), constant_text(default)); + } + } + } + + Ok(BulkQuery { + item, + connections: top_connection.connections, + parts, + defaults, + }) +} + +/// Checks the bulk rules of a mutation `analyze` accepted: one mutation +/// field, not a bulk operation itself, with at most one connection. +pub fn check_bulk_mutation( + schema: &Schema, + source: &str, + operation: &Operation, +) -> Result<(), Error> { + if operation.kind != OperationKind::Mutation { + return error("A bulk mutation is a mutation"); + } + let document = parse(source)?; + let (definition, fragments) = parts_of(&document); + let top = top_level_field(selection_set(definition), "mutation")?; + if matches!( + top.name.as_str(), + "bulkOperationRunMutation" | "bulkOperationRunQuery" + ) { + return error_at( + top.position, + format!("Shopify does not run `{}` in a bulk mutation", top.name), + ); + } + let root = schema.mutation.as_deref().unwrap_or_default(); + let ty = fields_of(schema, root) + .and_then(|fields| fields.get(&top.name)) + .map(|field| field.ty.name().to_string()) + .unwrap_or_default(); + let mut found = Vec::new(); + find_connections(schema, &fragments, &top.selection_set, &ty, &mut found, 0); + if let [first, second, ..] = found.as_slice() { + return error_at( + second.1, + format!( + "The mutation of a bulk operation selects one connection at most (`{}`), Shopify's limit: `{}` is a second one", + first.0, second.0 + ), + ); + } + Ok(()) +} + +/// The connection fields selected in `set`, at any depth, with where they are. +fn find_connections<'a>( + schema: &Schema, + fragments: &Fragments<'a>, + set: &'a SelectionSet<'a>, + parent: &str, + found: &mut Vec<(String, Pos)>, + depth: usize, +) { + // Fragments do not nest without end: `analyze` refused that. + if depth > 64 { + return; + } + for item in &set.items { + match item { + ast::Selection::Field(field) => { + let Some(ty) = fields_of(schema, parent) + .and_then(|fields| fields.get(&field.name)) + .map(|field| field.ty.name().to_string()) + else { + continue; + }; + if connection_node(schema, &ty).is_some() { + found.push((field.name.clone(), field.position)); + } + find_connections( + schema, + fragments, + &field.selection_set, + &ty, + found, + depth + 1, + ); + } + ast::Selection::InlineFragment(fragment) => { + let target = match &fragment.type_condition { + Some(ast::TypeCondition::On(name)) => name.as_str(), + None => parent, + }; + find_connections( + schema, + fragments, + &fragment.selection_set, + target, + found, + depth + 1, + ); + } + ast::Selection::FragmentSpread(spread) => { + if let Some(fragment) = fragments.get(spread.fragment_name.as_str()) { + let ast::TypeCondition::On(target) = &fragment.type_condition; + find_connections( + schema, + fragments, + &fragment.selection_set, + target, + found, + depth + 1, + ); + } + } + } + } +} + +struct Checker<'a, 's> { + schema: &'s Schema, + fragments: &'a Fragments<'a>, + /// The connections seen so far. + count: usize, + /// The `node` fields whose selection gains `__typename`. + typename: BTreeSet<(usize, usize)>, +} + +impl<'a> Checker<'a, '_> { + /// The variables are written into the text: a `JSON` value has no + /// GraphQL literal this crate can write for sure. + fn variables(&self, definition: &ast::OperationDefinition<'_, String>) -> Result<(), Error> { + let ast::OperationDefinition::Query(query) = definition else { + return Ok(()); + }; + for variable in &query.variable_definitions { + let mut seen = BTreeSet::new(); + let name = base_name(&variable.var_type); + if reaches_json(self.schema, name, &mut seen) { + return error_at( + variable.position, + format!( + "Variable `${}` may hold a `JSON` value, which a bulk query cannot take: Shopify takes no variables for a bulk query, and this crate writes them into its text as GraphQL literals", + variable.name + ), + ); + } + } + Ok(()) + } + + /// Checks a connection field of `parent` and what it selects, `depth` + /// levels below the top-level one. + fn connection( + &mut self, + field: &'a ast::Field<'a, String>, + parent: &str, + depth: usize, + ) -> Result { + self.count += 1; + if self.count > MAX_CONNECTIONS { + return error_at( + field.position, + format!( + "A bulk query has {MAX_CONNECTIONS} connections at most: `{}` is connection number {}", + field.name, self.count + ), + ); + } + if depth > MAX_DEPTH { + return error_at( + field.position, + format!( + "Connections nest {MAX_DEPTH} levels deep at most below the top-level one in a bulk query: `{}` is level {depth}", + field.name + ), + ); + } + if let Some(directive) = field.directives.first() { + return error_at( + directive.position, + format!( + "A connection of a bulk query cannot have directives such as `@{}`: Shopify writes its nodes on lines of their own", + directive.name + ), + ); + } + if let Some((argument, _)) = field + .arguments + .iter() + .find(|(name, _)| PAGINATION.contains(&name.as_str())) + { + return error_at( + field.position, + format!( + "Shopify ignores `{argument}` in a bulk query and returns every object of `{}`: remove it", + field.name + ), + ); + } + let shape = format!( + "A connection of a bulk query selects `edges {{ node {{ … }} }}` and nothing else, as Shopify documents it (`{}`)", + field.name + ); + let edges = only_field(&field.selection_set, "edges", &shape)?; + let node = only_field(&edges.selection_set, "node", &shape)?; + + let ty = self.field_type(parent, field).unwrap_or_default(); + let node_type = connection_node(self.schema, &ty) + .unwrap_or_default() + .to_string(); + if !implements_node(self.schema, &node_type) { + return error_at( + field.position, + format!( + "Shopify bulk queries read connections of `Node` objects: the nodes of `{}`, `{node_type}`, do not all implement `Node`", + field.name + ), + ); + } + + let children = self.node_selection(&node.selection_set, &node_type, depth)?; + if let Some(child) = children.first() { + let has_id = node.selection_set.items.iter().any(|item| { + matches!(item, ast::Selection::Field(id) if id.name == "id" && id.alias.is_none() && id.directives.is_empty()) + }); + if !has_id { + return error_at( + node.position, + format!( + "The nodes of `{}` have the nested connection `{}`: select their `id`, without an alias or a directive, in this `node {{ … }}`. Shopify refuses the query otherwise, and places each nested line under its parent by that `id`", + field.name, child.name + ), + ); + } + } + if children.len() > 1 { + for (index, later) in children.iter().enumerate() { + for earlier in &children[..index] { + if let Some(shared) = earlier + .connection + .types + .iter() + .find(|ty| later.connection.types.contains(ty)) + { + return error_at( + later.position, + format!( + "`{}` and `{}`, connections of each node of `{}`, may both return `{shared}`: their lines in the results could not be told apart. Query one of them in another bulk query", + earlier.connection.key, later.connection.key, field.name + ), + ); + } + } + } + for child in &children { + self.typename.insert((child.node.line, child.node.column)); + } + } + Ok(Connection { + key: field.alias.as_ref().unwrap_or(&field.name).clone(), + types: concrete_types(self.schema, &node_type), + connections: children.into_iter().map(|child| child.connection).collect(), + }) + } + + /// The type name of `field` on `parent`. + fn field_type(&self, parent: &str, field: &ast::Field<'_, String>) -> Option { + fields_of(self.schema, parent) + .and_then(|fields| fields.get(&field.name)) + .map(|definition| definition.ty.name().to_string()) + } + + fn field_definition(&self, parent: &str, field: &ast::Field<'_, String>) -> Option<&Field> { + fields_of(self.schema, parent).and_then(|fields| fields.get(&field.name)) + } + + /// Refuses an alias Shopify or this crate writes in the lines. + fn check_key(field: &ast::Field<'_, String>) -> Result<(), Error> { + if let Some(alias) = &field.alias + && alias.starts_with("__") + { + return error_at( + field.position, + format!( + "`{alias}` cannot be an alias in a bulk query: the lines of its results hold `__parentId` and `__typename`" + ), + ); + } + Ok(()) + } + + /// Checks what a `node { … }` selects, and returns its connections. + fn node_selection( + &mut self, + set: &'a SelectionSet<'a>, + node_type: &str, + depth: usize, + ) -> Result, Error> { + let mut children = Vec::new(); + for item in &set.items { + match item { + ast::Selection::Field(field) => { + Self::check_key(field)?; + let Some(definition) = self.field_definition(node_type, field) else { + continue; + }; + let ty = definition.ty.clone(); + if connection_node(self.schema, ty.name()).is_some() { + if !matches!(ty.nullable(), TypeRef::Named(_)) { + return error_at( + field.position, + format!( + "`{}` is a list of connections, which a bulk query cannot read", + field.name + ), + ); + } + let connection = self.connection(field, node_type, depth + 1)?; + let node = only_field(&field.selection_set, "edges", "") + .and_then(|edges| only_field(&edges.selection_set, "node", "")) + .map(|node| node.position) + .unwrap_or(field.position); + children.push(Child { + name: field.name.clone(), + position: field.position, + node, + connection, + }); + } else if !field.selection_set.items.is_empty() { + self.plain(&field.selection_set, ty.name(), &field.name, false)?; + } + } + ast::Selection::InlineFragment(fragment) => { + let target = match &fragment.type_condition { + Some(ast::TypeCondition::On(name)) => name.as_str(), + None => node_type, + }; + self.plain(&fragment.selection_set, target, "", true)?; + } + ast::Selection::FragmentSpread(spread) => { + if let Some(fragment) = self.fragments.get(spread.fragment_name.as_str()) { + let ast::TypeCondition::On(target) = &fragment.type_condition; + self.plain(&fragment.selection_set, target, "", true)?; + } + } + } + } + Ok(children) + } + + /// Checks a selection that may hold no connection: under the field + /// `under`, or in a fragment. + fn plain( + &self, + set: &'a SelectionSet<'a>, + parent: &str, + under: &str, + fragment: bool, + ) -> Result<(), Error> { + for item in &set.items { + match item { + ast::Selection::Field(field) => { + Self::check_key(field)?; + let Some(definition) = self.field_definition(parent, field) else { + continue; + }; + let ty = definition.ty.name().to_string(); + if connection_node(self.schema, &ty).is_some() { + let place = if fragment { + "inside a fragment".to_string() + } else { + format!("under `{under}`, which is not a connection") + }; + return error_at( + field.position, + format!( + "The connection `{}` is {place}: in a bulk query, a nested connection is written right in the `node {{ … }}` of its parent connection", + field.name + ), + ); + } + if !field.selection_set.items.is_empty() { + let under = if fragment { under } else { &field.name }; + self.plain(&field.selection_set, &ty, under, fragment)?; + } + } + ast::Selection::InlineFragment(inline) => { + let target = match &inline.type_condition { + Some(ast::TypeCondition::On(name)) => name.as_str(), + None => parent, + }; + self.plain(&inline.selection_set, target, under, true)?; + } + ast::Selection::FragmentSpread(spread) => { + if let Some(definition) = self.fragments.get(spread.fragment_name.as_str()) { + let ast::TypeCondition::On(target) = &definition.type_condition; + self.plain(&definition.selection_set, target, under, true)?; + } + } + } + } + Ok(()) + } +} + +/// A nested connection, with where its field and its `node` are. +struct Child { + name: String, + position: Pos, + node: Pos, + connection: Connection, +} + +/// The single field `name` of `set`, without alias, arguments or directives. +fn only_field<'a>( + set: &'a SelectionSet<'a>, + name: &str, + shape: &str, +) -> Result<&'a ast::Field<'a, String>, Error> { + match set.items.as_slice() { + [ast::Selection::Field(field)] + if field.name == name + && field.alias.is_none() + && field.arguments.is_empty() + && field.directives.is_empty() => + { + Ok(field) + } + [ast::Selection::Field(field), ..] if field.name == "nodes" => error_at( + field.position, + format!("{shape}: Shopify does not document `nodes` for bulk queries"), + ), + [item] => error_at( + item_position(item), + format!("{shape}: write `{name}`, without alias, arguments or directives"), + ), + [first, second, ..] => { + let other = if matches!(first, ast::Selection::Field(field) if field.name == name) { + second + } else { + first + }; + error_at( + item_position(other), + format!("{shape}: {} is refused beside `{name}`", item_name(other)), + ) + } + [] => error_at(set_position(set), shape.to_string()), + } +} + +/// A selection as a message names it. +fn item_name(item: &ast::Selection<'_, String>) -> String { + match item { + ast::Selection::Field(field) => format!("`{}`", field.name), + ast::Selection::InlineFragment(_) | ast::Selection::FragmentSpread(_) => { + "a fragment".to_string() + } + } +} + +fn base_name<'t>(ty: &'t ast::Type<'_, String>) -> &'t str { + match ty { + ast::Type::NamedType(name) => name, + ast::Type::ListType(inner) | ast::Type::NonNullType(inner) => base_name(inner), + } +} + +/// A value of input type `name` may hold a `JSON` value. +fn reaches_json<'s>(schema: &'s Schema, name: &'s str, seen: &mut BTreeSet<&'s str>) -> bool { + if name == "JSON" { + return true; + } + match schema.get(name) { + Some(TypeDef::Input { fields, .. }) if seen.insert(name) => fields + .values() + .any(|field| reaches_json(schema, field.ty.name(), seen)), + _ => false, + } +} + +/// The selection on the nodes of a connection field of the analyzed operation. +fn connection_nodes(field: &SelectedField) -> &Selection { + let FieldBase::Object(connection) = &field.base else { + unreachable!("a connection has subfields"); + }; + let FieldBase::Object(edge) = &connection.fields[0].base else { + unreachable!("`edges` has subfields"); + }; + let FieldBase::Object(node) = &edge.fields[0].base else { + unreachable!("`node` has subfields"); + }; + node +} + +/// `selection` with each connection made the list of its nodes. +fn item_selection(schema: &Schema, selection: &Selection) -> Selection { + let mut item = selection.clone(); + for field in &mut item.fields { + if let Some(node) = connection_node(schema, field.ty.name()) { + let nodes = item_selection(schema, connection_nodes(field)); + field.ty = TypeRef::NonNull(Box::new(TypeRef::List(Box::new(TypeRef::NonNull( + Box::new(TypeRef::Named(node.to_string())), + ))))); + field.base = FieldBase::Object(nodes); + field.conditional = false; + field.connection = true; + } + } + item +} + +/// A constant value as GraphQL text. +fn constant_text(value: &Value<'_>) -> String { + match value { + ast::Value::Variable(name) => format!("${name}"), + ast::Value::Int(number) => number.as_i64().unwrap_or_default().to_string(), + // `Debug` keeps a `.` or an exponent: `1.0`, `1e300`. + ast::Value::Float(number) => format!("{number:?}"), + ast::Value::String(text) => string_literal(text), + ast::Value::Boolean(value) => value.to_string(), + ast::Value::Null => "null".to_string(), + ast::Value::Enum(name) => name.clone(), + ast::Value::List(items) => { + let items: Vec = items.iter().map(constant_text).collect(); + format!("[{}]", items.join(", ")) + } + ast::Value::Object(fields) => { + let fields: Vec = fields + .iter() + .map(|(name, value)| format!("{name}: {}", constant_text(value))) + .collect(); + format!("{{{}}}", fields.join(", ")) + } + } +} + +/// A string as a GraphQL string literal: JSON's escapes are GraphQL's. +pub fn string_literal(text: &str) -> String { + serde_json::to_string(text).expect("a string serializes") +} + +fn has_variable(value: &Value<'_>) -> bool { + match value { + ast::Value::Variable(_) => true, + ast::Value::List(items) => items.iter().any(has_variable), + ast::Value::Object(fields) => fields.values().any(has_variable), + _ => false, + } +} + +fn value_part(value: &Value<'_>) -> ValuePart { + match value { + ast::Value::Variable(name) => ValuePart::Variable(name.clone()), + ast::Value::List(items) if items.iter().any(has_variable) => { + ValuePart::List(items.iter().map(value_part).collect()) + } + ast::Value::Object(fields) if fields.values().any(has_variable) => ValuePart::Object( + fields + .iter() + .map(|(name, value)| Argument { + name: name.clone(), + value: value_part(value), + }) + .collect(), + ), + constant => ValuePart::Text(constant_text(constant)), + } +} + +/// Writes a document back as text, without its variable definitions, with +/// `__typename` where the lines need it. +struct Printer<'c> { + typename: &'c BTreeSet<(usize, usize)>, + parts: Vec, + text: String, +} + +impl Printer<'_> { + fn finish(mut self) -> Vec { + if !self.text.is_empty() { + self.parts.push(Part::Text(std::mem::take(&mut self.text))); + } + self.parts + } + + fn operation(&mut self, definition: &ast::OperationDefinition<'_, String>) { + let (name, directives, set) = match definition { + ast::OperationDefinition::SelectionSet(set) => (None, &[][..], set), + ast::OperationDefinition::Query(query) => ( + query.name.as_deref(), + &query.directives[..], + &query.selection_set, + ), + ast::OperationDefinition::Mutation(mutation) => ( + mutation.name.as_deref(), + &mutation.directives[..], + &mutation.selection_set, + ), + ast::OperationDefinition::Subscription(subscription) => ( + subscription.name.as_deref(), + &subscription.directives[..], + &subscription.selection_set, + ), + }; + if name.is_some() || !directives.is_empty() { + self.text.push_str("query"); + if let Some(name) = name { + self.text.push(' '); + self.text.push_str(name); + } + self.directives(directives); + self.text.push(' '); + } + self.selection_set(set, false); + } + + fn fragment(&mut self, fragment: &ast::FragmentDefinition<'_, String>) { + let ast::TypeCondition::On(condition) = &fragment.type_condition; + self.text + .push_str(&format!("fragment {} on {condition}", fragment.name)); + self.directives(&fragment.directives); + self.text.push(' '); + self.selection_set(&fragment.selection_set, false); + } + + fn selection_set(&mut self, set: &SelectionSet<'_>, typename: bool) { + self.text.push('{'); + if typename { + self.text.push_str(" __typename"); + } + for item in &set.items { + self.text.push(' '); + match item { + ast::Selection::Field(field) => { + if let Some(alias) = &field.alias { + self.text.push_str(alias); + self.text.push_str(": "); + } + self.text.push_str(&field.name); + self.arguments(&field.arguments); + self.directives(&field.directives); + if !field.selection_set.items.is_empty() { + self.text.push(' '); + let typename = self + .typename + .contains(&(field.position.line, field.position.column)); + self.selection_set(&field.selection_set, typename); + } + } + ast::Selection::InlineFragment(fragment) => { + self.text.push_str("..."); + if let Some(ast::TypeCondition::On(condition)) = &fragment.type_condition { + self.text.push_str(" on "); + self.text.push_str(condition); + } + self.directives(&fragment.directives); + self.text.push(' '); + self.selection_set(&fragment.selection_set, false); + } + ast::Selection::FragmentSpread(spread) => { + self.text.push_str("..."); + self.text.push_str(&spread.fragment_name); + self.directives(&spread.directives); + } + } + } + self.text.push_str(" }"); + } + + fn directives(&mut self, directives: &[ast::Directive<'_, String>]) { + for directive in directives { + self.text.push_str(" @"); + self.text.push_str(&directive.name); + self.arguments(&directive.arguments); + } + } + + fn arguments(&mut self, arguments: &[(String, Value<'_>)]) { + if arguments.is_empty() { + return; + } + if arguments.iter().any(|(_, value)| has_variable(value)) { + if !self.text.is_empty() { + self.parts.push(Part::Text(std::mem::take(&mut self.text))); + } + self.parts.push(Part::Arguments( + arguments + .iter() + .map(|(name, value)| Argument { + name: name.clone(), + value: value_part(value), + }) + .collect(), + )); + return; + } + let written: Vec = arguments + .iter() + .map(|(name, value)| format!("{name}: {}", constant_text(value))) + .collect(); + self.text.push('('); + self.text.push_str(&written.join(", ")); + self.text.push(')'); + } +} + +// ─── Code ──────────────────────────────────────────────────────────── + +/// The name of the `static` that holds the template of a bulk query. +pub fn template_ident() -> proc_macro2::Ident { + proc_macro2::Ident::new("__SHOPIFY_API_BULK_TEMPLATE", Span::mixed_site()) +} + +/// The item types of a bulk query, their `BulkItem` implementation, and the +/// `static` [`template_ident`] of its text. `krate` is the path of the +/// `shopify_api` crate in the generated code. +pub fn query_items( + schema: &Schema, + operation: &Operation, + bulk: &BulkQuery, + krate: &TokenStream, +) -> TokenStream { + let types = item_types(&bulk.item, ITEM_TYPE, krate); + let private = quote!(#krate::__private::bulk); + let item = format_ident!("{}", ITEM_TYPE); + + // Where each line goes. + let connections = connections_tokens(&bulk.connections, &private); + let parent = proc_macro2::Ident::new("__shopify_api_parent", Span::mixed_site()); + let slot = proc_macro2::Ident::new("__shopify_api_slot", Span::mixed_site()); + let line = proc_macro2::Ident::new("__shopify_api_line", Span::mixed_site()); + let number = proc_macro2::Ident::new("__shopify_api_number", Span::mixed_site()); + let child = proc_macro2::Ident::new("__shopify_api_child", Span::mixed_site()); + let mut arms = Vec::new(); + let top = field_idents(&bulk.item); + for (index, connection) in bulk.connections.iter().enumerate() { + let field = ident_of(&top, &connection.key); + arms.push(quote! { + (::core::option::Option::None, #index) => #private::push(&mut self.#field, #line, #number), + }); + if connection.connections.is_empty() { + continue; + } + let nested = nested_selection(&bulk.item, &connection.key); + let below = field_idents(nested); + for (inner, grandchild) in connection.connections.iter().enumerate() { + let inner_field = ident_of(&below, &grandchild.key); + arms.push(quote! { + (::core::option::Option::Some((#index, #child)), #inner) => match self.#field.get_mut(#child) { + ::core::option::Option::Some(#child) => #private::push(&mut #child.#inner_field, #line, #number), + ::core::option::Option::None => ::core::result::Result::Err(#private::unplaced()), + }, + }); + } + } + + let template = template_tokens(schema, operation, bulk, &private); + let template_ident = template_ident(); + let (parts_ident, variables_ident) = template_parts_idents(); + quote! { + #types + + impl #private::BulkItem for #item { + const CONNECTIONS: &'static [#private::BulkConnection] = #connections; + + fn __attach( + &mut self, + #parent: ::core::option::Option<(usize, usize)>, + #slot: usize, + #line: &[u8], + #number: usize, + ) -> #krate::Result { + match (#parent, #slot) { + #(#arms)* + _ => ::core::result::Result::Err(#private::unplaced()), + } + } + } + + #template + + static #template_ident: #private::BulkTemplate = #private::BulkTemplate { + parts: #parts_ident, + variables: #variables_ident, + }; + } +} + +fn ident_of<'i>(idents: &'i [(String, proc_macro2::Ident)], key: &str) -> &'i proc_macro2::Ident { + &idents + .iter() + .find(|(field, _)| field == key) + .expect("a connection is a field of its parent") + .1 +} + +/// The selection on the nodes of the connection `key` of `item`. +fn nested_selection<'s>(item: &'s Selection, key: &str) -> &'s Selection { + match item + .fields + .iter() + .find(|field| field.key == key) + .map(|field| &field.base) + { + Some(FieldBase::Object(selection)) => selection, + _ => unreachable!("a connection has subfields"), + } +} + +fn connections_tokens(connections: &[Connection], private: &TokenStream) -> TokenStream { + let items = connections.iter().map(|connection| { + let key = &connection.key; + let types = &connection.types; + let nested = connections_tokens(&connection.connections, private); + quote! { + #private::BulkConnection { + key: #key, + types: &[#(#types),*], + connections: #nested, + } + } + }); + quote!(&[#(#items),*]) +} + +/// The parts and the variables of the text, as `static`s named +/// `__SHOPIFY_API_BULK_PARTS` and `__SHOPIFY_API_BULK_VARIABLES`, with one +/// `static` per input object whose fields hold enums. +fn template_tokens( + schema: &Schema, + operation: &Operation, + bulk: &BulkQuery, + private: &TokenStream, +) -> TokenStream { + let names: Vec<&str> = operation + .variables + .iter() + .map(|variable| variable.name.as_str()) + .collect(); + let parts = bulk.parts.iter().map(|part| match part { + Part::Text(text) => quote!(#private::BulkPart::Text(#text)), + Part::Arguments(arguments) => { + let arguments = arguments_tokens(arguments, &names, private); + quote!(#private::BulkPart::Arguments(#arguments)) + } + }); + let mut inputs = BTreeMap::new(); + let variables: Vec = operation + .variables + .iter() + .map(|variable| { + let name = &variable.name; + let ty = type_tokens(schema, &variable.ty, private, &mut inputs); + let default = match bulk.defaults.get(name) { + Some(text) => quote!(::core::option::Option::Some(#text)), + None => quote!(::core::option::Option::None), + }; + quote! { + #private::BulkVariable { name: #name, ty: #ty, default: #default } + } + }) + .collect(); + let statics = inputs.into_iter().filter_map(|(name, fields)| { + let fields = fields?; + let ident = input_ident(&name); + let count = fields.len(); + let fields = fields.into_iter().map(|(field, ty)| quote!((#field, #ty))); + Some(quote! { + static #ident: [(&str, #private::BulkType); #count] = [#(#fields),*]; + }) + }); + let (parts_ident, variables_ident) = template_parts_idents(); + quote! { + #(#statics)* + static #parts_ident: &[#private::BulkPart] = &[#(#parts),*]; + static #variables_ident: &[#private::BulkVariable] = &[#(#variables),*]; + } +} + +/// The `static`s of the parts and of the variables of the text. +fn template_parts_idents() -> (proc_macro2::Ident, proc_macro2::Ident) { + ( + proc_macro2::Ident::new("__SHOPIFY_API_BULK_PARTS", Span::mixed_site()), + proc_macro2::Ident::new("__SHOPIFY_API_BULK_VARIABLES", Span::mixed_site()), + ) +} + +fn input_ident(name: &str) -> proc_macro2::Ident { + proc_macro2::Ident::new( + &format!("__SHOPIFY_API_BULK_INPUT_{name}"), + Span::mixed_site(), + ) +} + +fn arguments_tokens(arguments: &[Argument], names: &[&str], private: &TokenStream) -> TokenStream { + let items = arguments.iter().map(|argument| { + let name = &argument.name; + let value = value_tokens(&argument.value, names, private); + quote!(#private::BulkArgument { name: #name, value: #value }) + }); + quote!(&[#(#items),*]) +} + +fn value_tokens(value: &ValuePart, names: &[&str], private: &TokenStream) -> TokenStream { + match value { + ValuePart::Text(text) => quote!(#private::BulkValue::Text(#text)), + ValuePart::Variable(name) => { + let index = names + .iter() + .position(|declared| declared == name) + .expect("`analyze` checked that the variable is declared"); + quote!(#private::BulkValue::Variable(#index)) + } + ValuePart::List(items) => { + let items = items.iter().map(|item| value_tokens(item, names, private)); + quote!(#private::BulkValue::List(&[#(#items),*])) + } + ValuePart::Object(fields) => { + let fields = arguments_tokens(fields, names, private); + quote!(#private::BulkValue::Object(#fields)) + } + } +} + +/// Input objects by name: the fields that hold enums, with their type, or +/// `None` while they are being written. +type Inputs = BTreeMap>>; + +/// Where the enums of a value of type `ty` are, which are written bare. +fn type_tokens( + schema: &Schema, + ty: &TypeRef, + private: &TokenStream, + inputs: &mut Inputs, +) -> TokenStream { + match ty { + TypeRef::NonNull(inner) => type_tokens(schema, inner, private, inputs), + TypeRef::List(item) => { + let item = type_tokens(schema, item, private, inputs); + quote!(#private::BulkType::List(&#item)) + } + TypeRef::Named(name) => match schema.get(name) { + Some(TypeDef::Enum { .. }) => quote!(#private::BulkType::Enum), + Some(TypeDef::Input { fields, .. }) + if reaches_enum(schema, name, &mut BTreeSet::new()) => + { + if !inputs.contains_key(name) { + inputs.insert(name.clone(), None); + let written = fields + .iter() + .filter(|(_, field)| { + reaches_enum(schema, field.ty.name(), &mut BTreeSet::new()) + }) + .map(|(field, input)| { + ( + field.clone(), + type_tokens(schema, &input.ty, private, inputs), + ) + }) + .collect(); + inputs.insert(name.clone(), Some(written)); + } + let ident = input_ident(name); + quote!(#private::BulkType::Input(&#ident)) + } + _ => quote!(#private::BulkType::Plain), + }, + } +} + +/// A value of input type `name` may hold an enum value. +fn reaches_enum<'s>(schema: &'s Schema, name: &'s str, seen: &mut BTreeSet<&'s str>) -> bool { + match schema.get(name) { + Some(TypeDef::Enum { .. }) => true, + Some(TypeDef::Input { fields, .. }) if seen.insert(name) => fields + .values() + .any(|field| reaches_enum(schema, field.ty.name(), seen)), + _ => false, + } +} diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs index 33de621..5789fdb 100644 --- a/crates/shopify_api_graphql/src/codegen.rs +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -153,6 +153,10 @@ impl DataTypes<'_> { let on = selection.types.join("` or `"); let doc = if name == DATA_TYPE { format!(" The `data` of the operation, selected on `{on}`.") + } else if name == crate::bulk::ITEM_TYPE { + format!( + " A top-level object of the bulk query, with the objects of its nested connections, selected on `{on}`." + ) } else { format!(" Selection on `{on}`.") }; @@ -190,7 +194,7 @@ impl DataTypes<'_> { wrap(&field.ty, &base) }; - let default = optional.then(|| quote!(#[serde(default)])); + let default = (optional || field.connection).then(|| quote!(#[serde(default)])); let doc = format!(" `{}: {}`", field.key, field.ty); quote! { #[doc = #doc] @@ -216,6 +220,30 @@ pub fn data_types(operation: &Operation, krate: &TokenStream) -> TokenStream { quote!(#(#items)*) } +/// The structs of the items of a bulk query: `name`, and one struct per +/// nested selection, named after its path (`ItemVariants`). +pub fn item_types(selection: &Selection, name: &str, krate: &TokenStream) -> TokenStream { + let mut types = DataTypes { + krate, + names: BTreeSet::new(), + items: Vec::new(), + }; + types.object(selection, name.to_string()); + let items = types.items; + quote!(#(#items)*) +} + +/// The Rust fields of the struct of `selection`, by response key, as +/// [`item_types`] and [`data_types`] name them. +pub(crate) fn field_idents(selection: &Selection) -> Vec<(String, Ident)> { + let mut taken = BTreeSet::new(); + selection + .fields + .iter() + .map(|field| (field.key.clone(), field_ident(&field.key, &mut taken).0)) + .collect() +} + // ─── Variables ─────────────────────────────────────────────────────── /// The Rust type a variable value is converted to, or `None` when the variable @@ -271,6 +299,28 @@ pub fn variables_types( operation: &Operation, krate: &TokenStream, constructor: &TokenStream, +) -> TokenStream { + let data = Ident::new(DATA_TYPE, Span::call_site()); + let target = quote!(#krate::Operation<#data>); + variables_types_for( + schema, + operation, + krate, + constructor, + &target, + "`Shopify::execute`", + ) +} + +/// [`variables_types`] for an operation of type `target`, which `runner` +/// runs: a bulk query or a bulk mutation. +pub fn variables_types_for( + schema: &Schema, + operation: &Operation, + krate: &TokenStream, + constructor: &TokenStream, + target: &TokenStream, + runner: &str, ) -> TokenStream { let mut inputs = BTreeSet::new(); for variable in &operation.variables { @@ -351,27 +401,29 @@ pub fn variables_types( derives.push(quote!(::core::default::Default)); } let serde = serde_path(krate); - let data = Ident::new(DATA_TYPE, Span::call_site()); let variables = Ident::new(VARIABLES_TYPE, Span::call_site()); + let struct_doc = format!( + " The variables of the operation; those left to `None` are not sent. {runner} runs it." + ); + let operation_doc = format!(" The operation with its variables, for {runner}."); quote! { #(#aliases)* - /// The variables of the operation; those left to `None` are not - /// sent. `Shopify::execute` runs it. + #[doc = #struct_doc] #[derive(#(#derives),*)] #[serde(crate = #serde)] pub struct #variables { #(#fields)* } - /// The operation with its variables, for `Shopify::execute`. - pub fn operation(variables: #variables) -> #krate::Operation<#data> { + #[doc = #operation_doc] + pub fn operation(variables: #variables) -> #target { let operation = #constructor; #(#setters)* operation } - impl ::core::convert::From<#variables> for #krate::Operation<#data> { + impl ::core::convert::From<#variables> for #target { fn from(variables: #variables) -> Self { operation(variables) } diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs index 08e5ee8..8a5d391 100644 --- a/crates/shopify_api_graphql/src/lib.rs +++ b/crates/shopify_api_graphql/src/lib.rs @@ -23,6 +23,8 @@ #[doc(hidden)] pub mod analyze; #[doc(hidden)] +pub mod bulk; +#[doc(hidden)] pub mod codegen; #[doc(hidden)] pub mod literal; diff --git a/crates/shopify_api_graphql/tests/bulk.rs b/crates/shopify_api_graphql/tests/bulk.rs new file mode 100644 index 0000000..2864d77 --- /dev/null +++ b/crates/shopify_api_graphql/tests/bulk.rs @@ -0,0 +1,262 @@ +//! Bulk operations: the rules checked on top of `analyze`, the text a bulk +//! query sends and where its lines go. + +use std::sync::OnceLock; + +use shopify_api_graphql::bulk::{ + Argument, BulkQuery, Connection, Part, ValuePart, analyze_bulk_query, check_bulk_mutation, + query_items, +}; +use shopify_api_graphql::{FieldBase, Schema, analyze}; + +/// A small schema: connections of `Thing`s, an input object that holds an +/// enum and itself, a `JSON` argument. +const SCHEMA: &str = r#"{"format":2,"apiVersion":"2026-10","query":"QueryRoot","mutation":"Mutation","types":{ +"QueryRoot":{"o":{"f":{ + "things":["ThingConnection!",{"filter":"Filter","tags":"[Color!]","data":"JSON","first":"Int","q":"String","sort":"Color"}], + "thing":["Thing",{"id":"ID!"}] +}}}, +"Mutation":{"o":{"f":{"make":["MakePayload",{"id":"ID!","filter":"Filter"}]}}}, +"MakePayload":{"o":{"f":{"a":"ThingConnection!","b":"ThingConnection!","thing":"Thing"}}}, +"Node":{"n":{"f":{"id":"ID!"},"t":["Thing"]}}, +"Thing":{"o":{"f":{"id":"ID!","name":"String","parts":["ThingConnection!",{"q":"String"}],"tags":"[Color!]"},"t":["Node"]}}, +"ThingConnection":{"o":{"f":{"edges":"[ThingEdge!]!","nodes":"[Thing!]!","pageInfo":"PageInfo!"}}}, +"ThingEdge":{"o":{"f":{"node":"Thing!","cursor":"String!"}}}, +"PageInfo":{"o":{"f":{"hasNextPage":"Boolean!"}}}, +"Filter":{"i":{"color":"Color","nested":"Filter","name":"String","colors":"[Color!]"}}, +"Color":{"e":["RED","BLUE"]}, +"ID":"s","String":"s","Boolean":"s","Int":"s","Float":"s","JSON":"s" +}}"#; + +fn schema() -> &'static Schema { + static SCHEMA_ONCE: OnceLock = OnceLock::new(); + SCHEMA_ONCE.get_or_init(|| Schema::from_json(SCHEMA).unwrap()) +} + +fn bulk(source: &str) -> BulkQuery { + let operation = analyze(schema(), source).unwrap_or_else(|error| panic!("{error}")); + analyze_bulk_query(schema(), source, &operation).unwrap_or_else(|error| panic!("{error}")) +} + +fn refusal(source: &str) -> String { + let operation = analyze(schema(), source).unwrap_or_else(|error| panic!("{error}")); + let refused = match operation.kind { + shopify_api_graphql::OperationKind::Query => { + analyze_bulk_query(schema(), source, &operation).err() + } + shopify_api_graphql::OperationKind::Mutation => { + check_bulk_mutation(schema(), source, &operation).err() + } + }; + refused.expect("refused").to_string() +} + +fn text(parts: &[Part]) -> String { + parts + .iter() + .map(|part| match part { + Part::Text(text) => text.clone(), + _ => "(…)".to_string(), + }) + .collect() +} + +#[test] +fn the_text_keeps_constants_and_sets_variables_apart() { + let query = bulk( + r#"query Things($filter: Filter, $q: String = "x \"y\"", $named: Boolean!) { + things(filter: $filter, q: $q, sort: RED) { edges { node { id name @include(if: $named) } } } + }"#, + ); + assert_eq!( + text(&query.parts), + "query Things { things(…) { edges { node { id name @include(…) } } } }" + ); + let Part::Arguments(arguments) = &query.parts[1] else { + panic!("arguments"); + }; + assert_eq!( + named(arguments), + [ + ("filter", &ValuePart::Variable("filter".into())), + ("q", &ValuePart::Variable("q".into())), + ("sort", &ValuePart::Text("RED".into())), + ] + ); + assert_eq!(query.defaults["q"], r#""x \"y\"""#); +} + +fn named(arguments: &[Argument]) -> Vec<(&str, &ValuePart)> { + arguments + .iter() + .map(|argument| (argument.name.as_str(), &argument.value)) + .collect() +} + +#[test] +fn constants_are_written_back_as_graphql() { + let query = bulk( + r#"{ things(filter: {name: """block "quoted" +text""", colors: [RED, BLUE], nested: null}, q: "$q stays", sort: null) { edges { node { id } } } }"#, + ); + assert_eq!( + text(&query.parts), + r#"{ things(filter: {colors: [RED, BLUE], name: "block \"quoted\"\ntext", nested: null}, q: "$q stays", sort: null) { edges { node { id } } } }"# + ); +} + +#[test] +fn variables_deep_in_values_are_set_apart_with_their_place() { + let query = bulk( + "query($c: Color!, $n: String) { things(filter: {colors: [RED, $c], nested: {name: $n}}) { edges { node { id } } } }", + ); + let Part::Arguments(arguments) = &query.parts[1] else { + panic!("arguments"); + }; + let ValuePart::Object(fields) = &arguments[0].value else { + panic!("an object"); + }; + assert_eq!(fields[0].name, "colors"); + assert_eq!( + fields[0].value, + ValuePart::List(vec![ + ValuePart::Text("RED".into()), + ValuePart::Variable("c".into()) + ]) + ); + assert_eq!(fields[1].name, "nested"); + assert!( + matches!(&fields[1].value, ValuePart::Object(nested) if nested[0].value == ValuePart::Variable("n".into())) + ); +} + +#[test] +fn connections_become_lists_of_their_nodes() { + let query = bulk( + "{ things { edges { node { id name parts(q: \"x\") { edges { node { id parts { edges { node { name } } } } } } } } } }", + ); + assert_eq!(shape(&query.connections), "parts: Thing [parts: Thing []]"); + let parts = query + .item + .fields + .iter() + .find(|field| field.key == "parts") + .unwrap(); + assert!(parts.connection); + assert_eq!(parts.ty.to_string(), "[Thing!]!"); + let FieldBase::Object(nodes) = &parts.base else { + panic!("an object"); + }; + let nested = nodes + .fields + .iter() + .find(|field| field.key == "parts") + .unwrap(); + assert!(nested.connection); + // One connection per parent: no `__typename` is needed. + assert!(!text(&query.parts).contains("__typename")); +} + +/// `key: Types [nested]` of each connection. +fn shape(connections: &[Connection]) -> String { + connections + .iter() + .map(|connection| { + format!( + "{}: {} [{}]", + connection.key, + connection.types.join(" "), + shape(&connection.connections) + ) + }) + .collect::>() + .join(", ") +} + +#[test] +fn siblings_that_may_return_one_type_are_refused() { + assert_eq!( + refusal( + "{ things { edges { node { id a: parts { edges { node { id } } } b: parts { edges { node { id } } } } } } }" + ), + "`a` and `b`, connections of each node of `things`, may both return `Thing`: their lines in the results could not be told apart. Query one of them in another bulk query (line 1, column 65)" + ); +} + +#[test] +fn json_variables_are_refused() { + assert_eq!( + refusal("query($d: JSON) { things(data: $d) { edges { node { id } } } }"), + "Variable `$d` may hold a `JSON` value, which a bulk query cannot take: Shopify takes no variables for a bulk query, and this crate writes them into its text as GraphQL literals (line 1, column 7)" + ); +} + +#[test] +fn the_rules_of_shopify_are_refusals() { + for (source, message) in [ + ( + "{ thing(id: \"1\") { id parts { edges { node { id } } } } }", + "The top-level field of a bulk query is a connection: `thing` is `Thing`. Run it as an ordinary query, or select a connection such as `products` (line 1, column 3)", + ), + ( + "{ things { edges { cursor node { id } } } }", + "A connection of a bulk query selects `edges { node { … } }` and nothing else, as Shopify documents it (`things`): `cursor` is refused beside `node` (line 1, column 20)", + ), + ( + "{ things { edges { n: node { id } } } }", + "A connection of a bulk query selects `edges { node { … } }` and nothing else, as Shopify documents it (`things`): write `node`, without alias, arguments or directives (line 1, column 20)", + ), + ( + "{ things { edges { node { id parts @include(if: true) { edges { node { id } } } } } } }", + "A connection of a bulk query cannot have directives such as `@include`: Shopify writes its nodes on lines of their own (line 1, column 36)", + ), + ( + "{ things { edges { node { name parts { edges { node { id } } } } } } }", + "The nodes of `things` have the nested connection `parts`: select their `id`, without an alias or a directive, in this `node { … }`. Shopify refuses the query otherwise, and places each nested line under its parent by that `id` (line 1, column 20)", + ), + ( + "{ things { edges { node { id @include(if: true) parts { edges { node { id } } } } } } }", + "The nodes of `things` have the nested connection `parts`: select their `id`, without an alias or a directive, in this `node { … }`. Shopify refuses the query otherwise, and places each nested line under its parent by that `id` (line 1, column 20)", + ), + ( + "{ things { edges { node { id __typename: name } } } }", + "`__typename` cannot be an alias in a bulk query: the lines of its results hold `__parentId` and `__typename` (line 1, column 30)", + ), + ( + "mutation { make(id: \"1\") { a { edges { node { id } } } b { edges { node { id } } } } }", + "The mutation of a bulk operation selects one connection at most (`a`), Shopify's limit: `b` is a second one (line 1, column 56)", + ), + ( + "mutation { ...M } fragment M on Mutation { make(id: \"1\") { thing { id } } }", + "A bulk mutation selects one top-level field, not a fragment (line 1, column 15)", + ), + ] { + assert_eq!(refusal(source), message, "{source}"); + } + // One connection in a mutation, at any depth. + let source = "mutation { make(id: \"1\") { a { edges { node { id } } } thing { id } } }"; + let operation = analyze(schema(), source).unwrap(); + check_bulk_mutation(schema(), source, &operation).unwrap(); +} + +#[test] +fn the_enums_of_input_objects_are_described_for_the_variables() { + let source = "query($filter: Filter, $tags: [Color!], $q: String) { things(filter: $filter, tags: $tags, q: $q) { edges { node { id } } } }"; + let operation = analyze(schema(), source).unwrap(); + let query = analyze_bulk_query(schema(), source, &operation).unwrap(); + let code = query_items(schema(), &operation, &query, "e::quote!(::shopify_api)).to_string(); + // `Filter` holds an enum, a list of them and itself; `name` holds none. + assert!( + code.contains( + "static __SHOPIFY_API_BULK_INPUT_Filter : [(& str , :: shopify_api :: __private :: bulk :: BulkType) ; 3usize] = [(\"color\" , :: shopify_api :: __private :: bulk :: BulkType :: Enum) , (\"colors\" , :: shopify_api :: __private :: bulk :: BulkType :: List (& :: shopify_api :: __private :: bulk :: BulkType :: Enum)) , (\"nested\" , :: shopify_api :: __private :: bulk :: BulkType :: Input (& __SHOPIFY_API_BULK_INPUT_Filter))]" + ), + "{code}" + ); + assert!(code.contains("name : \"tags\" , ty : :: shopify_api :: __private :: bulk :: BulkType :: List (& :: shopify_api :: __private :: bulk :: BulkType :: Enum)"), "{code}"); + assert!( + code.contains( + "name : \"q\" , ty : :: shopify_api :: __private :: bulk :: BulkType :: Plain" + ), + "{code}" + ); +} From fedd60ac14abba1c790ead9a9b5c3f966bea2e4e Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:13:08 +0100 Subject: [PATCH 107/135] =?UTF-8?q?feat(macros):=20`bulk("=E2=80=A6")`=20a?= =?UTF-8?q?nd=20`bulk(file("=E2=80=A6"))`=20sources=20for=20`graphql!`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A bulk query builds a `BulkQuery`, a bulk mutation a `BulkMutation` (one line of variables), in the inline form and in modules, with the variables, literals and `input!` of any operation. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api_macros/src/lib.rs | 303 +++++++++++++++++++++------ 1 file changed, 236 insertions(+), 67 deletions(-) diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 621aeff..fd6883f 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -11,7 +11,12 @@ use std::time::SystemTime; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, quote_spanned}; -use shopify_api_graphql::codegen::{DATA_TYPE, data_types, deprecation_warning, variables_types}; +use shopify_api_graphql::bulk::{ + BulkQuery, ITEM_TYPE, analyze_bulk_query, check_bulk_mutation, query_items, template_ident, +}; +use shopify_api_graphql::codegen::{ + DATA_TYPE, data_types, deprecation_warning, variables_types, variables_types_for, +}; use shopify_api_graphql::literal::{self, Literals, Value, VariableValue}; use shopify_api_graphql::project::{cargo_home, may_download, metadata_snippet, project_schema}; use shopify_api_graphql::{ @@ -33,32 +38,58 @@ enum Source { Literal(LitStr), /// `file("graphql/orders.graphql")`, relative to the crate's `Cargo.toml`. File(LitStr), + /// `bulk("…")` or `bulk(file("…"))`: a bulk query or a bulk mutation. + Bulk(Box), } -impl Parse for Source { - fn parse(input: ParseStream) -> syn::Result { +const SOURCE_FORM: &str = + "expected the GraphQL operation as a string literal, `file(\"path.graphql\")` or `bulk(…)`"; + +impl Source { + fn parse_text(input: ParseStream, bulk: bool) -> syn::Result { + let expected = if bulk { + "`bulk(…)` takes the operation as a string literal or `file(\"path.graphql\")`" + } else { + SOURCE_FORM + }; if input.peek(Ident) && input.peek2(syn::token::Paren) { let keyword: Ident = input.parse()?; - if keyword != "file" { - return Err(syn::Error::new( - keyword.span(), - "expected the GraphQL operation as a string literal, or `file(\"path.graphql\")`", - )); - } let content; syn::parenthesized!(content in input); - let path: LitStr = content.parse()?; - if !content.is_empty() { - return Err(content.error("`file(…)` takes one path")); + if keyword == "file" { + let path: LitStr = content.parse()?; + if !content.is_empty() { + return Err(content.error("`file(…)` takes one path")); + } + return Ok(Self::File(path)); } - return Ok(Self::File(path)); + if keyword == "bulk" && !bulk { + let source = Self::parse_text(&content, true)?; + if !content.is_empty() { + return Err(content.error("`bulk(…)` takes one operation")); + } + return Ok(Self::Bulk(Box::new(source))); + } + return Err(syn::Error::new(keyword.span(), expected)); } - input.parse().map(Self::Literal).map_err(|error| { - syn::Error::new( - error.span(), - "expected the GraphQL operation as a string literal, or `file(\"path.graphql\")`", - ) - }) + input + .parse() + .map(Self::Literal) + .map_err(|error| syn::Error::new(error.span(), expected)) + } + + /// The text, and whether it is a bulk operation. + fn text(&self) -> (&Self, bool) { + match self { + Self::Bulk(source) => (source, true), + other => (other, false), + } + } +} + +impl Parse for Source { + fn parse(input: ParseStream) -> syn::Result { + Self::parse_text(input, false) } } @@ -181,6 +212,7 @@ struct Text { impl Text { fn read(source: &Source) -> syn::Result { match source { + Source::Bulk(source) => Self::read(source), Source::Literal(query) => Ok(Self { query: query.clone(), file: None, @@ -341,23 +373,44 @@ impl LoadedSchema { /// Checks an operation, pointing a refusal at its text. fn check(&self, text: &Text) -> syn::Result { - analyze(self.schema(), &text.query.value()).map_err(|error| { - let file = match &text.file { - Some(file) => { - let relative = manifest_dir() - .and_then(|dir| file.strip_prefix(dir).ok().map(Path::to_path_buf)); - format!(" in {}", relative.as_deref().unwrap_or(file).display()) - } - None => String::new(), - }; - syn::Error::new( - text.span(), - format!( - "{error}{file}\n(checked against the Shopify Admin API {})", - self.schema().api_version - ), - ) - }) + analyze(self.schema(), &text.query.value()).map_err(|error| self.text_error(text, error)) + } + + /// A refusal of an operation, at its text. + fn text_error(&self, text: &Text, error: impl std::fmt::Display) -> syn::Error { + let file = match &text.file { + Some(file) => { + let relative = manifest_dir() + .and_then(|dir| file.strip_prefix(dir).ok().map(Path::to_path_buf)); + format!(" in {}", relative.as_deref().unwrap_or(file).display()) + } + None => String::new(), + }; + syn::Error::new( + text.span(), + format!( + "{error}{file}\n(checked against the Shopify Admin API {})", + self.schema().api_version + ), + ) + } + + /// Checks a bulk operation: what `check` checks, then Shopify's bulk rules. + fn check_bulk(&self, text: &Text) -> syn::Result<(Operation, Option)> { + let operation = self.check(text)?; + let source = text.query.value(); + let bulk = match operation.kind { + OperationKind::Query => Some( + analyze_bulk_query(self.schema(), &source, &operation) + .map_err(|error| self.text_error(text, error))?, + ), + OperationKind::Mutation => { + check_bulk_mutation(self.schema(), &source, &operation) + .map_err(|error| self.text_error(text, error))?; + None + } + }; + Ok((operation, bulk)) } } @@ -406,21 +459,94 @@ fn kind(operation: &Operation, krate: &TokenStream) -> TokenStream { } } -/// `Operation::::new(…)` for the checked operation. -fn constructor( - schema: &Schema, - operation: &Operation, - query: &TokenStream, - krate: &TokenStream, -) -> TokenStream { - let data = format_ident!("{}", DATA_TYPE); - let kind = kind(operation, krate); - let api_version = &schema.api_version; - let name = match &operation.name { - Some(name) => quote!(::core::option::Option::Some(#name)), - None => quote!(::core::option::Option::None), - }; - quote!(#krate::Operation::<#data>::__checked(#query, #kind, #name, #api_version)) +/// What `graphql!` builds from a checked operation. +enum Flavor { + /// An `Operation`. + Plain, + /// A `BulkQuery`. + BulkQuery(Box), + /// A `BulkMutation`: the variables of one line. + BulkMutation, +} + +impl Flavor { + fn of(schema: &LoadedSchema, source: &Source, text: &Text) -> syn::Result<(Operation, Self)> { + if !source.text().1 { + return Ok((schema.check(text)?, Self::Plain)); + } + let (operation, bulk) = schema.check_bulk(text)?; + let flavor = match bulk { + Some(bulk) => Self::BulkQuery(Box::new(bulk)), + None => Self::BulkMutation, + }; + Ok((operation, flavor)) + } + + /// The type built. + fn target(&self, krate: &TokenStream) -> TokenStream { + let data = format_ident!("{}", DATA_TYPE); + let item = format_ident!("{}", ITEM_TYPE); + match self { + Self::Plain => quote!(#krate::Operation<#data>), + Self::BulkQuery(_) => quote!(#krate::bulk::BulkQuery<#item>), + Self::BulkMutation => quote!(#krate::bulk::BulkMutation<#data>), + } + } + + /// What runs it, for the documentation. + fn runner(&self) -> &'static str { + match self { + Self::Plain => "`Shopify::execute`", + Self::BulkQuery(_) => "`Shopify::bulk_query`", + Self::BulkMutation => "`Shopify::bulk_mutation`, one per line,", + } + } + + /// The result types, and what a bulk query needs to run. + fn types(&self, schema: &Schema, operation: &Operation, krate: &TokenStream) -> TokenStream { + match self { + Self::BulkQuery(bulk) => query_items(schema, operation, bulk, krate), + Self::Plain | Self::BulkMutation => data_types(operation, krate), + } + } + + /// The checked operation, without its variables. + fn constructor( + &self, + schema: &Schema, + operation: &Operation, + query: &TokenStream, + krate: &TokenStream, + ) -> TokenStream { + let data = format_ident!("{}", DATA_TYPE); + let item = format_ident!("{}", ITEM_TYPE); + let api_version = &schema.api_version; + let name = match &operation.name { + Some(name) => quote!(::core::option::Option::Some(#name)), + None => quote!(::core::option::Option::None), + }; + match self { + Self::Plain => { + let kind = kind(operation, krate); + quote!(#krate::Operation::<#data>::__checked(#query, #kind, #name, #api_version)) + } + Self::BulkQuery(_) => { + let template = template_ident(); + quote!(#krate::bulk::BulkQuery::<#item>::__checked(&#template, #query, #name, #api_version)) + } + Self::BulkMutation => { + quote!(#krate::bulk::BulkMutation::<#data>::__checked(#query, #name, #api_version)) + } + } + } + + /// The method that sets a variable converted by `IntoVariable`. + fn converting_setter(&self) -> Ident { + match self { + Self::Plain => format_ident!("variable"), + Self::BulkQuery(_) | Self::BulkMutation => format_ident!("__converted_variable"), + } + } } /// `graphql!("…", name = value)`: the operation as a value. @@ -431,7 +557,7 @@ fn expand_expression( ) -> syn::Result { let krate = quote!(::shopify_api); let text = Text::read(source)?; - let operation = schema.check(&text)?; + let (operation, flavor) = Flavor::of(schema, source, &text)?; // Each value with the variable it is for. let mut given: Vec<(&Variable, &Value)> = Vec::new(); @@ -486,6 +612,7 @@ fn expand_expression( // declares the types of the operation: they cannot name them. let mut literals = Literals::new(schema.schema(), krate.clone()); let mut setters = Vec::new(); + let converting = flavor.converting_setter(); for (declared, value) in &given { let key = &declared.name; match literals @@ -494,7 +621,9 @@ fn expand_expression( { VariableValue::Converted { ty, value } => { let tokens = literal::argument(&value); - setters.push(quote_spanned!(value.span=> .variable::<#ty, _>(#key, #tokens))); + let mut method = converting.clone(); + method.set_span(value.span); + setters.push(quote_spanned!(value.span=> .#method::<#ty, _>(#key, #tokens))); } VariableValue::Literal(code) => { setters.push(quote!(.__literal_variable(#key, #code))); @@ -506,9 +635,9 @@ fn expand_expression( let tracking = schema.tracking(); let file = text.tracking(); let warnings = deprecation_warnings(schema.schema(), &operation, &text); - let types = data_types(&operation, &krate); + let types = flavor.types(schema.schema(), &operation, &krate); let query = &text.query; - let constructor = constructor(schema.schema(), &operation, "e!(#query), &krate); + let constructor = flavor.constructor(schema.schema(), &operation, "e!(#query), &krate); Ok(quote! { ({ #tracking @@ -532,24 +661,37 @@ fn expand_module(schema: &LoadedSchema, module: &Module) -> syn::Result #krate::Operation<#data> { + #[doc = #doc] + pub fn operation() -> #target { #constructor } } - } else { + } else if matches!(flavor, Flavor::Plain) { variables_types(schema.schema(), &operation, &krate, &constructor) + } else { + variables_types_for( + schema.schema(), + &operation, + &krate, + &constructor, + &target, + flavor.runner(), + ) }; let tracking = schema.tracking(); let file = text.tracking(); let warnings = deprecation_warnings(schema.schema(), &operation, &text); - let types = data_types(&operation, &krate); + let types = flavor.types(schema.schema(), &operation, &krate); let query = &text.query; let api_version = &schema.schema().api_version; let operation_name = match &operation.name { @@ -779,16 +921,43 @@ mod tests { assert!(matches!(modules[2].visibility, Visibility::Inherited)); } + // `bulk(…)` around either source, in both forms. + let Input::Expression { + source: Source::Bulk(inner), + variables, + } = syn::parse_str::(r#"bulk("{ shop { name } }"), first = 1"#).unwrap() + else { + panic!("a bulk expression"); + }; + assert!(matches!(*inner, Source::Literal(_))); + assert_eq!(variables.len(), 1); + let Input::Modules(modules) = syn::parse_str::( + r#"pub mod a = bulk(file("a.graphql")); mod b = bulk("{ shop { id } }");"#, + ) + .unwrap() else { + panic!("modules"); + }; + assert!( + matches!(&modules[0].source, Source::Bulk(inner) if matches!(**inner, Source::File(_))) + ); + assert!( + matches!(&modules[1].source, Source::Bulk(inner) if matches!(**inner, Source::Literal(_))) + ); + for (source, message) in [ + ("first = 1", SOURCE_FORM), + (r#"path("x.graphql")"#, SOURCE_FORM), + (r#"file("a", "b")"#, "`file(…)` takes one path"), ( - "first = 1", - "expected the GraphQL operation as a string literal, or `file(\"path.graphql\")`", + r#"bulk(bulk("{ shop { id } }"))"#, + "`bulk(…)` takes the operation as a string literal or `file(\"path.graphql\")`", ), ( - r#"path("x.graphql")"#, - "expected the GraphQL operation as a string literal, or `file(\"path.graphql\")`", + "bulk(1)", + "`bulk(…)` takes the operation as a string literal or `file(\"path.graphql\")`", ), - (r#"file("a", "b")"#, "`file(…)` takes one path"), + (r#"bulk("a", "b")"#, "`bulk(…)` takes one operation"), + (r#"bulk(file("a", "b"))"#, "`file(…)` takes one path"), ( r#""{ shop { name } }", 1"#, "expected a variable: `name = value`", From dea188f3f64e3b7617cb15f87558ecdf324df473 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:13:08 +0100 Subject: [PATCH 108/135] feat(bulk): run typed bulk queries and mutations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Shopify::bulk_query` starts a `graphql!(bulk(…))` query with `groupObjects`, waits, and streams its items (`BulkItems`): each top-level object with the objects of its nested connections in their lists, placed by `__parentId` and `__typename`, one item held at a time. `start_bulk_query` and `download_bulk_items` split it. Shopify takes no variables for a bulk query: `BulkQuery::text` writes them into the text as GraphQL literals, enum values bare, after the checks of any operation. An enum value or a field that is not a GraphQL name is refused (`InvalidValueReason::NotAGraphqlName`). `Shopify::bulk_mutation` checks and writes every line, stages them, runs, and streams `BulkMutationResult`s; `start_bulk_mutation` only starts. Both run at the Admin API version the operation was checked against. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/shopify_api/Cargo.toml | 1 + crates/shopify_api/src/bulk.rs | 37 +- crates/shopify_api/src/bulk/rows.rs | 236 ++++- crates/shopify_api/src/bulk/typed.rs | 926 ++++++++++++++++++++ crates/shopify_api/src/graphql/check.rs | 7 + crates/shopify_api/src/graphql/operation.rs | 16 + crates/shopify_api/src/lib.rs | 1 + crates/shopify_api/tests/bulk_typed.rs | 470 ++++++++++ 9 files changed, 1678 insertions(+), 17 deletions(-) create mode 100644 crates/shopify_api/src/bulk/typed.rs create mode 100644 crates/shopify_api/tests/bulk_typed.rs diff --git a/Cargo.lock b/Cargo.lock index 6149bcd..ba3055a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1437,6 +1437,7 @@ dependencies = [ "chrono", "clap", "futures-core", + "graphql-parser", "hex", "hmac", "reqwest", diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml index 212f058..94d5d94 100644 --- a/crates/shopify_api/Cargo.toml +++ b/crates/shopify_api/Cargo.toml @@ -57,6 +57,7 @@ clap = { workspace = true, optional = true } shopify_api_graphql = { workspace = true, optional = true } [dev-dependencies] +graphql-parser.workspace = true tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time", "test-util", "net", "io-util"] } trybuild.workspace = true diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 553b887..d6e64aa 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -56,8 +56,19 @@ use crate::{Error, Page, Result, Shopify, UserError}; use shopify_api_macros::{__graphql_internal as graphql, __input_internal as input}; mod rows; +mod typed; pub use rows::{BulkGroups, BulkRows, DEFAULT_MAX_LINE_LENGTH}; +pub use typed::{BulkItem, BulkItems, BulkMutation, BulkMutationResult, BulkQuery}; + +/// What the code `graphql!(bulk(…))` generates refers to. Not a public API. +#[doc(hidden)] +pub mod __private { + pub use super::typed::{ + BulkArgument, BulkConnection, BulkItem, BulkPart, BulkTemplate, BulkType, BulkValue, + BulkVariable, push, unplaced, + }; +} /// How long a download waits for the answer, then for each chunk of it; a /// transport that does not stream gives it the whole download. @@ -598,6 +609,23 @@ impl Shopify { I: IntoIterator, I::Item: Serialize, { + self.stage_jsonl(|body| { + for item in variables { + serde_json::to_writer(&mut *body, &item) + .map_err(|error| Error::variables(None, &error))?; + body.push(b'\n'); + } + Ok(()) + }) + .await + } + + /// Reserves an upload target, then uploads the JSONL file `write_file` + /// writes to it. Returns its staged upload path. + async fn stage_jsonl( + &self, + write_file: impl FnOnce(&mut Vec) -> Result<()>, + ) -> Result { let data = self .execute_own(staged_uploads::Variables { input: vec![input!(StagedUploadInput { @@ -643,14 +671,7 @@ impl Shopify { // The storage server wants the length of the body up front: the // file is built in memory, once, in the body itself. let (content_type, body) = - multipart(¶meters, "bulk_op_vars.jsonl", "text/jsonl", |body| { - for item in variables { - serde_json::to_writer(&mut *body, &item) - .map_err(|error| Error::variables(None, &error))?; - body.push(b'\n'); - } - Ok(()) - })?; + multipart(¶meters, "bulk_op_vars.jsonl", "text/jsonl", write_file)?; let request = HttpRequest::new(Method::Post, &url) .with_header("Content-Type", content_type) .with_body(body) diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index 2505a53..6cc5cb3 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -1,6 +1,6 @@ //! The results of a bulk operation, read line by line as they download. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::fmt; use std::marker::PhantomData; use std::ops::Range; @@ -11,6 +11,7 @@ use futures_core::{FusedStream, Stream}; use serde::Deserialize; use serde::de::DeserializeOwned; +use super::typed::BulkItem; use crate::transport::BodyStream; use crate::{Error, Result}; @@ -285,6 +286,20 @@ struct Keys { id: Option, #[serde(rename = "__parentId")] parent_id: Option, + #[serde(rename = "__typename")] + typename: Option, +} + +/// The error of a line whose `__parentId` matches no object it may be a child of. +fn misplaced(number: usize, missing_id: bool, grouped: bool) -> Error { + let message = if missing_id { + "has a `__parentId` that no `id` before it matches, and an object before it has no `id`: select `id`, without an alias, on every object that has nested connections" + } else if grouped { + "is a child of neither the top-level object before it nor one of its children, though the query ran with `groupObjects`" + } else { + "is a child of neither the top-level object before it nor one of its children: run the query with `groupObjects`" + }; + super::bulk_error(format!("line {number} of the results {message}")) } struct Group { @@ -380,14 +395,8 @@ impl BulkGroups { } fn misplaced(&self, number: usize) -> Error { - let message = if self.group.as_ref().is_some_and(|group| group.missing_id) { - "has a `__parentId` that no `id` before it matches, and an object before it has no `id`: select `id`, without an alias, on every object that has nested connections" - } else if self.grouped { - "is a child of neither the top-level object before it nor one of its children, though the query ran with `groupObjects`" - } else { - "is a child of neither the top-level object before it nor one of its children: run the query with `groupObjects`" - }; - super::bulk_error(format!("line {number} of the results {message}")) + let missing_id = self.group.as_ref().is_some_and(|group| group.missing_id); + misplaced(number, missing_id, self.grouped) } /// [`BulkRows::max_line_length`]. @@ -481,6 +490,215 @@ impl FusedStream for BulkGroups } } +struct ItemGroup { + item: I, + /// The `id` of the item. + id: Option, + /// The children of the item that have connections, by `id`: their + /// connection and their index in it. + children: HashMap, + /// An object of the group that has connections has no `id`. + missing_id: bool, +} + +/// The results of a bulk query declared with `graphql!(bulk(…))`, one +/// top-level object at a time, read as its generated `Item` with the +/// objects of its nested connections in their lists. +/// [`Shopify::bulk_query`](crate::Shopify::bulk_query) and +/// [`Shopify::download_bulk_items`](crate::Shopify::download_bulk_items) +/// return it. +/// +/// It reads the lines as [`BulkGroups`] does, in the order `groupObjects` +/// writes: an item is complete when the next top-level object, or the end +/// of the file, arrives. One item is held at a time, with every nested +/// object read so far: its memory follows the largest item, as well as the +/// line being read. +/// +/// A nested line goes to its parent by its `__parentId`, and, when its +/// parent has several connections, to the connection that returns its +/// `__typename`, which [`BulkQuery::text`](crate::bulk::BulkQuery::text) +/// selects for that. +/// +/// # Errors +/// +/// Any error ends the stream: a line that does not read as its type, a +/// nested line out of place, the errors of [`BulkRows`] and those of +/// [`BulkGroups`]. +#[must_use = "a stream does nothing until it is read"] +pub struct BulkItems { + lines: Lines, + group: Option>, + grouped: bool, +} + +impl Unpin for BulkItems {} + +impl fmt::Debug for BulkItems { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BulkItems") + .field("lines", &self.lines) + .finish_non_exhaustive() + } +} + +impl BulkItems { + pub(crate) fn new(body: Option, url: &str) -> Self { + Self { + lines: Lines::new(body, url), + group: None, + grouped: false, + } + } + + pub(crate) fn grouped(mut self) -> Self { + self.grouped = true; + self + } + + /// [`BulkRows::max_line_length`]. + pub fn max_line_length(mut self, bytes: usize) -> Self { + self.lines.max = bytes; + self + } + + /// The number of the last line read, from 1, blank lines included. + pub fn line(&self) -> usize { + self.lines.line + } + + fn fail(&mut self, error: Error) -> Poll>> { + self.lines.finish(); + self.group = None; + Poll::Ready(Some(Err(error))) + } +} + +impl BulkItems { + /// The next item, `None` at the end of the file. + pub async fn next_item(&mut self) -> Option> { + std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context)).await + } + + /// Every item, up to the first error. + pub async fn collect(mut self) -> Result> { + let mut items = Vec::new(); + while let Some(item) = self.next_item().await { + items.push(item?); + } + Ok(items) + } + + /// Places the nested line `number` in the item of `group`. + fn attach( + group: Option<&mut ItemGroup>, + grouped: bool, + keys: Keys, + parent_id: &str, + line: &[u8], + number: usize, + ) -> Result<()> { + let Some(group) = group else { + return Err(misplaced(number, false, grouped)); + }; + let (parent, connections) = if group.id.as_deref() == Some(parent_id) { + (None, I::CONNECTIONS) + } else if let Some(&(slot, index)) = group.children.get(parent_id) { + (Some((slot, index)), I::CONNECTIONS[slot].connections) + } else { + return Err(misplaced(number, group.missing_id, grouped)); + }; + let slot = match connections { + [] => return Err(misplaced(number, group.missing_id, grouped)), + [_] => 0, + _ => { + let typename = keys.typename.as_deref().ok_or_else(|| { + super::bulk_error(format!( + "line {number} of the results has no `__typename`, which tells which connection of its parent it belongs to" + )) + })?; + connections + .iter() + .position(|connection| connection.types.contains(&typename)) + .ok_or_else(|| { + super::bulk_error(format!( + "line {number} of the results has a `__typename` that no connection of its parent returns" + )) + })? + } + }; + let index = group.item.__attach(parent, slot, line, number)?; + if parent.is_none() && !I::CONNECTIONS[slot].connections.is_empty() { + match keys.id { + Some(id) => { + group.children.insert(id, (slot, index)); + } + None => group.missing_id = true, + } + } + Ok(()) + } +} + +impl Stream for BulkItems { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + loop { + let (number, range) = match this.lines.poll_line(context) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + return Poll::Ready(this.group.take().map(|group| Ok(group.item))); + } + Poll::Ready(Some(Err(error))) => return this.fail(error), + Poll::Ready(Some(Ok(line))) => line, + }; + let line = &this.lines.buffer[range]; + let keys = match crate::decode::from_jsonl_line::(line, number) { + Ok(keys) => keys, + Err(error) => return this.fail(error), + }; + match keys.parent_id.clone() { + None => { + let item = match crate::decode::from_jsonl_line::(line, number) { + Ok(item) => item, + Err(error) => return this.fail(error), + }; + let next = ItemGroup { + item, + missing_id: keys.id.is_none() && !I::CONNECTIONS.is_empty(), + id: keys.id, + children: HashMap::new(), + }; + if let Some(done) = this.group.replace(next) { + return Poll::Ready(Some(Ok(done.item))); + } + } + Some(parent_id) => { + let attached = Self::attach( + this.group.as_mut(), + this.grouped, + keys, + &parent_id, + line, + number, + ); + if let Err(error) = attached { + return this.fail(error); + } + } + } + } + } +} + +impl FusedStream for BulkItems { + fn is_terminated(&self) -> bool { + self.lines.done && self.group.is_none() + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/shopify_api/src/bulk/typed.rs b/crates/shopify_api/src/bulk/typed.rs new file mode 100644 index 0000000..b6fcb4e --- /dev/null +++ b/crates/shopify_api/src/bulk/typed.rs @@ -0,0 +1,926 @@ +//! Bulk operations declared with `graphql!(bulk(…))`: checked when the +//! crate compiles, their results read as the types it generates. + +use std::fmt; + +use serde::Deserialize; +use serde::de::DeserializeOwned; +use serde_json::value::RawValue; + +use super::{ + BulkOperation, BulkRows, BulkWaitOptions, bulk_error, run_mutation, run_query, started, +}; +use crate::error::is_graphql_name; +use crate::graphql::check::Invalid; +use crate::{ + Error, GraphqlError, IntoVariable, InvalidValueReason, Operation, OperationKind, Result, + Shopify, VariableType, +}; + +pub use super::rows::BulkItems; + +/// The text of a bulk query, with its variables apart. Not a public API. +#[doc(hidden)] +#[derive(Debug)] +pub struct BulkTemplate { + pub parts: &'static [BulkPart], + pub variables: &'static [BulkVariable], +} + +#[doc(hidden)] +#[derive(Debug)] +pub enum BulkPart { + Text(&'static str), + /// `(name: value, …)`, where a value holds a variable. + Arguments(&'static [BulkArgument]), +} + +#[doc(hidden)] +#[derive(Debug)] +pub struct BulkArgument { + pub name: &'static str, + pub value: BulkValue, +} + +#[doc(hidden)] +#[derive(Debug)] +pub enum BulkValue { + /// A constant, as GraphQL text. + Text(&'static str), + /// The variable of this index in [`BulkTemplate::variables`]. + Variable(usize), + List(&'static [BulkValue]), + Object(&'static [BulkArgument]), +} + +#[doc(hidden)] +#[derive(Debug)] +pub struct BulkVariable { + pub name: &'static str, + pub ty: BulkType, + /// Its default value, as GraphQL text. + pub default: Option<&'static str>, +} + +/// Where the enum values of a variable are: they are written bare. +#[doc(hidden)] +#[derive(Debug)] +pub enum BulkType { + /// No enum value. + Plain, + Enum, + List(&'static BulkType), + /// An input object: its fields that hold enum values. + Input(&'static [(&'static str, BulkType)]), +} + +/// A nested connection of a bulk query, and where its lines go. +#[doc(hidden)] +#[derive(Debug)] +pub struct BulkConnection { + pub key: &'static str, + /// The `__typename`s of its nodes. + pub types: &'static [&'static str], + pub connections: &'static [BulkConnection], +} + +/// The type of a top-level object of a bulk query declared with +/// `graphql!(bulk(…))`, which `graphql!` implements: the item of +/// [`BulkItems`]. Its items are not a public API. +pub trait BulkItem: DeserializeOwned { + /// The nested connections of the item, in the order of their slots. + #[doc(hidden)] + const CONNECTIONS: &'static [BulkConnection]; + + /// Reads `line` as an object of the connection `slot` of the item, or, + /// with `parent`, of the child `parent.1` of the connection `parent.0`. + /// Returns its index in its list. + #[doc(hidden)] + fn __attach( + &mut self, + parent: Option<(usize, usize)>, + slot: usize, + line: &[u8], + number: usize, + ) -> Result; +} + +/// What `BulkItem::__attach` pushes with. Not a public API. +#[doc(hidden)] +pub fn push(list: &mut Vec, line: &[u8], number: usize) -> Result { + list.push(crate::decode::from_jsonl_line(line, number)?); + Ok(list.len() - 1) +} + +/// The error of a line `BulkItem::__attach` has no place for. Not a public API. +#[doc(hidden)] +pub fn unplaced() -> Error { + bulk_error("a nested line of the results has no place in the item") +} + +/// A bulk query checked by `graphql!(bulk("…"))`, and its variables. Its +/// results are read as `I`, one top-level object at a time. +/// +/// Shopify takes no variables for a bulk query: [`BulkQuery::text`] writes +/// them into the text. +pub struct BulkQuery { + operation: Operation, + template: &'static BulkTemplate, +} + +impl BulkQuery { + /// What `graphql!` builds. + #[doc(hidden)] + pub fn __checked( + template: &'static BulkTemplate, + query: &'static str, + name: Option<&'static str>, + checked_against: &'static str, + ) -> Self { + Self { + operation: Operation::__checked(query, OperationKind::Query, name, checked_against), + template, + } + } + + /// What the `Variables` of a `graphql!` module set a variable with. + #[doc(hidden)] + pub fn __variable(mut self, name: &str, value: T) -> Self { + self.operation = self.operation.__variable(name, value); + self + } + + /// What `graphql!` sets a variable written as a Rust expression with. + #[doc(hidden)] + pub fn __converted_variable>( + mut self, + name: &str, + value: V, + ) -> Self { + self.operation = self.operation.variable(name, value); + self + } + + /// What `graphql!` sets a variable written as a literal to. + #[doc(hidden)] + pub fn __literal_variable( + mut self, + name: &str, + value: std::result::Result, Invalid>, + ) -> Self { + self.operation = self.operation.__literal_variable(name, value); + self + } + + /// The text of the query as written, with its variables. + pub fn query(&self) -> &str { + self.operation.query() + } + + /// The Admin API version the query was checked against. + pub fn checked_against(&self) -> Option<&'static str> { + self.operation.checked_against() + } + + /// The text Shopify runs: without variable definitions, each variable + /// written in as a GraphQL literal (an enum value bare, an input object + /// as `{field: value}`), and `__typename` selected on the nodes of the + /// connections that share a parent, which tells their lines apart. A + /// variable without a value is left out, as GraphQL leaves out an + /// argument whose variable has none, or takes its default value. + /// + /// Fails with [`Error::InvalidValue`] for a value the variables refuse + /// ([`Shopify::execute`] would), and for an enum value or a field name + /// that is not a GraphQL name. + pub fn text(&self) -> Result { + let values = self.operation.variable_values()?; + let writer = Writer { + template: self.template, + values, + }; + let mut text = String::new(); + for part in self.template.parts { + match part { + BulkPart::Text(part) => text.push_str(part), + BulkPart::Arguments(arguments) => { + let written = writer.arguments(arguments)?; + if !written.is_empty() { + text.push('('); + text.push_str(&written.join(", ")); + text.push(')'); + } + } + } + } + Ok(text) + } +} + +impl Clone for BulkQuery { + fn clone(&self) -> Self { + Self { + operation: self.operation.clone(), + template: self.template, + } + } +} + +impl fmt::Debug for BulkQuery { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BulkQuery") + .field("operation", &self.operation) + .finish_non_exhaustive() + } +} + +/// Writes the variables of a bulk query into its text. +struct Writer<'a> { + template: &'static BulkTemplate, + values: &'a [(String, Box)], +} + +impl Writer<'_> { + /// `name: value` for each argument whose value is not left out. + fn arguments(&self, arguments: &[BulkArgument]) -> Result> { + let mut written = Vec::new(); + for argument in arguments { + if let Some(value) = self.value(&argument.value)? { + written.push(format!("{}: {value}", argument.name)); + } + } + Ok(written) + } + + /// The value as GraphQL text, `None` when its variable has no value. + fn value(&self, value: &BulkValue) -> Result> { + match value { + BulkValue::Text(text) => Ok(Some((*text).to_string())), + BulkValue::Variable(index) => { + let variable = &self.template.variables[*index]; + match self.values.iter().find(|(name, _)| name == variable.name) { + Some((_, json)) => { + let mut text = String::new(); + Json::new(json.get()) + .write(&variable.ty, &mut text) + .map_err(|invalid| invalid.into_error(variable.name))?; + Ok(Some(text)) + } + None => Ok(variable.default.map(str::to_string)), + } + } + BulkValue::List(items) => { + let mut written = Vec::new(); + for item in *items { + // An item whose variable has no value is `null`. + written.push(self.value(item)?.unwrap_or_else(|| "null".to_string())); + } + Ok(Some(format!("[{}]", written.join(", ")))) + } + BulkValue::Object(fields) => { + Ok(Some(format!("{{{}}}", self.arguments(fields)?.join(", ")))) + } + } + } +} + +/// Reads the JSON of a value, which `serde_json` wrote, and writes it as a +/// GraphQL literal: strings and numbers as JSON writes them, which GraphQL +/// reads alike, enum values bare, object keys unquoted. +struct Json<'a> { + text: &'a [u8], + at: usize, +} + +impl<'a> Json<'a> { + fn new(text: &'a str) -> Self { + Self { + text: text.as_bytes(), + at: 0, + } + } + + fn skip_whitespace(&mut self) { + while self + .text + .get(self.at) + .is_some_and(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r')) + { + self.at += 1; + } + } + + /// The JSON text of the string that starts here, quotes included. + fn string(&mut self) -> &'a str { + let start = self.at; + self.at += 1; + while let Some(byte) = self.text.get(self.at) { + match byte { + b'\\' => self.at += 2, + b'"' => { + self.at += 1; + break; + } + _ => self.at += 1, + } + } + let end = self.at.min(self.text.len()); + // Cut at ASCII quotes of UTF-8 text: still UTF-8. + std::str::from_utf8(&self.text[start..end]).unwrap_or("\"\"") + } + + fn name(token: &str) -> std::result::Result { + let name: String = serde_json::from_str(token) + .map_err(|_| Invalid::new(InvalidValueReason::NotAGraphqlName))?; + if is_graphql_name(&name) { + Ok(name) + } else { + Err(Invalid::new(InvalidValueReason::NotAGraphqlName)) + } + } + + fn write(&mut self, ty: &BulkType, out: &mut String) -> std::result::Result<(), Invalid> { + self.skip_whitespace(); + match self.text.get(self.at) { + Some(b'[') => { + self.at += 1; + let item = match ty { + BulkType::List(item) => item, + other => other, + }; + out.push('['); + let mut index = 0; + loop { + self.skip_whitespace(); + match self.text.get(self.at) { + Some(b']') | None => { + self.at += 1; + break; + } + Some(b',') => { + self.at += 1; + continue; + } + _ => {} + } + if index > 0 { + out.push_str(", "); + } + self.write(item, out) + .map_err(|invalid| invalid.index(index))?; + index += 1; + } + out.push(']'); + } + Some(b'{') => { + self.at += 1; + let fields = match element(ty) { + BulkType::Input(fields) => *fields, + _ => &[], + }; + out.push('{'); + let mut first = true; + loop { + self.skip_whitespace(); + match self.text.get(self.at) { + Some(b'}') | None => { + self.at += 1; + break; + } + Some(b',') => { + self.at += 1; + continue; + } + _ => {} + } + let key = self.string(); + let key = Self::name(key)?; + self.skip_whitespace(); + // The `:` after the key. + self.at += 1; + if !first { + out.push_str(", "); + } + first = false; + out.push_str(&key); + out.push_str(": "); + match fields.iter().find(|(name, _)| *name == key) { + Some((name, field)) => self + .write(field, out) + .map_err(|invalid| invalid.field(name))?, + None => self.write(&BulkType::Plain, out)?, + } + } + out.push('}'); + } + Some(b'"') => { + let token = self.string(); + if matches!(element(ty), BulkType::Enum) { + out.push_str(&Self::name(token)?); + } else { + out.push_str(token); + } + } + _ => { + // `true`, `false`, `null` or a number, which read alike. + let start = self.at; + while self.text.get(self.at).is_some_and(|byte| { + !matches!(byte, b',' | b']' | b'}' | b' ' | b'\t' | b'\n' | b'\r') + }) { + self.at += 1; + } + out.push_str(std::str::from_utf8(&self.text[start..self.at]).unwrap_or("null")); + } + } + Ok(()) + } +} + +/// The type of a value that is not a list where `ty` stands: GraphQL reads +/// a single value where a list is expected as its one item. +fn element(ty: &BulkType) -> &BulkType { + match ty { + BulkType::List(item) => element(item), + other => other, + } +} + +/// One line of a bulk mutation checked by `graphql!(bulk("mutation …"))`: +/// the variables of one run of the mutation. +/// [`Shopify::bulk_mutation`] runs an iterator of them. +pub struct BulkMutation { + operation: Operation, +} + +impl BulkMutation { + /// What `graphql!` builds. + #[doc(hidden)] + pub fn __checked( + query: &'static str, + name: Option<&'static str>, + checked_against: &'static str, + ) -> Self { + Self { + operation: Operation::__checked(query, OperationKind::Mutation, name, checked_against), + } + } + + /// What the `Variables` of a `graphql!` module set a variable with. + #[doc(hidden)] + pub fn __variable(mut self, name: &str, value: T) -> Self { + self.operation = self.operation.__variable(name, value); + self + } + + /// What `graphql!` sets a variable written as a Rust expression with. + #[doc(hidden)] + pub fn __converted_variable>( + mut self, + name: &str, + value: V, + ) -> Self { + self.operation = self.operation.variable(name, value); + self + } + + /// What `graphql!` sets a variable written as a literal to. + #[doc(hidden)] + pub fn __literal_variable( + mut self, + name: &str, + value: std::result::Result, Invalid>, + ) -> Self { + self.operation = self.operation.__literal_variable(name, value); + self + } + + /// The text of the mutation. + pub fn query(&self) -> &str { + self.operation.query() + } + + /// The Admin API version the mutation was checked against. + pub fn checked_against(&self) -> Option<&'static str> { + self.operation.checked_against() + } + + /// The line of the JSONL file of variables: the variables as one JSON + /// object. Fails as [`Shopify::execute`] would for a value refused. + pub fn line(&self) -> Result { + let values = self.operation.variable_values()?; + let mut line = String::from("{"); + for (index, (name, value)) in values.iter().enumerate() { + if index > 0 { + line.push(','); + } + line.push_str( + &serde_json::to_string(name).map_err(|error| Error::variables(None, &error))?, + ); + line.push(':'); + line.push_str(value.get()); + } + line.push('}'); + Ok(line) + } +} + +impl Clone for BulkMutation { + fn clone(&self) -> Self { + Self { + operation: self.operation.clone(), + } + } +} + +impl fmt::Debug for BulkMutation { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BulkMutation") + .field("operation", &self.operation) + .finish() + } +} + +/// A line of the results of a bulk mutation: what one run of the mutation +/// returned. Shopify runs the lines in no set order: `index` tells which +/// line of variables it ran with. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[non_exhaustive] +pub struct BulkMutationResult { + /// The `data` of the mutation; its `userErrors` are in it. + #[serde(default = "none")] + pub data: Option, + /// The errors of the run: a variable Shopify refused, a missing scope. + #[serde(default)] + pub errors: Vec, + /// The line of variables it ran with, from 0: Shopify's `__lineNumber`. + /// Shopify's documentation does not show it on every line of errors. + #[serde(rename = "__lineNumber", default)] + pub index: Option, +} + +fn none() -> Option { + None +} + +/// The lines of a bulk mutation, checked and written as its JSONL file. +struct Lines { + mutation: String, + checked_against: Option<&'static str>, + jsonl: Vec, +} + +impl Lines { + /// `None` when there is no line. + fn of>>(lines: impl IntoIterator) -> Result> { + let mut lines = lines.into_iter().map(Into::into); + let Some(first) = lines.next() else { + return Ok(None); + }; + let mut jsonl = first.line()?.into_bytes(); + jsonl.push(b'\n'); + for (index, line) in lines.enumerate() { + if line.query() != first.query() { + return Err(bulk_error(format!( + "line {} of the bulk mutation was built from another mutation than line 1: a bulk operation runs one mutation", + index + 2 + ))); + } + jsonl.extend_from_slice(line.line()?.as_bytes()); + jsonl.push(b'\n'); + } + Ok(Some(Self { + mutation: first.query().to_string(), + checked_against: first.checked_against(), + jsonl, + })) + } +} + +impl Shopify { + /// Runs a bulk query declared with `graphql!(bulk(…))` to its end, then + /// reads its results one top-level object at a time, with the objects + /// of its nested connections in their lists, as they download (see + /// [`BulkItems`]). Fails when the operation does not complete. + /// + /// It runs with `groupObjects`, which [`BulkItems`] needs: Shopify is + /// slower with it, and more likely to time out. + /// + /// ```no_run + /// use shopify_api::bulk::BulkWaitOptions; + /// + /// shopify_api::graphql! { + /// mod all_products = bulk("query($filter: String) { + /// products(query: $filter) { edges { node { + /// id title + /// variants { edges { node { sku } } } + /// } } } + /// }"); + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let mut products = shopify + /// .bulk_query( + /// all_products::Variables { filter: Some("status:active".into()) }, + /// BulkWaitOptions::default(), + /// ) + /// .await?; + /// while let Some(product) = products.next_item().await { + /// let product = product?; + /// println!("{} has {} variants", product.title, product.variants.len()); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn bulk_query( + &self, + query: impl Into>, + options: BulkWaitOptions, + ) -> Result> { + let operation = self.start_bulk_query(query).await?; + match self.completed_url(&operation.id, options).await? { + Some(url) => Ok(self.download_bulk_items(&url).await?.grouped()), + None => Ok(BulkItems::new(None, "").grouped()), + } + } + + /// Starts a bulk query declared with `graphql!(bulk(…))`, with + /// `groupObjects`, and returns the operation: wait for it with + /// [`Shopify::wait_for_bulk_operation`], then read its results with + /// [`Shopify::download_bulk_items`]. + /// + /// It sends [`BulkQuery::text`] to the Admin API version the query was + /// checked against, as [`Shopify::execute`] would. + pub async fn start_bulk_query( + &self, + query: impl Into>, + ) -> Result { + let query = query.into(); + let text = query.text()?; + let operation = Operation::from(run_query::Variables { + query: text, + group_objects: true, + }) + .checked_as(query.checked_against()); + let data = self.execute(operation).await?; + let payload = data + .bulk_operation_run_query + .ok_or_else(|| bulk_error("bulkOperationRunQuery returned nothing"))?; + started( + "bulkOperationRunQuery", + payload.bulk_operation, + &payload.user_errors, + ) + } + + /// Downloads the results of a bulk query started with + /// [`Shopify::start_bulk_query`], its `url` or its `partial_data_url`, + /// and reads them as [`Shopify::bulk_query`] does. The item type names + /// the query: `all_products::Item`. + /// + /// ```no_run + /// use shopify_api::bulk::{BulkOperationStatus, BulkWaitOptions}; + /// + /// shopify_api::graphql! { + /// mod all_products = bulk("{ products { edges { node { id title } } } }"); + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let started = shopify.start_bulk_query(all_products::operation()).await?; + /// let operation = shopify + /// .wait_for_bulk_operation(&started.id, BulkWaitOptions::default()) + /// .await?; + /// if let (BulkOperationStatus::Completed, Some(url)) = (&operation.status, &operation.url) { + /// let products: Vec = + /// shopify.download_bulk_items(url).await?.collect().await?; + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn download_bulk_items(&self, url: &str) -> Result> { + let body = self.open_bulk_results(url).await?; + Ok(BulkItems::new(Some(body), url)) + } + + /// Runs a bulk mutation declared with `graphql!(bulk("mutation …"))` + /// over `lines`, the variables of each run, to its end; then reads the + /// result of each run as it downloads. Fails when the operation does + /// not complete. + /// + /// Every line is checked and written before anything is sent: a value + /// refused fails as [`Shopify::execute`] would, and a line of another + /// mutation with [`Error::Bulk`]. Without lines, nothing runs and no + /// result is read. + /// + /// ```no_run + /// use shopify_api::bulk::BulkWaitOptions; + /// + /// shopify_api::graphql! { + /// mod add_tags = bulk("mutation($id: ID!, $tags: [String!]!) { + /// tagsAdd(id: $id, tags: $tags) { userErrors { field message } } + /// }"); + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let ids = ["gid://shopify/Product/1", "gid://shopify/Product/2"]; + /// let lines = ids.iter().map(|id| add_tags::Variables { + /// id: id.to_string(), + /// tags: vec!["sale".to_string()], + /// }); + /// let mut results = shopify.bulk_mutation(lines, BulkWaitOptions::default()).await?; + /// while let Some(result) = results.next_row().await { + /// let result = result?; + /// let errors = result.data.and_then(|data| data.tags_add).map(|payload| payload.user_errors); + /// println!("line {:?}: {errors:?}", result.index); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn bulk_mutation( + &self, + lines: impl IntoIterator, + options: BulkWaitOptions, + ) -> Result>> + where + D: DeserializeOwned, + L: Into>, + { + let Some(lines) = Lines::of(lines)? else { + return Ok(BulkRows::new(None, "")); + }; + let operation = self.start_lines(lines).await?; + match self.completed_url(&operation.id, options).await? { + Some(url) => self.download_bulk_results_stream(&url).await, + None => Ok(BulkRows::new(None, "")), + } + } + + /// Starts a bulk mutation declared with `graphql!(bulk("mutation …"))` + /// over `lines`, and returns the operation. Its results read as + /// [`BulkMutationResult`]s with [`Shopify::download_bulk_results_stream`]. + /// + /// Every line is checked and written before anything is sent, as + /// [`Shopify::bulk_mutation`] does. Fails with [`Error::Bulk`] without lines. + pub async fn start_bulk_mutation( + &self, + lines: impl IntoIterator, + ) -> Result + where + L: Into>, + { + let lines = Lines::of(lines)? + .ok_or_else(|| bulk_error("a bulk mutation needs one line of variables at least"))?; + self.start_lines(lines).await + } + + async fn start_lines(&self, lines: Lines) -> Result { + let jsonl = lines.jsonl; + let path = self + .stage_jsonl(move |body| { + body.extend_from_slice(&jsonl); + Ok(()) + }) + .await?; + let operation = Operation::from(run_mutation::Variables { + mutation: lines.mutation, + staged_upload_path: path, + client_identifier: None, + }) + .checked_as(lines.checked_against); + let data = self.execute(operation).await?; + let payload = data + .bulk_operation_run_mutation + .ok_or_else(|| bulk_error("bulkOperationRunMutation returned nothing"))?; + started( + "bulkOperationRunMutation", + payload.bulk_operation, + &payload.user_errors, + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn written(json: &str, ty: &BulkType) -> std::result::Result { + let mut out = String::new(); + Json::new(json) + .write(ty, &mut out) + .map(|()| out) + .map_err(|invalid| invalid.into_error("v").to_string()) + } + + static COLORS: BulkType = BulkType::List(&BulkType::Enum); + static INPUT_FIELDS: [(&str, BulkType); 2] = [ + ("status", BulkType::Enum), + ("nested", BulkType::Input(&INPUT_FIELDS)), + ]; + static INPUT: BulkType = BulkType::Input(&INPUT_FIELDS); + + #[test] + fn strings_keep_the_escapes_of_json() { + for (value, expected) in [ + ("plain", r#""plain""#), + ("a \"quoted\" word", r#""a \"quoted\" word""#), + ("back\\slash", r#""back\\slash""#), + ("two\nlines\r\tand a tab", r#""two\nlines\r\tand a tab""#), + ("café ☕ 𝄞", "\"café ☕ 𝄞\""), + ("\u{1}\u{1f}", r#""\u0001\u001f""#), + ("$filter and ${x}", r#""$filter and ${x}""#), + ("\"\"\" block", r#""\"\"\" block""#), + ] { + let json = serde_json::to_string(value).unwrap(); + assert_eq!( + written(&json, &BulkType::Plain).unwrap(), + expected, + "{value:?}" + ); + // GraphQL reads it back as the same string. + let query = format!("{{ f(a: {expected}) }}"); + let document = graphql_parser::parse_query::(&query).unwrap(); + let graphql_parser::query::Definition::Operation( + graphql_parser::query::OperationDefinition::SelectionSet(set), + ) = &document.definitions[0] + else { + panic!("a selection set"); + }; + let graphql_parser::query::Selection::Field(field) = &set.items[0] else { + panic!("a field"); + }; + assert_eq!( + field.arguments[0].1, + graphql_parser::query::Value::String(value.to_string()), + "{value:?}" + ); + } + } + + #[test] + fn scalars_are_written_as_json_writes_them() { + assert_eq!(written("12", &BulkType::Plain).unwrap(), "12"); + assert_eq!(written("-1.5e300", &BulkType::Plain).unwrap(), "-1.5e300"); + assert_eq!(written("true", &BulkType::Plain).unwrap(), "true"); + assert_eq!(written("null", &BulkType::Plain).unwrap(), "null"); + assert_eq!(written("null", &BulkType::Enum).unwrap(), "null"); + assert_eq!( + written("[[1,2],[],[null]]", &BulkType::Plain).unwrap(), + "[[1, 2], [], [null]]" + ); + } + + #[test] + fn enum_values_are_bare_wherever_they_stand() { + assert_eq!(written(r#""ACTIVE""#, &BulkType::Enum).unwrap(), "ACTIVE"); + assert_eq!( + written(r#"["RED","BLUE"]"#, &COLORS).unwrap(), + "[RED, BLUE]" + ); + // One value where a list is expected. + assert_eq!(written(r#""RED""#, &COLORS).unwrap(), "RED"); + assert_eq!( + written( + r#"{"status":"DRAFT","title":"A \"b\"","nested":{"status":"ACTIVE","tags":["X"]}}"#, + &INPUT + ) + .unwrap(), + r#"{status: DRAFT, title: "A \"b\"", nested: {status: ACTIVE, tags: ["X"]}}"# + ); + assert_eq!( + written( + r#"[{"status":"DRAFT"},{"status":null}]"#, + &BulkType::List(&INPUT) + ) + .unwrap(), + "[{status: DRAFT}, {status: null}]" + ); + // A string is not an enum value where none is expected. + assert_eq!( + written(r#""ACTIVE""#, &BulkType::Plain).unwrap(), + r#""ACTIVE""# + ); + } + + #[test] + fn what_is_not_a_graphql_name_is_refused() { + for (json, ty, path) in [ + (r#""ACTIVE) { x }""#, &BulkType::Enum, "$v"), + (r#""""#, &BulkType::Enum, "$v"), + (r#"["RED","1BLUE"]"#, &COLORS, "$v[1]"), + ( + r#"{"nested":{"status":"no way"}}"#, + &INPUT, + "$v.nested.status", + ), + (r#"{"a b":1}"#, &BulkType::Plain, "$v"), + ] { + assert_eq!( + written(json, ty).unwrap_err(), + format!( + "invalid value at `{path}`: not a GraphQL name, as an enum value or a field written into a bulk query must be" + ), + "{json}" + ); + } + } +} diff --git a/crates/shopify_api/src/graphql/check.rs b/crates/shopify_api/src/graphql/check.rs index be15c20..d9e4f6c 100644 --- a/crates/shopify_api/src/graphql/check.rs +++ b/crates/shopify_api/src/graphql/check.rs @@ -25,6 +25,10 @@ pub enum InvalidValueReason { NullJson, /// A value whose `Serialize` implementation failed. Unserializable, + /// An enum value or an input field name that is not a GraphQL name: a + /// bulk query writes its variables into its text, where it would not + /// read as written. + NotAGraphqlName, } impl std::fmt::Display for InvalidValueReason { @@ -34,6 +38,9 @@ impl std::fmt::Display for InvalidValueReason { Self::IntOutOfRange => "Int out of 32-bit range", Self::NullJson => "null for a non-null JSON field", Self::Unserializable => "could not serialize", + Self::NotAGraphqlName => { + "not a GraphQL name, as an enum value or a field written into a bulk query must be" + } }) } } diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs index c24fd1d..2597016 100644 --- a/crates/shopify_api/src/graphql/operation.rs +++ b/crates/shopify_api/src/graphql/operation.rs @@ -291,6 +291,22 @@ impl Operation { self.own } + /// Sends the operation as one checked against `version`, not as one of + /// this crate's: a bulk operation runs the operation of the caller. + pub(crate) fn checked_as(mut self, version: Option<&'static str>) -> Self { + self.checked_against = version; + self.own = false; + self + } + + /// The variables set, each as the JSON it is sent as; an error when one + /// was refused. + pub(crate) fn variable_values(&self) -> Result<&[(String, Box)]> { + self.variables + .as_deref() + .map_err(|failure| failure.to_error()) + } + /// The Admin API version the operation is sent to when the client pins /// none: the one it was checked against, else [`ApiVersion::DEFAULT`]. pub fn api_version(&self) -> Result { diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index 2c39862..beb772c 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -107,6 +107,7 @@ pub use shopify_api_macros::input; /// What the code `graphql!` and `input!` generate refers to. Not a public API. #[doc(hidden)] pub mod __private { + pub use crate::bulk::__private as bulk; pub use crate::graphql::literal; pub use serde; pub use serde_json; diff --git a/crates/shopify_api/tests/bulk_typed.rs b/crates/shopify_api/tests/bulk_typed.rs new file mode 100644 index 0000000..56cac33 --- /dev/null +++ b/crates/shopify_api/tests/bulk_typed.rs @@ -0,0 +1,470 @@ +//! Bulk operations declared with `graphql!(bulk(…))`, against a scripted Shopify. +#![cfg(feature = "testing")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde_json::{Value, json}; +use shopify_api::bulk::{BulkMutation, BulkMutationResult, BulkWaitOptions}; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::transport::{HttpRequest, HttpResponse}; +use shopify_api::{Error, InvalidValueReason, graphql}; + +const RESULTS_URL: &str = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-east1/bulk-operation-outputs/1.jsonl"; +const UPLOAD_URL: &str = "https://shopify-staged-uploads.storage.googleapis.com/"; + +graphql! { + /// Products, their variants with their metafields, and their images. + pub mod catalog = bulk("{ + products(query: \"status:active\") { edges { node { + id title + variants { edges { node { id sku metafields { edges { node { key value } } } } } } + media { edges { node { ... on MediaImage { id alt } } } } + } } } + }"); + + mod by_title = bulk("query($filter: String, $sort: ProductSortKeys = TITLE) { + products(query: $filter, sortKey: $sort, reverse: true) { edges { node { id } } } + }"); + + mod add_tags = bulk("mutation($id: ID!, $tags: [String!]!) { + tagsAdd(id: $id, tags: $tags) { userErrors { field message } } + }"); +} + +fn operation(kind: &str, status: &str, url: Option<&str>) -> Value { + json!({ + "id": "gid://shopify/BulkOperation/1", + "type": kind, + "status": status, + "errorCode": null, + "createdAt": "2026-10-22T10:00:00Z", + "completedAt": if status == "COMPLETED" { json!("2026-10-22T10:01:00Z") } else { Value::Null }, + "objectCount": "2", + "rootObjectCount": "2", + "fileSize": url.map(|_| "120"), + "url": url, + "partialDataUrl": null, + "query": "{ products { edges { node { id } } } }", + }) +} + +fn operation_name(request: &HttpRequest) -> Option { + request + .json()? + .get("operationName")? + .as_str() + .map(str::to_string) +} + +fn fast() -> BulkWaitOptions { + BulkWaitOptions::new().poll_interval(Duration::from_millis(1)) +} + +/// A Shopify that runs any bulk operation at once, its results `jsonl`; +/// the uploads it receives go to `uploads`. +fn shopify_with(jsonl: &'static str) -> (MockTransport, Arc>>) { + let mock = MockTransport::new(); + let uploads = Arc::new(Mutex::new(Vec::new())); + let seen = uploads.clone(); + mock.respond_with(move |request| { + if request.url == RESULTS_URL { + return Ok(HttpResponse::new(200, jsonl)); + } + if request.url == UPLOAD_URL { + seen.lock().unwrap().push(request.clone()); + return Ok(HttpResponse::new(201, "")); + } + let data = match operation_name(request).as_deref() { + Some("BulkOperationRunQuery") => json!({ "bulkOperationRunQuery": { + "bulkOperation": operation("QUERY", "CREATED", None), "userErrors": [], + } }), + Some("BulkOperationRunMutation") => json!({ "bulkOperationRunMutation": { + "bulkOperation": operation("MUTATION", "CREATED", None), "userErrors": [], + } }), + Some("StagedUploadsCreate") => json!({ "stagedUploadsCreate": { + "stagedTargets": [{ + "url": UPLOAD_URL, + "resourceUrl": null, + "parameters": [{ "name": "key", "value": "tmp/1/bulk/vars.jsonl" }], + }], + "userErrors": [], + } }), + Some("BulkOperation") => { + json!({ "bulkOperation": operation("QUERY", "COMPLETED", Some(RESULTS_URL)) }) + } + other => panic!("unexpected operation {other:?}"), + }; + Ok(HttpResponse::json(200, &json!({ "data": data }))) + }); + (mock, uploads) +} + +const CATALOG: &str = r#"{"id":"gid://shopify/Product/1","title":"Shirt"} +{"__typename":"ProductVariant","id":"gid://shopify/ProductVariant/1","sku":"S-1","__parentId":"gid://shopify/Product/1"} +{"key":"color","value":"red","__parentId":"gid://shopify/ProductVariant/1"} +{"__typename":"MediaImage","id":"gid://shopify/MediaImage/1","alt":"Front","__parentId":"gid://shopify/Product/1"} +{"key":"size","value":"M","__parentId":"gid://shopify/ProductVariant/1"} +{"__typename":"ProductVariant","id":"gid://shopify/ProductVariant/2","sku":null,"__parentId":"gid://shopify/Product/1"} +{"__typename":"Video","__parentId":"gid://shopify/Product/1"} +{"id":"gid://shopify/Product/2","title":"Hat"} +"#; + +#[tokio::test] +async fn a_bulk_query_sends_its_text_with_group_objects_and_reads_its_items() { + let (mock, _) = shopify_with(CATALOG); + let shopify = client(&mock); + + let products: Vec = shopify + .bulk_query(catalog::operation(), fast()) + .await + .unwrap() + .collect() + .await + .unwrap(); + + let start = &mock.graphql_requests()[0]; + // `__typename` on the nodes of the two connections of a product, which + // tells their lines apart; not on those of `metafields`, alone under + // its variant. + assert_eq!( + start.variables, + json!({ + "query": "{ products(query: \"status:active\") { edges { node { id title \ + variants { edges { node { __typename id sku metafields { edges { node { key value } } } } } } \ + media { edges { node { __typename ... on MediaImage { id alt } } } } } } } }", + "groupObjects": true, + }) + ); + // The version the query was checked against. + assert!(mock.requests()[0].url.contains("/admin/api/2026-10/")); + + assert_eq!(products.len(), 2); + let shirt = &products[0]; + assert_eq!(shirt.title, "Shirt"); + let skus: Vec> = shirt + .variants + .iter() + .map(|variant| variant.sku.as_deref()) + .collect(); + assert_eq!(skus, [Some("S-1"), None]); + // Two levels deep: under the variant they belong to. + let keys: Vec<&str> = shirt.variants[0] + .metafields + .iter() + .map(|field| field.key.as_str()) + .collect(); + assert_eq!(keys, ["color", "size"]); + assert!(shirt.variants[1].metafields.is_empty()); + // An interface: the fields of a fragment are there when it applies. + assert_eq!(shirt.media.len(), 2); + assert_eq!(shirt.media[0].alt.as_deref(), Some("Front")); + assert_eq!(shirt.media[1].id, None); + let hat = &products[1]; + assert_eq!(hat.title, "Hat"); + assert!(hat.variants.is_empty() && hat.media.is_empty()); +} + +#[tokio::test] +async fn the_variables_of_a_bulk_query_are_written_into_its_text() { + let (mock, _) = shopify_with(""); + let shopify = client(&mock); + + // A string with quotes, a backslash, a newline and a `$`; the default + // of `$sort`. + let filter = "title:\"Café \\ $filter\"\nvendor:x"; + let items = shopify + .bulk_query( + by_title::Variables { + filter: Some(filter.to_string()), + sort: None, + }, + fast(), + ) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert!(items.is_empty()); + let text = mock.graphql_requests()[0].variables["query"] + .as_str() + .unwrap() + .to_string(); + assert_eq!( + text, + r#"{ products(query: "title:\"Café \\ $filter\"\nvendor:x", sortKey: TITLE, reverse: true) { edges { node { id } } } }"# + ); + + // An enum value bare; a variable without a value or a default left out. + let query = by_title::operation(by_title::Variables { + filter: None, + sort: Some("CREATED_AT".into()), + }); + assert_eq!( + query.text().unwrap(), + "{ products(sortKey: CREATED_AT, reverse: true) { edges { node { id } } } }" + ); + assert_eq!(query.query(), by_title::QUERY); +} + +#[tokio::test] +async fn an_inline_bulk_query_writes_lists_of_enum_values_bare() { + let (mock, _) = shopify_with( + "{\"id\":\"gid://shopify/WebhookSubscription/1\",\"topic\":\"ORDERS_CREATE\"}\n", + ); + let shopify = client(&mock); + + let hooks = shopify + .bulk_query( + graphql!( + bulk("query Hooks($topics: [WebhookSubscriptionTopic!], $format: WebhookSubscriptionFormat, $uri: String) { + webhookSubscriptions(topics: $topics, format: $format, uri: $uri, query: \"a $b\") { edges { node { id topic } } } + }"), + topics = [ORDERS_CREATE, raw("PRODUCTS_UPDATE")], + format = JSON, + ), + fast(), + ) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(hooks[0].topic, "ORDERS_CREATE"); + assert_eq!( + mock.graphql_requests()[0].variables["query"], + "query Hooks { webhookSubscriptions(topics: [ORDERS_CREATE, PRODUCTS_UPDATE], format: JSON, query: \"a $b\") { edges { node { id topic } } } }" + ); +} + +#[tokio::test] +async fn an_enum_value_that_is_not_a_name_fails_before_anything_is_sent() { + let (mock, _) = shopify_with(""); + let shopify = client(&mock); + + let error = shopify + .bulk_query( + graphql!( + bulk( + "query($topics: [WebhookSubscriptionTopic!]) { + webhookSubscriptions(topics: $topics) { edges { node { id } } } + }" + ), + topics = [ORDERS_CREATE, raw("X) { shop { name } } #")], + ), + fast(), + ) + .await + .unwrap_err(); + let Error::InvalidValue { path, reason, .. } = &error else { + panic!("{error:?}"); + }; + assert_eq!(path, "$topics[1]"); + assert_eq!(*reason, InvalidValueReason::NotAGraphqlName); + assert!(mock.requests().is_empty()); +} + +#[tokio::test] +async fn a_child_out_of_place_ends_the_stream() { + let (mock, _) = shopify_with( + r#"{"id":"gid://shopify/Product/1","title":"Shirt"} +{"__typename":"ProductVariant","id":"gid://shopify/ProductVariant/1","sku":"S-1","__parentId":"gid://shopify/Product/9"} +{"id":"gid://shopify/Product/2","title":"Hat"} +"#, + ); + let shopify = client(&mock); + let mut items = shopify + .bulk_query(catalog::operation(), fast()) + .await + .unwrap(); + let error = items.next_item().await.unwrap().unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 2 of the results is a child of neither the top-level object before it nor one of its children, though the query ran with `groupObjects`" + ); + assert!(items.next_item().await.is_none()); +} + +#[tokio::test] +async fn a_child_no_connection_returns_ends_the_stream() { + for (line, message) in [ + ( + r#"{"__typename":"Collection","id":"gid://shopify/Collection/1","__parentId":"gid://shopify/Product/1"}"#, + "line 2 of the results has a `__typename` that no connection of its parent returns", + ), + ( + r#"{"id":"gid://shopify/ProductVariant/1","__parentId":"gid://shopify/Product/1"}"#, + "line 2 of the results has no `__typename`, which tells which connection of its parent it belongs to", + ), + ] { + let jsonl: &'static str = Box::leak( + format!("{{\"id\":\"gid://shopify/Product/1\",\"title\":\"Shirt\"}}\n{line}\n") + .into_boxed_str(), + ); + let (mock, _) = shopify_with(jsonl); + let shopify = client(&mock); + let mut items = shopify + .bulk_query(catalog::operation(), fast()) + .await + .unwrap(); + let error = items.next_item().await.unwrap().unwrap_err(); + assert_eq!(error.to_string(), format!("bulk operation: {message}")); + assert!(items.next_item().await.is_none()); + } +} + +#[tokio::test] +async fn a_line_that_does_not_read_as_its_type_ends_the_stream() { + let (mock, _) = shopify_with( + r#"{"id":"gid://shopify/Product/1","title":"Shirt"} +{"__typename":"ProductVariant","id":"gid://shopify/ProductVariant/1","sku":12,"__parentId":"gid://shopify/Product/1"} +{"id":"gid://shopify/Product/2","title":"Hat"} +"#, + ); + let shopify = client(&mock); + let mut items = shopify + .bulk_query(catalog::operation(), fast()) + .await + .unwrap(); + let error = items.next_item().await.unwrap().unwrap_err(); + assert!(matches!(error, Error::Decode { .. }), "{error:?}"); + assert!(error.to_string().contains("at line 2"), "{error}"); + assert!(items.next_item().await.is_none()); +} + +#[tokio::test] +async fn the_items_of_an_operation_started_by_hand_are_read_from_its_url() { + let (mock, _) = shopify_with(CATALOG); + let shopify = client(&mock); + + let started = shopify + .start_bulk_query(catalog::operation()) + .await + .unwrap(); + let operation = shopify + .wait_for_bulk_operation(&started.id, fast()) + .await + .unwrap(); + let products: Vec = shopify + .download_bulk_items(operation.url.as_deref().unwrap()) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(products[0].variants[0].metafields.len(), 2); + assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], true); +} + +#[tokio::test] +async fn a_bulk_mutation_stages_its_lines_and_reads_typed_results() { + let (mock, uploads) = shopify_with( + r#"{"data":{"tagsAdd":{"userErrors":[]}},"__lineNumber":1} +{"data":{"tagsAdd":{"userErrors":[{"field":["id"],"message":"Product does not exist"}]}},"__lineNumber":0} +{"errors":[{"message":"Variable $id of type ID! was provided invalid value","locations":[{"line":1,"column":10}]}]} +"#, + ); + let shopify = client(&mock); + + let lines = + ["gid://shopify/Product/1", "gid://shopify/Product/2"].map(|id| add_tags::Variables { + id: id.to_string(), + tags: vec!["sale".to_string(), "a \"b\"".to_string()], + }); + let mut rows = shopify.bulk_mutation(lines, fast()).await.unwrap(); + let mut results: Vec> = Vec::new(); + while let Some(row) = rows.next_row().await { + results.push(row.unwrap()); + } + + let sent = mock.graphql_requests(); + assert_eq!(sent[1].variables["mutation"], add_tags::QUERY); + assert_eq!( + sent[1].variables["stagedUploadPath"], + "tmp/1/bulk/vars.jsonl" + ); + let body = String::from_utf8(uploads.lock().unwrap()[0].body.clone()).unwrap(); + assert!( + body.contains( + "{\"id\":\"gid://shopify/Product/1\",\"tags\":[\"sale\",\"a \\\"b\\\"\"]}\n\ + {\"id\":\"gid://shopify/Product/2\",\"tags\":[\"sale\",\"a \\\"b\\\"\"]}\n" + ), + "{body}" + ); + + assert_eq!(results.len(), 3); + assert_eq!(results[0].index, Some(1)); + assert!(results[0].errors.is_empty()); + let refused = results[1].data.as_ref().unwrap().tags_add.as_ref().unwrap(); + assert_eq!(refused.user_errors[0].message, "Product does not exist"); + assert_eq!(results[1].index, Some(0)); + assert!(results[2].data.is_none()); + assert_eq!(results[2].index, None); + assert_eq!( + results[2].errors[0].message, + "Variable $id of type ID! was provided invalid value" + ); +} + +#[tokio::test] +async fn the_lines_of_an_inline_bulk_mutation_are_checked_before_anything_is_sent() { + let (mock, _) = shopify_with(""); + let shopify = client(&mock); + let deltas: [i64; 2] = [1, 1 << 40]; + let lines = deltas.map(|delta| { + graphql!( + bulk("mutation($input: InventoryAdjustQuantitiesInput!) { + inventoryAdjustQuantities(input: $input) { userErrors { message } } + }"), + input = { + name: "available", + reason: "correction", + changes: [{ delta: delta, inventoryItemId: "gid://shopify/InventoryItem/1", locationId: "gid://shopify/Location/1" }], + }, + ) + }); + let error = shopify.bulk_mutation(lines, fast()).await.unwrap_err(); + let Error::InvalidValue { path, reason, .. } = &error else { + panic!("{error:?}"); + }; + assert_eq!(path, "$input.changes[0].delta"); + assert_eq!(*reason, InvalidValueReason::IntOutOfRange); + assert!(mock.requests().is_empty()); + + // No line: nothing runs. + let none: Vec = Vec::new(); + let mut results = shopify.bulk_mutation(none, fast()).await.unwrap(); + assert!(results.next_row().await.is_none()); + assert!(mock.requests().is_empty()); + let none: Vec = Vec::new(); + let error = shopify.start_bulk_mutation(none).await.unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: a bulk mutation needs one line of variables at least" + ); +} + +#[tokio::test] +async fn the_lines_of_a_bulk_mutation_run_one_mutation() { + let (mock, _) = shopify_with(""); + let shopify = client(&mock); + let line = graphql!( + bulk("mutation($id: ID!) { tagsAdd(id: $id, tags: [\"a\"]) { userErrors { message } } }"), + id = "gid://shopify/Product/1", + ); + assert_eq!(line.line().unwrap(), r#"{"id":"gid://shopify/Product/1"}"#); + + // Each `graphql!` has its own types: only lines built by hand can mix + // mutations. + let lines = [ + BulkMutation::::__checked("mutation { a }", None, "2026-10"), + BulkMutation::::__checked("mutation { b }", None, "2026-10"), + ]; + let error = shopify.start_bulk_mutation(lines).await.unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 2 of the bulk mutation was built from another mutation than line 1: a bulk operation runs one mutation" + ); + assert!(mock.requests().is_empty()); +} From 4936edf27c40d29ad3437e4f3da33621d8462515 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:13:08 +0100 Subject: [PATCH 109/135] =?UTF-8?q?test(ui):=20the=20refusals=20of=20`grap?= =?UTF-8?q?hql!(bulk(=E2=80=A6))`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New files sort first in trybuild's crate numbering: the trait suffixes of the literal tests change with it. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/tests/ui/bulk_aliased_id.rs | 3 +++ crates/shopify_api/tests/ui/bulk_aliased_id.stderr | 6 ++++++ .../tests/ui/bulk_connection_in_fragment.rs | 3 +++ .../tests/ui/bulk_connection_in_fragment.stderr | 6 ++++++ crates/shopify_api/tests/ui/bulk_connection_nodes.rs | 3 +++ .../shopify_api/tests/ui/bulk_connection_nodes.stderr | 6 ++++++ .../shopify_api/tests/ui/bulk_connection_page_info.rs | 3 +++ .../tests/ui/bulk_connection_page_info.stderr | 6 ++++++ .../tests/ui/bulk_connection_under_object.rs | 3 +++ .../tests/ui/bulk_connection_under_object.stderr | 6 ++++++ crates/shopify_api/tests/ui/bulk_enum_value.rs | 6 ++++++ crates/shopify_api/tests/ui/bulk_enum_value.stderr | 6 ++++++ crates/shopify_api/tests/ui/bulk_form.rs | 5 +++++ crates/shopify_api/tests/ui/bulk_form.stderr | 5 +++++ crates/shopify_api/tests/ui/bulk_missing_id.rs | 3 +++ crates/shopify_api/tests/ui/bulk_missing_id.stderr | 6 ++++++ .../tests/ui/bulk_mutation_of_a_bulk_operation.rs | 3 +++ .../tests/ui/bulk_mutation_of_a_bulk_operation.stderr | 6 ++++++ .../shopify_api/tests/ui/bulk_mutation_two_fields.rs | 3 +++ .../tests/ui/bulk_mutation_two_fields.stderr | 6 ++++++ crates/shopify_api/tests/ui/bulk_not_node.rs | 3 +++ crates/shopify_api/tests/ui/bulk_not_node.stderr | 6 ++++++ .../shopify_api/tests/ui/bulk_pagination_argument.rs | 3 +++ .../tests/ui/bulk_pagination_argument.stderr | 6 ++++++ crates/shopify_api/tests/ui/bulk_reserved_alias.rs | 3 +++ crates/shopify_api/tests/ui/bulk_reserved_alias.stderr | 6 ++++++ crates/shopify_api/tests/ui/bulk_same_type_siblings.rs | 3 +++ .../tests/ui/bulk_same_type_siblings.stderr | 6 ++++++ crates/shopify_api/tests/ui/bulk_too_deep.rs | 3 +++ crates/shopify_api/tests/ui/bulk_too_deep.stderr | 6 ++++++ .../shopify_api/tests/ui/bulk_too_many_connections.rs | 3 +++ .../tests/ui/bulk_too_many_connections.stderr | 6 ++++++ crates/shopify_api/tests/ui/bulk_top_level_nodes.rs | 3 +++ .../shopify_api/tests/ui/bulk_top_level_nodes.stderr | 6 ++++++ .../tests/ui/bulk_top_level_not_a_connection.rs | 3 +++ .../tests/ui/bulk_top_level_not_a_connection.stderr | 6 ++++++ .../shopify_api/tests/ui/bulk_two_top_level_fields.rs | 3 +++ .../tests/ui/bulk_two_top_level_fields.stderr | 6 ++++++ crates/shopify_api/tests/ui/bulk_variable_unknown.rs | 6 ++++++ .../shopify_api/tests/ui/bulk_variable_unknown.stderr | 5 +++++ .../ui/literal_maybe_non_null_with_default.stderr | 4 ++-- crates/shopify_api/tests/ui/literal_one_of.stderr | 4 ++-- .../tests/ui/literal_option_in_field.stderr | 2 +- .../tests/ui/literal_wrong_input_type.stderr | 6 +++--- .../shopify_api/tests/ui/literal_wrong_scalar.stderr | 10 +++++----- 45 files changed, 199 insertions(+), 13 deletions(-) create mode 100644 crates/shopify_api/tests/ui/bulk_aliased_id.rs create mode 100644 crates/shopify_api/tests/ui/bulk_aliased_id.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_connection_in_fragment.rs create mode 100644 crates/shopify_api/tests/ui/bulk_connection_in_fragment.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_connection_nodes.rs create mode 100644 crates/shopify_api/tests/ui/bulk_connection_nodes.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_connection_page_info.rs create mode 100644 crates/shopify_api/tests/ui/bulk_connection_page_info.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_connection_under_object.rs create mode 100644 crates/shopify_api/tests/ui/bulk_connection_under_object.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_enum_value.rs create mode 100644 crates/shopify_api/tests/ui/bulk_enum_value.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_form.rs create mode 100644 crates/shopify_api/tests/ui/bulk_form.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_missing_id.rs create mode 100644 crates/shopify_api/tests/ui/bulk_missing_id.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.rs create mode 100644 crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_mutation_two_fields.rs create mode 100644 crates/shopify_api/tests/ui/bulk_mutation_two_fields.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_not_node.rs create mode 100644 crates/shopify_api/tests/ui/bulk_not_node.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_pagination_argument.rs create mode 100644 crates/shopify_api/tests/ui/bulk_pagination_argument.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_reserved_alias.rs create mode 100644 crates/shopify_api/tests/ui/bulk_reserved_alias.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_same_type_siblings.rs create mode 100644 crates/shopify_api/tests/ui/bulk_same_type_siblings.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_too_deep.rs create mode 100644 crates/shopify_api/tests/ui/bulk_too_deep.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_too_many_connections.rs create mode 100644 crates/shopify_api/tests/ui/bulk_too_many_connections.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_top_level_nodes.rs create mode 100644 crates/shopify_api/tests/ui/bulk_top_level_nodes.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.rs create mode 100644 crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_two_top_level_fields.rs create mode 100644 crates/shopify_api/tests/ui/bulk_two_top_level_fields.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_variable_unknown.rs create mode 100644 crates/shopify_api/tests/ui/bulk_variable_unknown.stderr diff --git a/crates/shopify_api/tests/ui/bulk_aliased_id.rs b/crates/shopify_api/tests/ui/bulk_aliased_id.rs new file mode 100644 index 0000000..d9d9c4f --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_aliased_id.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { productId: id variants { edges { node { sku } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_aliased_id.stderr b/crates/shopify_api/tests/ui/bulk_aliased_id.stderr new file mode 100644 index 0000000..9c29362 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_aliased_id.stderr @@ -0,0 +1,6 @@ +error: The nodes of `products` have the nested connection `variants`: select their `id`, without an alias or a directive, in this `node { … }`. Shopify refuses the query otherwise, and places each nested line under its parent by that `id` (line 1, column 22) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_aliased_id.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { productId: id variants { edges { node { sku } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_connection_in_fragment.rs b/crates/shopify_api/tests/ui/bulk_connection_in_fragment.rs new file mode 100644 index 0000000..8eb1bbc --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_in_fragment.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id ... on Product { variants { edges { node { sku } } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_connection_in_fragment.stderr b/crates/shopify_api/tests/ui/bulk_connection_in_fragment.stderr new file mode 100644 index 0000000..73e85ab --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_in_fragment.stderr @@ -0,0 +1,6 @@ +error: The connection `variants` is inside a fragment: in a bulk query, a nested connection is written right in the `node { … }` of its parent connection (line 1, column 49) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_connection_in_fragment.rs:2:40 + | +2 | ...i::graphql!(bulk("{ products { edges { node { id ... on Product { variants { edges { node { sku } } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_connection_nodes.rs b/crates/shopify_api/tests/ui/bulk_connection_nodes.rs new file mode 100644 index 0000000..7548595 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_nodes.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { nodes { id } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_connection_nodes.stderr b/crates/shopify_api/tests/ui/bulk_connection_nodes.stderr new file mode 100644 index 0000000..2004eef --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_nodes.stderr @@ -0,0 +1,6 @@ +error: A connection of a bulk query selects `edges { node { … } }` and nothing else, as Shopify documents it (`products`): Shopify does not document `nodes` for bulk queries (line 1, column 14) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_connection_nodes.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { nodes { id } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_connection_page_info.rs b/crates/shopify_api/tests/ui/bulk_connection_page_info.rs new file mode 100644 index 0000000..1e43a22 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_page_info.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id } } pageInfo { hasNextPage } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_connection_page_info.stderr b/crates/shopify_api/tests/ui/bulk_connection_page_info.stderr new file mode 100644 index 0000000..eeb4e93 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_page_info.stderr @@ -0,0 +1,6 @@ +error: A connection of a bulk query selects `edges { node { … } }` and nothing else, as Shopify documents it (`products`): `pageInfo` is refused beside `edges` (line 1, column 36) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_connection_page_info.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { id } } pageInfo { hasNextPage } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_connection_under_object.rs b/crates/shopify_api/tests/ui/bulk_connection_under_object.rs new file mode 100644 index 0000000..4721a72 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_under_object.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ orders { edges { node { id customer { orders { edges { node { id } } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_connection_under_object.stderr b/crates/shopify_api/tests/ui/bulk_connection_under_object.stderr new file mode 100644 index 0000000..6e1095c --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_under_object.stderr @@ -0,0 +1,6 @@ +error: The connection `orders` is under `customer`, which is not a connection: in a bulk query, a nested connection is written right in the `node { … }` of its parent connection (line 1, column 41) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_connection_under_object.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ orders { edges { node { id customer { orders { edges { node { id } } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_enum_value.rs b/crates/shopify_api/tests/ui/bulk_enum_value.rs new file mode 100644 index 0000000..bc3ea71 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_enum_value.rs @@ -0,0 +1,6 @@ +fn main() { + let _ = shopify_api::graphql!( + bulk("query($sort: ProductSortKeys) { products(sortKey: $sort) { edges { node { id } } } }"), + sort = TITEL, + ); +} diff --git a/crates/shopify_api/tests/ui/bulk_enum_value.stderr b/crates/shopify_api/tests/ui/bulk_enum_value.stderr new file mode 100644 index 0000000..743dc31 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_enum_value.stderr @@ -0,0 +1,6 @@ +error: `TITEL` is not a value of the enum `ProductSortKeys` (did you mean `TITLE`?): `$sort` takes `CREATED_AT`, `ID`, `INVENTORY_TOTAL`, `PRODUCT_TYPE`, `PUBLISHED_AT`, `RELEVANCE`, `TITLE`, `UPDATED_AT` or `VENDOR` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_enum_value.rs:4:16 + | +4 | sort = TITEL, + | ^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_form.rs b/crates/shopify_api/tests/ui/bulk_form.rs new file mode 100644 index 0000000..a1baa70 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_form.rs @@ -0,0 +1,5 @@ +shopify_api::graphql! { + mod nested = bulk(bulk("{ products { edges { node { id } } } }")); +} + +fn main() {} diff --git a/crates/shopify_api/tests/ui/bulk_form.stderr b/crates/shopify_api/tests/ui/bulk_form.stderr new file mode 100644 index 0000000..ddd5133 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_form.stderr @@ -0,0 +1,5 @@ +error: `bulk(…)` takes the operation as a string literal or `file("path.graphql")` + --> tests/ui/bulk_form.rs:2:23 + | +2 | mod nested = bulk(bulk("{ products { edges { node { id } } } }")); + | ^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_missing_id.rs b/crates/shopify_api/tests/ui/bulk_missing_id.rs new file mode 100644 index 0000000..37da153 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_missing_id.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { title variants { edges { node { sku } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_missing_id.stderr b/crates/shopify_api/tests/ui/bulk_missing_id.stderr new file mode 100644 index 0000000..d0bc03e --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_missing_id.stderr @@ -0,0 +1,6 @@ +error: The nodes of `products` have the nested connection `variants`: select their `id`, without an alias or a directive, in this `node { … }`. Shopify refuses the query otherwise, and places each nested line under its parent by that `id` (line 1, column 22) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_missing_id.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { title variants { edges { node { sku } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.rs b/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.rs new file mode 100644 index 0000000..f6a6296 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("mutation { bulkOperationRunQuery(query: \"{ shop { name } }\", groupObjects: false) { userErrors { message } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.stderr b/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.stderr new file mode 100644 index 0000000..d435856 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.stderr @@ -0,0 +1,6 @@ +error: Shopify does not run `bulkOperationRunQuery` in a bulk mutation (line 1, column 12) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_mutation_of_a_bulk_operation.rs:2:40 + | +2 | ...l!(bulk("mutation { bulkOperationRunQuery(query: \"{ shop { name } }\", groupObjects: false) { userErrors { message } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_mutation_two_fields.rs b/crates/shopify_api/tests/ui/bulk_mutation_two_fields.rs new file mode 100644 index 0000000..2e1932e --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_mutation_two_fields.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("mutation { a: tagsAdd(id: \"gid://shopify/Product/1\", tags: [\"x\"]) { userErrors { message } } b: tagsAdd(id: \"gid://shopify/Product/2\", tags: [\"x\"]) { userErrors { message } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_mutation_two_fields.stderr b/crates/shopify_api/tests/ui/bulk_mutation_two_fields.stderr new file mode 100644 index 0000000..4e26585 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_mutation_two_fields.stderr @@ -0,0 +1,6 @@ +error: A bulk mutation selects one top-level field: Shopify runs one per operation (line 1, column 94) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_mutation_two_fields.rs:2:40 + | +2 | ...lk("mutation { a: tagsAdd(id: \"gid://shopify/Product/1\", tags: [\"x\"]) { userErrors { message } } b: tagsAdd(id: \"gid://shopify/Product/2\", tags: [\"x\"]) { userErrors { message } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_not_node.rs b/crates/shopify_api/tests/ui/bulk_not_node.rs new file mode 100644 index 0000000..55dd0a6 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_not_node.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ deletionEvents { edges { node { occurredAt } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_not_node.stderr b/crates/shopify_api/tests/ui/bulk_not_node.stderr new file mode 100644 index 0000000..d3f0165 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_not_node.stderr @@ -0,0 +1,6 @@ +error: Shopify bulk queries read connections of `Node` objects: the nodes of `deletionEvents`, `DeletionEvent`, do not all implement `Node` (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_not_node.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ deletionEvents { edges { node { occurredAt } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_pagination_argument.rs b/crates/shopify_api/tests/ui/bulk_pagination_argument.rs new file mode 100644 index 0000000..8c866b8 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_pagination_argument.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products(first: 10) { edges { node { id } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_pagination_argument.stderr b/crates/shopify_api/tests/ui/bulk_pagination_argument.stderr new file mode 100644 index 0000000..dd6c91c --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_pagination_argument.stderr @@ -0,0 +1,6 @@ +error: Shopify ignores `first` in a bulk query and returns every object of `products`: remove it (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_pagination_argument.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products(first: 10) { edges { node { id } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_reserved_alias.rs b/crates/shopify_api/tests/ui/bulk_reserved_alias.rs new file mode 100644 index 0000000..4ac3d1c --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_alias.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { __parentId: id } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_reserved_alias.stderr b/crates/shopify_api/tests/ui/bulk_reserved_alias.stderr new file mode 100644 index 0000000..b204df3 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_alias.stderr @@ -0,0 +1,6 @@ +error: `__parentId` cannot be an alias in a bulk query: the lines of its results hold `__parentId` and `__typename` (line 1, column 29) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_reserved_alias.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { __parentId: id } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_same_type_siblings.rs b/crates/shopify_api/tests/ui/bulk_same_type_siblings.rs new file mode 100644 index 0000000..184f93b --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_same_type_siblings.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id custom: metafields(namespace: \"custom\") { edges { node { key } } } other: metafields(namespace: \"other\") { edges { node { key } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_same_type_siblings.stderr b/crates/shopify_api/tests/ui/bulk_same_type_siblings.stderr new file mode 100644 index 0000000..b11a692 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_same_type_siblings.stderr @@ -0,0 +1,6 @@ +error: `custom` and `other`, connections of each node of `products`, may both return `Metafield`: their lines in the results could not be told apart. Query one of them in another bulk query (line 1, column 99) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_same_type_siblings.rs:2:40 + | +2 | ...lk("{ products { edges { node { id custom: metafields(namespace: \"custom\") { edges { node { key } } } other: metafields(namespace: \"other\") { edges { node { key } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_too_deep.rs b/crates/shopify_api/tests/ui/bulk_too_deep.rs new file mode 100644 index 0000000..5450f59 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_too_deep.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id collections { edges { node { id products { edges { node { id variants { edges { node { sku } } } } } } } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_too_deep.stderr b/crates/shopify_api/tests/ui/bulk_too_deep.stderr new file mode 100644 index 0000000..d0b3fae --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_too_deep.stderr @@ -0,0 +1,6 @@ +error: Connections nest 2 levels deep at most below the top-level one in a bulk query: `variants` is level 3 (line 1, column 93) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_too_deep.rs:2:40 + | +2 | ...lk("{ products { edges { node { id collections { edges { node { id products { edges { node { id variants { edges { node { sku } } } } } } } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_too_many_connections.rs b/crates/shopify_api/tests/ui/bulk_too_many_connections.rs new file mode 100644 index 0000000..495fdb9 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_too_many_connections.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id variants { edges { node { sku } } } media { edges { node { alt } } } collections { edges { node { title } } } metafields { edges { node { key } } } sellingPlanGroups { edges { node { name } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_too_many_connections.stderr b/crates/shopify_api/tests/ui/bulk_too_many_connections.stderr new file mode 100644 index 0000000..4606112 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_too_many_connections.stderr @@ -0,0 +1,6 @@ +error: A bulk query has 5 connections at most: `sellingPlanGroups` is connection number 6 (line 1, column 180) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_too_many_connections.rs:2:40 + | +2 | ...lk("{ products { edges { node { id variants { edges { node { sku } } } media { edges { node { alt } } } collections { edges { node { title } } } metafields { edges { node { key } } } sellingPlanGroups { edges { node { name } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_top_level_nodes.rs b/crates/shopify_api/tests/ui/bulk_top_level_nodes.rs new file mode 100644 index 0000000..8845660 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_top_level_nodes.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ nodes(ids: [\"gid://shopify/Product/1\"]) { id } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_top_level_nodes.stderr b/crates/shopify_api/tests/ui/bulk_top_level_nodes.stderr new file mode 100644 index 0000000..dab5718 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_top_level_nodes.stderr @@ -0,0 +1,6 @@ +error: `nodes` cannot be the top-level field of a bulk query: select a connection, such as `products` (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_top_level_nodes.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ nodes(ids: [\"gid://shopify/Product/1\"]) { id } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.rs b/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.rs new file mode 100644 index 0000000..036aec0 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ shop { name } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.stderr b/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.stderr new file mode 100644 index 0000000..5c4bdad --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.stderr @@ -0,0 +1,6 @@ +error: The top-level field of a bulk query is a connection: `shop` is `Shop!`. Run it as an ordinary query, or select a connection such as `products` (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_top_level_not_a_connection.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ shop { name } }")); + | ^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_two_top_level_fields.rs b/crates/shopify_api/tests/ui/bulk_two_top_level_fields.rs new file mode 100644 index 0000000..4ce3b50 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_two_top_level_fields.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id } } } orders { edges { node { id } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_two_top_level_fields.stderr b/crates/shopify_api/tests/ui/bulk_two_top_level_fields.stderr new file mode 100644 index 0000000..ce50dea --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_two_top_level_fields.stderr @@ -0,0 +1,6 @@ +error: A bulk query selects one top-level field: Shopify runs one per operation (line 1, column 38) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_two_top_level_fields.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { id } } } orders { edges { node { id } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_variable_unknown.rs b/crates/shopify_api/tests/ui/bulk_variable_unknown.rs new file mode 100644 index 0000000..ca92070 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_variable_unknown.rs @@ -0,0 +1,6 @@ +fn main() { + let _ = shopify_api::graphql!( + bulk("query($q: String) { products(query: $q) { edges { node { id } } } }"), + filter = "x", + ); +} diff --git a/crates/shopify_api/tests/ui/bulk_variable_unknown.stderr b/crates/shopify_api/tests/ui/bulk_variable_unknown.stderr new file mode 100644 index 0000000..0289c9f --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_variable_unknown.stderr @@ -0,0 +1,5 @@ +error: The operation has no variable `$filter`: it declares $q + --> tests/ui/bulk_variable_unknown.rs:4:9 + | +4 | filter = "x", + | ^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr index 5602a79..69a130a 100644 --- a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -7,13 +7,13 @@ error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[Inven | | an `Option`: `None` leaves the field out | required by a bound introduced by this call | - = help: the trait `__ShopifyApiNoNull4_c23fa03b` is not implemented for `Vec>` + = help: the trait `__ShopifyApiNoNull4_c24bed09` is not implemented for `Vec>` help: this trait has no implementations, consider adding one --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c23fa03b` +note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c24bed09` --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); diff --git a/crates/shopify_api/tests/ui/literal_one_of.stderr b/crates/shopify_api/tests/ui/literal_one_of.stderr index cce9aa3..bf5eaa3 100644 --- a/crates/shopify_api/tests/ui/literal_one_of.stderr +++ b/crates/shopify_api/tests/ui/literal_one_of.stderr @@ -35,7 +35,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Optio | `Option<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2385860` is not implemented for `Option<&str>` + = help: the trait `main::__ShopifyApiExpect1_c2391752` is not implemented for `Option<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:7:13 | @@ -52,7 +52,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Maybe | `Maybe<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2385860` is not implemented for `Maybe<&str>` + = help: the trait `main::__ShopifyApiExpect1_c2391752` is not implemented for `Maybe<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:8:13 | diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr index 9f7c335..8e7c733 100644 --- a/crates/shopify_api/tests/ui/literal_option_in_field.stderr +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -7,7 +7,7 @@ error[E0277]: `vendor` of `ProductUpdateInput` expects a `String`, not `Option` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect1_c2385b33` is not implemented for `Option` + = help: the trait `__ShopifyApiExpect1_c239102d` is not implemented for `Option` = note: `vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null` note: required by a bound in `Checks::build` --> tests/ui/literal_option_in_field.rs:3:13 diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr index c0e960e..d69fa60 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -9,8 +9,8 @@ error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built wit 6 | | ); | |_____- required by a bound introduced by this call | - = help: the trait `__ShopifyApiExpect2_c2384416` is not implemented for `InputObject<2493993284262097346>` -help: the following other types implement trait `__ShopifyApiExpect2_c2384416` + = help: the trait `__ShopifyApiExpect2_c2391234` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2_c2391234` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -22,7 +22,7 @@ help: the following other types implement trait `__ShopifyApiExpect2_c2384416` | | | | |_____`&InputObject<960560859991546817>` | `InputObject<960560859991546817>` -note: required for `Vec>` to implement `__ShopifyApiExpect1_c2384416` +note: required for `Vec>` to implement `__ShopifyApiExpect1_c2391234` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr index bdec6bf..8152d03 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr @@ -7,7 +7,7 @@ error[E0277]: `quantity` of `DraftOrderLineItemInput` expects an `Int`, not `&st | `&'static str` doesn't satisfy the trait bound | any integer type | - = help: the trait `main::__ShopifyApiExpect1_c2384be1` is not implemented for `&str` + = help: the trait `main::__ShopifyApiExpect1_c2391187` is not implemented for `&str` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 | @@ -24,7 +24,7 @@ error[E0277]: `title` of `DraftOrderLineItemInput` expects a `String`, not `u8` | `u8` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect3_c2384be1` is not implemented for `u8` + = help: the trait `__ShopifyApiExpect3_c2391187` is not implemented for `u8` = note: `title?: value` takes an `Option`, `None` leaving the field out; `title: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -42,7 +42,7 @@ error[E0277]: `requiresShipping` of `DraftOrderLineItemInput` expects a `Boolean | `{integer}` doesn't satisfy the trait bound | `bool` | - = help: the trait `__ShopifyApiExpect5_c2384be1` is not implemented for `{integer}` + = help: the trait `__ShopifyApiExpect5_c2391187` is not implemented for `{integer}` = note: `requiresShipping?: value` takes an `Option`, `None` leaving the field out; `requiresShipping: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -60,8 +60,8 @@ error[E0277]: `value` of `WeightInput` expects a `Float`, not `u64` | `u64` doesn't satisfy the trait bound | `f64`, `f32`, `i32` or `u32` | - = help: the trait `main::__ShopifyApiExpect1_c2384be1` is not implemented for `u64` - = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c2384be1`, but not `main::__ShopifyApiExpect1_c2384be1` + = help: the trait `main::__ShopifyApiExpect1_c2391187` is not implemented for `u64` + = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c2391187`, but not `main::__ShopifyApiExpect1_c2391187` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:4:13 | From 5354482d5c1a119719b24019228154345dcb5fda Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:14:55 +0100 Subject: [PATCH 110/135] =?UTF-8?q?docs(bulk):=20lead=20with=20`graphql!(b?= =?UTF-8?q?ulk(=E2=80=A6))`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A "Bulk operations" section in the documentation of `graphql!`: the rules checked, the items and their connections, the variables written into the text, bulk mutations, and what is not checked. The module docs of `bulk`, the README, the CHANGELOG and MIGRATION show the typed path first. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + MIGRATION.md | 5 + README.md | 36 +++++++ crates/shopify_api/docs/graphql.md | 156 +++++++++++++++++++++++++++++ crates/shopify_api/src/bulk.rs | 59 ++++++----- 5 files changed, 237 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c61404..b15faa8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,10 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Bulk results read as they download, in memory that follows the line being read rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. - `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group; so is a child whose parent has no unaliased `id`, which the error names. - `run_bulk_mutation_iter` and `stage_bulk_variables_iter` take the variables from an iterator; the JSONL is written straight into the body of the upload, in memory once. +- Bulk operations checked at compile time: `graphql!(bulk("…"))`, `bulk(file("…"))`, inline or in a module. A bulk query is checked against Shopify's bulk rules for API 2026-10: one top-level field, a connection (not `node` or `nodes`); five connections at most, two levels deep below it; `edges { node { … } }` and nothing else (no `nodes`, `cursor`, `pageInfo`, nor `first`, `last`, `after`, `before`); `Node` objects; a nested connection written right in the `node` of its parent; an unaliased `id` on every node with nested connections (an error that asks for it, never added silently); two connections of one node that may return the same type, such as two aliased `metafields`, are refused. What the guide does not show is refused. A bulk mutation is one mutation field, not a bulk operation, with one connection at most. +- The items of a bulk query are generated types: `Item`, each nested connection a `Vec` of its nodes. `Shopify::bulk_query` runs it with `groupObjects` and returns `BulkItems` (`next_item`, `collect`, `Stream`), one item in memory at a time, nested lines placed by `__parentId`, and by `__typename` where a node has several connections: the text sent selects it there. `start_bulk_query` and `download_bulk_items` split the steps; `BulkQuery::text` is the text sent. +- The variables of a bulk query, which Shopify does not take, are given as for any operation (literals and `input!` included) and written into its text as GraphQL literals, from the parsed operation: strings escaped as JSON, enum values bare (in input objects and lists too), input objects with unquoted keys, a variable without a value left out or given its default. The values are checked as for any operation; an enum value or a field that is not a GraphQL name fails with `InvalidValueReason::NotAGraphqlName`. A variable that may hold `JSON` is refused at compile time. +- `Shopify::bulk_mutation` runs a `graphql!(bulk("mutation …"))` over an iterator of its `Variables`: every line is checked and written before anything is sent, then staged, run, and read as `BulkMutationResult` (`data`, `errors`, `index`, Shopify's `__lineNumber`). `start_bulk_mutation` only starts it. Typed bulk operations run at the Admin API version they were checked against. - `Transport`, the HTTP layer as a trait, with `send_streaming` (a default goes through `send`), `StreamingResponse` and `BodyStream`. The default `ReqwestTransport` never follows a redirection, and streams: the timeout of a request bounds the wait for the headers and for each chunk, not the whole body. A client of your own goes through `transport::reqwest_0_13::from_builder`: reqwest appears in the API only under `transport::reqwest_0_13`, named after its major version, so that a later reqwest comes next to it. The client runs on Tokio. - `testing::MockTransport` (`push_data`, `push_chunks`, `push_streaming`, `respond_with`…), and `testing::client`, which retries without waiting, even for a scripted `Retry-After`. `testing` also gives the signing helpers: `webhooks::sign`, `ShopifyApp::sign_query`, `sign_app_proxy`, `sign_session_token`. - `oauth`: `ShopifyApp`, with install links, the verification of callbacks, admin launches and app proxy requests, the code exchange, session tokens and the token exchange. `verify_session_token` takes the tokens of Shopify admin and of checkout and customer account UI extensions (a `dest` without `https://`); `SessionToken::subject` is the staff member's ID or the customer's GID. `ShopifyApp::with_token_store` gives the clients it builds a `TokenStore`. diff --git a/MIGRATION.md b/MIGRATION.md index 61ff770..2218938 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -170,6 +170,11 @@ shopify.execute(graphql!( | `ShopifyUserError` | `UserError` | | `parse_jsonl(&str)` | `bulk::parse_jsonl(&[u8])`: `parse_jsonl(text.as_bytes())` | +New in 1.0: a query or a mutation declared with `graphql!(bulk("…"))` is +checked when the crate compiles, and `bulk_query` and `bulk_mutation` read +its results as generated types, in place of a hand-written struct and +`bulk_query_rows` or `bulk_query_grouped`. + `object_count`, `root_object_count` and `file_size` are numbers, and `created_at` and `completed_at` are `chrono::DateTime`. A failed operation is an `Error::Bulk` whose `operation` holds it, with its `error_code` and diff --git a/README.md b/README.md index 9a93220..23eccc4 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,42 @@ let products = shopify ## Bulk operations +`graphql!(bulk(…))` checks a bulk query against the schema and Shopify's +bulk rules (one top-level connection, five connections at most, two levels +deep, `edges { node }`, an `id` on each parent…), and reads its results as +generated types: each nested connection is a `Vec` of its nodes, put back +under its parent as the file downloads, one product in memory at a time. + +```rust,ignore +use shopify_api::bulk::BulkWaitOptions; + +graphql! { + mod catalog = bulk("query($filter: String) { + products(query: $filter) { edges { node { + id title + variants { edges { node { sku } } } + } } } + }"); +} + +let mut products = shopify + .bulk_query(catalog::Variables { filter: Some("status:active".into()) }, BulkWaitOptions::default()) + .await?; +while let Some(product) = products.next_item().await { + let product = product?; + println!("{}: {} variants", product.title, product.variants.len()); +} +``` + +Shopify takes no variables for a bulk query: they are written into its text +as GraphQL literals. A bulk mutation, `bulk("mutation …")`, runs over an +iterator of its `Variables` with `bulk_mutation`, which checks every line +before uploading them and reads a typed result per line. See the +[documentation of `graphql!`](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html#bulk-operations) +for the rules, and what is not checked. + +The untyped methods run any text: + ```rust,ignore use shopify_api::bulk::BulkWaitOptions; diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index d1ecfe7..4681070 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -351,6 +351,161 @@ graphql! { } ``` +# Bulk operations + +`bulk("…")`, or `bulk(file("…"))`, declares a bulk operation: a query Shopify +runs over a whole catalog in the background, or a mutation it runs once per +line of variables. It is checked like any operation, then against Shopify's +rules for bulk operations, and its results are read as generated types. + +```rust,no_run +use shopify_api::bulk::BulkWaitOptions; +use shopify_api::{Shopify, graphql}; + +graphql! { + pub mod catalog = bulk("query($filter: String) { + products(query: $filter) { edges { node { + id title + variants { edges { node { sku } } } + } } } + }"); +} + +async fn export(shopify: &Shopify) -> shopify_api::Result<()> { + let mut products = shopify + .bulk_query( + catalog::Variables { filter: Some("status:active".into()) }, + BulkWaitOptions::default(), + ) + .await?; + while let Some(product) = products.next_item().await { + let product: catalog::Item = product?; + println!("{}: {} variants", product.title, product.variants.len()); + } + Ok(()) +} +``` + +## The rules of a bulk query + +These follow Shopify's guide for API 2026-10 +([bulk queries](https://shopify.dev/docs/api/usage/bulk-operations/queries)). +Where the guide is silent, what it does not show is refused: a query +`graphql!` accepts is one the guide describes. + +- One top-level field, which is a connection, not `node` or `nodes`. +- Five connections at most, the top-level one included, nested two levels + deep at most below it. +- Each connection selected as `edges { node { … } }` and nothing else: no + `nodes`, `cursor` or `pageInfo`, no alias or directive on them, and no + `first`, `last`, `after` or `before`, which Shopify ignores in a bulk query. +- The nodes of a connection implement `Node`. +- A nested connection is written right in the `node { … }` of its parent + connection: not in a fragment, nor under another field. +- A node with nested connections selects `id`, without an alias or a + directive. Shopify refuses the query without it, and the lines of the + children are placed under their parent by that `id`: `graphql!` asks you to + add it rather than adding it itself. +- Two connections of one node that may return the same type, such as two + aliased `metafields(…)`, are refused: their lines could not be told apart. +- No alias starting with `__`. + +## The items of a bulk query + +The result type is `Item`, an object of the top-level connection, with the +fields it selects. A nested connection is a `Vec` of its nodes, +`product.variants: Vec`, not `{ edges: [{ node }] }`: Shopify +writes each node on a line of its own, and the reader puts it back under +its parent. Other nested objects stay as in any operation. A connection of +an interface or a union gives one struct, the fields of each fragment +optional, as in any operation. + +[`Shopify::bulk_query`] starts the query with `groupObjects`, waits for it, +and returns [`BulkItems`](crate::bulk::BulkItems): `next_item().await`, one +item at a time, `collect().await` into a `Vec`, or a `Stream`. One item is +held at a time, with its nested objects: memory follows the largest item, +not the file. A line that does not read as its type, or a nested line that +has no place, ends the stream with an error. [`Shopify::start_bulk_query`] +and [`Shopify::download_bulk_items`] split the steps, for an operation you +wait for yourself. + +The text sent is not the text written. Where a node has several nested +connections, their nodes gain `__typename`, which tells their lines apart; +the types do not show it. [`BulkQuery::text`](crate::bulk::BulkQuery::text) +gives the text sent. + +## Variables of a bulk query + +Shopify takes no variables for a bulk query. Declare them all the same and +give them as for any operation, literals and [`input!`](crate::input!) +included: when the query runs, each value is written into its text as a +GraphQL literal, and the variable definitions are left out. + +- A string as JSON escapes it, which GraphQL reads alike; a `$` in a string + stays a `$`. Numbers, booleans and `null` as they are. +- An enum value bare (`sortKey: TITLE`), in an input object and in a list + too. One that is not a GraphQL name, which `raw(…)` or a `String` field of + `Variables` may hold, fails with [`Error::InvalidValue`](crate::Error::InvalidValue) + (`NotAGraphqlName`) before anything is sent, as do the values any + operation refuses. +- An input object as `{field: value}`, a list as `[a, b]`. +- A variable without a value takes its default value, or is left out with + its argument or field, as GraphQL leaves out an argument whose variable + has no value; in a list, it is `null`. +- A variable that may hold a `JSON` value is refused at compile time. + +## Bulk mutations + +`bulk("mutation …")` is one mutation field, not `bulkOperationRunQuery` or +`bulkOperationRunMutation`, with one connection at most in what it selects +(Shopify's [rules](https://shopify.dev/docs/api/usage/bulk-operations/imports)). +Its `Variables`, or an inline `graphql!(bulk("mutation …"), …)`, are one line +of variables: [`Shopify::bulk_mutation`] takes an iterator of them. + +```rust,no_run +use shopify_api::bulk::BulkWaitOptions; +use shopify_api::{Shopify, graphql}; + +graphql! { + pub mod tag = bulk("mutation($id: ID!, $tags: [String!]!) { + tagsAdd(id: $id, tags: $tags) { userErrors { field message } } + }"); +} + +async fn tag_all(shopify: &Shopify, ids: &[String]) -> shopify_api::Result<()> { + let lines = ids.iter().map(|id| tag::Variables { id: id.clone(), tags: vec!["sale".into()] }); + let mut results = shopify.bulk_mutation(lines, BulkWaitOptions::default()).await?; + while let Some(result) = results.next_row().await { + let result = result?; + // `index`: the line of variables it ran with, from 0. + if let Some(payload) = result.data.and_then(|data| data.tags_add) { + for error in payload.user_errors { + println!("line {:?}: {}", result.index, error.message); + } + } + } + Ok(()) +} +``` + +Every line is checked and written before anything is sent: one value refused +fails the call. Shopify runs the lines in no set order; each result is a +[`BulkMutationResult`](crate::bulk::BulkMutationResult), the `data` of the +mutation, its `errors`, and the `index` of its line. + +## What is not checked + +- What Shopify refuses at run time and its guide does not list: a + connection its bulk queries cannot read, a field that times out, missing + access scopes. Those come back as the user errors of + `bulkOperationRunQuery`, or as a failed operation. +- Shopify may accept more than `graphql!` does (`nodes`, `first`, a + connection in a fragment): the untyped methods of [`bulk`](crate::bulk) + send any text. +- The order of the lines: the reader relies on the order `groupObjects` + writes, each child after its parent and before the next top-level object. + A file of another order is an error, not a misplaced child. + # Schema and API version No schema ships with `shopify_api`. Each crate that uses `graphql!` keeps the @@ -449,6 +604,7 @@ scripts an answer that leaves out a non-null field. # Limits - Subscriptions are refused, and one inline `graphql!` takes one operation. +- A bulk operation follows the rules above: see [what is not checked](#what-is-not-checked). - An error in the operation points at the whole operation; the line and column in its message locate the mistake inside it. An error in a value points at the value. diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index d6e64aa..6ca259a 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -1,48 +1,61 @@ //! Bulk operations: a query over a whole catalog, or a mutation over //! thousands of inputs, run by Shopify in the background, outside the rate limit. //! +//! Declare one with [`graphql!`](crate::graphql!)`(bulk(…))`: it is checked +//! against the schema and Shopify's bulk rules when the crate compiles, and +//! its results are read as generated types, each nested connection a `Vec` +//! of its nodes (see [the bulk operations of `graphql!`](crate::graphql!#bulk-operations)). +//! //! ```no_run -//! use serde::Deserialize; //! use shopify_api::bulk::BulkWaitOptions; //! -//! #[derive(Deserialize)] -//! struct Product { -//! id: String, -//! title: String, +//! shopify_api::graphql! { +//! mod all_products = bulk("{ +//! products { edges { node { id title variants { edges { node { sku } } } } } } +//! }"); //! } //! //! # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { -//! // Start, wait for the end, download and read every line. -//! let products: Vec = shopify -//! .bulk_query_rows("{ products { edges { node { id title } } } }", BulkWaitOptions::default()) +//! // Start, wait for the end, download, and read each product with its variants. +//! let products: Vec = shopify +//! .bulk_query(all_products::operation(), BulkWaitOptions::default()) +//! .await? +//! .collect() //! .await?; +//! for product in &products { +//! println!("{} has {} variants", product.title, product.variants.len()); +//! } //! # Ok(()) //! # } //! ``` //! -//! [`Shopify::bulk_query_rows`] holds every row in memory. For an export -//! of gigabytes, [`Shopify::bulk_query_stream`] reads the rows as the file -//! downloads ([`BulkRows`]), and [`Shopify::bulk_query_grouped`] each -//! top-level object with its nested objects ([`BulkGroups`]). Neither holds -//! the file: [`BulkRows`] holds the line being read and the rest of the -//! chunk it ends in, in a buffer sized for the longest recent line; [`BulkGroups`] holds that, and the group being read, -//! its top-level object with every child read so far and their IDs. A -//! product with 2,000 variants is held with its 2,000 variants. +//! [`Shopify::bulk_query`] reads the file as it downloads, one top-level +//! object at a time ([`BulkItems`]); [`Shopify::bulk_mutation`] runs a +//! mutation over an iterator of its `Variables` and reads the result of each +//! run ([`BulkMutationResult`]). //! -//! The query of a bulk operation is a plain string. To have it checked when -//! the crate compiles, declare it with [`graphql!`](crate::graphql!) and pass -//! its `QUERY`: +//! The untyped methods run any text, checked by nothing, and read each line +//! as the type you give, a `serde_json::Value` or a struct of yours: //! //! ```no_run -//! shopify_api::graphql! { -//! mod all_products = "{ products { edges { node { id title } } } }"; -//! } +//! use shopify_api::bulk::BulkWaitOptions; //! //! # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { -//! let operation = shopify.run_bulk_query(all_products::QUERY).await?; +//! let rows: Vec = shopify +//! .bulk_query_rows("{ products { edges { node { id title } } } }", BulkWaitOptions::default()) +//! .await?; //! # Ok(()) //! # } //! ``` +//! +//! [`Shopify::bulk_query_rows`] holds every row in memory. For an export +//! of gigabytes, [`Shopify::bulk_query_stream`] reads the rows as the file +//! downloads ([`BulkRows`]), and [`Shopify::bulk_query_grouped`] each +//! top-level object with its nested objects ([`BulkGroups`]). Neither holds +//! the file: [`BulkRows`] holds the line being read and the rest of the +//! chunk it ends in, in a buffer sized for the longest recent line; [`BulkGroups`] and [`BulkItems`] hold that, and the group being read, +//! its top-level object with every child read so far and their IDs. A +//! product with 2,000 variants is held with its 2,000 variants. use std::time::Duration; From fbbdeb921dc8c8cab6a3acc5838c36561aa8dd63 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:13:15 +0100 Subject: [PATCH 111/135] fix(bulk): refuse enum values `true`, `false` and `null` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A bulk query writes an enum variable bare. A `String` or `raw("…")` holding `null`, `true` or `false` passed the name check and was sent as `null` or a boolean: another value than the one given. They now fail with `InvalidValueReason::ReservedEnumValue` before anything is sent; a real `null` is still written `null`. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/docs/graphql.md | 6 ++++-- crates/shopify_api/src/bulk/typed.rs | 13 ++++++++++++- crates/shopify_api/src/graphql/check.rs | 7 +++++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 4681070..a8e27a8 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -446,8 +446,10 @@ GraphQL literal, and the variable definitions are left out. - An enum value bare (`sortKey: TITLE`), in an input object and in a list too. One that is not a GraphQL name, which `raw(…)` or a `String` field of `Variables` may hold, fails with [`Error::InvalidValue`](crate::Error::InvalidValue) - (`NotAGraphqlName`) before anything is sent, as do the values any - operation refuses. + (`NotAGraphqlName`) before anything is sent, as does an enum value + `true`, `false` or `null` (`ReservedEnumValue`), which would read as a + boolean or as `null`, and as do the values any operation refuses. A + `None` is still written `null`. - An input object as `{field: value}`, a list as `[a, b]`. - A variable without a value takes its default value, or is left out with its argument or field, as GraphQL leaves out an argument whose variable diff --git a/crates/shopify_api/src/bulk/typed.rs b/crates/shopify_api/src/bulk/typed.rs index b6fcb4e..d4e0edd 100644 --- a/crates/shopify_api/src/bulk/typed.rs +++ b/crates/shopify_api/src/bulk/typed.rs @@ -339,6 +339,17 @@ impl<'a> Json<'a> { } } + /// An enum value: a GraphQL name but `true`, `false` and `null`, which + /// would read as another kind of value. + fn enum_value(token: &str) -> std::result::Result { + let name = Self::name(token)?; + if matches!(name.as_str(), "true" | "false" | "null") { + Err(Invalid::new(InvalidValueReason::ReservedEnumValue)) + } else { + Ok(name) + } + } + fn write(&mut self, ty: &BulkType, out: &mut String) -> std::result::Result<(), Invalid> { self.skip_whitespace(); match self.text.get(self.at) { @@ -416,7 +427,7 @@ impl<'a> Json<'a> { Some(b'"') => { let token = self.string(); if matches!(element(ty), BulkType::Enum) { - out.push_str(&Self::name(token)?); + out.push_str(&Self::enum_value(token)?); } else { out.push_str(token); } diff --git a/crates/shopify_api/src/graphql/check.rs b/crates/shopify_api/src/graphql/check.rs index d9e4f6c..aa2963b 100644 --- a/crates/shopify_api/src/graphql/check.rs +++ b/crates/shopify_api/src/graphql/check.rs @@ -29,6 +29,10 @@ pub enum InvalidValueReason { /// bulk query writes its variables into its text, where it would not /// read as written. NotAGraphqlName, + /// An enum value `true`, `false` or `null`, which GraphQL does not + /// allow: written into a bulk query, it would read as a boolean or as + /// `null`. + ReservedEnumValue, } impl std::fmt::Display for InvalidValueReason { @@ -41,6 +45,9 @@ impl std::fmt::Display for InvalidValueReason { Self::NotAGraphqlName => { "not a GraphQL name, as an enum value or a field written into a bulk query must be" } + Self::ReservedEnumValue => { + "`true`, `false` or `null`, which GraphQL does not allow as an enum value" + } }) } } From 95aa6bbfb9530929b61b4da5dbc3eaf6de60e128 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:13:20 +0100 Subject: [PATCH 112/135] fix(bulk): refuse strings the GraphQL parser misreads A bulk query is sent as text written back from what `graphql-parser` read, and 0.4.1, its latest release, reads `\b` as U+0010 and splits and indents block strings unlike the specification (a lone `\r`, Unicode whitespace). Its values carry no position and input objects are sorted maps, so the original tokens cannot be mapped back reliably. Each string token of a bulk query is now decoded as the specification does and compared with what the parser read; a difference is a compile error that says what to write instead (`\u0008` for `\b`, a quoted string for a block string). Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api_graphql/src/bulk.rs | 3 + .../shopify_api_graphql/src/bulk/strings.rs | 255 ++++++++++++++++++ crates/shopify_api_graphql/tests/bulk.rs | 31 +++ 3 files changed, 289 insertions(+) create mode 100644 crates/shopify_api_graphql/src/bulk/strings.rs diff --git a/crates/shopify_api_graphql/src/bulk.rs b/crates/shopify_api_graphql/src/bulk.rs index f9bb8a7..74eee2e 100644 --- a/crates/shopify_api_graphql/src/bulk.rs +++ b/crates/shopify_api_graphql/src/bulk.rs @@ -24,6 +24,8 @@ //! as GraphQL literals at run time: the text is kept as [`Part`]s, with the //! argument lists that hold a variable apart. +mod strings; + use std::collections::{BTreeMap, BTreeSet}; use graphql_parser::Pos; @@ -244,6 +246,7 @@ pub fn analyze_bulk_query( if operation.kind != OperationKind::Query { return error("A bulk query is a query"); } + strings::check(source)?; let document = parse(source)?; let (definition, fragments) = parts_of(&document); let mut checker = Checker { diff --git a/crates/shopify_api_graphql/src/bulk/strings.rs b/crates/shopify_api_graphql/src/bulk/strings.rs new file mode 100644 index 0000000..6dfd6ab --- /dev/null +++ b/crates/shopify_api_graphql/src/bulk/strings.rs @@ -0,0 +1,255 @@ +//! The strings of a bulk query read as GraphQL reads them. +//! +//! A bulk query is sent as text written back from what `graphql-parser` +//! read, which decodes some strings unlike GraphQL: `\b` as U+0010, not +//! U+0008, and block strings split and indented with Unicode whitespace and +//! without a lone `\r` as a line break. Its values carry no position, and +//! the fields of an input object are kept sorted, so the text of a string +//! cannot be found back for its value. Each string of the source is +//! decoded here as the GraphQL specification does, and a string the +//! parser reads otherwise is refused. + +use super::error_at; +use crate::analyze::Error; +use graphql_parser::Pos; + +/// Refuses a string or block string of `source` that `graphql-parser` +/// does not read as GraphQL does. +pub(super) fn check(source: &str) -> Result<(), Error> { + let mut lexer = Lexer { + source, + at: 0, + line: 1, + column: 1, + }; + while let Some((position, token)) = lexer.next_string() { + let expected = if token.starts_with("\"\"\"") { + block_string(&token[3..token.len() - 3]) + } else { + quoted_string(&token[1..token.len() - 1]) + }; + if expected.is_some() && expected == parsed(token) { + continue; + } + let advice = if token.starts_with("\"\"\"") { + "Write it as a quoted string, with escapes" + } else if token.contains("\\b") { + "Write `\\u0008` rather than `\\b`" + } else { + "Write the characters it holds with `\\uXXXX` escapes" + }; + return error_at( + position, + format!( + "This string would not reach Shopify as written: the GraphQL parser this crate uses reads it otherwise, and a bulk query is sent as the text it read. {advice}" + ), + ); + } + Ok(()) +} + +/// The string the token is for `graphql-parser`. +fn parsed(token: &str) -> Option { + use graphql_parser::query::{Definition, OperationDefinition, Selection, Value}; + let source = format!("{{ f(a: {token}) }}"); + let document = graphql_parser::parse_query::(&source).ok()?; + let Some(Definition::Operation(OperationDefinition::SelectionSet(set))) = + document.definitions.into_iter().next() + else { + return None; + }; + let Some(Selection::Field(field)) = set.items.into_iter().next() else { + return None; + }; + match field.arguments.into_iter().next() { + Some((_, Value::String(value))) => Some(value), + _ => None, + } +} + +struct Lexer<'a> { + source: &'a str, + /// A byte offset. + at: usize, + line: usize, + column: usize, +} + +impl<'a> Lexer<'a> { + fn rest(&self) -> &'a str { + &self.source[self.at..] + } + + /// Moves `bytes` on, counting lines as the parser does. + fn advance(&mut self, bytes: usize) { + let end = self.at + bytes; + for character in self.source[self.at..end].chars() { + if character == '\n' { + self.line += 1; + self.column = 1; + } else if character == '\t' { + self.column += 8; + } else { + self.column += 1; + } + } + self.at = end; + } + + /// The next string token, quotes included, and where it starts. The + /// source parsed: every string ends. + fn next_string(&mut self) -> Option<(Pos, &'a str)> { + loop { + let rest = self.rest(); + let character = rest.chars().next()?; + match character { + '#' => { + let end = rest.find(['\n', '\r']).unwrap_or(rest.len()); + self.advance(end); + } + '"' => { + let position = Pos { + line: self.line, + column: self.column, + }; + let length = string_length(rest)?; + let token = &rest[..length]; + self.advance(length); + return Some((position, token)); + } + other => self.advance(other.len_utf8()), + } + } + } +} + +/// The length in bytes of the string token at the start of `rest`. +fn string_length(rest: &str) -> Option { + if let Some(body) = rest.strip_prefix("\"\"\"") { + let mut from = 0; + loop { + let end = from + body[from..].find("\"\"\"")?; + if body[..end].ends_with('\\') { + from = end + 3; + } else { + return Some(end + 6); + } + } + } + let mut escaped = false; + for (index, character) in rest.char_indices().skip(1) { + match character { + '"' if !escaped => return Some(index + 1), + _ => escaped = !escaped && character == '\\', + } + } + None +} + +/// The value of a quoted string, as the specification reads it. +fn quoted_string(body: &str) -> Option { + let mut value = String::with_capacity(body.len()); + let mut characters = body.chars(); + while let Some(character) = characters.next() { + match character { + '\\' => { + let escaped = match characters.next()? { + '"' => '"', + '\\' => '\\', + '/' => '/', + 'b' => '\u{8}', + 'f' => '\u{c}', + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + 'u' => { + let hex: String = characters.by_ref().take(4).collect(); + if hex.len() != 4 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return None; + } + char::from_u32(u32::from_str_radix(&hex, 16).ok()?)? + } + _ => return None, + }; + value.push(escaped); + } + // A line terminator ends a line, not a string. + '\n' | '\r' => return None, + other => value.push(other), + } + } + Some(value) +} + +/// The value of a block string, as the specification reads it. +fn block_string(body: &str) -> Option { + let raw = body.replace("\\\"\"\"", "\"\"\""); + let raw = raw.replace("\r\n", "\n").replace('\r', "\n"); + let lines: Vec<&str> = raw.split('\n').collect(); + let indent = |line: &str| line.len() - line.trim_start_matches([' ', '\t']).len(); + let common = lines + .iter() + .skip(1) + .filter(|line| indent(line) < line.len()) + .map(|line| indent(line)) + .min(); + let lines: Vec<&str> = lines + .iter() + .enumerate() + .map(|(index, line)| match common { + Some(common) if index > 0 => line.get(common..).unwrap_or(""), + _ => line, + }) + .collect(); + let blank = |line: &&str| line.trim_start_matches([' ', '\t']).is_empty(); + let first = lines.iter().position(|line| !blank(line)); + let last = lines.iter().rposition(|line| !blank(line)); + match (first, last) { + (Some(first), Some(last)) => Some(lines[first..=last].join("\n")), + _ => Some(String::new()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strings_end_where_the_parser_ends_them() { + assert_eq!(string_length(r#""a\"b" x"#), Some(6)); + assert_eq!(string_length(r#""a\\" x"#), Some(5)); + assert_eq!(string_length(r#""""a\"""b""" x"#), Some(12)); + assert_eq!(string_length(r#""""""" x"#), Some(6)); + } + + #[test] + fn comments_hide_quotes() { + assert!(check("# \"\\b\"\n{ f }").is_ok()); + assert!(check("{ f(a: \"# \\b\") }").is_err()); + } + + #[test] + fn the_parser_is_checked_for_every_escape() { + for escape in [ + r"\u0008", r#"\""#, r"\\", r"\/", r"\f", r"\n", r"\r", r"\t", r"\u00e9", r"\uFFFF", + ] { + let source = format!("{{ f(a: \"x{escape}y\") }}"); + assert!(check(&source).is_ok(), "{escape}"); + } + let error = check("{ f(a: \"x\\by\") }").unwrap_err(); + assert!(error.message.contains("`\\u0008`"), "{}", error.message); + assert_eq!(error.position, Some((1, 8))); + } + + #[test] + fn block_strings_follow_the_specification() { + assert_eq!( + block_string("\n a\n b\n \\\"\"\"\n "), + Some("a\n b\n\"\"\"".to_string()) + ); + assert_eq!(block_string("a\rb"), Some("a\nb".to_string())); + assert!(check("{ f(a: \"\"\"\n a\n b\n \"\"\") }").is_ok()); + assert!(check("{ f(a: \"\"\"a\rb\"\"\") }").is_err()); + assert!(check("{ f(a: \"\"\"\n\u{a0}a\n\u{a0}b\"\"\") }").is_err()); + } +} diff --git a/crates/shopify_api_graphql/tests/bulk.rs b/crates/shopify_api_graphql/tests/bulk.rs index 2864d77..46c7461 100644 --- a/crates/shopify_api_graphql/tests/bulk.rs +++ b/crates/shopify_api_graphql/tests/bulk.rs @@ -173,6 +173,37 @@ fn shape(connections: &[Connection]) -> String { .join(", ") } +#[test] +fn strings_the_parser_misreads_are_refused() { + let escape = "This string would not reach Shopify as written: the GraphQL parser this crate uses reads it otherwise, and a bulk query is sent as the text it read. Write `\\u0008` rather than `\\b`"; + let block = "This string would not reach Shopify as written: the GraphQL parser this crate uses reads it otherwise, and a bulk query is sent as the text it read. Write it as a quoted string, with escapes"; + assert_eq!( + refusal(r#"{ things(q: "a\bb") { edges { node { id } } } }"#), + format!("{escape} (line 1, column 13)") + ); + assert_eq!( + refusal("query($q: String = \"\\b\") { things(q: $q) { edges { node { id } } } }"), + format!("{escape} (line 1, column 20)") + ); + assert_eq!( + refusal("{ things(q: \"\"\"a\rb\"\"\") { edges { node { id } } } }"), + format!("{block} (line 1, column 13)") + ); + assert_eq!( + refusal("{ things(q: \"\"\"\n\u{a0}a\n\u{a0}b\"\"\") { edges { node { id } } } }"), + format!("{block} (line 1, column 13)") + ); + // In a comment, a `\b` is nothing. + bulk("# \"\\b\"\n{ things(q: \"\\u0008\") { edges { node { id } } } }"); + // `\u{…}` and surrogate pairs do not parse. + for source in [ + r#"{ things(q: "\u{1F600}") { edges { node { id } } } }"#, + r#"{ things(q: "\uD83D\uDE00") { edges { node { id } } } }"#, + ] { + assert!(analyze(schema(), source).is_err(), "{source}"); + } +} + #[test] fn siblings_that_may_return_one_type_are_refused() { assert_eq!( From 1a731066328514769b78ddc000e362035c61110a Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:13:36 +0100 Subject: [PATCH 113/135] fix(bulk): place lines by a string `id` and a reserved typename alias - A line's `id` places its children only when it is a string: another value, such as `id: totalInventory`, no longer fails every line with `Error::Decode`. On a node with nested connections, which must select `id` itself, another field aliased `id` is refused at compile time. - Where lines need it, the text sent selects `_shopifyApiTypename: __typename` and lines are routed by that key alone: a `__typename` of the query, aliased or conditional, is left as written instead of merging with an unconditional one. The alias is reserved and refused in a bulk query. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/docs/graphql.md | 21 +++-- crates/shopify_api/src/bulk/rows.rs | 89 ++++++++++++++++++- crates/shopify_api/src/bulk/typed.rs | 10 ++- crates/shopify_api/tests/bulk_typed.rs | 24 ++--- .../tests/ui/bulk_reserved_alias.stderr | 2 +- crates/shopify_api_graphql/src/bulk.rs | 53 +++++++++-- crates/shopify_api_graphql/tests/bulk.rs | 26 +++++- 7 files changed, 191 insertions(+), 34 deletions(-) diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index a8e27a8..1534f05 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -403,12 +403,19 @@ Where the guide is silent, what it does not show is refused: a query - A nested connection is written right in the `node { … }` of its parent connection: not in a fragment, nor under another field. - A node with nested connections selects `id`, without an alias or a - directive. Shopify refuses the query without it, and the lines of the - children are placed under their parent by that `id`: `graphql!` asks you to - add it rather than adding it itself. + directive, and no other field aliased `id`. Shopify refuses the query + without it, and the lines of the children are placed under their parent + by that `id`: `graphql!` asks you to add it rather than adding it itself. + Elsewhere, `id` may be the alias of any field. - Two connections of one node that may return the same type, such as two aliased `metafields(…)`, are refused: their lines could not be told apart. -- No alias starting with `__`. +- No alias starting with `__`, nor `_shopifyApiTypename`. +- A string the GraphQL parser of `graphql!` reads otherwise than the + GraphQL specification: the query is sent as the text it read. That is a + `\b` escape, which it reads as U+0010 (write `\u0008`), and a block string + with a lone carriage return or indented with other whitespace than spaces + and tabs (write a quoted string). Escapes `\u{…}` and surrogate pairs do not + parse at all. ## The items of a bulk query @@ -430,8 +437,10 @@ and [`Shopify::download_bulk_items`] split the steps, for an operation you wait for yourself. The text sent is not the text written. Where a node has several nested -connections, their nodes gain `__typename`, which tells their lines apart; -the types do not show it. [`BulkQuery::text`](crate::bulk::BulkQuery::text) +connections, their nodes gain `_shopifyApiTypename: __typename`, which +tells their lines apart; the types do not show it, and a `__typename` you +select is left as you wrote it. `_shopifyApiTypename` is reserved: it cannot +be an alias in a bulk query, nor can an alias that starts with `__`. [`BulkQuery::text`](crate::bulk::BulkQuery::text) gives the text sent. ## Variables of a bulk query diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index 6cc5cb3..52d653e 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -281,15 +281,89 @@ impl FusedStream for BulkRows { } } +/// The alias of the `__typename` that [`BulkQuery::text`](crate::bulk::BulkQuery::text) +/// selects where nested lines need it, `shopify_api_graphql::bulk::TYPENAME_KEY`. +pub(crate) const TYPENAME_KEY: &str = "_shopifyApiTypename"; + +/// What places a line. Its `id` is read only when it is a string: an alias +/// `id` of another field is the query's to read, and an object whose lines +/// are placed under it selects `id` itself. #[derive(Deserialize)] struct Keys { + #[serde(default, deserialize_with = "string_or_none")] id: Option, #[serde(rename = "__parentId")] parent_id: Option, - #[serde(rename = "__typename")] + #[serde(rename = "_shopifyApiTypename")] typename: Option, } +/// A string, or `None` for any other value. +fn string_or_none<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> std::result::Result, D::Error> { + struct Visitor; + impl<'de> serde::de::Visitor<'de> for Visitor { + type Value = Option; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("any value") + } + + fn visit_str(self, value: &str) -> std::result::Result { + Ok(Some(value.to_string())) + } + + fn visit_string(self, value: String) -> std::result::Result { + Ok(Some(value)) + } + + fn visit_bool(self, _: bool) -> std::result::Result { + Ok(None) + } + + fn visit_i64(self, _: i64) -> std::result::Result { + Ok(None) + } + + fn visit_u64(self, _: u64) -> std::result::Result { + Ok(None) + } + + fn visit_f64(self, _: f64) -> std::result::Result { + Ok(None) + } + + fn visit_unit(self) -> std::result::Result { + Ok(None) + } + + fn visit_none(self) -> std::result::Result { + Ok(None) + } + + fn visit_seq>( + self, + mut seq: A, + ) -> std::result::Result { + while seq.next_element::()?.is_some() {} + Ok(None) + } + + fn visit_map>( + self, + mut map: A, + ) -> std::result::Result { + while map + .next_entry::()? + .is_some() + {} + Ok(None) + } + } + deserializer.deserialize_any(Visitor) +} + /// The error of a line whose `__parentId` matches no object it may be a child of. fn misplaced(number: usize, missing_id: bool, grouped: bool) -> Error { let message = if missing_id { @@ -517,7 +591,8 @@ struct ItemGroup { /// A nested line goes to its parent by its `__parentId`, and, when its /// parent has several connections, to the connection that returns its /// `__typename`, which [`BulkQuery::text`](crate::bulk::BulkQuery::text) -/// selects for that. +/// selects for that under the alias `_shopifyApiTypename`. A `__typename` +/// the query selects itself is not read to place lines. /// /// # Errors /// @@ -614,7 +689,7 @@ impl BulkItems { _ => { let typename = keys.typename.as_deref().ok_or_else(|| { super::bulk_error(format!( - "line {number} of the results has no `__typename`, which tells which connection of its parent it belongs to" + "line {number} of the results has no `{TYPENAME_KEY}`, the `__typename` that tells which connection of its parent it belongs to" )) })?; connections @@ -622,7 +697,7 @@ impl BulkItems { .position(|connection| connection.types.contains(&typename)) .ok_or_else(|| { super::bulk_error(format!( - "line {number} of the results has a `__typename` that no connection of its parent returns" + "line {number} of the results has a `{TYPENAME_KEY}`, its `__typename`, that no connection of its parent returns" )) })? } @@ -701,6 +776,12 @@ impl FusedStream for BulkItems { #[cfg(test)] mod tests { + #[cfg(feature = "cli")] + #[test] + fn the_typename_key_is_the_one_the_macros_select() { + assert_eq!(super::TYPENAME_KEY, shopify_api_graphql::bulk::TYPENAME_KEY); + } + use super::*; use crate::transport::{TransportError, chunks}; diff --git a/crates/shopify_api/src/bulk/typed.rs b/crates/shopify_api/src/bulk/typed.rs index d4e0edd..e1c623d 100644 --- a/crates/shopify_api/src/bulk/typed.rs +++ b/crates/shopify_api/src/bulk/typed.rs @@ -184,14 +184,16 @@ impl BulkQuery { /// The text Shopify runs: without variable definitions, each variable /// written in as a GraphQL literal (an enum value bare, an input object - /// as `{field: value}`), and `__typename` selected on the nodes of the - /// connections that share a parent, which tells their lines apart. A + /// as `{field: value}`), and `_shopifyApiTypename: __typename` selected + /// on the nodes of the connections that share a parent, which tells + /// their lines apart. A /// variable without a value is left out, as GraphQL leaves out an /// argument whose variable has none, or takes its default value. /// /// Fails with [`Error::InvalidValue`] for a value the variables refuse - /// ([`Shopify::execute`] would), and for an enum value or a field name - /// that is not a GraphQL name. + /// ([`Shopify::execute`] would), for an enum value or a field name + /// that is not a GraphQL name, and for an enum value `true`, `false` or + /// `null`, which would read as another value. pub fn text(&self) -> Result { let values = self.operation.variable_values()?; let writer = Writer { diff --git a/crates/shopify_api/tests/bulk_typed.rs b/crates/shopify_api/tests/bulk_typed.rs index 56cac33..0332106 100644 --- a/crates/shopify_api/tests/bulk_typed.rs +++ b/crates/shopify_api/tests/bulk_typed.rs @@ -101,12 +101,12 @@ fn shopify_with(jsonl: &'static str) -> (MockTransport, Arc tests/ui/bulk_reserved_alias.rs:2:40 | diff --git a/crates/shopify_api_graphql/src/bulk.rs b/crates/shopify_api_graphql/src/bulk.rs index 74eee2e..79bff29 100644 --- a/crates/shopify_api_graphql/src/bulk.rs +++ b/crates/shopify_api_graphql/src/bulk.rs @@ -16,7 +16,8 @@ //! - the nodes of a connection implement `Node`; //! - a nested connection written in the `node { … }` of its parent, not in //! a fragment or under another field; -//! - an object with nested connections selects `id`, without an alias; +//! - an object with nested connections selects `id`, without an alias, +//! and no other field under the key `id`; //! - two connections of one object that may return the same type are //! refused: their lines could not be told apart. //! @@ -50,6 +51,11 @@ pub const MAX_DEPTH: usize = 2; /// The name of the type generated for each top-level object of a bulk query. pub const ITEM_TYPE: &str = "Item"; +/// The alias of the `__typename` written on the nodes of the connections +/// that share a parent, which tells their lines apart. The lines are routed +/// by it alone: a `__typename` the query selects is left as written. +pub const TYPENAME_KEY: &str = "_shopifyApiTypename"; + /// Arguments Shopify ignores in a bulk query: it reads every object. const PAGINATION: [&str; 4] = ["first", "last", "after", "before"]; @@ -432,7 +438,7 @@ struct Checker<'a, 's> { fragments: &'a Fragments<'a>, /// The connections seen so far. count: usize, - /// The `node` fields whose selection gains `__typename`. + /// The `node` fields whose selection gains `__typename`, aliased [`TYPENAME_KEY`]. typename: BTreeSet<(usize, usize)>, } @@ -531,6 +537,15 @@ impl<'a> Checker<'a, '_> { let children = self.node_selection(&node.selection_set, &node_type, depth)?; if let Some(child) = children.first() { + if let Some(other) = self.aliased_id(&node.selection_set, 0) { + return error_at( + other.position, + format!( + "`id: {}` is refused on the nodes of `{}`, which have the nested connection `{}`: each nested line is placed under its parent by the `id` of that parent. Give `{}` another alias", + other.name, field.name, child.name, other.name + ), + ); + } let has_id = node.selection_set.items.iter().any(|item| { matches!(item, ast::Selection::Field(id) if id.name == "id" && id.alias.is_none() && id.directives.is_empty()) }); @@ -585,15 +600,39 @@ impl<'a> Checker<'a, '_> { fields_of(self.schema, parent).and_then(|fields| fields.get(&field.name)) } + /// A field other than `id` aliased `id` in `set` or its fragments. + fn aliased_id( + &self, + set: &'a SelectionSet<'a>, + depth: usize, + ) -> Option<&'a ast::Field<'a, String>> { + // Fragments do not nest without end: `analyze` refused that. + if depth > 64 { + return None; + } + set.items.iter().find_map(|item| match item { + ast::Selection::Field(field) => { + (field.alias.as_deref() == Some("id") && field.name != "id").then_some(field) + } + ast::Selection::InlineFragment(fragment) => { + self.aliased_id(&fragment.selection_set, depth + 1) + } + ast::Selection::FragmentSpread(spread) => self + .fragments + .get(spread.fragment_name.as_str()) + .and_then(|fragment| self.aliased_id(&fragment.selection_set, depth + 1)), + }) + } + /// Refuses an alias Shopify or this crate writes in the lines. fn check_key(field: &ast::Field<'_, String>) -> Result<(), Error> { if let Some(alias) = &field.alias - && alias.starts_with("__") + && (alias.starts_with("__") || alias == TYPENAME_KEY) { return error_at( field.position, format!( - "`{alias}` cannot be an alias in a bulk query: the lines of its results hold `__parentId` and `__typename`" + "`{alias}` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `{TYPENAME_KEY}` where this crate selects `__typename` to place them" ), ); } @@ -880,7 +919,7 @@ fn value_part(value: &Value<'_>) -> ValuePart { } /// Writes a document back as text, without its variable definitions, with -/// `__typename` where the lines need it. +/// `__typename` aliased [`TYPENAME_KEY`] where the lines need it. struct Printer<'c> { typename: &'c BTreeSet<(usize, usize)>, parts: Vec, @@ -938,7 +977,9 @@ impl Printer<'_> { fn selection_set(&mut self, set: &SelectionSet<'_>, typename: bool) { self.text.push('{'); if typename { - self.text.push_str(" __typename"); + self.text.push(' '); + self.text.push_str(TYPENAME_KEY); + self.text.push_str(": __typename"); } for item in &set.items { self.text.push(' '); diff --git a/crates/shopify_api_graphql/tests/bulk.rs b/crates/shopify_api_graphql/tests/bulk.rs index 46c7461..9bc4347 100644 --- a/crates/shopify_api_graphql/tests/bulk.rs +++ b/crates/shopify_api_graphql/tests/bulk.rs @@ -204,6 +204,30 @@ fn strings_the_parser_misreads_are_refused() { } } +#[test] +fn another_field_aliased_id_is_refused_beside_a_nested_connection() { + let message = "`id: name` is refused on the nodes of `things`, which have the nested connection `parts`: each nested line is placed under its parent by the `id` of that parent. Give `name` another alias"; + assert_eq!( + refusal("{ things { edges { node { id: name parts { edges { node { id } } } } } } }"), + format!("{message} (line 1, column 27)") + ); + assert_eq!( + refusal( + "{ things { edges { node { ...F parts { edges { node { id } } } } } } } fragment F on Thing { id: name }" + ), + format!("{message} (line 1, column 94)") + ); + // The analysis refuses two fields under one key before the bulk rules. + let error = analyze( + schema(), + "{ things { edges { node { id id: name parts { edges { node { id } } } } } } }", + ) + .unwrap_err(); + assert!(error.message.contains("`id` is selected twice"), "{error}"); + // Without a nested connection, `id` may name any field. + bulk("{ things { edges { node { id: name parts: name } } } }"); +} + #[test] fn siblings_that_may_return_one_type_are_refused() { assert_eq!( @@ -251,7 +275,7 @@ fn the_rules_of_shopify_are_refusals() { ), ( "{ things { edges { node { id __typename: name } } } }", - "`__typename` cannot be an alias in a bulk query: the lines of its results hold `__parentId` and `__typename` (line 1, column 30)", + "`__typename` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 30)", ), ( "mutation { make(id: \"1\") { a { edges { node { id } } } b { edges { node { id } } } } }", From fc857dc10eb0c0b37e3e25fcd8ee8ddadb31aea6 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:13:43 +0100 Subject: [PATCH 114/135] test(ui): pin the bulk refusals and the reserved `__shopify_api_` prefix UI tests for a `\b` string, the `_shopifyApiTypename` alias and an `id` alias beside a nested connection. A constant named like a binding of the generated code (`__shopify_api_parent`, `__shopify_api_value0`) fails to compile with E0308: no binding form escapes a constant in scope (`ref`, `mut` and `x @ _` all give E0530), so the prefix is documented as reserved and the error pinned, for bulk and literal code alike. The new files shift trybuild's crate indexes, which the hashed names of five `literal_*` snapshots follow. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/docs/graphql.md | 4 +++ .../ui/bulk_id_alias_beside_connection.rs | 3 ++ .../ui/bulk_id_alias_beside_connection.stderr | 6 ++++ .../tests/ui/bulk_reserved_prefix_constant.rs | 7 +++++ .../ui/bulk_reserved_prefix_constant.stderr | 31 +++++++++++++++++++ .../tests/ui/bulk_string_escape.rs | 4 +++ .../tests/ui/bulk_string_escape.stderr | 6 ++++ .../shopify_api/tests/ui/bulk_typename_key.rs | 3 ++ .../tests/ui/bulk_typename_key.stderr | 6 ++++ ...literal_maybe_non_null_with_default.stderr | 4 +-- .../tests/ui/literal_one_of.stderr | 4 +-- .../tests/ui/literal_option_in_field.stderr | 2 +- .../ui/literal_reserved_prefix_constant.rs | 8 +++++ .../literal_reserved_prefix_constant.stderr | 21 +++++++++++++ .../tests/ui/literal_wrong_input_type.stderr | 6 ++-- .../tests/ui/literal_wrong_scalar.stderr | 10 +++--- 16 files changed, 112 insertions(+), 13 deletions(-) create mode 100644 crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.rs create mode 100644 crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.rs create mode 100644 crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_string_escape.rs create mode 100644 crates/shopify_api/tests/ui/bulk_string_escape.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_typename_key.rs create mode 100644 crates/shopify_api/tests/ui/bulk_typename_key.stderr create mode 100644 crates/shopify_api/tests/ui/literal_reserved_prefix_constant.rs create mode 100644 crates/shopify_api/tests/ui/literal_reserved_prefix_constant.stderr diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 1534f05..c199545 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -633,6 +633,10 @@ scripts an answer that leaves out a non-null field. - Enum values are checked where they are written; the `String` fields of `Variables` and `raw(…)` are not. - The generated code refers to `::shopify_api`: the dependency cannot be renamed. +- Names that start with `__shopify_api_` or `__SHOPIFY_API_` are reserved + to the generated code. Its bindings are hygienic, but a constant of such a + name in scope makes a pattern of the generated code refer to it: the code + then fails to compile (E0308 or E0530). It never changes meaning. - Under `#![no_implicit_prelude]`, a literal or an `input!` that holds a Rust expression does not compile: its messages are `#[diagnostic::on_unimplemented]`, whose `diagnostic` namespace that attribute hides. Literals of constants, diff --git a/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.rs b/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.rs new file mode 100644 index 0000000..a36ef88 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id: handle variants { edges { node { sku } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.stderr b/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.stderr new file mode 100644 index 0000000..aefdad4 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.stderr @@ -0,0 +1,6 @@ +error: `id: handle` is refused on the nodes of `products`, which have the nested connection `variants`: each nested line is placed under its parent by the `id` of that parent. Give `handle` another alias (line 1, column 29) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_id_alias_beside_connection.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { id: handle variants { edges { node { sku } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.rs b/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.rs new file mode 100644 index 0000000..96c1a91 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.rs @@ -0,0 +1,7 @@ +// A constant named like a binding of the generated code: a compile error, not a change of meaning. +#![allow(non_upper_case_globals)] +const __shopify_api_parent: usize = 0; + +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id variants { edges { node { sku } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.stderr b/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.stderr new file mode 100644 index 0000000..f95f7f8 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.stderr @@ -0,0 +1,31 @@ +error[E0308]: mismatched types + --> tests/ui/bulk_reserved_prefix_constant.rs:6:13 + | +3 | const __shopify_api_parent: usize = 0; + | --------------------------------- constant defined here +... +6 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { id variants { edges { node { sku } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | expected `Option<(usize, usize)>`, found `usize` + | expected due to this + | `__shopify_api_parent` is interpreted as a constant, not a new binding + | + = note: expected enum `Option<(usize, usize)>` + found type `usize` + = note: this error originates in the macro `shopify_api::graphql` (in Nightly builds, run with -Z macro-backtrace for more info) +help: introduce a new binding instead + | +6 - let _ = shopify_api::graphql!(bulk("{ products { edges { node { id variants { edges { node { sku } } } } } } }")); +6 + let _ = other___shopify_api_parent; + | + +error[E0308]: mismatched types + --> tests/ui/bulk_reserved_prefix_constant.rs:6:13 + | +6 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { id variants { edges { node { sku } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `Option<_>` + | + = note: expected type `usize` + found enum `Option<_>` + = note: this error originates in the macro `shopify_api::graphql` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/bulk_string_escape.rs b/crates/shopify_api/tests/ui/bulk_string_escape.rs new file mode 100644 index 0000000..595d66f --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_string_escape.rs @@ -0,0 +1,4 @@ +fn main() { + // `graphql-parser` reads `\b` as U+0010, and the bulk text is written back from what it read. + let _ = shopify_api::graphql!(bulk(r#"{ products(query: "a\bb") { edges { node { id } } } }"#)); +} diff --git a/crates/shopify_api/tests/ui/bulk_string_escape.stderr b/crates/shopify_api/tests/ui/bulk_string_escape.stderr new file mode 100644 index 0000000..57ab65c --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_string_escape.stderr @@ -0,0 +1,6 @@ +error: This string would not reach Shopify as written: the GraphQL parser this crate uses reads it otherwise, and a bulk query is sent as the text it read. Write `\u0008` rather than `\b` (line 1, column 19) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_string_escape.rs:3:40 + | +3 | let _ = shopify_api::graphql!(bulk(r#"{ products(query: "a\bb") { edges { node { id } } } }"#)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_typename_key.rs b/crates/shopify_api/tests/ui/bulk_typename_key.rs new file mode 100644 index 0000000..b33fc54 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_typename_key.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { _shopifyApiTypename: title } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_typename_key.stderr b/crates/shopify_api/tests/ui/bulk_typename_key.stderr new file mode 100644 index 0000000..54626dd --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_typename_key.stderr @@ -0,0 +1,6 @@ +error: `_shopifyApiTypename` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 29) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_typename_key.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { _shopifyApiTypename: title } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr index 69a130a..a96ddba 100644 --- a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -7,13 +7,13 @@ error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[Inven | | an `Option`: `None` leaves the field out | required by a bound introduced by this call | - = help: the trait `__ShopifyApiNoNull4_c24bed09` is not implemented for `Vec>` + = help: the trait `__ShopifyApiNoNull4_c2391752` is not implemented for `Vec>` help: this trait has no implementations, consider adding one --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c24bed09` +note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c2391752` --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); diff --git a/crates/shopify_api/tests/ui/literal_one_of.stderr b/crates/shopify_api/tests/ui/literal_one_of.stderr index bf5eaa3..7ece298 100644 --- a/crates/shopify_api/tests/ui/literal_one_of.stderr +++ b/crates/shopify_api/tests/ui/literal_one_of.stderr @@ -35,7 +35,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Optio | `Option<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2391752` is not implemented for `Option<&str>` + = help: the trait `main::__ShopifyApiExpect1_c2392dae` is not implemented for `Option<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:7:13 | @@ -52,7 +52,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Maybe | `Maybe<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2391752` is not implemented for `Maybe<&str>` + = help: the trait `main::__ShopifyApiExpect1_c2392dae` is not implemented for `Maybe<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:8:13 | diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr index 8e7c733..fcce46f 100644 --- a/crates/shopify_api/tests/ui/literal_option_in_field.stderr +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -7,7 +7,7 @@ error[E0277]: `vendor` of `ProductUpdateInput` expects a `String`, not `Option` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect1_c239102d` is not implemented for `Option` + = help: the trait `__ShopifyApiExpect1_c2392f79` is not implemented for `Option` = note: `vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null` note: required by a bound in `Checks::build` --> tests/ui/literal_option_in_field.rs:3:13 diff --git a/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.rs b/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.rs new file mode 100644 index 0000000..983b5ea --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.rs @@ -0,0 +1,8 @@ +// A constant named like a binding of the generated code: a compile error, not a change of meaning. +#![allow(non_upper_case_globals)] +const __shopify_api_value0: &str = ""; + +fn main() { + let title = String::from("Shirt"); + let _ = shopify_api::input!(ProductInput { title: title }); +} diff --git a/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.stderr b/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.stderr new file mode 100644 index 0000000..d8794ab --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.stderr @@ -0,0 +1,21 @@ +error[E0308]: mismatched types + --> tests/ui/literal_reserved_prefix_constant.rs:7:13 + | +3 | const __shopify_api_value0: &str = ""; + | -------------------------------- constant defined here +... +7 | let _ = shopify_api::input!(ProductInput { title: title }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | expected type parameter `V2`, found `&str` + | expected due to this + | `__shopify_api_value0` is interpreted as a constant, not a new binding + | + = note: expected type parameter `V2` + found reference `&'static str` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) +help: introduce a new binding instead + | +7 - let _ = shopify_api::input!(ProductInput { title: title }); +7 + let _ = other___shopify_api_value0; + | diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr index d69fa60..41a9411 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -9,8 +9,8 @@ error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built wit 6 | | ); | |_____- required by a bound introduced by this call | - = help: the trait `__ShopifyApiExpect2_c2391234` is not implemented for `InputObject<2493993284262097346>` -help: the following other types implement trait `__ShopifyApiExpect2_c2391234` + = help: the trait `__ShopifyApiExpect2_c1d687d2` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2_c1d687d2` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -22,7 +22,7 @@ help: the following other types implement trait `__ShopifyApiExpect2_c2391234` | | | | |_____`&InputObject<960560859991546817>` | `InputObject<960560859991546817>` -note: required for `Vec>` to implement `__ShopifyApiExpect1_c2391234` +note: required for `Vec>` to implement `__ShopifyApiExpect1_c1d687d2` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr index 8152d03..89f0444 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr @@ -7,7 +7,7 @@ error[E0277]: `quantity` of `DraftOrderLineItemInput` expects an `Int`, not `&st | `&'static str` doesn't satisfy the trait bound | any integer type | - = help: the trait `main::__ShopifyApiExpect1_c2391187` is not implemented for `&str` + = help: the trait `main::__ShopifyApiExpect1_c1d68fcb` is not implemented for `&str` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 | @@ -24,7 +24,7 @@ error[E0277]: `title` of `DraftOrderLineItemInput` expects a `String`, not `u8` | `u8` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect3_c2391187` is not implemented for `u8` + = help: the trait `__ShopifyApiExpect3_c1d68fcb` is not implemented for `u8` = note: `title?: value` takes an `Option`, `None` leaving the field out; `title: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -42,7 +42,7 @@ error[E0277]: `requiresShipping` of `DraftOrderLineItemInput` expects a `Boolean | `{integer}` doesn't satisfy the trait bound | `bool` | - = help: the trait `__ShopifyApiExpect5_c2391187` is not implemented for `{integer}` + = help: the trait `__ShopifyApiExpect5_c1d68fcb` is not implemented for `{integer}` = note: `requiresShipping?: value` takes an `Option`, `None` leaving the field out; `requiresShipping: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -60,8 +60,8 @@ error[E0277]: `value` of `WeightInput` expects a `Float`, not `u64` | `u64` doesn't satisfy the trait bound | `f64`, `f32`, `i32` or `u32` | - = help: the trait `main::__ShopifyApiExpect1_c2391187` is not implemented for `u64` - = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c2391187`, but not `main::__ShopifyApiExpect1_c2391187` + = help: the trait `main::__ShopifyApiExpect1_c1d68fcb` is not implemented for `u64` + = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c1d68fcb`, but not `main::__ShopifyApiExpect1_c1d68fcb` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:4:13 | From 1b43409d5c882e862be7ef5e254c37b9485de601 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:13:43 +0100 Subject: [PATCH 115/135] test(bulk): regressions for the text and the routing of bulk queries Enum values `true`, `false` and `null` in a variable, a list and an input field; every GraphQL escape and block strings, in constants and defaults, decoded by the test's own decoder against the value written; a string variable of every code point; `id` aliases of other types on an item and a child; routing by `_shopifyApiTypename` beside a conditional `__typename`. The changelog says what changed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +- crates/shopify_api/tests/bulk_text.rs | 453 ++++++++++++++++++++++++++ 2 files changed, 456 insertions(+), 3 deletions(-) create mode 100644 crates/shopify_api/tests/bulk_text.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index b15faa8..f92612b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,9 +25,9 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Bulk results read as they download, in memory that follows the line being read rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. - `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group; so is a child whose parent has no unaliased `id`, which the error names. - `run_bulk_mutation_iter` and `stage_bulk_variables_iter` take the variables from an iterator; the JSONL is written straight into the body of the upload, in memory once. -- Bulk operations checked at compile time: `graphql!(bulk("…"))`, `bulk(file("…"))`, inline or in a module. A bulk query is checked against Shopify's bulk rules for API 2026-10: one top-level field, a connection (not `node` or `nodes`); five connections at most, two levels deep below it; `edges { node { … } }` and nothing else (no `nodes`, `cursor`, `pageInfo`, nor `first`, `last`, `after`, `before`); `Node` objects; a nested connection written right in the `node` of its parent; an unaliased `id` on every node with nested connections (an error that asks for it, never added silently); two connections of one node that may return the same type, such as two aliased `metafields`, are refused. What the guide does not show is refused. A bulk mutation is one mutation field, not a bulk operation, with one connection at most. -- The items of a bulk query are generated types: `Item`, each nested connection a `Vec` of its nodes. `Shopify::bulk_query` runs it with `groupObjects` and returns `BulkItems` (`next_item`, `collect`, `Stream`), one item in memory at a time, nested lines placed by `__parentId`, and by `__typename` where a node has several connections: the text sent selects it there. `start_bulk_query` and `download_bulk_items` split the steps; `BulkQuery::text` is the text sent. -- The variables of a bulk query, which Shopify does not take, are given as for any operation (literals and `input!` included) and written into its text as GraphQL literals, from the parsed operation: strings escaped as JSON, enum values bare (in input objects and lists too), input objects with unquoted keys, a variable without a value left out or given its default. The values are checked as for any operation; an enum value or a field that is not a GraphQL name fails with `InvalidValueReason::NotAGraphqlName`. A variable that may hold `JSON` is refused at compile time. +- Bulk operations checked at compile time: `graphql!(bulk("…"))`, `bulk(file("…"))`, inline or in a module. A bulk query is checked against Shopify's bulk rules for API 2026-10: one top-level field, a connection (not `node` or `nodes`); five connections at most, two levels deep below it; `edges { node { … } }` and nothing else (no `nodes`, `cursor`, `pageInfo`, nor `first`, `last`, `after`, `before`); `Node` objects; a nested connection written right in the `node` of its parent; an unaliased `id` on every node with nested connections (an error that asks for it, never added silently), and no other field aliased `id` there; no alias `_shopifyApiTypename` or starting with `__`; no string that the parser reads unlike GraphQL (a `\b` escape, which it reads as U+0010: write `\u0008`; a block string with a lone carriage return or indented with other whitespace than spaces and tabs); two connections of one node that may return the same type, such as two aliased `metafields`, are refused. What the guide does not show is refused. A bulk mutation is one mutation field, not a bulk operation, with one connection at most. +- The items of a bulk query are generated types: `Item`, each nested connection a `Vec` of its nodes. `Shopify::bulk_query` runs it with `groupObjects` and returns `BulkItems` (`next_item`, `collect`, `Stream`), one item in memory at a time, nested lines placed by `__parentId`, and by `__typename` where a node has several connections: the text sent selects it there as `_shopifyApiTypename: __typename`, and a `__typename` of the query is left as written. A line's `id` places its children only when it is a string: `id` may alias another field where no connection is nested. `start_bulk_query` and `download_bulk_items` split the steps; `BulkQuery::text` is the text sent. +- The variables of a bulk query, which Shopify does not take, are given as for any operation (literals and `input!` included) and written into its text as GraphQL literals, from the parsed operation: strings escaped as JSON, enum values bare (in input objects and lists too), input objects with unquoted keys, a variable without a value left out or given its default. The values are checked as for any operation; an enum value or a field that is not a GraphQL name fails with `InvalidValueReason::NotAGraphqlName`, an enum value `true`, `false` or `null` with `InvalidValueReason::ReservedEnumValue`. A variable that may hold `JSON` is refused at compile time. - `Shopify::bulk_mutation` runs a `graphql!(bulk("mutation …"))` over an iterator of its `Variables`: every line is checked and written before anything is sent, then staged, run, and read as `BulkMutationResult` (`data`, `errors`, `index`, Shopify's `__lineNumber`). `start_bulk_mutation` only starts it. Typed bulk operations run at the Admin API version they were checked against. - `Transport`, the HTTP layer as a trait, with `send_streaming` (a default goes through `send`), `StreamingResponse` and `BodyStream`. The default `ReqwestTransport` never follows a redirection, and streams: the timeout of a request bounds the wait for the headers and for each chunk, not the whole body. A client of your own goes through `transport::reqwest_0_13::from_builder`: reqwest appears in the API only under `transport::reqwest_0_13`, named after its major version, so that a later reqwest comes next to it. The client runs on Tokio. - `testing::MockTransport` (`push_data`, `push_chunks`, `push_streaming`, `respond_with`…), and `testing::client`, which retries without waiting, even for a scripted `Retry-After`. `testing` also gives the signing helpers: `webhooks::sign`, `ShopifyApp::sign_query`, `sign_app_proxy`, `sign_session_token`. diff --git a/crates/shopify_api/tests/bulk_text.rs b/crates/shopify_api/tests/bulk_text.rs new file mode 100644 index 0000000..9c2ed59 --- /dev/null +++ b/crates/shopify_api/tests/bulk_text.rs @@ -0,0 +1,453 @@ +//! What the text of a bulk query holds, and how its lines are placed: the +//! values written into it, its strings, and the keys that route its lines. +#![cfg(feature = "testing")] + +use shopify_api::testing::{MockTransport, client}; +use shopify_api::{Error, InvalidValueReason, graphql, input}; + +const URL: &str = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-east1/bulk-operation-outputs/text.jsonl"; + +graphql! { + mod sorted = bulk("query($sort: ProductSortKeys) { products(sortKey: $sort) { edges { node { title } } } }"); + mod topics = bulk("query($topics: [WebhookSubscriptionTopic!]) { webhookSubscriptions(topics: $topics) { edges { node { id } } } }"); + mod priced = bulk("query($context: ContextualPricingContext!) { products { edges { node { contextualPricing(context: $context) { priceRange { minVariantPrice { amount } } } } } } }"); + mod aliased_id = bulk("{ products { edges { node { id: totalInventory title } } } }"); + mod aliased_child_id = bulk("{ products { edges { node { id variants { edges { node { id: inventoryQuantity sku } } } } } } }"); + mod typenames = bulk("{ products { edges { node { id variants { edges { node { __typename kind: __typename sku } } } media { edges { node { __typename @include(if: false) alt } } } } } } }"); +} + +// ─── Enum values `true`, `false` and `null` ────────────────────────────── + +fn refused_as_reserved(result: shopify_api::Result, path: &str) { + let error = result.unwrap_err(); + let Error::InvalidValue { + path: at, reason, .. + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!(at, path); + assert_eq!(*reason, InvalidValueReason::ReservedEnumValue); +} + +#[test] +fn an_enum_variable_true_false_or_null_is_refused() { + for word in ["null", "true", "false"] { + let text = sorted::operation(sorted::Variables { + sort: Some(word.into()), + }) + .text(); + refused_as_reserved(text, "$sort"); + } + // A real `null` is still `null`, and a name that only starts like one is a name. + let text = graphql!( + bulk("query($sort: ProductSortKeys) { products(sortKey: $sort) { edges { node { title } } } }"), + sort = null, + ) + .text() + .unwrap(); + assert!(text.contains("products(sortKey: null)"), "{text}"); + let text = sorted::operation(sorted::Variables { + sort: Some("nullable".into()), + }) + .text() + .unwrap(); + assert!(text.contains("products(sortKey: nullable)"), "{text}"); +} + +#[test] +fn an_enum_true_false_or_null_in_a_list_is_refused() { + for word in ["null", "true", "false"] { + let text = topics::operation(topics::Variables { + topics: Some(vec!["ORDERS_CREATE".into(), word.into()]), + }) + .text(); + refused_as_reserved(text, "$topics[1]"); + } +} + +#[test] +fn an_enum_true_false_or_null_in_an_input_field_is_refused() { + for text in [ + priced::operation(priced::Variables { + context: input!(ContextualPricingContext { + country: raw("null") + }), + }) + .text(), + priced::operation(priced::Variables { + context: input!(ContextualPricingContext { + country: raw("true") + }), + }) + .text(), + priced::operation(priced::Variables { + context: input!(ContextualPricingContext { + country: raw("false") + }), + }) + .text(), + ] { + refused_as_reserved(text, "$context.country"); + } + let text = priced::operation(priced::Variables { + context: input!(ContextualPricingContext { country: null }), + }) + .text() + .unwrap(); + assert!( + text.contains("contextualPricing(context: {country: null})"), + "{text}" + ); +} + +// ─── Strings ───────────────────────────────────────────────────────────── + +/// A GraphQL string token, quoted or block, read as the specification +/// reads it: a decoder of the test's own, not the crate's. +fn decode(token: &str) -> String { + if let Some(body) = token.strip_prefix("\"\"\"") { + let body = body.strip_suffix("\"\"\"").unwrap(); + let raw = body.replace("\\\"\"\"", "\"\"\""); + let lines: Vec = raw + .replace("\r\n", "\n") + .replace('\r', "\n") + .split('\n') + .map(str::to_string) + .collect(); + let white = |line: &str| line.chars().take_while(|c| *c == ' ' || *c == '\t').count(); + let common = lines[1..] + .iter() + .filter(|line| white(line) < line.chars().count()) + .map(|line| white(line)) + .min(); + let mut lines: Vec = lines + .iter() + .enumerate() + .map(|(index, line)| match common { + Some(common) if index > 0 => line.chars().skip(common).collect(), + _ => line.clone(), + }) + .collect(); + while lines + .first() + .is_some_and(|line| white(line) == line.chars().count()) + { + lines.remove(0); + } + while lines + .last() + .is_some_and(|line| white(line) == line.chars().count()) + { + lines.pop(); + } + return lines.join("\n"); + } + let body = token.strip_prefix('"').unwrap().strip_suffix('"').unwrap(); + let mut out = String::new(); + let mut chars = body.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + assert!(c != '\n' && c != '\r', "a line break in {token:?}"); + out.push(c); + continue; + } + match chars.next().unwrap() { + '"' => out.push('"'), + '\\' => out.push('\\'), + '/' => out.push('/'), + 'b' => out.push('\u{8}'), + 'f' => out.push('\u{c}'), + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + 'u' => { + let hex: String = chars.by_ref().take(4).collect(); + let code = u32::from_str_radix(&hex, 16).unwrap(); + if (0xD800..0xDC00).contains(&code) { + // A surrogate pair. + assert_eq!(chars.next(), Some('\\')); + assert_eq!(chars.next(), Some('u')); + let low: String = chars.by_ref().take(4).collect(); + let low = u32::from_str_radix(&low, 16).unwrap(); + out.push( + char::from_u32(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)).unwrap(), + ); + } else { + out.push(char::from_u32(code).unwrap()); + } + } + other => panic!("unknown escape \\{other} in {token:?}"), + } + } + out +} + +/// The string token that follows `after` in `text`. +fn token_after<'t>(text: &'t str, after: &str) -> &'t str { + let start = text + .find(after) + .unwrap_or_else(|| panic!("{after} in {text}")) + + after.len(); + let rest = &text[start..]; + let mut escaped = false; + for (index, c) in rest.char_indices().skip(1) { + match c { + '"' if !escaped => return &rest[..=index], + _ => escaped = !escaped && c == '\\', + } + } + panic!("an unterminated string in {text}"); +} + +/// The value Shopify reads for the string of `products(query: …)`. +fn sent(query: shopify_api::bulk::BulkQuery) -> String { + decode(token_after(&query.text().unwrap(), "products(query: ")) +} + +#[test] +fn every_escape_reaches_shopify_as_written() { + // Each escape GraphQL defines, but `\b`, which `graphql!` refuses + // (`tests/ui/bulk_string_escape.rs`): the value written, and the one + // Shopify reads in the text sent, decoded by the test. + let cases = [ + ( + sent(graphql!(bulk( + r#"{ products(query: "a\"b") { edges { node { id } } } }"# + ))), + "a\"b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\\b") { edges { node { id } } } }"# + ))), + "a\\b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\/b") { edges { node { id } } } }"# + ))), + "a/b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\u0008b") { edges { node { id } } } }"# + ))), + "a\u{8}b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\fb") { edges { node { id } } } }"# + ))), + "a\u{c}b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\nb") { edges { node { id } } } }"# + ))), + "a\nb", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\rb") { edges { node { id } } } }"# + ))), + "a\rb", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\tb") { edges { node { id } } } }"# + ))), + "a\tb", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\u00e9\u20AC\uFFFFb") { edges { node { id } } } }"# + ))), + "aé€\u{FFFF}b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\u0000\u001f\u007fb") { edges { node { id } } } }"# + ))), + "a\u{0}\u{1f}\u{7f}b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "é😀 \u2028 $x #y") { edges { node { id } } } }"# + ))), + "é😀 \u{2028} $x #y", + ), + ( + sent(graphql!(bulk( + r#"query($filter: String = "a\"\\\/\u0008\f\n\r\t\u00e9b") { products(query: $filter) { edges { node { id } } } }"# + ))), + "a\"\\/\u{8}\u{c}\n\r\téb", + ), + ]; + for (index, (sent, written)) in cases.iter().enumerate() { + assert_eq!(sent, written, "case {index}"); + } +} + +#[test] +fn block_strings_reach_shopify_as_written() { + let cases = [ + ( + sent(graphql!(bulk( + r#"{ products(query: """plain""") { edges { node { id } } } }"# + ))), + "plain", + ), + ( + sent(graphql!(bulk( + "{ products(query: \"\"\"\n first\n indented\n last\n \"\"\") { edges { node { id } } } }" + ))), + "first\n indented\nlast", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: """a \""" b""") { edges { node { id } } } }"# + ))), + "a \"\"\" b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: """no \n escape \u0041""") { edges { node { id } } } }"# + ))), + "no \\n escape \\u0041", + ), + ( + sent(graphql!(bulk( + "{ products(query: \"\"\"\r\n\ta\r\n\t\tb\r\n\"\"\") { edges { node { id } } } }" + ))), + "a\n\tb", + ), + ( + sent(graphql!(bulk( + "query($filter: String = \"\"\"\n x\n \"y\"\n\"\"\") { products(query: $filter) { edges { node { id } } } }" + ))), + "x\n\"y\"", + ), + ]; + for (index, (sent, written)) in cases.iter().enumerate() { + assert_eq!(sent, written, "case {index}"); + } +} + +#[test] +fn a_string_variable_reaches_shopify_as_given() { + let value: String = (0..=0x10ffff).filter_map(char::from_u32).collect(); + let query = graphql!( + bulk("query($filter: String) { products(query: $filter) { edges { node { title } } } }"), + filter = value.clone(), + ); + assert_eq!(sent(query), value); +} + +// ─── The keys that place lines ─────────────────────────────────────────── + +#[tokio::test] +async fn an_item_with_an_alias_id_of_another_type_reads() { + let mock = MockTransport::new(); + mock.push_chunks( + 200, + [b"{\"id\":12,\"title\":\"Shirt\"}\n{\"id\":7,\"title\":\"Hat\"}\n".as_slice()], + ); + let items = client(&mock) + .download_bulk_items::(URL) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(items[0].id, 12); + assert_eq!(items[0].title, "Shirt"); + assert_eq!(items[1].id, 7); +} + +#[tokio::test] +async fn a_child_with_an_alias_id_of_another_type_reads() { + let mock = MockTransport::new(); + mock.push_chunks( + 200, + [b"{\"id\":\"P1\"}\n{\"id\":12,\"sku\":\"S-1\",\"__parentId\":\"P1\"}\n{\"id\":[1],\"sku\":\"S-2\",\"__parentId\":\"P1\"}\n{\"id\":\"P2\"}\n".as_slice()], + ); + let items = client(&mock) + .download_bulk_items::(URL) + .await + .unwrap() + .collect() + .await; + // `[1]` is not an `Int`: that line alone fails, as its type says. + let error = items.unwrap_err(); + assert!(matches!(error, Error::Decode { .. }), "{error:?}"); + + let mock = MockTransport::new(); + mock.push_chunks( + 200, + [b"{\"id\":\"P1\"}\n{\"id\":12,\"sku\":\"S-1\",\"__parentId\":\"P1\"}\n{\"id\":\"P2\"}\n".as_slice()], + ); + let items = client(&mock) + .download_bulk_items::(URL) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(items[0].variants[0].id, Some(12)); + assert_eq!(items[0].variants[0].sku.as_deref(), Some("S-1")); + assert!(items[1].variants.is_empty()); +} + +#[tokio::test] +async fn lines_are_placed_by_the_reserved_key_not_by_the_query_s_typename() { + let text = typenames::operation().text().unwrap(); + assert_eq!( + text, + "{ products { edges { node { id \ + variants { edges { node { _shopifyApiTypename: __typename __typename kind: __typename sku } } } \ + media { edges { node { _shopifyApiTypename: __typename __typename @include(if: false) alt } } } } } } }" + ); + // The query's own `__typename` is absent where its `@include` left it + // out, and says nothing of where a line goes. + let mock = MockTransport::new(); + mock.push_chunks(200, [br#"{"id":"P1"} +{"_shopifyApiTypename":"ProductVariant","__typename":"ProductVariant","kind":"ProductVariant","sku":"S-1","__parentId":"P1"} +{"_shopifyApiTypename":"MediaImage","alt":"Front","__parentId":"P1"} +"# + .as_slice()]); + let items = client(&mock) + .download_bulk_items::(URL) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(items[0].variants[0].typename, "ProductVariant"); + assert_eq!(items[0].variants[0].kind, "ProductVariant"); + assert_eq!(items[0].media[0].typename, None); + assert_eq!(items[0].media[0].alt.as_deref(), Some("Front")); + + // A `__typename` alone does not place a line. + let mock = MockTransport::new(); + mock.push_chunks( + 200, + [br#"{"id":"P1"} +{"__typename":"ProductVariant","kind":"ProductVariant","sku":"S-1","__parentId":"P1"} +"# + .as_slice()], + ); + let error = client(&mock) + .download_bulk_items::(URL) + .await + .unwrap() + .collect() + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 2 of the results has no `_shopifyApiTypename`, the `__typename` that tells which connection of its parent it belongs to" + ); +} From b4ee73fa1d790e94e483f6f31a3a557010be9cd6 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:38:39 +0100 Subject: [PATCH 116/135] fix(graphql): refuse block strings the parser panics on, before parsing graphql-parser 0.4 measures the common indentation of a block string in bytes over any Unicode whitespace, then cuts each line at that byte: a line indented with U+00A0 (two bytes) beside one indented with U+2003 (three bytes) made `graphql!` panic, bulk or not. Every parse now goes through `analyze::parse`, which first runs the parser's own indentation steps on each block string of the source and refuses one whose cut falls inside a character, at its line and column. The string lexer of the bulk checks moves to `source`, shared. A test compares the check with the parser's panics over a grid of whitespace mixes; UI tests pin the refusal for an ordinary and a bulk operation. The other UI outputs change because trybuild numbers its test crates in file order. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api/docs/graphql.md | 3 + .../tests/ui/block_string_unicode_indent.rs | 4 + .../ui/block_string_unicode_indent.stderr | 6 + .../ui/bulk_block_string_unicode_indent.rs | 3 + .../bulk_block_string_unicode_indent.stderr | 6 + ...literal_maybe_non_null_with_default.stderr | 4 +- .../tests/ui/literal_one_of.stderr | 4 +- .../tests/ui/literal_option_in_field.stderr | 2 +- .../tests/ui/literal_wrong_input_type.stderr | 6 +- .../tests/ui/literal_wrong_scalar.stderr | 10 +- crates/shopify_api_graphql/src/analyze.rs | 30 ++- crates/shopify_api_graphql/src/bulk.rs | 2 +- .../shopify_api_graphql/src/bulk/strings.rs | 99 +-------- crates/shopify_api_graphql/src/lib.rs | 1 + crates/shopify_api_graphql/src/source.rs | 205 ++++++++++++++++++ crates/shopify_api_graphql/tests/bulk.rs | 13 ++ 17 files changed, 280 insertions(+), 120 deletions(-) create mode 100644 crates/shopify_api/tests/ui/block_string_unicode_indent.rs create mode 100644 crates/shopify_api/tests/ui/block_string_unicode_indent.stderr create mode 100644 crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.rs create mode 100644 crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.stderr create mode 100644 crates/shopify_api_graphql/src/source.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index f92612b..335b7bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - No name the macros generate is in scope where the values are evaluated: a local, closure, function or constant of yours with the name of a generated item stays yours. - One `graphql! { … }` holds several modules, `;` between them. A module's `Variables` runs as it is, `shopify.execute(module::Variables { … })`, and it names each input object its variables may hold: `pub type MetafieldsSetInput = InputObject<…>`. - Deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. -- `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. +- `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. So is a block string whose lines are indented with different Unicode whitespace (U+00A0 and U+2003), on which the GraphQL parser would panic. - `Operation`, what `graphql!` builds, or `Operation::new` for any text: `execute` and `execute_response` take `impl Into>`, a module's `Variables` included. `body()` is the exact JSON text sent, and `variable_json(name)` the text of one variable; `with_name` sets the `operationName`. - No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. A local package (of the workspace, or a path dependency) that cargo was asked to build downloads the file when it is missing or does not hold the pinned version, once per build; any other crate never downloads nor writes it, and fails to build when its file is missing or does not fit, a packaged crate in the verification of `cargo package` included. A packaged, vendored or checked-out crate (a `Cargo.toml.orig`, a `.cargo-checksum.json` or a `.cargo-ok` in the package directory, a `.cargo-ok` above it, or a path under `$CARGO_HOME`, with or without symbolic links resolved) never downloads: where a crate is decides only between a download and a compile error, never which schema it gets. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. - `schema = ""` in `[package.metadata.shopify_api]` names another schema file than `graphql/admin.schema.json`, relative to the package's `Cargo.toml`, for that package only. It must name a file inside the package, which `cargo package` ships: a relative path with `/` and portable names (no `:`, `\`, `<>"|?*` or control character, no name ending in `.` or a space, no device name such as `CON`); an absolute path, or one that climbs out with `..`, is an error (a symbolic link inside the package may point elsewhere). A dependency keeps the one its own `Cargo.toml` names. The file follows the rules of the default one (version, download, older format), `shopify-api schema download` and `shopify-api check` use it, and an edit of the key compiles the crate again. diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index c199545..2c877e2 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -615,6 +615,9 @@ scripts an answer that leaves out a non-null field. # Limits - Subscriptions are refused, and one inline `graphql!` takes one operation. +- A block string whose lines are indented with different Unicode whitespace, + such as U+00A0 on one and U+2003 on another, is refused: the GraphQL parser + of `graphql!` cannot read it. Indent with spaces or tabs. - A bulk operation follows the rules above: see [what is not checked](#what-is-not-checked). - An error in the operation points at the whole operation; the line and column in its message locate the mistake inside it. An error in a value diff --git a/crates/shopify_api/tests/ui/block_string_unicode_indent.rs b/crates/shopify_api/tests/ui/block_string_unicode_indent.rs new file mode 100644 index 0000000..58321d9 --- /dev/null +++ b/crates/shopify_api/tests/ui/block_string_unicode_indent.rs @@ -0,0 +1,4 @@ +fn main() { + // Lines indented with U+00A0 (two bytes) and U+2003 (three bytes): `graphql-parser` would panic. + let _ = shopify_api::graphql!("query { products(first: 1, query: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") { nodes { id } } }"); +} diff --git a/crates/shopify_api/tests/ui/block_string_unicode_indent.stderr b/crates/shopify_api/tests/ui/block_string_unicode_indent.stderr new file mode 100644 index 0000000..ec67528 --- /dev/null +++ b/crates/shopify_api/tests/ui/block_string_unicode_indent.stderr @@ -0,0 +1,6 @@ +error: This block string indents its lines with different Unicode whitespace, which the GraphQL parser this crate uses cannot read. Indent it with spaces or tabs, or write it as a quoted string (line 1, column 35) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/block_string_unicode_indent.rs:3:35 + | +3 | let _ = shopify_api::graphql!("query { products(first: 1, query: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") { nodes { id } } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.rs b/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.rs new file mode 100644 index 0000000..49a4649 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products(query: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") { edges { node { id } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.stderr b/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.stderr new file mode 100644 index 0000000..ef7b62d --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.stderr @@ -0,0 +1,6 @@ +error: This block string indents its lines with different Unicode whitespace, which the GraphQL parser this crate uses cannot read. Indent it with spaces or tabs, or write it as a quoted string (line 1, column 19) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_block_string_unicode_indent.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products(query: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") { edges { node { id } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr index a96ddba..ab6ef19 100644 --- a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -7,13 +7,13 @@ error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[Inven | | an `Option`: `None` leaves the field out | required by a bound introduced by this call | - = help: the trait `__ShopifyApiNoNull4_c2391752` is not implemented for `Vec>` + = help: the trait `__ShopifyApiNoNull4_c23911f8` is not implemented for `Vec>` help: this trait has no implementations, consider adding one --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c2391752` +note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c23911f8` --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); diff --git a/crates/shopify_api/tests/ui/literal_one_of.stderr b/crates/shopify_api/tests/ui/literal_one_of.stderr index 7ece298..bf91fa6 100644 --- a/crates/shopify_api/tests/ui/literal_one_of.stderr +++ b/crates/shopify_api/tests/ui/literal_one_of.stderr @@ -35,7 +35,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Optio | `Option<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2392dae` is not implemented for `Option<&str>` + = help: the trait `main::__ShopifyApiExpect1_c2391234` is not implemented for `Option<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:7:13 | @@ -52,7 +52,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Maybe | `Maybe<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2392dae` is not implemented for `Maybe<&str>` + = help: the trait `main::__ShopifyApiExpect1_c2391234` is not implemented for `Maybe<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:8:13 | diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr index fcce46f..e93185d 100644 --- a/crates/shopify_api/tests/ui/literal_option_in_field.stderr +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -7,7 +7,7 @@ error[E0277]: `vendor` of `ProductUpdateInput` expects a `String`, not `Option` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect1_c2392f79` is not implemented for `Option` + = help: the trait `__ShopifyApiExpect1_c2391187` is not implemented for `Option` = note: `vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null` note: required by a bound in `Checks::build` --> tests/ui/literal_option_in_field.rs:3:13 diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr index 41a9411..a94dcf6 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -9,8 +9,8 @@ error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built wit 6 | | ); | |_____- required by a bound introduced by this call | - = help: the trait `__ShopifyApiExpect2_c1d687d2` is not implemented for `InputObject<2493993284262097346>` -help: the following other types implement trait `__ShopifyApiExpect2_c1d687d2` + = help: the trait `__ShopifyApiExpect2_c1d68278` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2_c1d68278` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -22,7 +22,7 @@ help: the following other types implement trait `__ShopifyApiExpect2_c1d687d2` | | | | |_____`&InputObject<960560859991546817>` | `InputObject<960560859991546817>` -note: required for `Vec>` to implement `__ShopifyApiExpect1_c1d687d2` +note: required for `Vec>` to implement `__ShopifyApiExpect1_c1d68278` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr index 89f0444..7ec41e0 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr @@ -7,7 +7,7 @@ error[E0277]: `quantity` of `DraftOrderLineItemInput` expects an `Int`, not `&st | `&'static str` doesn't satisfy the trait bound | any integer type | - = help: the trait `main::__ShopifyApiExpect1_c1d68fcb` is not implemented for `&str` + = help: the trait `main::__ShopifyApiExpect1_c1d69ff9` is not implemented for `&str` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 | @@ -24,7 +24,7 @@ error[E0277]: `title` of `DraftOrderLineItemInput` expects a `String`, not `u8` | `u8` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect3_c1d68fcb` is not implemented for `u8` + = help: the trait `__ShopifyApiExpect3_c1d69ff9` is not implemented for `u8` = note: `title?: value` takes an `Option`, `None` leaving the field out; `title: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -42,7 +42,7 @@ error[E0277]: `requiresShipping` of `DraftOrderLineItemInput` expects a `Boolean | `{integer}` doesn't satisfy the trait bound | `bool` | - = help: the trait `__ShopifyApiExpect5_c1d68fcb` is not implemented for `{integer}` + = help: the trait `__ShopifyApiExpect5_c1d69ff9` is not implemented for `{integer}` = note: `requiresShipping?: value` takes an `Option`, `None` leaving the field out; `requiresShipping: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -60,8 +60,8 @@ error[E0277]: `value` of `WeightInput` expects a `Float`, not `u64` | `u64` doesn't satisfy the trait bound | `f64`, `f32`, `i32` or `u32` | - = help: the trait `main::__ShopifyApiExpect1_c1d68fcb` is not implemented for `u64` - = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c1d68fcb`, but not `main::__ShopifyApiExpect1_c1d68fcb` + = help: the trait `main::__ShopifyApiExpect1_c1d69ff9` is not implemented for `u64` + = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c1d69ff9`, but not `main::__ShopifyApiExpect1_c1d69ff9` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:4:13 | diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs index 78c80b8..78d0a8e 100644 --- a/crates/shopify_api_graphql/src/analyze.rs +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -188,21 +188,29 @@ pub struct Operation { pub deprecations: Vec, } +/// Parses `source`, after refusing the block strings the parser panics on. +pub(crate) fn parse(source: &str) -> Result> { + if let Some(position) = crate::source::unreadable_block_strings(source) { + return error_at( + position, + "This block string indents its lines with different Unicode whitespace, which the GraphQL parser this crate uses cannot read. Indent it with spaces or tabs, or write it as a quoted string", + ); + } + graphql_parser::parse_query(source).or_else(|parse_error| { + let text = parse_error.to_string(); + let detail = text.strip_prefix("query parse error: ").unwrap_or(&text); + error(format!( + "Invalid GraphQL: {}", + detail.trim().replace('\n', " ") + )) + }) +} + /// Parses `source`, checks it against `schema` and returns its shape. /// /// `source` contains exactly one query or mutation, and the fragments it uses. pub fn analyze(schema: &Schema, source: &str) -> Result { - let document: Document = match graphql_parser::parse_query(source) { - Ok(document) => document, - Err(parse_error) => { - let text = parse_error.to_string(); - let detail = text.strip_prefix("query parse error: ").unwrap_or(&text); - return error(format!( - "Invalid GraphQL: {}", - detail.trim().replace('\n', " ") - )); - } - }; + let document = parse(source)?; // Checked on the text: the parser keeps only the last of the two. if let Some((field, position)) = input_objects::duplicate_field(source) { diff --git a/crates/shopify_api_graphql/src/bulk.rs b/crates/shopify_api_graphql/src/bulk.rs index 79bff29..0ade2f3 100644 --- a/crates/shopify_api_graphql/src/bulk.rs +++ b/crates/shopify_api_graphql/src/bulk.rs @@ -176,7 +176,7 @@ fn implements_node(schema: &Schema, name: &str) -> bool { fn parse(source: &str) -> Result, Error> { // `analyze` read it first: a failure here is not expected. - graphql_parser::parse_query(source).or_else(|_| error("Invalid GraphQL")) + crate::analyze::parse(source) } /// The operation and the fragments of a document `analyze` accepted. diff --git a/crates/shopify_api_graphql/src/bulk/strings.rs b/crates/shopify_api_graphql/src/bulk/strings.rs index 6dfd6ab..2bbe195 100644 --- a/crates/shopify_api_graphql/src/bulk/strings.rs +++ b/crates/shopify_api_graphql/src/bulk/strings.rs @@ -11,17 +11,12 @@ use super::error_at; use crate::analyze::Error; -use graphql_parser::Pos; +use crate::source::{Lexer, unreadable_block_string}; /// Refuses a string or block string of `source` that `graphql-parser` /// does not read as GraphQL does. pub(super) fn check(source: &str) -> Result<(), Error> { - let mut lexer = Lexer { - source, - at: 0, - line: 1, - column: 1, - }; + let mut lexer = Lexer::new(source); while let Some((position, token)) = lexer.next_string() { let expected = if token.starts_with("\"\"\"") { block_string(&token[3..token.len() - 3]) @@ -51,6 +46,9 @@ pub(super) fn check(source: &str) -> Result<(), Error> { /// The string the token is for `graphql-parser`. fn parsed(token: &str) -> Option { use graphql_parser::query::{Definition, OperationDefinition, Selection, Value}; + if unreadable_block_string(token) { + return None; + } let source = format!("{{ f(a: {token}) }}"); let document = graphql_parser::parse_query::(&source).ok()?; let Some(Definition::Operation(OperationDefinition::SelectionSet(set))) = @@ -67,85 +65,6 @@ fn parsed(token: &str) -> Option { } } -struct Lexer<'a> { - source: &'a str, - /// A byte offset. - at: usize, - line: usize, - column: usize, -} - -impl<'a> Lexer<'a> { - fn rest(&self) -> &'a str { - &self.source[self.at..] - } - - /// Moves `bytes` on, counting lines as the parser does. - fn advance(&mut self, bytes: usize) { - let end = self.at + bytes; - for character in self.source[self.at..end].chars() { - if character == '\n' { - self.line += 1; - self.column = 1; - } else if character == '\t' { - self.column += 8; - } else { - self.column += 1; - } - } - self.at = end; - } - - /// The next string token, quotes included, and where it starts. The - /// source parsed: every string ends. - fn next_string(&mut self) -> Option<(Pos, &'a str)> { - loop { - let rest = self.rest(); - let character = rest.chars().next()?; - match character { - '#' => { - let end = rest.find(['\n', '\r']).unwrap_or(rest.len()); - self.advance(end); - } - '"' => { - let position = Pos { - line: self.line, - column: self.column, - }; - let length = string_length(rest)?; - let token = &rest[..length]; - self.advance(length); - return Some((position, token)); - } - other => self.advance(other.len_utf8()), - } - } - } -} - -/// The length in bytes of the string token at the start of `rest`. -fn string_length(rest: &str) -> Option { - if let Some(body) = rest.strip_prefix("\"\"\"") { - let mut from = 0; - loop { - let end = from + body[from..].find("\"\"\"")?; - if body[..end].ends_with('\\') { - from = end + 3; - } else { - return Some(end + 6); - } - } - } - let mut escaped = false; - for (index, character) in rest.char_indices().skip(1) { - match character { - '"' if !escaped => return Some(index + 1), - _ => escaped = !escaped && character == '\\', - } - } - None -} - /// The value of a quoted string, as the specification reads it. fn quoted_string(body: &str) -> Option { let mut value = String::with_capacity(body.len()); @@ -214,14 +133,6 @@ fn block_string(body: &str) -> Option { mod tests { use super::*; - #[test] - fn strings_end_where_the_parser_ends_them() { - assert_eq!(string_length(r#""a\"b" x"#), Some(6)); - assert_eq!(string_length(r#""a\\" x"#), Some(5)); - assert_eq!(string_length(r#""""a\"""b""" x"#), Some(12)); - assert_eq!(string_length(r#""""""" x"#), Some(6)); - } - #[test] fn comments_hide_quotes() { assert!(check("# \"\\b\"\n{ f }").is_ok()); diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs index 8a5d391..1dcd4ff 100644 --- a/crates/shopify_api_graphql/src/lib.rs +++ b/crates/shopify_api_graphql/src/lib.rs @@ -33,6 +33,7 @@ pub mod project; mod restrict; #[doc(hidden)] pub mod schema; +mod source; #[doc(hidden)] pub use analyze::{ diff --git a/crates/shopify_api_graphql/src/source.rs b/crates/shopify_api_graphql/src/source.rs new file mode 100644 index 0000000..4c31add --- /dev/null +++ b/crates/shopify_api_graphql/src/source.rs @@ -0,0 +1,205 @@ +//! The string tokens of a GraphQL source, found without the parser. +//! +//! `graphql-parser` 0.4 panics on some block strings: it measures the +//! common indentation of their lines in bytes, over any Unicode whitespace, +//! then cuts every line at that byte, which can fall inside a character +//! (a line indented with U+00A0, two bytes, and another with U+2003, three +//! bytes). Those are refused here, before the parser reads them. + +use graphql_parser::Pos; + +/// The first block string of `source` the parser cannot read, if any, and +/// where it starts. +pub(crate) fn unreadable_block_strings(source: &str) -> Option { + let mut lexer = Lexer::new(source); + while let Some((position, token)) = lexer.next_string() { + if unreadable_block_string(token) { + return Some(position); + } + } + None +} + +/// Whether the parser panics on this string token: the same steps as its +/// `unquote_block_string`, without the cut. +pub(crate) fn unreadable_block_string(token: &str) -> bool { + let Some(body) = token + .strip_prefix("\"\"\"") + .and_then(|body| body.strip_suffix("\"\"\"")) + else { + return false; + }; + let lines = body.lines(); + let mut common = usize::MAX; + let mut first = None; + let mut last = 0; + for (index, line) in lines.clone().enumerate() { + let indent = line.len() - line.trim_start().len(); + if indent == line.len() { + continue; + } + first.get_or_insert(index); + last = index; + if index != 0 { + common = common.min(indent); + } + } + let Some(first) = first else { + return false; + }; + lines + .enumerate() + .skip(first) + .take(last - first + 1) + .any(|(index, line)| index != 0 && line.len() >= common && !line.is_char_boundary(common)) +} + +pub(crate) struct Lexer<'a> { + source: &'a str, + /// A byte offset. + at: usize, + line: usize, + column: usize, +} + +impl<'a> Lexer<'a> { + pub(crate) fn new(source: &'a str) -> Self { + Lexer { + source, + at: 0, + line: 1, + column: 1, + } + } + + fn rest(&self) -> &'a str { + &self.source[self.at..] + } + + /// Moves `bytes` on, counting lines as the parser does. + fn advance(&mut self, bytes: usize) { + let end = self.at + bytes; + for character in self.source[self.at..end].chars() { + if character == '\n' { + self.line += 1; + self.column = 1; + } else if character == '\t' { + self.column += 8; + } else { + self.column += 1; + } + } + self.at = end; + } + + /// The next string token, quotes included, and where it starts; `None` + /// at the end, or at a string that does not end. + pub(crate) fn next_string(&mut self) -> Option<(Pos, &'a str)> { + loop { + let rest = self.rest(); + let character = rest.chars().next()?; + match character { + '#' => { + let end = rest.find(['\n', '\r']).unwrap_or(rest.len()); + self.advance(end); + } + '"' => { + let position = Pos { + line: self.line, + column: self.column, + }; + let length = string_length(rest)?; + let token = &rest[..length]; + self.advance(length); + return Some((position, token)); + } + other => self.advance(other.len_utf8()), + } + } + } +} + +/// The length in bytes of the string token at the start of `rest`. +fn string_length(rest: &str) -> Option { + if let Some(body) = rest.strip_prefix("\"\"\"") { + let mut from = 0; + loop { + let end = from + body[from..].find("\"\"\"")?; + if body[..end].ends_with('\\') { + from = end + 3; + } else { + return Some(end + 6); + } + } + } + let mut escaped = false; + for (index, character) in rest.char_indices().skip(1) { + match character { + '"' if !escaped => return Some(index + 1), + _ => escaped = !escaped && character == '\\', + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strings_end_where_the_parser_ends_them() { + assert_eq!(string_length(r#""a\"b" x"#), Some(6)); + assert_eq!(string_length(r#""a\\" x"#), Some(5)); + assert_eq!(string_length(r#""""a\"""b""" x"#), Some(12)); + assert_eq!(string_length(r#""""""" x"#), Some(6)); + } + + /// Whether `graphql-parser` panics on the block string `token`. + fn parser_panics(token: &str) -> bool { + let source = format!("{{ f(a: {token}) }}"); + std::panic::catch_unwind(|| { + let _ = graphql_parser::parse_query::(&source); + }) + .is_err() + } + + #[test] + fn unreadable_block_strings_are_those_the_parser_panics_on() { + let whitespace = [ + " ", "\t", "\u{a0}", "\u{2003}", "\u{3000}", "\u{1680}", "\u{2028}", + ]; + let mut tokens = Vec::new(); + for a in whitespace { + for b in whitespace { + for c in ["", " ", "\u{a0}"] { + for line in ["x", ""] { + tokens.push(format!("\"\"\"\n{a}{c}x\n{b}{line}\n{c}{a}y\"\"\"")); + tokens.push(format!("\"\"\"x\n{a}{b}x\n{b}\n{c}{line}\"\"\"")); + } + } + } + } + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(|_| {})); + let mismatches: Vec<_> = tokens + .iter() + .filter(|token| parser_panics(token) != unreadable_block_string(token)) + .collect(); + std::panic::set_hook(previous); + assert!(mismatches.is_empty(), "{mismatches:?}"); + assert!(tokens.iter().any(|token| unreadable_block_string(token))); + } + + #[test] + fn finds_the_unreadable_block_string() { + assert_eq!( + unreadable_block_strings("{ f(a: \"\"\"\n\u{a0}a\n\u{a0}b\"\"\") }"), + None + ); + let position = unreadable_block_strings( + "# \"\"\"\n{ f(a: \"x\", b: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") }", + ) + .unwrap(); + assert_eq!((position.line, position.column), (2, 16)); + } +} diff --git a/crates/shopify_api_graphql/tests/bulk.rs b/crates/shopify_api_graphql/tests/bulk.rs index 9bc4347..7ec6ae8 100644 --- a/crates/shopify_api_graphql/tests/bulk.rs +++ b/crates/shopify_api_graphql/tests/bulk.rs @@ -193,6 +193,19 @@ fn strings_the_parser_misreads_are_refused() { refusal("{ things(q: \"\"\"\n\u{a0}a\n\u{a0}b\"\"\") { edges { node { id } } } }"), format!("{block} (line 1, column 13)") ); + // Lines indented with U+00A0 (two bytes) and U+2003 (three bytes) make + // `graphql-parser` panic: refused before it reads them, bulk or not. + let indent = "This block string indents its lines with different Unicode whitespace, which the GraphQL parser this crate uses cannot read. Indent it with spaces or tabs, or write it as a quoted string"; + for source in [ + "{ things(q: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") { edges { node { id } } } }", + "{ thing(id: \"\"\"\n\u{2003}a\n\u{a0}b\"\"\") { id } }", + ] { + assert_eq!( + analyze(schema(), source).unwrap_err().to_string(), + format!("{indent} (line 1, column 13)"), + "{source}" + ); + } // In a comment, a `\b` is nothing. bulk("# \"\\b\"\n{ things(q: \"\\u0008\") { edges { node { id } } } }"); // `\u{…}` and surrogate pairs do not parse. From 4bb2d3c6ab80579227e869364e889440a632f1f0 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:38:54 +0100 Subject: [PATCH 117/135] fix(bulk): refuse a reserved alias on the top-level connection too `_shopifyApiTypename: products` and `__x: products` were accepted: the top-level field went straight to `Checker::connection`, without the `check_key` every field of a node goes through. The docs and changelog reserve these aliases in the whole bulk query, so the top-level field is checked as well. Pinned by a unit test and a UI test. Co-Authored-By: Claude Opus 5.5 --- .../tests/ui/bulk_reserved_alias_top_level.rs | 3 +++ .../tests/ui/bulk_reserved_alias_top_level.stderr | 6 ++++++ .../ui/literal_maybe_non_null_with_default.stderr | 4 ++-- crates/shopify_api/tests/ui/literal_one_of.stderr | 4 ++-- .../tests/ui/literal_option_in_field.stderr | 2 +- .../tests/ui/literal_wrong_input_type.stderr | 6 +++--- .../shopify_api/tests/ui/literal_wrong_scalar.stderr | 10 +++++----- crates/shopify_api_graphql/src/bulk.rs | 1 + crates/shopify_api_graphql/tests/bulk.rs | 8 ++++++++ 9 files changed, 31 insertions(+), 13 deletions(-) create mode 100644 crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.rs create mode 100644 crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.stderr diff --git a/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.rs b/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.rs new file mode 100644 index 0000000..fa5eb4a --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ _shopifyApiTypename: products { edges { node { id } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.stderr b/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.stderr new file mode 100644 index 0000000..186c9aa --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.stderr @@ -0,0 +1,6 @@ +error: `_shopifyApiTypename` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_reserved_alias_top_level.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ _shopifyApiTypename: products { edges { node { id } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr index ab6ef19..a08c83e 100644 --- a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -7,13 +7,13 @@ error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[Inven | | an `Option`: `None` leaves the field out | required by a bound introduced by this call | - = help: the trait `__ShopifyApiNoNull4_c23911f8` is not implemented for `Vec>` + = help: the trait `__ShopifyApiNoNull4_c2391f4b` is not implemented for `Vec>` help: this trait has no implementations, consider adding one --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c23911f8` +note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c2391f4b` --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); diff --git a/crates/shopify_api/tests/ui/literal_one_of.stderr b/crates/shopify_api/tests/ui/literal_one_of.stderr index bf91fa6..418d349 100644 --- a/crates/shopify_api/tests/ui/literal_one_of.stderr +++ b/crates/shopify_api/tests/ui/literal_one_of.stderr @@ -35,7 +35,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Optio | `Option<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2391234` is not implemented for `Option<&str>` + = help: the trait `main::__ShopifyApiExpect1_c2391187` is not implemented for `Option<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:7:13 | @@ -52,7 +52,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Maybe | `Maybe<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2391234` is not implemented for `Maybe<&str>` + = help: the trait `main::__ShopifyApiExpect1_c2391187` is not implemented for `Maybe<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:8:13 | diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr index e93185d..adc9cbc 100644 --- a/crates/shopify_api/tests/ui/literal_option_in_field.stderr +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -7,7 +7,7 @@ error[E0277]: `vendor` of `ProductUpdateInput` expects a `String`, not `Option` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect1_c2391187` is not implemented for `Option` + = help: the trait `__ShopifyApiExpect1_c2393afa` is not implemented for `Option` = note: `vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null` note: required by a bound in `Checks::build` --> tests/ui/literal_option_in_field.rs:3:13 diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr index a94dcf6..f68771b 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -9,8 +9,8 @@ error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built wit 6 | | ); | |_____- required by a bound introduced by this call | - = help: the trait `__ShopifyApiExpect2_c1d68278` is not implemented for `InputObject<2493993284262097346>` -help: the following other types implement trait `__ShopifyApiExpect2_c1d68278` + = help: the trait `__ShopifyApiExpect2_c1d69ff9` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2_c1d69ff9` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -22,7 +22,7 @@ help: the following other types implement trait `__ShopifyApiExpect2_c1d68278` | | | | |_____`&InputObject<960560859991546817>` | `InputObject<960560859991546817>` -note: required for `Vec>` to implement `__ShopifyApiExpect1_c1d68278` +note: required for `Vec>` to implement `__ShopifyApiExpect1_c1d69ff9` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr index 7ec41e0..36229e2 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr @@ -7,7 +7,7 @@ error[E0277]: `quantity` of `DraftOrderLineItemInput` expects an `Int`, not `&st | `&'static str` doesn't satisfy the trait bound | any integer type | - = help: the trait `main::__ShopifyApiExpect1_c1d69ff9` is not implemented for `&str` + = help: the trait `main::__ShopifyApiExpect1_c1d69a2e` is not implemented for `&str` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 | @@ -24,7 +24,7 @@ error[E0277]: `title` of `DraftOrderLineItemInput` expects a `String`, not `u8` | `u8` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect3_c1d69ff9` is not implemented for `u8` + = help: the trait `__ShopifyApiExpect3_c1d69a2e` is not implemented for `u8` = note: `title?: value` takes an `Option`, `None` leaving the field out; `title: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -42,7 +42,7 @@ error[E0277]: `requiresShipping` of `DraftOrderLineItemInput` expects a `Boolean | `{integer}` doesn't satisfy the trait bound | `bool` | - = help: the trait `__ShopifyApiExpect5_c1d69ff9` is not implemented for `{integer}` + = help: the trait `__ShopifyApiExpect5_c1d69a2e` is not implemented for `{integer}` = note: `requiresShipping?: value` takes an `Option`, `None` leaving the field out; `requiresShipping: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -60,8 +60,8 @@ error[E0277]: `value` of `WeightInput` expects a `Float`, not `u64` | `u64` doesn't satisfy the trait bound | `f64`, `f32`, `i32` or `u32` | - = help: the trait `main::__ShopifyApiExpect1_c1d69ff9` is not implemented for `u64` - = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c1d69ff9`, but not `main::__ShopifyApiExpect1_c1d69ff9` + = help: the trait `main::__ShopifyApiExpect1_c1d69a2e` is not implemented for `u64` + = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c1d69a2e`, but not `main::__ShopifyApiExpect1_c1d69a2e` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:4:13 | diff --git a/crates/shopify_api_graphql/src/bulk.rs b/crates/shopify_api_graphql/src/bulk.rs index 0ade2f3..1903a90 100644 --- a/crates/shopify_api_graphql/src/bulk.rs +++ b/crates/shopify_api_graphql/src/bulk.rs @@ -264,6 +264,7 @@ pub fn analyze_bulk_query( checker.variables(definition)?; let top = top_level_field(selection_set(definition), "query")?; + Checker::check_key(top)?; if top.name == "node" || top.name == "nodes" { return error_at( top.position, diff --git a/crates/shopify_api_graphql/tests/bulk.rs b/crates/shopify_api_graphql/tests/bulk.rs index 7ec6ae8..cc08df1 100644 --- a/crates/shopify_api_graphql/tests/bulk.rs +++ b/crates/shopify_api_graphql/tests/bulk.rs @@ -290,6 +290,14 @@ fn the_rules_of_shopify_are_refusals() { "{ things { edges { node { id __typename: name } } } }", "`__typename` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 30)", ), + ( + "{ _shopifyApiTypename: things { edges { node { id } } } }", + "`_shopifyApiTypename` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 3)", + ), + ( + "{ __things: things { edges { node { id } } } }", + "`__things` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 3)", + ), ( "mutation { make(id: \"1\") { a { edges { node { id } } } b { edges { node { id } } } } }", "The mutation of a bulk operation selects one connection at most (`a`), Shopify's limit: `b` is a second one (line 1, column 56)", From 2e096b23d11e78e3e839e2e9d3cd9f00fa7ca4c2 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:39:00 +0100 Subject: [PATCH 118/135] docs(bulk): a `None` in `Variables` is absence, not `null` The variables section said a `None` is written `null`. A `None` in an optional field of a module's `Variables` leaves the variable out: its argument goes, or takes the variable's default. Only a `null` given as a value (`sort = null`, an inline `Option` that is `None`, a `None` in a list, `null` or `Maybe::Null` in an input object) is written `null`, and it replaces the default. The docs and changelog say so; a test pins the three cases. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api/docs/graphql.md | 12 +++++++++--- crates/shopify_api/tests/bulk_text.rs | 23 +++++++++++++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 335b7bb..d1fad80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - `run_bulk_mutation_iter` and `stage_bulk_variables_iter` take the variables from an iterator; the JSONL is written straight into the body of the upload, in memory once. - Bulk operations checked at compile time: `graphql!(bulk("…"))`, `bulk(file("…"))`, inline or in a module. A bulk query is checked against Shopify's bulk rules for API 2026-10: one top-level field, a connection (not `node` or `nodes`); five connections at most, two levels deep below it; `edges { node { … } }` and nothing else (no `nodes`, `cursor`, `pageInfo`, nor `first`, `last`, `after`, `before`); `Node` objects; a nested connection written right in the `node` of its parent; an unaliased `id` on every node with nested connections (an error that asks for it, never added silently), and no other field aliased `id` there; no alias `_shopifyApiTypename` or starting with `__`; no string that the parser reads unlike GraphQL (a `\b` escape, which it reads as U+0010: write `\u0008`; a block string with a lone carriage return or indented with other whitespace than spaces and tabs); two connections of one node that may return the same type, such as two aliased `metafields`, are refused. What the guide does not show is refused. A bulk mutation is one mutation field, not a bulk operation, with one connection at most. - The items of a bulk query are generated types: `Item`, each nested connection a `Vec` of its nodes. `Shopify::bulk_query` runs it with `groupObjects` and returns `BulkItems` (`next_item`, `collect`, `Stream`), one item in memory at a time, nested lines placed by `__parentId`, and by `__typename` where a node has several connections: the text sent selects it there as `_shopifyApiTypename: __typename`, and a `__typename` of the query is left as written. A line's `id` places its children only when it is a string: `id` may alias another field where no connection is nested. `start_bulk_query` and `download_bulk_items` split the steps; `BulkQuery::text` is the text sent. -- The variables of a bulk query, which Shopify does not take, are given as for any operation (literals and `input!` included) and written into its text as GraphQL literals, from the parsed operation: strings escaped as JSON, enum values bare (in input objects and lists too), input objects with unquoted keys, a variable without a value left out or given its default. The values are checked as for any operation; an enum value or a field that is not a GraphQL name fails with `InvalidValueReason::NotAGraphqlName`, an enum value `true`, `false` or `null` with `InvalidValueReason::ReservedEnumValue`. A variable that may hold `JSON` is refused at compile time. +- The variables of a bulk query, which Shopify does not take, are given as for any operation (literals and `input!` included) and written into its text as GraphQL literals, from the parsed operation: strings escaped as JSON, enum values bare (in input objects and lists too), input objects with unquoted keys, a variable without a value (a `None` in `Variables`) left out or given its default, an explicit `null` written `null`. The values are checked as for any operation; an enum value or a field that is not a GraphQL name fails with `InvalidValueReason::NotAGraphqlName`, an enum value `true`, `false` or `null` with `InvalidValueReason::ReservedEnumValue`. A variable that may hold `JSON` is refused at compile time. - `Shopify::bulk_mutation` runs a `graphql!(bulk("mutation …"))` over an iterator of its `Variables`: every line is checked and written before anything is sent, then staged, run, and read as `BulkMutationResult` (`data`, `errors`, `index`, Shopify's `__lineNumber`). `start_bulk_mutation` only starts it. Typed bulk operations run at the Admin API version they were checked against. - `Transport`, the HTTP layer as a trait, with `send_streaming` (a default goes through `send`), `StreamingResponse` and `BodyStream`. The default `ReqwestTransport` never follows a redirection, and streams: the timeout of a request bounds the wait for the headers and for each chunk, not the whole body. A client of your own goes through `transport::reqwest_0_13::from_builder`: reqwest appears in the API only under `transport::reqwest_0_13`, named after its major version, so that a later reqwest comes next to it. The client runs on Tokio. - `testing::MockTransport` (`push_data`, `push_chunks`, `push_streaming`, `respond_with`…), and `testing::client`, which retries without waiting, even for a scripted `Retry-After`. `testing` also gives the signing helpers: `webhooks::sign`, `ShopifyApp::sign_query`, `sign_app_proxy`, `sign_session_token`. diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 2c877e2..6a5720a 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -457,12 +457,18 @@ GraphQL literal, and the variable definitions are left out. `Variables` may hold, fails with [`Error::InvalidValue`](crate::Error::InvalidValue) (`NotAGraphqlName`) before anything is sent, as does an enum value `true`, `false` or `null` (`ReservedEnumValue`), which would read as a - boolean or as `null`, and as do the values any operation refuses. A - `None` is still written `null`. + boolean or as `null`, and as do the values any operation refuses. - An input object as `{field: value}`, a list as `[a, b]`. - A variable without a value takes its default value, or is left out with its argument or field, as GraphQL leaves out an argument whose variable - has no value; in a list, it is `null`. + has no value; in a list, it is `null`. A `None` in an optional field of a + module's `Variables` is such a variable without a value, not a `null`: + `sorted::Variables { sort: None }` sends `products { … }`, or + `products(sortKey: TITLE)` if `$sort` defaults to `TITLE`. +- A `null` given as a value is written `null` and replaces the default: + `sort = null`, or `sort = option` with `None` in an inline `graphql!`, + sends `products(sortKey: null)`. So does a `None` in a list, and `null` or + a `Maybe::Null` in an input object. - A variable that may hold a `JSON` value is refused at compile time. ## Bulk mutations diff --git a/crates/shopify_api/tests/bulk_text.rs b/crates/shopify_api/tests/bulk_text.rs index 9c2ed59..b7c4e69 100644 --- a/crates/shopify_api/tests/bulk_text.rs +++ b/crates/shopify_api/tests/bulk_text.rs @@ -9,6 +9,7 @@ const URL: &str = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-e graphql! { mod sorted = bulk("query($sort: ProductSortKeys) { products(sortKey: $sort) { edges { node { title } } } }"); + mod sorted_by_title = bulk("query($sort: ProductSortKeys = TITLE) { products(sortKey: $sort) { edges { node { title } } } }"); mod topics = bulk("query($topics: [WebhookSubscriptionTopic!]) { webhookSubscriptions(topics: $topics) { edges { node { id } } } }"); mod priced = bulk("query($context: ContextualPricingContext!) { products { edges { node { contextualPricing(context: $context) { priceRange { minVariantPrice { amount } } } } } } }"); mod aliased_id = bulk("{ products { edges { node { id: totalInventory title } } } }"); @@ -55,6 +56,28 @@ fn an_enum_variable_true_false_or_null_is_refused() { assert!(text.contains("products(sortKey: nullable)"), "{text}"); } +#[test] +fn a_none_in_variables_is_absence_and_null_is_null() { + // `None` in `Variables` leaves the variable out: its argument goes, or + // takes the variable's default. + let text = sorted::operation(sorted::Variables { sort: None }) + .text() + .unwrap(); + assert_eq!(text, "{ products { edges { node { title } } } }"); + let text = sorted_by_title::operation(sorted_by_title::Variables { sort: None }) + .text() + .unwrap(); + assert!(text.contains("products(sortKey: TITLE)"), "{text}"); + // An explicit `null` is written, and replaces the default. + let text = graphql!( + bulk("query($sort: ProductSortKeys = TITLE) { products(sortKey: $sort) { edges { node { title } } } }"), + sort = null, + ) + .text() + .unwrap(); + assert!(text.contains("products(sortKey: null)"), "{text}"); +} + #[test] fn an_enum_true_false_or_null_in_a_list_is_refused() { for word in ["null", "true", "false"] { From 924e54fc1b67d6d112e409f77047898c18972f55 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:39:01 +0100 Subject: [PATCH 119/135] test(client): run the `ShopifyBuilder` doctest without a default transport Without `rustls` or `native-tls`, `build` has no transport and the example failed with `NoTransport` under `--no-default-features`. Its body now runs only with a transport feature, the text shown unchanged. `check:features`, which CI's `features` job runs, now also runs the doctests of `shopify_api` without default features. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/client.rs | 4 ++++ mise.toml | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index 1b1591d..9554faa 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -303,6 +303,9 @@ fn jitter_fraction() -> f64 { /// Builds a [`Shopify`] client. /// /// ``` +/// # // Without `rustls` or `native-tls`, `build` needs a `transport(…)`. +/// # #[cfg(any(feature = "rustls", feature = "native-tls"))] +/// # { /// use std::time::Duration; /// use shopify_api::{ApiVersion, RetryPolicy, Shopify}; /// @@ -311,6 +314,7 @@ fn jitter_fraction() -> f64 { /// .api_version(ApiVersion::V2026_10) /// .retry(RetryPolicy::new(6).with_max_delay(Duration::from_secs(10))) /// .build()?; +/// # } /// # Ok::<(), shopify_api::Error>(()) /// ``` #[must_use] diff --git a/mise.toml b/mise.toml index 3fbbc47..9c47e91 100644 --- a/mise.toml +++ b/mise.toml @@ -28,12 +28,13 @@ description = "Build and test the client with its default features only" run = "cargo test -p shopify_api --locked" [tasks."check:features"] -description = "Build the client without its default features, then with each feature alone: what feature unification in the workspace hides" +description = "Build the client without its default features, then with each feature alone, and run its doctests without them: what feature unification in the workspace hides" run = [ "cargo check -p shopify_api --no-default-features --lib --locked", "cargo check -p shopify_api --no-default-features --features webhooks --lib --locked", "cargo check -p shopify_api --no-default-features --features oauth --lib --locked", "cargo check -p shopify_api --no-default-features --features testing --lib --locked", + "cargo test -p shopify_api --no-default-features --doc --locked", ] [tasks.doc] From d78f8c7e681aea865bdae7b1f650ebdc299874a7 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:48:59 +0100 Subject: [PATCH 120/135] docs(bulk): an optional enum value sent as `null` is written `raw(option)` Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/docs/graphql.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 6a5720a..3b50f24 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -466,7 +466,7 @@ GraphQL literal, and the variable definitions are left out. `sorted::Variables { sort: None }` sends `products { … }`, or `products(sortKey: TITLE)` if `$sort` defaults to `TITLE`. - A `null` given as a value is written `null` and replaces the default: - `sort = null`, or `sort = option` with `None` in an inline `graphql!`, + `sort = null`, or `sort = raw(option)` with `None` in an inline `graphql!`, sends `products(sortKey: null)`. So does a `None` in a list, and `null` or a `Maybe::Null` in an input object. - A variable that may hold a `JSON` value is refused at compile time. From 3162911c794bc88066ae543a6010f0abd6e45b4c Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:18:09 +0100 Subject: [PATCH 121/135] fix(oauth)!: an extension session token is not an admin session verify_session_token takes only the tokens of Shopify admin again: dest exactly https://{shop}.myshopify.com, iss exactly its /admin, compared whole (a prefix let https://s.myshopify.com.evil.example/admin pass). SessionToken::subject is user_id again. verify_extension_session_token verifies the tokens of checkout and customer account UI extensions, which any buyer gets, as an ExtensionSessionToken (shop, customer, claims) that does not exchange for a token. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- MIGRATION.md | 10 + README.md | 17 ++ crates/shopify_api/src/oauth.rs | 377 +++++++++++++++++++++++++++--- crates/shopify_api/tests/oauth.rs | 63 ++++- 5 files changed, 426 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d1fad80..2a0cab8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,7 +31,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - `Shopify::bulk_mutation` runs a `graphql!(bulk("mutation …"))` over an iterator of its `Variables`: every line is checked and written before anything is sent, then staged, run, and read as `BulkMutationResult` (`data`, `errors`, `index`, Shopify's `__lineNumber`). `start_bulk_mutation` only starts it. Typed bulk operations run at the Admin API version they were checked against. - `Transport`, the HTTP layer as a trait, with `send_streaming` (a default goes through `send`), `StreamingResponse` and `BodyStream`. The default `ReqwestTransport` never follows a redirection, and streams: the timeout of a request bounds the wait for the headers and for each chunk, not the whole body. A client of your own goes through `transport::reqwest_0_13::from_builder`: reqwest appears in the API only under `transport::reqwest_0_13`, named after its major version, so that a later reqwest comes next to it. The client runs on Tokio. - `testing::MockTransport` (`push_data`, `push_chunks`, `push_streaming`, `respond_with`…), and `testing::client`, which retries without waiting, even for a scripted `Retry-After`. `testing` also gives the signing helpers: `webhooks::sign`, `ShopifyApp::sign_query`, `sign_app_proxy`, `sign_session_token`. -- `oauth`: `ShopifyApp`, with install links, the verification of callbacks, admin launches and app proxy requests, the code exchange, session tokens and the token exchange. `verify_session_token` takes the tokens of Shopify admin and of checkout and customer account UI extensions (a `dest` without `https://`); `SessionToken::subject` is the staff member's ID or the customer's GID. `ShopifyApp::with_token_store` gives the clients it builds a `TokenStore`. +- `oauth`: `ShopifyApp`, with install links, the verification of callbacks, admin launches and app proxy requests, the code exchange, session tokens and the token exchange. `verify_session_token` takes only the session tokens of Shopify admin: `dest` exactly `https://{shop}.myshopify.com` and `iss` exactly its `/admin`, compared whole; `SessionToken::user_id` is the staff member's ID. `verify_extension_session_token` takes the tokens of checkout and customer account UI extensions, which any buyer gets (a `dest` with or without `https://`, `iss` optional but then the admin's), as an `ExtensionSessionToken` with `shop()`, `customer()` (the customer's GID) and `claims()`: a type of its own, which does not exchange for a token, so that a buyer's token never passes for an admin session. `ShopifyApp::with_token_store` gives the clients it builds a `TokenStore`. - An error shows nothing of what the crate did not write (`Error` documents the contract): no body, value or map key of an answer, no message of serde or of a `Serialize` implementation, no query string or user of an address. `Error::Http` displays the status, the address, the content type and the length of the body; `Error::raw_http_body` (or the `raw_body: RawBody` field) gives the body. `Error::Decode` displays the kind of mismatch, its line and column, and a path of the type's own field names and indexes, with `[key]` for a map key. `Error::Variables` names the variable that does not serialize. `Error::sensitive_detail` gives serde's message, the `Serialize` implementation's or the token endpoint's, all kept out of `Display` and `Debug` (`SensitiveDetail`). The `Debug` of `GraphqlErrors` counts the entries of partial `data`, and that of `GraphqlError` shows `extensions.code` and counts the other extensions (Shopify echoes an invalid variable's whole value in `extensions.value`). Shopify's own messages in `errors` and `userErrors` are shown as they are. `Error::Http` carries Shopify's `X-Request-Id`. - `Error::Bulk { message, operation }` holds the operation that ended without completing, with its `error_code` and `partial_data_url`; `Error::Timeout { message, id }` the ID of the bulk operation waited for, to cancel it. diff --git a/MIGRATION.md b/MIGRATION.md index 2218938..d50de49 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -253,6 +253,16 @@ rule as `Webhook::verify`. Topics are accepted as `orders/create` or `ORDERS_CREATE`. +## OAuth and session tokens + +New in 1.0, under the `oauth` feature: `ShopifyApp`. Its +`verify_session_token` takes only the session tokens of Shopify admin, which +a staff member's browser sends; trust them to load a shop's stored token. +The token of a checkout or customer account UI extension, which any buyer +gets, verifies with `verify_extension_session_token`, as an +`ExtensionSessionToken` (`shop()`, `customer()`), and is refused by +`verify_session_token`. + ## Schema download | 0.10 | 1.0 | diff --git a/README.md b/README.md index 23eccc4..22b3508 100644 --- a/README.md +++ b/README.md @@ -458,6 +458,14 @@ let session = app.verify_session_token(bearer)?; let token = app.exchange_session_token(&session, RequestedToken::ExpiringOffline).await?; let shopify = app.client(session.shop(), token)?; +// Or, once the token is stored: verify the session, then load the shop's token. +let session = app.verify_session_token(bearer)?; +let shopify = app.client(session.shop(), my_database.offline_token(session.shop())?)?; + +// A checkout or customer account UI extension: the shop, and the customer if logged in. +let extension = app.verify_extension_session_token(bearer)?; +let customer = extension.customer(); // Some("gid://shopify/Customer/…") + // Install link and callback, admin launches, app proxies. let link = app.authorization_url(&shop, &request); let callback = app.verify_query(query_string)?; @@ -465,6 +473,15 @@ let token = app.exchange_code(&callback).await?; let proxied = app.verify_app_proxy(query_string)?; ``` +`verify_session_token` takes only the tokens of Shopify admin (`dest` and +`iss` exactly `https://{shop}.myshopify.com` and its `/admin`), which Shopify +gives a staff member: they may open the admin side of the app, such as the +stored offline token of the shop. The tokens of checkout and customer account +UI extensions are signed with the same secret, but any buyer of the shop gets +one, logged in or not: `verify_extension_session_token` verifies them, as an +`ExtensionSessionToken` that does not exchange for a token, so that one can +never pass for the other. + ## Testing your code Feature `testing`: a `MockTransport` records what the client sends and answers diff --git a/crates/shopify_api/src/oauth.rs b/crates/shopify_api/src/oauth.rs index 67ce43d..c058754 100644 --- a/crates/shopify_api/src/oauth.rs +++ b/crates/shopify_api/src/oauth.rs @@ -18,6 +18,13 @@ //! # } //! ``` //! +//! [`verify_session_token`](ShopifyApp::verify_session_token) takes only the +//! tokens of Shopify admin, which a staff member's browser sends. The tokens +//! of checkout and customer account UI extensions, which any buyer gets, are +//! verified by [`verify_extension_session_token`](ShopifyApp::verify_extension_session_token), +//! as an [`ExtensionSessionToken`]: a type of its own, so that one never +//! passes for the other. +//! //! An app outside Shopify admin installs through a link and a callback: //! //! ```no_run @@ -192,13 +199,18 @@ pub enum RequestedToken { Online, } -/// A session token whose signature and dates were verified. +/// A session token of Shopify admin, from [`ShopifyApp::verify_session_token`]: +/// its signature, dates, `dest` and `iss` were verified. +/// +/// Only Shopify admin issues it, to a staff member of the shop: it is what +/// opens the admin side of an app. The tokens of checkout and customer account +/// UI extensions, which any buyer gets, are an [`ExtensionSessionToken`]. /// /// `Debug` hides the token itself, which is a bearer. #[derive(Clone, PartialEq)] pub struct SessionToken { shop: ShopDomain, - subject: Option, + user_id: Option, session_id: Option, expires_at: DateTime, claims: Value, @@ -210,7 +222,7 @@ impl std::fmt::Debug for SessionToken { formatter .debug_struct("SessionToken") .field("shop", &self.shop) - .field("subject", &self.subject) + .field("user_id", &self.user_id) .field("session_id", &self.session_id) .field("expires_at", &self.expires_at) .finish_non_exhaustive() @@ -223,11 +235,9 @@ impl SessionToken { &self.shop } - /// `sub`: the ID of the staff member for a token of Shopify admin - /// (`42`), the GID of the customer for a token of a checkout or customer - /// account UI extension (`gid://shopify/Customer/1`), when one is logged in. - pub fn subject(&self) -> Option<&str> { - self.subject.as_deref() + /// `sub`: the ID of the staff member, such as `42`. + pub fn user_id(&self) -> Option<&str> { + self.user_id.as_deref() } /// The session, `sid`. @@ -250,6 +260,103 @@ impl SessionToken { } } +/// A session token of a checkout or customer account UI extension, from +/// [`ShopifyApp::verify_extension_session_token`]: its signature, dates and +/// `dest` were verified. +/// +/// Any buyer of the shop gets one, logged in or not: it proves which shop +/// and, through [`customer`](Self::customer), which customer, never a staff +/// member. It is not a [`SessionToken`], and does not exchange for a token. +/// +/// `Debug` hides the token itself, which is a bearer. +#[derive(Clone, PartialEq)] +pub struct ExtensionSessionToken { + shop: ShopDomain, + customer: Option, + expires_at: DateTime, + claims: Value, + token: String, +} + +impl std::fmt::Debug for ExtensionSessionToken { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ExtensionSessionToken") + .field("shop", &self.shop) + .field("customer", &self.customer) + .field("expires_at", &self.expires_at) + .finish_non_exhaustive() + } +} + +impl ExtensionSessionToken { + /// The shop of `dest`. + pub fn shop(&self) -> &ShopDomain { + &self.shop + } + + /// `sub`: the GID of the logged-in customer, such as + /// `gid://shopify/Customer/1`. Shopify only sends it when a customer is + /// logged in and the app may read customers. + pub fn customer(&self) -> Option<&str> { + self.customer.as_deref() + } + + pub fn expires_at(&self) -> DateTime { + self.expires_at + } + + /// Every claim of the token. + pub fn claims(&self) -> &Value { + &self.claims + } + + /// The token itself, as the extension sent it. + pub fn as_str(&self) -> &str { + &self.token + } +} + +/// The claims of a session token whose signature, dates and audience were verified. +struct Verified { + claims: Value, + expires_at: DateTime, + token: String, +} + +impl Verified { + fn text(&self, name: &str) -> Option { + self.claims + .get(name) + .and_then(Value::as_str) + .map(str::to_string) + } + + fn claim(&self, name: &str) -> Option<&str> { + self.claims.get(name).and_then(Value::as_str) + } +} + +/// The shop of a host that is a whole `*.myshopify.com` domain. +fn shop_of_host(host: &str) -> Result { + Some(host) + // A whole domain: a bare handle is not what Shopify writes. + .filter(|host| host.to_ascii_lowercase().ends_with(".myshopify.com")) + .and_then(|host| ShopDomain::new(host).ok()) + .ok_or_else(|| invalid("the `dest` of the session token is not a shop")) +} + +/// Checks that `iss` is exactly the admin of `shop`. +fn check_admin_issuer(issuer: &str, shop: &ShopDomain) -> Result<()> { + if issuer == format!("{}/admin", shop.origin()) { + Ok(()) + } else { + Err(invalid( + "the `iss` of the session token is not the admin of its `dest`", + )) + } +} + impl ShopifyApp { pub fn new(client_id: impl Into, client_secret: impl Into) -> Self { Self { @@ -471,18 +578,84 @@ impl ShopifyApp { // ─── Session tokens ────────────────────────────────────────────── - /// Verifies a session token from the app's frontend (the bearer of its - /// requests): signed by the app's secret with HS256, issued for the app, - /// within its dates, from a shop. + /// Verifies a session token of Shopify admin (the bearer of the requests + /// of the app's embedded frontend): signed by the app's secret with HS256, + /// issued for the app, within its dates, with a `dest` of exactly + /// `https://{shop}.myshopify.com` and an `iss` of exactly + /// `https://{shop}.myshopify.com/admin`. /// - /// The tokens of Shopify admin and of UI extensions both verify: the - /// `dest` of an extension's token is the shop's domain without `https://`, - /// and it may have no `iss`. + /// Only Shopify admin issues such a token, to a staff member: trust it to + /// open the admin side of the app, such as loading the shop's stored + /// offline token. The tokens of checkout and customer account UI + /// extensions, which any buyer gets, are refused here: verify them with + /// [`verify_extension_session_token`](Self::verify_extension_session_token). pub fn verify_session_token(&self, token: &str) -> Result { self.verify_session_token_at(token, Utc::now()) } fn verify_session_token_at(&self, token: &str, now: DateTime) -> Result { + let verified = self.verify_jwt(token, now)?; + let destination = verified + .claim("dest") + .ok_or_else(|| invalid("the session token has no `dest`"))?; + let shop = destination + .strip_prefix("https://") + .ok_or_else(|| invalid("the `dest` of the session token is not the admin of a shop")) + .and_then(shop_of_host)?; + if destination != shop.origin() { + return Err(invalid("the `dest` of the session token is not a shop")); + } + let issuer = verified.claim("iss").ok_or_else(|| { + invalid("the session token has no `iss`: it is not from Shopify admin") + })?; + check_admin_issuer(issuer, &shop)?; + Ok(SessionToken { + user_id: verified.text("sub"), + session_id: verified.text("sid"), + shop, + expires_at: verified.expires_at, + claims: verified.claims, + token: verified.token, + }) + } + + /// Verifies the session token of a checkout or customer account UI + /// extension (`shopify.sessionToken.get()`): signed by the app's secret with + /// HS256, issued for the app, within its dates, with a `dest` that is a + /// `*.myshopify.com` domain (Shopify writes it without `https://`). An + /// `iss`, when there is one, must be exactly `https://{shop}.myshopify.com/admin`. + /// + /// Any buyer of the shop can get such a token: it proves the shop and, + /// when one is logged in, the customer, never a staff member. It is a type + /// of its own so that it cannot reach what a [`SessionToken`] opens. + pub fn verify_extension_session_token(&self, token: &str) -> Result { + self.verify_extension_session_token_at(token, Utc::now()) + } + + fn verify_extension_session_token_at( + &self, + token: &str, + now: DateTime, + ) -> Result { + let verified = self.verify_jwt(token, now)?; + let destination = verified + .claim("dest") + .ok_or_else(|| invalid("the session token has no `dest`"))?; + let shop = shop_of_host(destination.strip_prefix("https://").unwrap_or(destination))?; + if let Some(issuer) = verified.claim("iss") { + check_admin_issuer(issuer, &shop)?; + } + Ok(ExtensionSessionToken { + customer: verified.text("sub"), + shop, + expires_at: verified.expires_at, + claims: verified.claims, + token: verified.token, + }) + } + + /// The signature, dates and audience of a session token, the same for every kind. + fn verify_jwt(&self, token: &str, now: DateTime) -> Result { let token = token.trim(); let token = token.strip_prefix("Bearer ").unwrap_or(token); let mut parts = token.split('.'); @@ -530,32 +703,11 @@ impl ShopifyApp { if !audience_matches { return Err(invalid("the session token was issued for another app")); } - let destination = claims - .get("dest") - .and_then(Value::as_str) - .ok_or_else(|| invalid("the session token has no `dest`"))?; - // `https://shop.myshopify.com` from Shopify admin, `shop.myshopify.com` from an extension. - let host = destination.strip_prefix("https://").unwrap_or(destination); - let shop = Some(host) - // A whole domain: a bare handle is not what Shopify writes. - .filter(|host| host.to_ascii_lowercase().ends_with(".myshopify.com")) - .and_then(|host| ShopDomain::new(host).ok()) - .ok_or_else(|| invalid("the `dest` of the session token is not a shop"))?; - let issuer = claims.get("iss").and_then(Value::as_str); - if issuer.is_some_and(|issuer| !issuer.starts_with(&shop.origin())) { - return Err(invalid( - "the `iss` and `dest` of the session token name different shops", - )); - } - let text = |name: &str| claims.get(name).and_then(Value::as_str).map(str::to_string); - Ok(SessionToken { - subject: text("sub"), - session_id: text("sid"), + Ok(Verified { expires_at: Utc .timestamp_opt(expires, 0) .single() .ok_or_else(|| invalid("the `exp` of the session token is out of range"))?, - shop, claims, token: token.to_string(), }) @@ -848,7 +1000,8 @@ mod tests { .verify_session_token_at(&format!("Bearer {token}"), at(now)) .unwrap(); assert_eq!(session.shop().as_str(), "my-shop.myshopify.com"); - assert_eq!(session.subject(), Some("42")); + assert_eq!(session.user_id(), Some("42")); + assert_eq!(session.session_id(), claims(now)["sid"].as_str()); assert_eq!(session.expires_at(), at(now + 60)); assert_eq!(session.as_str(), token); @@ -890,7 +1043,7 @@ mod tests { mixed["iss"] = json!("https://other-shop.myshopify.com/admin"); assert_eq!( refusal(&app().sign_session_token(&mixed), now), - "verification failed: the `iss` and `dest` of the session token name different shops" + "verification failed: the `iss` of the session token is not the admin of its `dest`" ); // A token whose header claims another algorithm is refused before its signature. let unsigned = format!( @@ -908,6 +1061,151 @@ mod tests { ); } + #[test] + fn an_admin_session_token_has_exactly_the_admin_issuer_and_destination() { + let now = 1_800_000_000; + let refusal = |claims: &Value| { + app() + .verify_session_token_at(&app().sign_session_token(claims), at(now)) + .unwrap_err() + .to_string() + }; + let not_admin = + "verification failed: the `iss` of the session token is not the admin of its `dest`"; + // `iss` is compared whole: a host that only starts with the shop's is another host. + for issuer in [ + "https://my-shop.myshopify.com.evil.example/admin", + "https://my-shop.myshopify.com", + "https://my-shop.myshopify.com/admin/", + "https://my-shop.myshopify.com/adminx", + "http://my-shop.myshopify.com/admin", + ] { + let mut token = claims(now); + token["iss"] = json!(issuer); + assert_eq!(refusal(&token), not_admin, "{issuer}"); + } + let mut no_issuer = claims(now); + no_issuer.as_object_mut().unwrap().remove("iss"); + assert_eq!( + refusal(&no_issuer), + "verification failed: the session token has no `iss`: it is not from Shopify admin" + ); + let mut bare = claims(now); + bare["dest"] = json!("my-shop.myshopify.com"); + assert_eq!( + refusal(&bare), + "verification failed: the `dest` of the session token is not the admin of a shop" + ); + for destination in [ + "https://my-shop.myshopify.com/", + "https://my-shop.myshopify.com/admin", + ] { + let mut token = claims(now); + token["dest"] = json!(destination); + assert!( + app() + .verify_session_token_at(&app().sign_session_token(&token), at(now)) + .is_err(), + "{destination}" + ); + } + } + + /// The payload of Shopify's documentation of the Session Token API of + /// checkout and customer account UI extensions: no `iss`, no `sid`, a + /// `dest` without `https://`, and `sub` only for a logged-in customer. + fn extension_claims(now: i64) -> Value { + json!({ + "dest": "store-name.myshopify.com", + "aud": "client-id", + "exp": now + 300, + "nbf": now, + "iat": now, + "jti": "6c992878-dbaf-48d1-bb9d-6d9b59814fd1", + "sub": "gid://shopify/Customer/1", + }) + } + + #[test] + fn verifies_extension_session_tokens() { + let now = 1_800_000_000; + let verify = |claims: &Value| { + app().verify_extension_session_token_at(&app().sign_session_token(claims), at(now)) + }; + let session = verify(&extension_claims(now)).unwrap(); + assert_eq!(session.shop().as_str(), "store-name.myshopify.com"); + assert_eq!(session.customer(), Some("gid://shopify/Customer/1")); + assert_eq!(session.expires_at(), at(now + 300)); + assert_eq!( + session.claims()["jti"], + "6c992878-dbaf-48d1-bb9d-6d9b59814fd1" + ); + + // An anonymous buyer: no `sub`. + let mut anonymous = extension_claims(now); + anonymous.as_object_mut().unwrap().remove("sub"); + assert_eq!(verify(&anonymous).unwrap().customer(), None); + // `dest` with `https://`, and an `iss` that is the admin of the same shop. + let mut admin_shaped = extension_claims(now); + admin_shaped["dest"] = json!("https://store-name.myshopify.com"); + admin_shaped["iss"] = json!("https://store-name.myshopify.com/admin"); + assert!(verify(&admin_shaped).is_ok()); + // An admin token verifies here too: it proves its shop as well. + assert_eq!( + verify(&claims(now)).unwrap().shop().as_str(), + "my-shop.myshopify.com" + ); + + // An `iss` is compared whole here as well. + let mut prefixed = extension_claims(now); + prefixed["iss"] = json!("https://store-name.myshopify.com.evil.example/admin"); + assert_eq!( + verify(&prefixed).unwrap_err().to_string(), + "verification failed: the `iss` of the session token is not the admin of its `dest`" + ); + // A bare handle, or another host, is still not a shop. + for destination in ["store-name", "store-name.example.com", "https://store-name"] { + let mut token = extension_claims(now); + token["dest"] = json!(destination); + assert!(verify(&token).is_err(), "{destination}"); + } + // The checks every session token gets. + let mut other_app = extension_claims(now); + other_app["aud"] = json!("other"); + assert!(verify(&other_app).is_err()); + assert!( + app() + .verify_extension_session_token_at( + &app().sign_session_token(&extension_claims(now)), + at(now + 311) + ) + .is_err() + ); + let foreign = + ShopifyApp::new("client-id", "other").sign_session_token(&extension_claims(now)); + assert!( + app() + .verify_extension_session_token_at(&foreign, at(now)) + .is_err() + ); + } + + #[test] + fn an_extension_session_token_is_not_an_admin_session() { + let now = 1_800_000_000; + let mut anonymous = extension_claims(now); + anonymous.as_object_mut().unwrap().remove("sub"); + for token in [extension_claims(now), anonymous] { + let token = app().sign_session_token(&token); + assert!(app().verify_session_token_at(&token, at(now)).is_err()); + assert!( + app() + .verify_extension_session_token_at(&token, at(now)) + .is_ok() + ); + } + } + #[test] fn an_empty_secret_verifies_nothing() { let unset = ShopifyApp::new("client-id", ""); @@ -946,6 +1244,9 @@ mod tests { let token = app().sign_session_token(&claims(now)); let session = app().verify_session_token(&token).unwrap(); assert!(!format!("{session:?}").contains(&token)); + let extension = app().sign_session_token(&extension_claims(now)); + let session = app().verify_extension_session_token(&extension).unwrap(); + assert!(!format!("{session:?}").contains(&extension)); } #[test] diff --git a/crates/shopify_api/tests/oauth.rs b/crates/shopify_api/tests/oauth.rs index 341415d..144054f 100644 --- a/crates/shopify_api/tests/oauth.rs +++ b/crates/shopify_api/tests/oauth.rs @@ -110,6 +110,7 @@ async fn an_online_token_names_its_staff_member() { let app = app(&mock); let now = now(); let bearer = app.sign_session_token(&json!({ + "iss": "https://my-shop.myshopify.com/admin", "dest": "https://my-shop.myshopify.com", "aud": "client-id", "exp": now + 60, @@ -127,7 +128,7 @@ async fn an_online_token_names_its_staff_member() { } #[test] -fn a_checkout_extension_session_token_verifies() { +fn a_checkout_extension_session_token_verifies_on_its_own_path() { let app = ShopifyApp::new("client-id", "client-secret"); let now = now(); // As a checkout UI extension sends it: `dest` without `https://`, no `iss`, a customer. @@ -140,18 +141,72 @@ fn a_checkout_extension_session_token_verifies() { "jti": "6c992878-dbaf-48d1-bb9d-6d9b59814fd1", "sub": "gid://shopify/Customer/1", })); - let session = app.verify_session_token(&bearer).unwrap(); + let session = app.verify_extension_session_token(&bearer).unwrap(); assert_eq!(session.shop().as_str(), "store-name.myshopify.com"); - assert_eq!(session.subject(), Some("gid://shopify/Customer/1")); + assert_eq!(session.customer(), Some("gid://shopify/Customer/1")); + assert!(app.verify_session_token(&bearer).is_err()); // A bare handle, or another host, is still not a shop. for dest in ["store-name", "store-name.example.com", "https://store-name"] { let bearer = app.sign_session_token(&json!({ "dest": dest, "aud": "client-id", "exp": now + 60 })); - assert!(app.verify_session_token(&bearer).is_err(), "{dest}"); + assert!( + app.verify_extension_session_token(&bearer).is_err(), + "{dest}" + ); } } +/// The reproduction of the review of 1.0: the token any buyer gets from +/// `shopify.sessionToken.get()` in a checkout UI extension (no `iss`, no `sid`, +/// no `sub`, `dest` without `https://`) must not pass as an admin session, +/// which an app trusts to load the stored offline token of `shop()`. +#[test] +fn a_buyer_checkout_token_is_not_an_admin_session() { + let app = ShopifyApp::new("client-id", "client-secret"); + let now = now(); + let checkout = app.sign_session_token(&json!({ + "dest": "victim.myshopify.com", "aud": "client-id", "exp": now + 300, "nbf": now - 1, + "iat": now, "jti": "x" + })); + assert_eq!( + app.verify_session_token(&checkout).unwrap_err().to_string(), + "verification failed: the `dest` of the session token is not the admin of a shop" + ); + let extension = app.verify_extension_session_token(&checkout).unwrap(); + assert_eq!(extension.shop().as_str(), "victim.myshopify.com"); + assert_eq!(extension.customer(), None); + + // With `https://` added to `dest`, it still has no `iss`. + let checkout = app.sign_session_token(&json!({ + "dest": "https://victim.myshopify.com", "aud": "client-id", "exp": now + 300, + })); + assert!(app.verify_session_token(&checkout).is_err()); + + // The admin token of the same shop verifies on both paths. + let admin = app.sign_session_token(&json!({ + "iss": "https://victim.myshopify.com/admin", "dest": "https://victim.myshopify.com", + "aud": "client-id", "sub": "42", "sid": "s", "exp": now + 60, "nbf": now - 1 + })); + let session = app.verify_session_token(&admin).unwrap(); + assert_eq!(session.shop().as_str(), "victim.myshopify.com"); + assert_eq!(session.user_id(), Some("42")); + assert_eq!(session.session_id(), Some("s")); +} + +/// `iss` was compared as a prefix: a host that starts with the shop's passed. +#[test] +fn an_issuer_that_only_starts_with_the_shop_is_refused() { + let app = ShopifyApp::new("client-id", "client-secret"); + let now = now(); + let token = app.sign_session_token(&json!({ + "iss": "https://s.myshopify.com.evil.example/admin", "dest": "https://s.myshopify.com", + "aud": "client-id", "exp": now + 60, + })); + assert!(app.verify_session_token(&token).is_err()); + assert!(app.verify_extension_session_token(&token).is_err()); +} + #[derive(Default, Clone)] struct Saved(std::sync::Arc>>); From 3f30e96d71eb0f0049bddb9385758ea79f109694 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:18:41 +0100 Subject: [PATCH 122/135] refactor!: RetryPolicy and BulkWaitOptions are neither Copy nor PartialEq So that a progress callback or a retry predicate can be added after 1.0 without a breaking change. They stay Clone, Debug and Default. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api/src/bulk.rs | 2 +- crates/shopify_api/src/client.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a0cab8..b98ff2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - `schema = ""` in `[package.metadata.shopify_api]` names another schema file than `graphql/admin.schema.json`, relative to the package's `Cargo.toml`, for that package only. It must name a file inside the package, which `cargo package` ships: a relative path with `/` and portable names (no `:`, `\`, `<>"|?*` or control character, no name ending in `.` or a space, no device name such as `CON`); an absolute path, or one that climbs out with `..`, is an error (a symbolic link inside the package may point elsewhere). A dependency keeps the one its own `Cargo.toml` names. The file follows the rules of the default one (version, download, older format), `shopify-api schema download` and `shopify-api check` use it, and an edit of the key compiles the crate again. - `@oneOf` input objects (`ProductSetIdentifiers`…) are checked at compile time: exactly one field, not `null`. - `shopify-api check` checks `.graphql` files against the schema. -- Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. The jitter of the backoff is random on every platform. +- Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. `RetryPolicy` and `BulkWaitOptions` are `Clone` and `Debug`, not `Copy` nor `PartialEq`, so that they may later hold a callback. The jitter of the backoff is random on every platform. - `Shopify::paginate`, `Page`. - Bulk results read as they download, in memory that follows the line being read rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. - `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group; so is a child whose parent has no unaliased `id`, which the error names. diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 6ca259a..d773efb 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -399,7 +399,7 @@ fn user_errors(errors: &impl Serialize) -> Result> { } /// How [`Shopify::wait_for_bulk_operation`] polls. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone)] pub struct BulkWaitOptions { first_poll: Duration, poll_interval: Duration, diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs index 9554faa..8583a8d 100644 --- a/crates/shopify_api/src/client.rs +++ b/crates/shopify_api/src/client.rs @@ -178,7 +178,7 @@ fn warn_mismatch(pinned: ApiVersion, checked: &'static str) { /// [`max_retry_after`](Self::max_retry_after) (five minutes by default) is not /// waited for: the request ends in [`Error::Throttled`](crate::Error::Throttled), /// with the wait Shopify asked for in its `retry_after`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone)] pub struct RetryPolicy { max_retries: u32, base_delay: Duration, From 5434497b93a775ba09183924bf8ceaed89a90bf0 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:22:44 +0100 Subject: [PATCH 123/135] refactor(bulk)!: one verb per meaning; groupObjects only for nested connections MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit start_bulk_* only starts and returns the operation; bulk_query* and bulk_mutation start, wait and read. - start_bulk_query takes a text (&str, String), GroupObjects(text) for groupObjects, or a graphql!(bulk(…)) query or its Variables, through the sealed StartBulkQuery trait. run_bulk_query and run_bulk_query_grouped(query, bool) are gone. - run_bulk_mutation and run_bulk_mutation_iter are start_bulk_mutation_text, over any iterator (a slice by reference); run_bulk_mutation_staged is start_bulk_mutation_staged. - A typed bulk query asks for groupObjects only when its item has nested connections: Shopify documents grouping as slower and more likely to time out. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +- MIGRATION.md | 10 +- README.md | 15 +- crates/shopify_api/docs/graphql.md | 4 +- crates/shopify_api/src/bulk.rs | 220 +++++++++++++++++------- crates/shopify_api/src/bulk/typed.rs | 58 +++---- crates/shopify_api/tests/bulk.rs | 49 +++++- crates/shopify_api/tests/bulk_stream.rs | 7 +- crates/shopify_api/tests/bulk_typed.rs | 42 +++++ crates/shopify_api/tests/live.rs | 2 +- 10 files changed, 304 insertions(+), 110 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b98ff2c..831431a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,9 +24,9 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - `Shopify::paginate`, `Page`. - Bulk results read as they download, in memory that follows the line being read rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. - `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group; so is a child whose parent has no unaliased `id`, which the error names. -- `run_bulk_mutation_iter` and `stage_bulk_variables_iter` take the variables from an iterator; the JSONL is written straight into the body of the upload, in memory once. +- `start_bulk_mutation_text` and `stage_bulk_variables_iter` take the variables from an iterator (a slice by reference too); the JSONL is written straight into the body of the upload, in memory once. - Bulk operations checked at compile time: `graphql!(bulk("…"))`, `bulk(file("…"))`, inline or in a module. A bulk query is checked against Shopify's bulk rules for API 2026-10: one top-level field, a connection (not `node` or `nodes`); five connections at most, two levels deep below it; `edges { node { … } }` and nothing else (no `nodes`, `cursor`, `pageInfo`, nor `first`, `last`, `after`, `before`); `Node` objects; a nested connection written right in the `node` of its parent; an unaliased `id` on every node with nested connections (an error that asks for it, never added silently), and no other field aliased `id` there; no alias `_shopifyApiTypename` or starting with `__`; no string that the parser reads unlike GraphQL (a `\b` escape, which it reads as U+0010: write `\u0008`; a block string with a lone carriage return or indented with other whitespace than spaces and tabs); two connections of one node that may return the same type, such as two aliased `metafields`, are refused. What the guide does not show is refused. A bulk mutation is one mutation field, not a bulk operation, with one connection at most. -- The items of a bulk query are generated types: `Item`, each nested connection a `Vec` of its nodes. `Shopify::bulk_query` runs it with `groupObjects` and returns `BulkItems` (`next_item`, `collect`, `Stream`), one item in memory at a time, nested lines placed by `__parentId`, and by `__typename` where a node has several connections: the text sent selects it there as `_shopifyApiTypename: __typename`, and a `__typename` of the query is left as written. A line's `id` places its children only when it is a string: `id` may alias another field where no connection is nested. `start_bulk_query` and `download_bulk_items` split the steps; `BulkQuery::text` is the text sent. +- The items of a bulk query are generated types: `Item`, each nested connection a `Vec` of its nodes. `Shopify::bulk_query` runs it, with `groupObjects` only when it has nested connections (Shopify is slower with it), and returns `BulkItems` (`next_item`, `collect`, `Stream`), one item in memory at a time, nested lines placed by `__parentId`, and by `__typename` where a node has several connections: the text sent selects it there as `_shopifyApiTypename: __typename`, and a `__typename` of the query is left as written. A line's `id` places its children only when it is a string: `id` may alias another field where no connection is nested. `start_bulk_query` and `download_bulk_items` split the steps; `BulkQuery::text` is the text sent. - The variables of a bulk query, which Shopify does not take, are given as for any operation (literals and `input!` included) and written into its text as GraphQL literals, from the parsed operation: strings escaped as JSON, enum values bare (in input objects and lists too), input objects with unquoted keys, a variable without a value (a `None` in `Variables`) left out or given its default, an explicit `null` written `null`. The values are checked as for any operation; an enum value or a field that is not a GraphQL name fails with `InvalidValueReason::NotAGraphqlName`, an enum value `true`, `false` or `null` with `InvalidValueReason::ReservedEnumValue`. A variable that may hold `JSON` is refused at compile time. - `Shopify::bulk_mutation` runs a `graphql!(bulk("mutation …"))` over an iterator of its `Variables`: every line is checked and written before anything is sent, then staged, run, and read as `BulkMutationResult` (`data`, `errors`, `index`, Shopify's `__lineNumber`). `start_bulk_mutation` only starts it. Typed bulk operations run at the Admin API version they were checked against. - `Transport`, the HTTP layer as a trait, with `send_streaming` (a default goes through `send`), `StreamingResponse` and `BodyStream`. The default `ReqwestTransport` never follows a redirection, and streams: the timeout of a request bounds the wait for the headers and for each chunk, not the whole body. A client of your own goes through `transport::reqwest_0_13::from_builder`: reqwest appears in the API only under `transport::reqwest_0_13`, named after its major version, so that a later reqwest comes next to it. The client runs on Tokio. @@ -38,7 +38,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO ### Changed - Tokens: 0.10 renewed a token before it expired and saved it with a `TokenStore`. 1.0 also renews when Shopify refuses one with a `401`; one renewal serves every clone of a client and the requests waiting for it; it runs in a task of its own, so a cancelled request does not lose a rotated refresh token; a failed renewal answers the requests waiting for it. Until a renewed token is saved, nothing is sent: each call tries a failed save again first, and fails with `Error::TokenStore`. A refresh answer without a refresh token keeps the current one. `Auth::with_token` starts from a stored token. -- Bulk operations: 0.10 ran, read, listed and waited for them, with typed statuses. 1.0 adds `bulk_query_rows` (the whole cycle), `run_bulk_mutation` (uploads the JSONL), `cancel_bulk_operation`, and polling that starts at one second and backs off. `BulkOperation` has numbers for its counts and `DateTime` for its dates; `BulkOperationStatus` and `BulkOperationType` serialize as Shopify writes them (`"COMPLETED"`, an unknown one as its text) and round-trip. +- Bulk operations: 0.10 ran, read, listed and waited for them, with typed statuses. 1.0 adds `bulk_query_rows` (the whole cycle), `start_bulk_mutation_text` (uploads the JSONL), `cancel_bulk_operation`, and polling that starts at one second and backs off. `BulkOperation` has numbers for its counts and `DateTime` for its dates; `BulkOperationStatus` and `BulkOperationType` serialize as Shopify writes them (`"COMPLETED"`, an unknown one as its text) and round-trip. - Webhook subscriptions: 0.10 listed, added, deleted and auto-configured them. 1.0 has `webhook_subscriptions` (every page), `create_`, `update_` (in place, new) and `delete_webhook_subscription`, and `sync_webhook_subscriptions`, which updates in place, creates before it deletes, and returns what it did. `WebhookSubscription` dates are `DateTime`. Subscriptions are JSON only: `WebhookSubscriptionSpec` has no format, and `sync_webhook_subscriptions` updates an XML subscription of a desired topic and address to JSON. - Webhook verification: 0.10 checked the HMAC. `Webhook::verify` also reads the headers (topic, shop, IDs; with or without `X-`, in any case, from any `(name, value)` pairs, `&http::HeaderMap` included), accepts several secrets during a rotation, and verifies JSON webhooks only, refusing a body whose first byte is not `{` (whitespace and a byte order mark before it included): the launch queries, session tokens and app proxy requests the client secret also signs, which an app proxy query can make read as XML, or as JSON after a tab, can never pass for a webhook. `Webhook::verify_payload_shop` checks that a destructive webhook names, in its payload, the unsigned shop of its headers. `Debug` of a `Webhook` shows the length of its body, not the body. - Schema download: `schema::download_public_admin_schema` and `download_admin_schema` take an `ApiVersion`. @@ -53,6 +53,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - `graphql` returns `data` as a `Value` and `graphql_as` reads it as a type; `post_graphql` and the `graphql-client` feature are gone; the untyped calls send no `operationName`. - `GraphqlResponse` is `RawResponse`; the `shopify_api::graphql` module is private (`graphql` is the macro); `parse_jsonl` takes bytes; the staged upload and connection types are internal. - The warp wrapper, the webhook payload structs, `utils` (`retry_async`, `read_json_tree`) and `graphql_at_path` are gone, as are `run_bulk_queries`, `run_bulk_mutations` and `BulkConcurrencyOptions`, and the features `debug`, `graphql-client`, `warp-wrapper`, `hmac`, `sha2`, `warp` and `graphql_client`. +- One verb per meaning in the bulk API: `start_bulk_*` only starts, `bulk_query*` and `bulk_mutation` start, wait and read. 0.10's `run_bulk_query(query)`, which only started, is `start_bulk_query(query)`, which also takes a `graphql!(bulk(…))` query; `run_bulk_query_with_grouping(query, true)` is `start_bulk_query(GroupObjects(query))`; `run_bulk_mutation(mutation, path)` is `start_bulk_mutation_staged(mutation, path, None)`, and `start_bulk_mutation_text(mutation, &rows)` uploads the rows first. - Rust 1.88, edition 2024. ### Packaging diff --git a/MIGRATION.md b/MIGRATION.md index d50de49..d9c97ee 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -153,9 +153,9 @@ shopify.execute(graphql!( | 0.10 | 1.0 | | --- | --- | -| `run_bulk_query(query)` → `BulkOperationPayload` | `run_bulk_query(query)` → `BulkOperation`; user errors are `Error::UserErrors` | -| `run_bulk_query_with_grouping(query, group)` | `run_bulk_query_grouped(query, group)` | -| `run_bulk_mutation(mutation, staged_upload_path)` | `run_bulk_mutation_staged(mutation, path, None)`, or `run_bulk_mutation(mutation, &rows)`, which uploads the rows | +| `run_bulk_query(query)` → `BulkOperationPayload` | `start_bulk_query(query)` → `BulkOperation`; user errors are `Error::UserErrors` | +| `run_bulk_query_with_grouping(query, true)` | `start_bulk_query(GroupObjects(query))` (`bulk::GroupObjects`); with `false`, `start_bulk_query(query)` | +| `run_bulk_mutation(mutation, staged_upload_path)` | `start_bulk_mutation_staged(mutation, path, None)`, or `start_bulk_mutation_text(mutation, &rows)`, which uploads the rows | | `stage_upload_jsonl(&rows)` | `stage_bulk_variables(&rows)` | | `get_bulk_operation(id)` | `bulk_operation(id)` | | `list_bulk_operations(BulkOperationsFilter { .. })` | `bulk_operations(BulkOperationsFilter::new().first(10))`, a `Page` | @@ -170,6 +170,10 @@ shopify.execute(graphql!( | `ShopifyUserError` | `UserError` | | `parse_jsonl(&str)` | `bulk::parse_jsonl(&[u8])`: `parse_jsonl(text.as_bytes())` | +In 1.0, `start_bulk_*` only starts an operation and returns it, and +`bulk_query*` and `bulk_mutation` start, wait and read: 0.10's `run_bulk_*` +only started. `start_bulk_query` takes a text or a typed query. + New in 1.0: a query or a mutation declared with `graphql!(bulk("…"))` is checked when the crate compiles, and `bulk_query` and `bulk_mutation` read its results as generated types, in place of a hand-written struct and diff --git a/README.md b/README.md index 22b3508..fa59816 100644 --- a/README.md +++ b/README.md @@ -353,15 +353,20 @@ let rows: Vec = shopify .bulk_query_rows("{ products { edges { node { id title } } } }", BulkWaitOptions::default()) .await?; -// One mutation per item, uploaded as JSONL first. -let operation = shopify.run_bulk_mutation( +// Start only: one mutation per item, uploaded as JSONL first. +let operation = shopify.start_bulk_mutation_text( "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", &inputs, ).await?; ``` -`run_bulk_query`, `wait_for_bulk_operation`, `bulk_operations`, -`cancel_bulk_operation` and `download_bulk_results` give each step on its own. +One verb per meaning: `start_bulk_*` only starts an operation and returns +it; `bulk_query*` and `bulk_mutation` start, wait and read. `start_bulk_query` +takes a text (`GroupObjects(text)` for `groupObjects`) or a +`graphql!(bulk(…))` query; `start_bulk_mutation` takes typed lines, and +`start_bulk_mutation_text` a text and its variables. With +`wait_for_bulk_operation`, `bulk_operations`, `cancel_bulk_operation` and +`download_bulk_results`, each step is on its own. ### Large exports: stream the rows @@ -404,7 +409,7 @@ while let Some(group) = products.next_group().await { `download_bulk_results_stream` and `download_bulk_results_grouped` read the results of an operation you ran yourself. For a bulk mutation over more -items than you want in memory, `run_bulk_mutation_iter` takes an iterator: +items than you want in memory, `start_bulk_mutation_text` takes an iterator: each item is serialized as it is taken. Use the `Vec` methods when the results fit in memory, the streams otherwise. diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index 3b50f24..f898f18 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -427,7 +427,9 @@ its parent. Other nested objects stay as in any operation. A connection of an interface or a union gives one struct, the fields of each fragment optional, as in any operation. -[`Shopify::bulk_query`] starts the query with `groupObjects`, waits for it, +[`Shopify::bulk_query`] starts the query, with `groupObjects` when it has +nested connections (Shopify is slower with it, and more likely to time out, +so a flat export goes without), waits for it, and returns [`BulkItems`](crate::bulk::BulkItems): `next_item().await`, one item at a time, `collect().await` into a `Vec`, or a `Stream`. One item is held at a time, with its nested objects: memory follows the largest item, diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index d773efb..872fe9e 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -65,13 +65,15 @@ use serde::{Deserialize, Serialize}; use tokio::time::Instant; use crate::transport::{HttpRequest, Method}; -use crate::{Error, Page, Result, Shopify, UserError}; +use crate::{Error, Operation, Page, Result, Shopify, UserError}; use shopify_api_macros::{__graphql_internal as graphql, __input_internal as input}; mod rows; mod typed; pub use rows::{BulkGroups, BulkRows, DEFAULT_MAX_LINE_LENGTH}; +#[doc(hidden)] +pub use typed::TypedQuery; pub use typed::{BulkItem, BulkItems, BulkMutation, BulkMutationResult, BulkQuery}; /// What the code `graphql!(bulk(…))` generates refers to. Not a public API. @@ -482,30 +484,148 @@ impl Default for BulkOperationsFilter { } } -impl Shopify { - /// Starts a bulk query. Shopify refuses a query that is not a bulk - /// query (one connection at the root, no `first`) with user errors, - /// returned as [`Error::UserErrors`]. - pub async fn run_bulk_query(&self, query: &str) -> Result { - self.run_bulk_query_grouped(query, false).await +/// What [`Shopify::start_bulk_query`] starts: the text of a bulk query +/// (`&str`, `String`), checked by nothing; the same text in [`GroupObjects`]; +/// or a query declared with `graphql!(bulk(…))`, or the `Variables` of its module. +/// +/// It is sealed: only this crate and `graphql!` implement it. `M` tells +/// the kinds apart and is inferred. +#[diagnostic::on_unimplemented( + message = "`{Self}` is not a bulk query to start", + label = "a `&str`, a `String`, `GroupObjects(…)`, or a `graphql!(bulk(…))` query or its `Variables`" +)] +pub trait StartBulkQuery: sealed::Sealed {} + +pub(crate) mod sealed { + /// The arguments of `bulkOperationRunQuery`. + #[doc(hidden)] + #[derive(Debug)] + pub struct Start { + pub(crate) query: String, + pub(crate) group_objects: bool, + /// `None` for a text checked by nothing, sent as the crate's own + /// operation; else the version a typed query was checked against. + pub(crate) checked_against: Option>, + } + + #[doc(hidden)] + pub trait Sealed { + fn __start(self) -> crate::Result; + } + + /// The kind of a text, checked by nothing. + #[doc(hidden)] + #[derive(Debug)] + pub enum Text {} +} + +/// The text of a bulk query to run with `groupObjects`: each object of a +/// nested connection is written right after its parent, which +/// [`Shopify::download_bulk_results_grouped`] needs. Shopify is slower with +/// it, and more likely to time out. +/// +/// ```no_run +/// use shopify_api::bulk::GroupObjects; +/// +/// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { +/// let operation = shopify +/// .start_bulk_query(GroupObjects( +/// "{ products { edges { node { id variants { edges { node { sku } } } } } } }", +/// )) +/// .await?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GroupObjects(pub Q); + +fn start_text(query: String, group_objects: bool) -> sealed::Start { + sealed::Start { + query, + group_objects, + checked_against: None, + } +} + +impl sealed::Sealed for &str { + fn __start(self) -> Result { + Ok(start_text(self.to_string(), false)) } +} +impl StartBulkQuery for &str {} + +impl sealed::Sealed for String { + fn __start(self) -> Result { + Ok(start_text(self, false)) + } +} +impl StartBulkQuery for String {} + +impl sealed::Sealed for &String { + fn __start(self) -> Result { + Ok(start_text(self.clone(), false)) + } +} +impl StartBulkQuery for &String {} + +impl> sealed::Sealed for GroupObjects { + fn __start(self) -> Result { + Ok(start_text(self.0.into(), true)) + } +} +impl> StartBulkQuery for GroupObjects {} - /// [`Shopify::run_bulk_query`], with nested objects written right after - /// their parent (`groupObjects`), which is slower. - pub async fn run_bulk_query_grouped( +impl Shopify { + /// Starts a bulk query, and returns the operation: wait for it with + /// [`Shopify::wait_for_bulk_operation`], then download its results. + /// + /// - A text (`&str`, `String`) is checked by nothing, and runs without + /// `groupObjects`; [`GroupObjects`]`(text)` runs it with. Read its + /// results with [`Shopify::download_bulk_results_stream`], or + /// [`Shopify::download_bulk_results_grouped`] for a grouped one. + /// Shopify refuses a text that is not a bulk query (one connection at + /// the root, no `first`) with user errors, returned as [`Error::UserErrors`]. + /// - A query declared with `graphql!(bulk(…))`, or the `Variables` of its + /// module, sends [`BulkQuery::text`] to the Admin API version it was + /// checked against, as [`Shopify::execute`] would, with `groupObjects` + /// only when it has nested connections. Read its results with + /// [`Shopify::download_bulk_items`]. + /// + /// [`Shopify::bulk_query`], [`Shopify::bulk_query_rows`] and the other + /// `bulk_query*` methods start, wait and read in one call. + /// + /// ```no_run + /// use shopify_api::bulk::BulkWaitOptions; + /// + /// shopify_api::graphql! { + /// mod all_products = bulk("{ products { edges { node { id title } } } }"); + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let typed = shopify.start_bulk_query(all_products::operation()).await?; + /// let untyped = shopify.start_bulk_query("{ products { edges { node { id } } } }").await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn start_bulk_query( &self, - query: &str, - group_objects: bool, + query: impl StartBulkQuery, ) -> Result { - let data = self - .execute_own(run_query::Variables { - query: query.to_string(), - group_objects, - }) - .await?; + let start = query.__start()?; + let variables = run_query::Variables { + query: start.query, + group_objects: start.group_objects, + }; + let data = match start.checked_against { + None => self.execute_own(variables).await?, + Some(version) => { + self.execute(Operation::from(variables).checked_as(version)) + .await? + } + }; let payload = data .bulk_operation_run_query - .ok_or_else(|| bulk_error("bulkOperationRunQuery returned nothing".to_string()))?; + .ok_or_else(|| bulk_error("bulkOperationRunQuery returned nothing"))?; started( "bulkOperationRunQuery", payload.bulk_operation, @@ -513,58 +633,36 @@ impl Shopify { ) } - /// Starts a bulk mutation over `variables`: one run of `mutation` per - /// item, which holds the variables of that run. The items are uploaded - /// as a JSONL file first. + /// Starts a bulk mutation over `variables`, checked by nothing: one run + /// of `mutation` per item, which holds the variables of that run. The + /// items are uploaded as a JSONL file first, each serialized as it is + /// taken: they need not all be in memory, only the file, which Shopify + /// caps at 100 MB. A slice or a `Vec` is given by reference. /// /// The upload target is reserved first: an item that does not /// serialize fails after it, and the target goes unused. /// + /// The typed counterpart is [`Shopify::start_bulk_mutation`], whose + /// lines hold their mutation. + /// /// ```no_run /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let mutation = "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }"; /// let rows = vec![ /// serde_json::json!({ "product": { "id": "gid://shopify/Product/1", "title": "New title" } }), /// serde_json::json!({ "product": { "id": "gid://shopify/Product/2", "title": "Other title" } }), /// ]; - /// let operation = shopify - /// .run_bulk_mutation( - /// "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", - /// &rows, - /// ) - /// .await?; - /// # Ok(()) - /// # } - /// ``` - pub async fn run_bulk_mutation( - &self, - mutation: &str, - variables: &[T], - ) -> Result { - self.run_bulk_mutation_iter(mutation, variables).await - } - - /// [`Shopify::run_bulk_mutation`] over the items of an iterator, each - /// serialized as it is taken: the items need not all be in memory, only - /// the JSONL file, which Shopify caps at 100 MB. - /// - /// The upload target is reserved first: an item that does not - /// serialize fails after it, and the target goes unused. + /// let operation = shopify.start_bulk_mutation_text(mutation, &rows).await?; /// - /// ```no_run - /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// // Or from an iterator, without the items in memory. /// let rows = (1..=50_000).map(|id| { /// serde_json::json!({ "product": { "id": format!("gid://shopify/Product/{id}"), "status": "ARCHIVED" } }) /// }); - /// let operation = shopify - /// .run_bulk_mutation_iter( - /// "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", - /// rows, - /// ) - /// .await?; + /// let operation = shopify.start_bulk_mutation_text(mutation, rows).await?; /// # Ok(()) /// # } /// ``` - pub async fn run_bulk_mutation_iter( + pub async fn start_bulk_mutation_text( &self, mutation: &str, variables: I, @@ -574,13 +672,13 @@ impl Shopify { I::Item: Serialize, { let path = self.stage_bulk_variables_iter(variables).await?; - self.run_bulk_mutation_staged(mutation, &path, None).await + self.start_bulk_mutation_staged(mutation, &path, None).await } - /// Starts a bulk mutation over a JSONL file already uploaded with - /// [`Shopify::stage_bulk_variables`]. `client_identifier` is yours, kept - /// with the operation. - pub async fn run_bulk_mutation_staged( + /// Starts a bulk mutation, checked by nothing, over a JSONL file already + /// uploaded with [`Shopify::stage_bulk_variables`]. `client_identifier` + /// is yours, kept with the operation. + pub async fn start_bulk_mutation_staged( &self, mutation: &str, staged_upload_path: &str, @@ -843,7 +941,7 @@ impl Shopify { query: &str, options: BulkWaitOptions, ) -> Result> { - let operation = self.run_bulk_query(query).await?; + let operation = self.start_bulk_query(query).await?; match self.completed_url(&operation.id, options).await? { Some(url) => self.download_bulk_results_stream(&url).await, None => Ok(BulkRows::new(None, "")), @@ -895,7 +993,7 @@ impl Shopify { query: &str, options: BulkWaitOptions, ) -> Result> { - let operation = self.run_bulk_query_grouped(query, true).await?; + let operation = self.start_bulk_query(GroupObjects(query)).await?; match self.completed_url(&operation.id, options).await? { Some(url) => Ok(self.download_bulk_results_grouped(&url).await?.grouped()), None => Ok(BulkGroups::new(None, "").grouped()), diff --git a/crates/shopify_api/src/bulk/typed.rs b/crates/shopify_api/src/bulk/typed.rs index e1c623d..67b6d59 100644 --- a/crates/shopify_api/src/bulk/typed.rs +++ b/crates/shopify_api/src/bulk/typed.rs @@ -8,7 +8,8 @@ use serde::de::DeserializeOwned; use serde_json::value::RawValue; use super::{ - BulkOperation, BulkRows, BulkWaitOptions, bulk_error, run_mutation, run_query, started, + BulkOperation, BulkRows, BulkWaitOptions, StartBulkQuery, bulk_error, run_mutation, sealed, + started, }; use crate::error::is_graphql_name; use crate::graphql::check::Invalid; @@ -118,6 +119,27 @@ pub fn unplaced() -> Error { bulk_error("a nested line of the results has no place in the item") } +/// The kind of a query declared with `graphql!(bulk(…))`, of item `I`, for +/// [`Shopify::start_bulk_query`]. Not a public API. +#[doc(hidden)] +#[derive(Debug)] +pub struct TypedQuery(std::marker::PhantomData); + +impl>> sealed::Sealed> for Q { + fn __start(self) -> Result { + let query = self.into(); + Ok(sealed::Start { + query: query.text()?, + // Grouping makes Shopify slower and more likely to time out: only + // when there are children to place. + group_objects: !I::CONNECTIONS.is_empty(), + checked_against: Some(query.checked_against()), + }) + } +} + +impl>> StartBulkQuery> for Q {} + /// A bulk query checked by `graphql!(bulk("…"))`, and its variables. Its /// results are read as `I`, one top-level object at a time. /// @@ -616,8 +638,9 @@ impl Shopify { /// of its nested connections in their lists, as they download (see /// [`BulkItems`]). Fails when the operation does not complete. /// - /// It runs with `groupObjects`, which [`BulkItems`] needs: Shopify is - /// slower with it, and more likely to time out. + /// It runs with `groupObjects` when the query has nested connections, + /// which [`BulkItems`] needs to place them: Shopify is slower with it, + /// and more likely to time out, so a flat export runs without. /// /// ```no_run /// use shopify_api::bulk::BulkWaitOptions; @@ -657,35 +680,6 @@ impl Shopify { } } - /// Starts a bulk query declared with `graphql!(bulk(…))`, with - /// `groupObjects`, and returns the operation: wait for it with - /// [`Shopify::wait_for_bulk_operation`], then read its results with - /// [`Shopify::download_bulk_items`]. - /// - /// It sends [`BulkQuery::text`] to the Admin API version the query was - /// checked against, as [`Shopify::execute`] would. - pub async fn start_bulk_query( - &self, - query: impl Into>, - ) -> Result { - let query = query.into(); - let text = query.text()?; - let operation = Operation::from(run_query::Variables { - query: text, - group_objects: true, - }) - .checked_as(query.checked_against()); - let data = self.execute(operation).await?; - let payload = data - .bulk_operation_run_query - .ok_or_else(|| bulk_error("bulkOperationRunQuery returned nothing"))?; - started( - "bulkOperationRunQuery", - payload.bulk_operation, - &payload.user_errors, - ) - } - /// Downloads the results of a bulk query started with /// [`Shopify::start_bulk_query`], its `url` or its `partial_data_url`, /// and reads them as [`Shopify::bulk_query`] does. The item type names diff --git a/crates/shopify_api/tests/bulk.rs b/crates/shopify_api/tests/bulk.rs index 00415f5..906e904 100644 --- a/crates/shopify_api/tests/bulk.rs +++ b/crates/shopify_api/tests/bulk.rs @@ -98,6 +98,48 @@ async fn a_bulk_query_runs_to_its_end_and_its_rows_are_read() { assert_eq!(sent.len(), 4, "a start and three polls"); } +#[tokio::test] +async fn a_text_bulk_query_groups_objects_only_when_asked() { + use shopify_api::bulk::GroupObjects; + + let mock = MockTransport::new(); + for _ in 0..5 { + mock.push_data(json!({ "bulkOperationRunQuery": { + "bulkOperation": operation("CREATED", None), + "userErrors": [], + } })); + } + let shopify = client(&mock); + let query = "{ products { edges { node { id variants { edges { node { sku } } } } } } }"; + + let started = shopify.start_bulk_query(query).await.unwrap(); + assert_eq!(started.status, BulkOperationStatus::Created); + shopify.start_bulk_query(query.to_string()).await.unwrap(); + shopify.start_bulk_query(&query.to_string()).await.unwrap(); + shopify.start_bulk_query(GroupObjects(query)).await.unwrap(); + shopify + .start_bulk_query(GroupObjects(query.to_string())) + .await + .unwrap(); + + let sent: Vec = mock + .graphql_requests() + .iter() + .map(|request| request.variables.clone()) + .collect(); + let expected = |grouped: bool| json!({ "query": query, "groupObjects": grouped }); + assert_eq!( + sent, + [ + expected(false), + expected(false), + expected(false), + expected(true), + expected(true) + ] + ); +} + #[tokio::test] async fn a_refused_bulk_query_returns_the_user_errors() { let mock = MockTransport::new(); @@ -108,7 +150,7 @@ async fn a_refused_bulk_query_returns_the_user_errors() { let shopify = client(&mock); let error = shopify - .run_bulk_query("{ products(first: 1) { nodes { id } } }") + .start_bulk_query("{ products(first: 1) { nodes { id } } }") .await .unwrap_err(); assert_eq!( @@ -190,7 +232,10 @@ async fn a_bulk_mutation_uploads_its_variables_then_runs() { json!({ "product": { "id": "gid://shopify/Product/2", "title": "B" } }), ]; let mutation = "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }"; - let started = shopify.run_bulk_mutation(mutation, &rows).await.unwrap(); + let started = shopify + .start_bulk_mutation_text(mutation, &rows) + .await + .unwrap(); assert_eq!(started.kind, shopify_api::bulk::BulkOperationType::Mutation); assert_eq!(started.status, BulkOperationStatus::Created); diff --git a/crates/shopify_api/tests/bulk_stream.rs b/crates/shopify_api/tests/bulk_stream.rs index a336bb2..49df47a 100644 --- a/crates/shopify_api/tests/bulk_stream.rs +++ b/crates/shopify_api/tests/bulk_stream.rs @@ -320,7 +320,7 @@ async fn bulk_variables_upload_from_an_iterator_as_from_a_slice() { } }); let started = shopify - .run_bulk_mutation_iter(mutation, rows) + .start_bulk_mutation_text(mutation, rows) .await .unwrap(); assert_eq!(started.kind, shopify_api::bulk::BulkOperationType::Mutation); @@ -331,7 +331,10 @@ async fn bulk_variables_upload_from_an_iterator_as_from_a_slice() { product: json!({ "id": format!("gid://shopify/Product/{id}"), "title": "é\n\"" }), }) .collect(); - shopify.run_bulk_mutation(mutation, &slice).await.unwrap(); + shopify + .start_bulk_mutation_text(mutation, &slice) + .await + .unwrap(); let uploads = uploads.lock().unwrap(); assert_eq!(uploads.len(), 2); diff --git a/crates/shopify_api/tests/bulk_typed.rs b/crates/shopify_api/tests/bulk_typed.rs index 0332106..3c84286 100644 --- a/crates/shopify_api/tests/bulk_typed.rs +++ b/crates/shopify_api/tests/bulk_typed.rs @@ -195,6 +195,8 @@ async fn the_variables_of_a_bulk_query_are_written_into_its_text() { text, r#"{ products(query: "title:\"Café \\ $filter\"\nvendor:x", sortKey: TITLE, reverse: true) { edges { node { id } } } }"# ); + // No nested connection: no `groupObjects`, which slows Shopify down. + assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], false); // An enum value bare; a variable without a value or a default left out. let query = by_title::operation(by_title::Variables { @@ -357,6 +359,46 @@ async fn the_items_of_an_operation_started_by_hand_are_read_from_its_url() { assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], true); } +#[tokio::test] +async fn a_typed_bulk_query_groups_objects_only_with_nested_connections() { + let mock = MockTransport::new(); + for _ in 0..3 { + mock.push_data(json!({ "bulkOperationRunQuery": { + "bulkOperation": operation("QUERY", "CREATED", None), + "userErrors": [], + } })); + } + let shopify = client(&mock); + + // Flat, given as the `Variables` of its module, or as its operation. + shopify + .start_bulk_query(by_title::Variables { + filter: None, + sort: None, + }) + .await + .unwrap(); + shopify + .start_bulk_query(by_title::operation(by_title::Variables { + filter: None, + sort: None, + })) + .await + .unwrap(); + // Nested connections, two levels deep. + shopify + .start_bulk_query(catalog::operation()) + .await + .unwrap(); + + let grouped: Vec = mock + .graphql_requests() + .iter() + .map(|request| request.variables["groupObjects"].clone()) + .collect(); + assert_eq!(grouped, [json!(false), json!(false), json!(true)]); +} + #[tokio::test] async fn a_bulk_mutation_stages_its_lines_and_reads_typed_results() { let (mock, uploads) = shopify_with( diff --git a/crates/shopify_api/tests/live.rs b/crates/shopify_api/tests/live.rs index 2d7c61d..b8243dc 100644 --- a/crates/shopify_api/tests/live.rs +++ b/crates/shopify_api/tests/live.rs @@ -61,7 +61,7 @@ async fn downloads_the_schema_through_the_shop() { async fn runs_a_bulk_query_to_its_end() { let shopify = live(); let operation = shopify - .run_bulk_query("{ products { edges { node { id title } } } }") + .start_bulk_query("{ products { edges { node { id title } } } }") .await .unwrap(); let listed = shopify From a8b93e991dbbaf8a566c6c0140e825d34117c9e3 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:24:12 +0100 Subject: [PATCH 124/135] test(live): a typed bulk query regroups two levels and sibling connections An ignored test, run by mise run test:live, for products { variants { metafields } media { ... on MediaImage } }: its items are compared with the raw JSONL regrouped by __parentId. It checks that Shopify keeps the _shopifyApiTypename alias and the groupObjects order at the second level. It creates a fixture product, tagged shopify-api-live-test, when the store has none of that shape. Co-Authored-By: Claude Opus 5.5 --- README.md | 16 ++- crates/shopify_api/docs/graphql.md | 6 +- crates/shopify_api/tests/live.rs | 203 ++++++++++++++++++++++++++++- 3 files changed, 222 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index fa59816..017c9b4 100644 --- a/README.md +++ b/README.md @@ -534,7 +534,21 @@ mise tasks # every task ``` The tests never reach Shopify: they script it with `MockTransport`. -`mise run test:live` runs a few against a real development store. +`mise run test:live` runs a few against a real development store: + +```bash +SHOPIFY_TEST_SHOP=my-dev-store SHOPIFY_TEST_ACCESS_TOKEN=shpat_… mise run test:live +# or SHOPIFY_TEST_CLIENT_ID and SHOPIFY_TEST_CLIENT_SECRET instead of the token +``` + +The token needs `read_products` and `write_products`. One of them runs a +typed bulk query, `products { variants { metafields } media }`, and compares +its items with the raw JSONL regrouped by `__parentId`: it confirms what +Shopify's guide does not show and the typed reader relies on, that the +`_shopifyApiTypename` alias is kept in the file and that `groupObjects` +writes each object right after its parent at the second level too. When +the store has no product with an image and a variant metafield, it creates +one, tagged `shopify-api-live-test`, and reuses it later. ## License diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index f898f18..b2884bf 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -523,7 +523,11 @@ mutation, its `errors`, and the `index` of its line. send any text. - The order of the lines: the reader relies on the order `groupObjects` writes, each child after its parent and before the next top-level object. - A file of another order is an error, not a misplaced child. + A file of another order is an error, not a misplaced child. Shopify's + guide shows it for one level; a live test of the repository + (`a_typed_bulk_query_regroups_two_levels_and_sibling_connections`, run by + `mise run test:live`) checks two levels, sibling connections, and that the + `_shopifyApiTypename` alias is kept in the file. # Schema and API version diff --git a/crates/shopify_api/tests/live.rs b/crates/shopify_api/tests/live.rs index b8243dc..fe539bd 100644 --- a/crates/shopify_api/tests/live.rs +++ b/crates/shopify_api/tests/live.rs @@ -1,13 +1,47 @@ //! Against a real development store. Ignored by default: `mise run test:live` //! runs them, with `SHOPIFY_TEST_SHOP` and either `SHOPIFY_TEST_ACCESS_TOKEN` -//! or `SHOPIFY_TEST_CLIENT_ID` and `SHOPIFY_TEST_CLIENT_SECRET`. +//! or `SHOPIFY_TEST_CLIENT_ID` and `SHOPIFY_TEST_CLIENT_SECRET`. The token +//! needs `read_products` and `write_products`: the typed bulk test creates a +//! product tagged `shopify-api-live-test` when the store has none of the +//! shape it reads, and reuses it on later runs. #![cfg(feature = "rustls")] +use std::collections::HashMap; use std::time::Duration; +use serde_json::Value; use shopify_api::bulk::{BulkOperationStatus, BulkOperationsFilter, BulkWaitOptions}; use shopify_api::{Auth, Shopify, graphql}; +graphql! { + /// Two levels of nested connections, two sibling connections under a + /// product, and the nodes of an interface (`Media`). + mod live_catalog = bulk("{ + products { edges { node { + id title + variants { edges { node { + id sku + metafields { edges { node { id namespace key value } } } + } } } + media { edges { node { id mediaContentType ... on MediaImage { alt } } } } + } } } + }"); + + mod seed_fixture = "mutation SeedLiveFixture($input: ProductSetInput!) { + productSet(input: $input, synchronous: true) { + product { id } + userErrors { field message } + } + }"; +} + +/// The tag of the product the typed bulk test creates. +const FIXTURE_TAG: &str = "shopify-api-live-test"; + +/// A small image, stable for years, that Shopify can fetch. +const FIXTURE_IMAGE: &str = + "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"; + fn live() -> Shopify { let env = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); let shop = env("SHOPIFY_TEST_SHOP").expect("SHOPIFY_TEST_SHOP"); @@ -83,3 +117,170 @@ async fn runs_a_bulk_query_to_its_end() { assert!(rows.iter().all(|row| row.get("id").is_some())); } } + +/// Starts `live_catalog`, waits for it, and reads its results twice: as +/// `BulkItems` and as raw JSONL lines. +async fn run_live_catalog(shopify: &Shopify) -> (Vec, Vec) { + let started = shopify + .start_bulk_query(live_catalog::operation()) + .await + .unwrap(); + let operation = shopify + .wait_for_bulk_operation( + &started.id, + BulkWaitOptions::new().timeout(Duration::from_secs(600)), + ) + .await + .unwrap(); + assert_eq!( + operation.status, + BulkOperationStatus::Completed, + "{operation:?}" + ); + let Some(url) = operation.url else { + return (Vec::new(), Vec::new()); + }; + let items = shopify + .download_bulk_items(&url) + .await + .unwrap() + .collect() + .await + .expect("the typed reader places every line: Shopify kept the alias and the order"); + let lines = shopify.download_bulk_results(&url).await.unwrap(); + (items, lines) +} + +fn has_the_shape(items: &[live_catalog::Item]) -> bool { + items.iter().any(|product| { + !product.media.is_empty() + && product + .variants + .iter() + .any(|variant| !variant.metafields.is_empty()) + }) +} + +async fn seed_fixture(shopify: &Shopify) { + let metafield = |value: &str| { + shopify_api::input!(MetafieldInput { + namespace: "shopify_api_test", + key: "note", + type: "single_line_text_field", + value: value, + }) + }; + let small = metafield("small"); + let medium = metafield("medium"); + let data = shopify + .execute(seed_fixture::Variables { + input: shopify_api::input!(ProductSetInput { + title: "shopify_api live test", + tags: [FIXTURE_TAG], + productOptions: [{ name: "Size", values: [{ name: "S" }, { name: "M" }] }], + variants: [ + { + optionValues: [{ optionName: "Size", name: "S" }], + price: "1.00", + metafields: [small], + }, + { + optionValues: [{ optionName: "Size", name: "M" }], + price: "1.00", + metafields: [medium], + }, + ], + files: [{ originalSource: FIXTURE_IMAGE, contentType: IMAGE, alt: "fixture" }], + }), + }) + .await + .unwrap(); + let payload = data.product_set.expect("productSet answered"); + assert!(payload.user_errors.is_empty(), "{:?}", payload.user_errors); +} + +/// What the typed reader relies on and Shopify's guide does not show: the +/// `_shopifyApiTypename: __typename` alias is kept in the JSONL, and the +/// order of `groupObjects` (each object right after its parent) holds at the +/// second level too. The items are compared with a regrouping of the raw +/// lines by `__parentId` alone. +#[tokio::test] +#[ignore = "calls a real store: mise run test:live"] +async fn a_typed_bulk_query_regroups_two_levels_and_sibling_connections() { + let shopify = live(); + let (mut items, mut lines) = run_live_catalog(&shopify).await; + if !has_the_shape(&items) { + seed_fixture(&shopify).await; + // The image is fetched in the background: wait until it is listed. + for _ in 0..20 { + (items, lines) = run_live_catalog(&shopify).await; + if has_the_shape(&items) { + break; + } + tokio::time::sleep(Duration::from_secs(15)).await; + } + } + assert!( + has_the_shape(&items), + "no product with an image and a variant metafield, even after creating one tagged `{FIXTURE_TAG}`" + ); + + // The raw lines, regrouped by `__parentId` alone. + let id = |line: &Value| line["id"].as_str().unwrap().to_string(); + let mut products = Vec::new(); + let mut kind_of = HashMap::new(); + let mut children: HashMap)>> = HashMap::new(); + for line in &lines { + match line.get("__parentId").and_then(Value::as_str) { + None => { + kind_of.insert(id(line), "Product"); + products.push(id(line)); + } + Some(parent) => { + let typename = line + .get("_shopifyApiTypename") + .and_then(Value::as_str) + .map(str::to_string); + if kind_of.get(parent) == Some(&"Product") { + // Two connections under a product: the alias tells them apart. + assert!(typename.is_some(), "no `_shopifyApiTypename`: {line}"); + if typename.as_deref() == Some("ProductVariant") { + kind_of.insert(id(line), "ProductVariant"); + } + } else { + // Alone under its variant: not aliased. + assert_eq!(kind_of.get(parent), Some(&"ProductVariant"), "{line}"); + assert!(typename.is_none(), "{line}"); + } + children + .entry(parent.to_string()) + .or_default() + .push((id(line), typename)); + } + } + } + + let ids = |list: &[(String, Option)], variants: bool| -> Vec { + list.iter() + .filter(|(_, typename)| (typename.as_deref() == Some("ProductVariant")) == variants) + .map(|(id, _)| id.clone()) + .collect() + }; + let none = Vec::new(); + assert_eq!( + items.iter().map(|item| item.id.clone()).collect::>(), + products + ); + for product in &items { + let below = children.get(&product.id).unwrap_or(&none); + let variants: Vec = product.variants.iter().map(|v| v.id.clone()).collect(); + assert_eq!(variants, ids(below, true), "{}", product.id); + let media: Vec = product.media.iter().map(|m| m.id.clone()).collect(); + assert_eq!(media, ids(below, false), "{}", product.id); + for variant in &product.variants { + let below = children.get(&variant.id).unwrap_or(&none); + let metafields: Vec = variant.metafields.iter().map(|m| m.id.clone()).collect(); + assert_eq!(metafields, ids(below, false), "{}", variant.id); + } + } +} From b061d8e1b700b28a90260bba9779a4319adde737 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:24:35 +0100 Subject: [PATCH 125/135] feat(bulk): BulkRows::collect is public, as BulkItems::collect Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/shopify_api/src/bulk/rows.rs | 5 +++-- crates/shopify_api/tests/bulk_stream.rs | 10 ++++++++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 831431a..e4b6bf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - `shopify-api check` checks `.graphql` files against the schema. - Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. `RetryPolicy` and `BulkWaitOptions` are `Clone` and `Debug`, not `Copy` nor `PartialEq`, so that they may later hold a callback. The jitter of the backoff is random on every platform. - `Shopify::paginate`, `Page`. -- Bulk results read as they download, in memory that follows the line being read rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. +- Bulk results read as they download, in memory that follows the line being read rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row` and `collect`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. - `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group; so is a child whose parent has no unaliased `id`, which the error names. - `start_bulk_mutation_text` and `stage_bulk_variables_iter` take the variables from an iterator (a slice by reference too); the JSONL is written straight into the body of the upload, in memory once. - Bulk operations checked at compile time: `graphql!(bulk("…"))`, `bulk(file("…"))`, inline or in a module. A bulk query is checked against Shopify's bulk rules for API 2026-10: one top-level field, a connection (not `node` or `nodes`); five connections at most, two levels deep below it; `edges { node { … } }` and nothing else (no `nodes`, `cursor`, `pageInfo`, nor `first`, `last`, `after`, `before`); `Node` objects; a nested connection written right in the `node` of its parent; an unaliased `id` on every node with nested connections (an error that asks for it, never added silently), and no other field aliased `id` there; no alias `_shopifyApiTypename` or starting with `__`; no string that the parser reads unlike GraphQL (a `\b` escape, which it reads as U+0010: write `\u0008`; a block string with a lone carriage return or indented with other whitespace than spaces and tabs); two connections of one node that may return the same type, such as two aliased `metafields`, are refused. What the guide does not show is refused. A bulk mutation is one mutation field, not a bulk operation, with one connection at most. diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs index 52d653e..641022e 100644 --- a/crates/shopify_api/src/bulk/rows.rs +++ b/crates/shopify_api/src/bulk/rows.rs @@ -251,8 +251,9 @@ impl BulkRows { std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context)).await } - /// Every row, up to the first error. - pub(crate) async fn collect(mut self) -> Result> { + /// Every row, in a `Vec`, up to the first error: a line that does not + /// decode ends it here, where [`next_row`](Self::next_row) would go on. + pub async fn collect(mut self) -> Result> { let mut rows = Vec::new(); while let Some(row) = self.next_row().await { rows.push(row?); diff --git a/crates/shopify_api/tests/bulk_stream.rs b/crates/shopify_api/tests/bulk_stream.rs index 49df47a..cfd68bf 100644 --- a/crates/shopify_api/tests/bulk_stream.rs +++ b/crates/shopify_api/tests/bulk_stream.rs @@ -149,6 +149,16 @@ async fn a_transport_that_only_sends_streams_through_the_default() { let collected: Vec = shopify.download_bulk_results(RESULTS_URL).await.unwrap(); assert_eq!(collected, parse_jsonl::(&body).unwrap()); + + // `BulkRows::collect`, as `BulkItems::collect`. + let rows: Vec = shopify + .download_bulk_results_stream(RESULTS_URL) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(rows, collected); } struct FailsAfter(Vec>); From 82ffa39a471137f0e51d84d4b026abc58a4f52f7 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:26:42 +0100 Subject: [PATCH 126/135] fix(graphql): the internal test schema applies to this repository's packages only The published macro honoured SHOPIFY_API_INTERNAL_TEST_SCHEMA for every package, dependencies included. It now applies only when CARGO_PKG_NAME is shopify_api or shopify_api-tests, the name trybuild gives its projects; any other crate keeps its own schema. Pinned by a unit test and by a probe workspace built with the variable set. Co-Authored-By: Claude Opus 5.5 --- .cargo/config.toml | 4 +- crates/shopify_api/src/bin/shopify-api.rs | 2 +- crates/shopify_api/tests/schema_override.rs | 31 ++++++- crates/shopify_api_graphql/src/lib.rs | 6 +- crates/shopify_api_graphql/src/project.rs | 91 +++++++++++++++++---- crates/shopify_api_macros/src/lib.rs | 65 ++++++++------- 6 files changed, 148 insertions(+), 51 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index eb4d2e0..a3c9464 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,6 +1,8 @@ # Internal to this repository's tests, not part of the API: the schema # `graphql!` checks every package against, the Admin schema 2026-10, without # network access. It reaches the projects `trybuild` compiles for the -# compile-fail tests, which have no schema file of their own. +# compile-fail tests, which have no schema file of their own. The macro +# honours it only for the packages `shopify_api` and `shopify_api-tests` +# (trybuild's name for its projects), never for another crate. [env] SHOPIFY_API_INTERNAL_TEST_SCHEMA = { value = "crates/shopify_api/graphql/admin.schema.json", relative = true } diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs index bcd2340..479bad0 100644 --- a/crates/shopify_api/src/bin/shopify-api.rs +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -319,7 +319,7 @@ fn load_schema(path: Option<&Path>) -> Result<(Schema, String), String> { }; let path = match path { Some(path) => path.to_path_buf(), - None => match schema_source(package_root().as_deref(), None)? { + None => match schema_source(package_root().as_deref(), None, None)? { SchemaSource::File(path) => path, SchemaSource::Project { dir, path, pinned } => { let schema = project_schema( diff --git a/crates/shopify_api/tests/schema_override.rs b/crates/shopify_api/tests/schema_override.rs index 82840d3..4c3325b 100644 --- a/crates/shopify_api/tests/schema_override.rs +++ b/crates/shopify_api/tests/schema_override.rs @@ -98,6 +98,11 @@ impl Workspace { } fn cargo(&self, args: &[&str]) -> Output { + self.cargo_with_test_schema(args, "") + } + + /// `cargo`, with the internal test variable set to `test_schema`. + fn cargo_with_test_schema(&self, args: &[&str], test_schema: &str) -> Output { let mut command = Command::new(std::env::var_os("CARGO").unwrap_or("cargo".into())); command .args(args) @@ -109,7 +114,7 @@ impl Workspace { .env_remove("CARGO_PRIMARY_PACKAGE"); // Empty is no file: the `[env]` of this repository's cargo config, // which the probes are under, sets the variable only when it is unset. - command.env(TEST_SCHEMA_ENV, ""); + command.env(TEST_SCHEMA_ENV, test_schema); command.output().unwrap() } @@ -238,3 +243,27 @@ fn a_schema_outside_the_package_is_a_compile_error() { workspace.library_metadata("schema = \"schemas/../schemas/override.json\"\n"); assert_eq!(workspace.app_version(), "2026-07"); } + +/// The internal test variable of this repository applies to `shopify_api` +/// and its `trybuild` projects only: a user's crate, here the library, +/// keeps its own schema, even when the variable names a file, or one that +/// does not exist. +#[test] +fn the_internal_test_schema_does_not_reach_other_packages() { + let workspace = Workspace::new("internal_test_schema"); + let elsewhere = workspace.root.join("override.json"); + for test_schema in [elsewhere.to_str().unwrap(), "missing.json"] { + workspace.touch_library(); + let output = workspace.cargo_with_test_schema(&["run", "-p", "probe_app"], test_schema); + assert!( + output.status.success(), + "{test_schema}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + String::from_utf8_lossy(&output.stdout), + "2026-04", + "{test_schema}" + ); + } +} diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs index 1dcd4ff..8993aea 100644 --- a/crates/shopify_api_graphql/src/lib.rs +++ b/crates/shopify_api_graphql/src/lib.rs @@ -16,7 +16,8 @@ //! //! `SHOPIFY_API_INTERNAL_TEST_SCHEMA` (`project::TEST_SCHEMA_ENV`) is //! internal to this repository's tests, not part of the API: a schema file -//! `graphql!` then uses for every package. +//! `graphql!` then uses for `shopify_api` and the projects `trybuild` +//! compiles for it (`project::TEST_SCHEMA_PACKAGES`), and no other package. #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] @@ -42,7 +43,8 @@ pub use analyze::{ }; #[doc(hidden)] pub use project::{ - PROJECT_SCHEMA_PATH, SchemaSource, TEST_SCHEMA_ENV, latest_api_version, schema_source, + PROJECT_SCHEMA_PATH, SchemaSource, TEST_SCHEMA_ENV, TEST_SCHEMA_PACKAGES, latest_api_version, + schema_source, test_schema_applies, }; #[doc(hidden)] pub use schema::{Field, INTROSPECTION_QUERY, InputValue, Schema, SchemaError, TypeDef, TypeRef}; diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs index 619bb92..9196ea0 100644 --- a/crates/shopify_api_graphql/src/project.rs +++ b/crates/shopify_api_graphql/src/project.rs @@ -29,13 +29,23 @@ use crate::{MINIMUM_API_VERSION, is_supported_api_version}; pub const PROJECT_SCHEMA_PATH: &str = "graphql/admin.schema.json"; /// Internal to this repository's tests, not part of the API: a schema file -/// `graphql!` uses for every package, relative to the `Cargo.toml` of the -/// crate being compiled, or absolute, as it is. This repository's -/// `.cargo/config.toml` sets it, for the projects `trybuild` compiles, which -/// have no schema file. It applies to every package, with no exception, so -/// that its effect does not depend on where a package is. +/// `graphql!` uses, relative to the `Cargo.toml` of the crate being +/// compiled, or absolute, as it is. This repository's `.cargo/config.toml` +/// sets it, for the projects `trybuild` compiles, which have no schema file. +/// It applies only to the packages [`TEST_SCHEMA_PACKAGES`] names, wherever +/// they are: any other package, a dependency or a user's crate, ignores it. pub const TEST_SCHEMA_ENV: &str = "SHOPIFY_API_INTERNAL_TEST_SCHEMA"; +/// The packages [`TEST_SCHEMA_ENV`] applies to, by `CARGO_PKG_NAME`: +/// `shopify_api` (its tests and doctests) and `shopify_api-tests`, the name +/// `trybuild` gives the projects of its compile-fail tests. +pub const TEST_SCHEMA_PACKAGES: [&str; 2] = ["shopify_api", "shopify_api-tests"]; + +/// Whether [`TEST_SCHEMA_ENV`] applies to the package named `package`. +pub fn test_schema_applies(package: Option<&str>) -> bool { + package.is_some_and(|package| TEST_SCHEMA_PACKAGES.contains(&package)) +} + /// The `[package.metadata]` table `shopify_api` reads. pub const METADATA_TABLE: &str = "shopify_api"; @@ -305,14 +315,17 @@ pub enum SchemaSource { /// The schema `graphql!` uses for the crate in `manifest_dir`: /// /// 1. the file `test_schema` names, the value of [`TEST_SCHEMA_ENV`] -/// (internal to this repository's tests); +/// (internal to this repository's tests), for a `package` it applies to +/// ([`test_schema_applies`]); any other package ignores it; /// 2. else the one [`SCHEMA_KEY`] names, else [`PROJECT_SCHEMA_PATH`], with /// the version `Cargo.toml` declares. pub fn schema_source( manifest_dir: Option<&Path>, test_schema: Option<&OsStr>, + package: Option<&str>, ) -> Result { - if let Some(named) = test_schema.filter(|value| !value.is_empty()) { + let test_schema = test_schema.filter(|value| !value.is_empty() && test_schema_applies(package)); + if let Some(named) = test_schema { let path = match manifest_dir { Some(dir) => dir.join(named), None => PathBuf::from(named), @@ -1092,7 +1105,7 @@ mod tests { "[package]\nname = \"app\"\n\n[package.metadata.shopify_api]\nschema = \"schemas/admin.json\"\n", ); assert_eq!( - schema_source(Some(&project.0), None), + schema_source(Some(&project.0), None, None), Ok(SchemaSource::Project { dir: project.0.clone(), path: project.0.join("schemas/admin.json"), @@ -1110,12 +1123,12 @@ mod tests { path: project.0.join(PROJECT_SCHEMA_PATH), pinned: None, }; - assert_eq!(schema_source(Some(&project.0), None), Ok(unpinned)); - assert!(schema_source(None, None).is_err()); + assert_eq!(schema_source(Some(&project.0), None, None), Ok(unpinned)); + assert!(schema_source(None, None, None).is_err()); project.manifest(Some("2026-07")); assert_eq!( - schema_source(Some(&project.0), None), + schema_source(Some(&project.0), None, None), Ok(SchemaSource::Project { dir: project.0.clone(), path: project.0.join(PROJECT_SCHEMA_PATH), @@ -1139,33 +1152,75 @@ mod tests { path: project.0.join("schemas/admin-2026-07.json"), pinned: Some("2026-07".to_string()), }; - assert_eq!(schema_source(Some(&project.0), None), Ok(expected.clone())); + assert_eq!( + schema_source(Some(&project.0), None, None), + Ok(expected.clone()) + ); // An empty test variable is no variable. assert_eq!( - schema_source(Some(&project.0), Some(OsStr::new(""))), + schema_source(Some(&project.0), Some(OsStr::new("")), Some("shopify_api")), Ok(expected) ); } + /// The published macro honours the internal variable only for this + /// repository's own packages: a user's crate, or a dependency, keeps its + /// own schema whatever the environment holds. + #[test] + fn the_test_variable_applies_only_to_this_repository() { + let project = Project::new("foreign"); + project.manifest(Some("2026-07")); + project.write("schemas/unstable.json", "{}"); + for package in [ + None, + Some("my_app"), + Some("shopify_api_graphql"), + Some("shopify_api-tests-extra"), + Some("shopify_api_extra"), + Some("openshop"), + ] { + assert!(!test_schema_applies(package), "{package:?}"); + for named in ["schemas/unstable.json", "missing.json"] { + assert!( + matches!( + schema_source(Some(&project.0), Some(OsStr::new(named)), package), + Ok(SchemaSource::Project { .. }) + ), + "{package:?} {named}" + ); + } + } + assert!(test_schema_applies(Some("shopify_api"))); + assert!(test_schema_applies(Some("shopify_api-tests"))); + } + #[test] - fn the_test_variable_names_a_file_for_every_package() { + fn the_test_variable_names_a_file_for_the_packages_of_this_repository() { let project = Project::new("named"); project.manifest(Some("2026-07")); let other = project.write("schemas/unstable.json", "{}"); assert_eq!( - schema_source(Some(&project.0), Some(OsStr::new("schemas/unstable.json"))), + schema_source( + Some(&project.0), + Some(OsStr::new("schemas/unstable.json")), + Some("shopify_api") + ), Ok(SchemaSource::File(other.clone())) ); assert_eq!( - schema_source(None, Some(other.as_os_str())), + schema_source(None, Some(other.as_os_str()), Some("shopify_api-tests")), Ok(SchemaSource::File(other)) ); assert!(matches!( - schema_source(Some(&project.0), Some(OsStr::new(""))), + schema_source(Some(&project.0), Some(OsStr::new("")), Some("shopify_api")), Ok(SchemaSource::Project { .. }) )); assert_eq!( - schema_source(Some(&project.0), Some(OsStr::new("missing.json"))), + schema_source( + Some(&project.0), + Some(OsStr::new("missing.json")), + Some("shopify_api") + ), Err(format!( "SHOPIFY_API_INTERNAL_TEST_SCHEMA names `{}`, which is not a file", project.0.join("missing.json").display() diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index fd6883f..fa56f7b 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -21,7 +21,7 @@ use shopify_api_graphql::literal::{self, Literals, Value, VariableValue}; use shopify_api_graphql::project::{cargo_home, may_download, metadata_snippet, project_schema}; use shopify_api_graphql::{ MINIMUM_API_VERSION, Operation, OperationKind, Schema, SchemaSource, TEST_SCHEMA_ENV, Variable, - analyze, is_supported_api_version, latest_api_version, schema_source, + analyze, is_supported_api_version, latest_api_version, schema_source, test_schema_applies, }; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; @@ -279,32 +279,34 @@ impl LoadedSchema { // file is downloaded or a compile error. let dir = manifest_dir(); let test_schema = std::env::var_os(TEST_SCHEMA_ENV); - let (path, schema) = match schema_source(dir.as_deref(), test_schema.as_deref())? { - SchemaSource::File(path) => { - let schema = read_schema(&path).map_err(|error| { - format!("`{}`, named by {TEST_SCHEMA_ENV}: {error}", path.display()) - })?; - (path, schema) - } - SchemaSource::Project { dir, path, pinned } => { - let primary = std::env::var_os("CARGO_PRIMARY_PACKAGE").is_some(); - let may_download = may_download(&dir, cargo_home().as_deref(), primary); - let read = |path: &Path| { - read_schema(path).map_err(|error| format!("`{}`: {error}", path.display())) - }; - // A proc macro has no progress to show. - let schema = project_schema( - &dir, - &path, - pinned.as_deref(), - may_download, - SystemTime::now(), - read, - |_, _| {}, - )?; - (path, schema) - } - }; + let package = std::env::var("CARGO_PKG_NAME").ok(); + let (path, schema) = + match schema_source(dir.as_deref(), test_schema.as_deref(), package.as_deref())? { + SchemaSource::File(path) => { + let schema = read_schema(&path).map_err(|error| { + format!("`{}`, named by {TEST_SCHEMA_ENV}: {error}", path.display()) + })?; + (path, schema) + } + SchemaSource::Project { dir, path, pinned } => { + let primary = std::env::var_os("CARGO_PRIMARY_PACKAGE").is_some(); + let may_download = may_download(&dir, cargo_home().as_deref(), primary); + let read = |path: &Path| { + read_schema(path).map_err(|error| format!("`{}`: {error}", path.display())) + }; + // A proc macro has no progress to show. + let schema = project_schema( + &dir, + &path, + pinned.as_deref(), + may_download, + SystemTime::now(), + read, + |_, _| {}, + )?; + (path, schema) + } + }; if !is_supported_api_version(&schema.api_version) { return Err(format!( "`{}` is the schema of `{}`, a version shopify_api does not call (from {MINIMUM_API_VERSION}, or `unstable`): \ @@ -353,8 +355,15 @@ impl LoadedSchema { }) .map(|path| path.to_string_lossy().to_string()) .collect(); + // The internal test variable is tracked only where it applies. + let package = std::env::var("CARGO_PKG_NAME").ok(); + let test_schema = test_schema_applies(package.as_deref()).then(|| { + quote!( + const _: ::core::option::Option<&str> = ::core::option_env!(#TEST_SCHEMA_ENV); + ) + }); quote! { - const _: ::core::option::Option<&str> = ::core::option_env!(#TEST_SCHEMA_ENV); + #test_schema #(const _: &[u8] = ::core::include_bytes!(#files);)* } } From 7fa5393b2a48a1e42ecefe99fa757bba706d4ccd Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:29:14 +0100 Subject: [PATCH 127/135] fix(graphql): generated code reaches the runtime crate through __private only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One function names the crate path; every generated item goes through ::shopify_api::__private (Result, Operation, OperationKind, InputObject, Maybe, bulk::BulkQuery, bulk::BulkMutation). The bulk codegen used #krate::Result, which a crate re-exporting shopify_api with a Result of its own shadowed. A probe app that depends only on a facade crate (extern crate facade as shopify_api) with its own Result, Operation and bulk now compiles. A future crate = … stays additive. Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk.rs | 4 +- crates/shopify_api/src/lib.rs | 1 + crates/shopify_api/tests/facade.rs | 113 ++++++++++++++++++++++ crates/shopify_api_graphql/src/bulk.rs | 2 +- crates/shopify_api_graphql/src/codegen.rs | 4 +- crates/shopify_api_graphql/src/literal.rs | 14 ++- crates/shopify_api_macros/src/lib.rs | 32 +++--- 7 files changed, 148 insertions(+), 22 deletions(-) create mode 100644 crates/shopify_api/tests/facade.rs diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 872fe9e..0b28500 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -80,8 +80,8 @@ pub use typed::{BulkItem, BulkItems, BulkMutation, BulkMutationResult, BulkQuery #[doc(hidden)] pub mod __private { pub use super::typed::{ - BulkArgument, BulkConnection, BulkItem, BulkPart, BulkTemplate, BulkType, BulkValue, - BulkVariable, push, unplaced, + BulkArgument, BulkConnection, BulkItem, BulkMutation, BulkPart, BulkQuery, BulkTemplate, + BulkType, BulkValue, BulkVariable, push, unplaced, }; } diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index beb772c..7f27479 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -109,6 +109,7 @@ pub use shopify_api_macros::input; pub mod __private { pub use crate::bulk::__private as bulk; pub use crate::graphql::literal; + pub use crate::{InputObject, Maybe, Operation, OperationKind, Result}; pub use serde; pub use serde_json; } diff --git a/crates/shopify_api/tests/facade.rs b/crates/shopify_api/tests/facade.rs new file mode 100644 index 0000000..0bdd213 --- /dev/null +++ b/crates/shopify_api/tests/facade.rs @@ -0,0 +1,113 @@ +//! The code `graphql!` and `input!` generate reaches `shopify_api` through +//! `::shopify_api::__private` only: an app that depends on a crate +//! re-exporting it, `extern crate facade as shopify_api`, compiles, even +//! when that crate has a `Result`, an `Operation` or a `bulk` of its own. +//! +//! Builds a small workspace with cargo, offline, in `CARGO_TARGET_TMPDIR`. + +use std::path::Path; +use std::process::Command; + +#[test] +fn the_generated_code_compiles_through_a_facade_with_names_of_its_own() { + let tmp = Path::new(env!("CARGO_TARGET_TMPDIR")); + let root = tmp.join("facade"); + let _ = std::fs::remove_dir_all(&root); + let shopify_api = Path::new(env!("CARGO_MANIFEST_DIR")); + let write = |path: &str, contents: &str| { + let path = root.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, contents).unwrap(); + }; + write( + "Cargo.toml", + "[workspace]\nresolver = \"3\"\nmembers = [\"facade\", \"app\"]\n", + ); + let lock = shopify_api.join("../../Cargo.lock"); + write("Cargo.lock", &std::fs::read_to_string(lock).unwrap()); + write( + "facade/Cargo.toml", + &format!( + "[package]\nname = \"probe_facade\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ + [dependencies]\nshopify_api = {{ path = '{}', default-features = false }}\n", + shopify_api.display() + ), + ); + write( + "facade/src/lib.rs", + "pub use shopify_api::*;\n\ + // Names of its own, which shadow those of the glob.\n\ + pub type Result = std::result::Result;\n\ + pub struct Operation;\n\ + pub struct OperationKind;\n\ + pub struct InputObject;\n\ + pub struct Maybe;\n\ + pub mod bulk {}\n", + ); + write( + "app/Cargo.toml", + "[package]\nname = \"probe_facade_app\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ + [dependencies]\nprobe_facade = { path = \"../facade\" }\n\ + [package.metadata.shopify_api]\napi-version = \"2026-10\"\n", + ); + write( + "app/graphql/admin.schema.json", + &std::fs::read_to_string(shopify_api.join("graphql/admin.schema.json")).unwrap(), + ); + write( + "app/src/main.rs", + r#"extern crate probe_facade as shopify_api; + +shopify_api::graphql! { + mod products = "query($first: Int!) { products(first: $first) { nodes { id title } } }"; + mod set = "mutation($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { userErrors { message } } + }"; + mod catalog = bulk("{ products { edges { node { + id + variants { edges { node { id } } } + media { edges { node { id } } } + } } } }"); + mod tags = bulk("mutation($id: ID!, $tags: [String!]!) { + tagsAdd(id: $id, tags: $tags) { userErrors { message } } + }"); +} + +fn main() { + let note: Option = None; + let metafield = shopify_api::input!(MetafieldsSetInput { + ownerId: "gid://shopify/Product/1", + namespace: "a", + key: "b", + type: "single_line_text_field", + value: "c", + }); + let _ = set::Variables { metafields: vec![metafield] }; + let _ = shopify_api::graphql!( + "mutation($p: ProductUpdateInput!) { productUpdate(product: $p) { userErrors { message } } }", + p = { id: "gid://shopify/Product/1", descriptionHtml?: note, status: ACTIVE }, + ); + let _ = products::operation(products::Variables { first: 1 }); + let _ = catalog::operation(); + let _ = shopify_api::graphql!(bulk("{ orders { edges { node { id } } } }")); + let _ = tags::Variables { id: String::new(), tags: Vec::new() }; + print!("ok"); +} +"#, + ); + + let output = Command::new(std::env::var_os("CARGO").unwrap_or("cargo".into())) + .args(["run", "--offline", "--quiet", "-p", "probe_facade_app"]) + .arg("--manifest-path") + .arg(root.join("Cargo.toml")) + .env("CARGO_TARGET_DIR", tmp.join("facade_target")) + .env_remove("CARGO_PRIMARY_PACKAGE") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(String::from_utf8_lossy(&output.stdout), "ok"); +} diff --git a/crates/shopify_api_graphql/src/bulk.rs b/crates/shopify_api_graphql/src/bulk.rs index 1903a90..e24cf09 100644 --- a/crates/shopify_api_graphql/src/bulk.rs +++ b/crates/shopify_api_graphql/src/bulk.rs @@ -1123,7 +1123,7 @@ pub fn query_items( #slot: usize, #line: &[u8], #number: usize, - ) -> #krate::Result { + ) -> #krate::__private::Result { match (#parent, #slot) { #(#arms)* _ => ::core::result::Result::Err(#private::unplaced()), diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs index 5789fdb..7922965 100644 --- a/crates/shopify_api_graphql/src/codegen.rs +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -301,7 +301,7 @@ pub fn variables_types( constructor: &TokenStream, ) -> TokenStream { let data = Ident::new(DATA_TYPE, Span::call_site()); - let target = quote!(#krate::Operation<#data>); + let target = quote!(#krate::__private::Operation<#data>); variables_types_for( schema, operation, @@ -333,7 +333,7 @@ pub fn variables_types_for( quote! { #[doc = #doc] #[allow(dead_code, reason = "the caller may not name every input object")] - pub type #ident = #krate::InputObject<#id>; + pub type #ident = #krate::__private::InputObject<#id>; } }); diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs index 4a11998..2abd15e 100644 --- a/crates/shopify_api_graphql/src/literal.rs +++ b/crates/shopify_api_graphql/src/literal.rs @@ -293,7 +293,7 @@ impl<'a> Literals<'a> { let krate = &self.krate; let id = input_object_id(name); Ok(quote_spanned! {span=> - #krate::InputObject::<#id>::__new(#name, #json) + #krate::__private::InputObject::<#id>::__new(#name, #json) }) } @@ -541,7 +541,11 @@ impl<'a> Literals<'a> { }; let arg = quote_spanned!(value.span=> #krate::__private::literal::#convert(#tokens)); - return Ok(build.argument(None, quote!(#krate::Maybe<::std::string::String>), arg)); + return Ok(build.argument( + None, + quote!(#krate::__private::Maybe<::std::string::String>), + arg, + )); } Value::Rust(expr) => expr.clone(), Value::Ident(ident) => ident_expr(ident), @@ -601,7 +605,7 @@ impl<'a> Literals<'a> { #[diagnostic::on_unimplemented(message = #message, label = #label)] trait #bound: literal::OptionalValue<#kind> {} impl #bound for ::core::option::Option {} - impl #bound for #krate::Maybe {} + impl #bound for #krate::__private::Maybe {} }); let generic = format_ident!("V{n}"); let value = build.argument( @@ -743,8 +747,8 @@ impl<'a> Literals<'a> { Some(TypeDef::Input { .. }) => { let id = input_object_id(name); impls.push(quote! { - impl #bound for #krate::InputObject<#id> {} - impl<'a> #bound for &'a #krate::InputObject<#id> {} + impl #bound for #krate::__private::InputObject<#id> {} + impl<'a> #bound for &'a #krate::__private::InputObject<#id> {} }); } // One impl for the types of the scalar: the refusal is this diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index fa56f7b..7ff73d7 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -463,8 +463,8 @@ fn deprecation_warnings(schema: &Schema, operation: &Operation, text: &Text) -> fn kind(operation: &Operation, krate: &TokenStream) -> TokenStream { match operation.kind { - OperationKind::Query => quote!(#krate::OperationKind::Query), - OperationKind::Mutation => quote!(#krate::OperationKind::Mutation), + OperationKind::Query => quote!(#krate::__private::OperationKind::Query), + OperationKind::Mutation => quote!(#krate::__private::OperationKind::Mutation), } } @@ -496,9 +496,9 @@ impl Flavor { let data = format_ident!("{}", DATA_TYPE); let item = format_ident!("{}", ITEM_TYPE); match self { - Self::Plain => quote!(#krate::Operation<#data>), - Self::BulkQuery(_) => quote!(#krate::bulk::BulkQuery<#item>), - Self::BulkMutation => quote!(#krate::bulk::BulkMutation<#data>), + Self::Plain => quote!(#krate::__private::Operation<#data>), + Self::BulkQuery(_) => quote!(#krate::__private::bulk::BulkQuery<#item>), + Self::BulkMutation => quote!(#krate::__private::bulk::BulkMutation<#data>), } } @@ -537,14 +537,14 @@ impl Flavor { match self { Self::Plain => { let kind = kind(operation, krate); - quote!(#krate::Operation::<#data>::__checked(#query, #kind, #name, #api_version)) + quote!(#krate::__private::Operation::<#data>::__checked(#query, #kind, #name, #api_version)) } Self::BulkQuery(_) => { let template = template_ident(); - quote!(#krate::bulk::BulkQuery::<#item>::__checked(&#template, #query, #name, #api_version)) + quote!(#krate::__private::bulk::BulkQuery::<#item>::__checked(&#template, #query, #name, #api_version)) } Self::BulkMutation => { - quote!(#krate::bulk::BulkMutation::<#data>::__checked(#query, #name, #api_version)) + quote!(#krate::__private::bulk::BulkMutation::<#data>::__checked(#query, #name, #api_version)) } } } @@ -558,13 +558,21 @@ impl Flavor { } } +/// The path of the runtime crate in the generated code, its only one: every +/// item is reached through `#krate::__private`, so that a crate re-exporting +/// `shopify_api` (`extern crate it as shopify_api`, or a future `crate = …`) +/// needs nothing but that module. +fn krate() -> TokenStream { + quote!(::shopify_api) +} + /// `graphql!("…", name = value)`: the operation as a value. fn expand_expression( schema: &LoadedSchema, source: &Source, variables: &[(Ident, Value)], ) -> syn::Result { - let krate = quote!(::shopify_api); + let krate = krate(); let text = Text::read(source)?; let (operation, flavor) = Flavor::of(schema, source, &text)?; @@ -668,7 +676,7 @@ fn expand_module(schema: &LoadedSchema, module: &Module) -> syn::Result syn::Result = #operation_name; /// A query or a mutation. - pub const KIND: #krate::OperationKind = #kind; + pub const KIND: #krate::__private::OperationKind = #kind; /// The Admin API version the operation was checked against. pub const API_VERSION: &str = #api_version; @@ -753,7 +761,7 @@ fn expand_input( let Value::Object(object) = &input.object else { unreachable!("`input!` reads an object"); }; - let mut literals = Literals::new(schema.schema(), quote!(::shopify_api)); + let mut literals = Literals::new(schema.schema(), krate()); let value = literals .input_object(&input.name.to_string(), input.name.span(), object) .map_err(|error| schema.literal_error(error))?; From efc8ec0dda289fa7571a9caeee437069f08cecff Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:30:02 +0100 Subject: [PATCH 128/135] docs: XML webhooks, bulk waits and the other notes of the comparison with 0.10 MIGRATION: what to do in order when subscribed in XML, verify_hmac marked JSON only, WebhookSubscription non_exhaustive with new required fields, wait_for_bulk_operation returns Ok with status Failed while the start-wait-read calls fail with Error::Bulk, access_token() then token(), the InvalidApiVersion and Timeout rows, ApiVersion::default() moving from 2026-04 to 2026-10. CHANGELOG: the matching Breaking bullets. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ MIGRATION.md | 39 ++++++++++++++++++++++++++++------ crates/shopify_api/src/bulk.rs | 7 ++++++ 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4b6bf1..21d1c02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,8 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - `GraphqlResponse` is `RawResponse`; the `shopify_api::graphql` module is private (`graphql` is the macro); `parse_jsonl` takes bytes; the staged upload and connection types are internal. - The warp wrapper, the webhook payload structs, `utils` (`retry_async`, `read_json_tree`) and `graphql_at_path` are gone, as are `run_bulk_queries`, `run_bulk_mutations` and `BulkConcurrencyOptions`, and the features `debug`, `graphql-client`, `warp-wrapper`, `hmac`, `sha2`, `warp` and `graphql_client`. - One verb per meaning in the bulk API: `start_bulk_*` only starts, `bulk_query*` and `bulk_mutation` start, wait and read. 0.10's `run_bulk_query(query)`, which only started, is `start_bulk_query(query)`, which also takes a `graphql!(bulk(…))` query; `run_bulk_query_with_grouping(query, true)` is `start_bulk_query(GroupObjects(query))`; `run_bulk_mutation(mutation, path)` is `start_bulk_mutation_staged(mutation, path, None)`, and `start_bulk_mutation_text(mutation, &rows)` uploads the rows first. +- Webhooks verify JSON bodies only: `webhooks::verify_hmac` and `Webhook::verify` refuse an XML body, which 0.10 verified. Move XML subscriptions to JSON before deploying (`sync_webhook_subscriptions`, `update_webhook_subscription`); see MIGRATION.md. `WebhookSubscription` is `#[non_exhaustive]`, with new required fields: a JSON stored by 0.10 no longer reads back. +- `Error::InvalidApiVersion { version, minimum }` is `{ version, reason }`; `Error::Timeout(String)` is `Timeout { message, id }`. - Rust 1.88, edition 2024. ### Packaging diff --git a/MIGRATION.md b/MIGRATION.md index d9c97ee..6725919 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -42,7 +42,7 @@ let shopify = Shopify::new("my-shop", Auth::access_token(token))?; | `shopify.get_shop()`, `shop_domain()` | `shopify.shop()`, a `ShopDomain` | | `shopify.get_query_url()` | `shopify.graphql_url(version)` | | `shopify.token_url()` | Gone: the client asks for its tokens itself | -| `shopify.request_client_credentials_token(id, secret)` | `Shopify::new(shop, Auth::client_credentials(id, secret))?`, then `shopify.access_token().await?` (the token, obtained if need be) or `shopify.token().await` (the whole `TokenData`) | +| `shopify.request_client_credentials_token(id, secret)` | `Shopify::new(shop, Auth::client_credentials(id, secret))?`, then `shopify.access_token().await?` (the token, obtained if need be), then `shopify.token().await` (the whole `TokenData`, `None` until a first token is obtained) | | `shopify.refresh_token_with_credentials(id, secret, refresh)` | `Auth::expiring_token(id, secret, token)`: the client refreshes before expiry and on a `401`, and saves with its `TokenStore` | `replace_auth` swapped the token of a client in place. A client's @@ -73,7 +73,8 @@ for a backoff after a `5xx` or a network failure. To keep 0.10's behaviour: Without a pinned version, an operation of `graphql!` goes to the version its schema was checked against (the `api-version` of your `Cargo.toml`, else the one of the schema file, else the latest on the first build), and an untyped -call to 2026-10. 0.10 sent everything to 2026-04 by default: pin it with +call to 2026-10: `ApiVersion::default()` and `ApiVersion::DEFAULT` move from +2026-04 to 2026-10. 0.10 sent everything to 2026-04 by default: pin it with `.api_version(ApiVersion::V2026_04)` to keep that. ## Errors @@ -91,6 +92,8 @@ call to 2026-10. 0.10 sent everything to 2026-04 by default: pin it with | A `Float` that is NaN or infinite, an `Int` beyond 32 bits, `null` for a non-null `JSON`, sent as they were | `InvalidValue { path, reason, detail }`, before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float `` | | `Authentication(text)` | `Auth { message, detail }`: what the token endpoint wrote is `error.sensitive_detail()` | | `MissingGraphqlData` | Gone: an answer without `data` (and without `errors`) gives `Value::Null` to `graphql`; `graphql_as` and `execute` then fail with `Decode` unless the type reads `null` | +| `InvalidApiVersion { version, minimum }` | `InvalidApiVersion { version, reason }`: `reason` says why the text is not a version shopify_api calls | +| `Timeout(String)` | `Timeout { message, id }`: `id` is the bulk operation waited for, which keeps running (cancel it with `cancel_bulk_operation`) | | `InvalidHeaderValue`, `Other` | Gone | `Error` no longer converts from `reqwest::Error` or `serde_json::Error`: a @@ -180,10 +183,15 @@ its results as generated types, in place of a hand-written struct and `bulk_query_rows` or `bulk_query_grouped`. `object_count`, `root_object_count` and `file_size` are numbers, and -`created_at` and `completed_at` are `chrono::DateTime`. A failed operation -is an `Error::Bulk` whose `operation` holds it, with its `error_code` and -`partial_data_url`; a wait that ran out is an `Error::Timeout` whose `id` is -the operation's, which keeps running. +`created_at` and `completed_at` are `chrono::DateTime`. +`wait_for_bulk_operation` returns the operation once it ends, as 0.10's +`wait_for_bulk` did: `Ok` with `status = Failed` (or `Canceled`) for one that +did not complete, so keep checking `status`. The calls that start, wait and +read (`bulk_query_rows`, `bulk_query_stream`, `bulk_query_grouped`, and the +typed `bulk_query` and `bulk_mutation`) fail instead, with an `Error::Bulk` +whose `operation` holds it, with its `error_code` and `partial_data_url`. A +wait that ran out is an `Error::Timeout` whose `id` is the operation's, +which keeps running. ## Webhooks @@ -248,7 +256,8 @@ rule as `Webhook::verify`. | 0.10 | 1.0 | | --- | --- | -| `shopify.verify_hmac(data, header)` | `webhooks::verify_hmac(secret, data, header)` | +| `shopify.verify_hmac(data, header)` | `webhooks::verify_hmac(secret, data, header)`, **JSON only**: an XML body is refused | +| `WebhookSubscription { id, topic, format, uri }` | `WebhookSubscription` is `#[non_exhaustive]`, with more fields (`filter`, `include_fields`, `metafield_namespaces`, `name`, `api_version`, `created_at`, `updated_at`), some required: it cannot be built with a literal, and a JSON stored by 0.10 no longer reads back as one | | `list_webhooks()` | `webhook_subscriptions()`, every page | | `add_webhook(address, topic, format)` | `create_webhook_subscription(&WebhookSubscriptionSpec::new(topic, address))`, always JSON | | `delete_webhook(id)` | `delete_webhook_subscription(id)` | @@ -257,6 +266,22 @@ rule as `Webhook::verify`. Topics are accepted as `orders/create` or `ORDERS_CREATE`. +### If you subscribed in XML + +0.10 verified any body, and `add_webhook` and `webhook_auto_config` took a +format: XML subscriptions were supported. 1.0 refuses every XML body, at run +time: the code compiles, and each XML delivery fails verification once the +1.0 handler is deployed. In this order: + +1. Move the subscriptions to JSON before you deploy a 1.0 handler, with + 0.10 still running: `sync_webhook_subscriptions` (it updates an XML + subscription of a desired topic and address to JSON) or + `update_webhook_subscription(id, &spec)` for each one, both always JSON. + `webhook_subscriptions()` lists what is left in XML (`format`). +2. Adapt the parsing of the payloads to JSON (`webhook.payload::()`). +3. Deploy. XML deliveries that Shopify still retries, sent before the + switch, will be refused: Shopify keeps retrying them, then gives up. + ## OAuth and session tokens New in 1.0, under the `oauth` feature: `ShopifyApp`. Its diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs index 0b28500..312afbf 100644 --- a/crates/shopify_api/src/bulk.rs +++ b/crates/shopify_api/src/bulk.rs @@ -850,6 +850,13 @@ impl Shopify { } /// Polls a bulk operation until it completes, fails, is canceled or expires. + /// + /// It returns the operation as it ended: an operation that failed is + /// `Ok`, with `status` [`BulkOperationStatus::Failed`] and its + /// `error_code`, so check `status`. The calls that start, wait and read, + /// such as [`Shopify::bulk_query_rows`] or [`Shopify::bulk_query`], fail + /// with [`Error::Bulk`] instead. A wait longer than the timeout of + /// `options` is an [`Error::Timeout`]; the operation keeps running. pub async fn wait_for_bulk_operation( &self, id: &str, From 123228f838bbc7d39f139c40b76984eddc8b4cb5 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:31:04 +0100 Subject: [PATCH 129/135] test(graphql): an input object literal is built through __private Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api_graphql/tests/literal.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs index 1dfddcf..514278e 100644 --- a/crates/shopify_api_graphql/tests/literal.rs +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -121,7 +121,7 @@ fn an_object_is_sent_field_by_field_in_its_order() { let id = input_object_id("ProductUpdateInput"); assert!( code.starts_with(&format!( - ":: shopify_api :: InputObject :: < {id}u64 > :: __new (\"ProductUpdateInput\" , ({{" + ":: shopify_api :: __private :: InputObject :: < {id}u64 > :: __new (\"ProductUpdateInput\" , ({{" )), "{code}" ); From feb6d4b91efb13f5821db95b42acef028affba78 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:43:29 +0100 Subject: [PATCH 130/135] fix(oauth): an admin token verified as an extension token has no customer `ExtensionSessionToken::customer` is the GID of a logged-in customer: the `sub` of an admin token, a staff member, stays in `claims()`. And `start_bulk_query` of anything else than a bulk query says so, rather than asking for `From` (`#[diagnostic::do_not_recommend]`). Co-Authored-By: Claude Opus 5.5 --- crates/shopify_api/src/bulk/typed.rs | 3 ++ crates/shopify_api/src/oauth.rs | 20 +++++++----- .../tests/ui/bulk_start_not_a_query.rs | 8 +++++ .../tests/ui/bulk_start_not_a_query.stderr | 31 +++++++++++++++++++ ...literal_maybe_non_null_with_default.stderr | 4 +-- .../tests/ui/literal_one_of.stderr | 4 +-- .../tests/ui/literal_option_in_field.stderr | 2 +- .../tests/ui/literal_wrong_input_type.stderr | 6 ++-- .../tests/ui/literal_wrong_scalar.stderr | 10 +++--- 9 files changed, 68 insertions(+), 20 deletions(-) create mode 100644 crates/shopify_api/tests/ui/bulk_start_not_a_query.rs create mode 100644 crates/shopify_api/tests/ui/bulk_start_not_a_query.stderr diff --git a/crates/shopify_api/src/bulk/typed.rs b/crates/shopify_api/src/bulk/typed.rs index 67b6d59..482fa6e 100644 --- a/crates/shopify_api/src/bulk/typed.rs +++ b/crates/shopify_api/src/bulk/typed.rs @@ -138,6 +138,9 @@ impl>> sealed::Sealed> for Q { } } +// Not suggested in errors: `start_bulk_query(42)` gets the message of +// `StartBulkQuery` rather than one about `From`. +#[diagnostic::do_not_recommend] impl>> StartBulkQuery> for Q {} /// A bulk query checked by `graphql!(bulk("…"))`, and its variables. Its diff --git a/crates/shopify_api/src/oauth.rs b/crates/shopify_api/src/oauth.rs index c058754..d38bb38 100644 --- a/crates/shopify_api/src/oauth.rs +++ b/crates/shopify_api/src/oauth.rs @@ -297,7 +297,9 @@ impl ExtensionSessionToken { /// `sub`: the GID of the logged-in customer, such as /// `gid://shopify/Customer/1`. Shopify only sends it when a customer is - /// logged in and the app may read customers. + /// logged in and the app may read customers. `None` for an admin token, + /// whose `sub` is a staff member, not a customer: it stays in + /// [`claims`](Self::claims). pub fn customer(&self) -> Option<&str> { self.customer.as_deref() } @@ -646,7 +648,10 @@ impl ShopifyApp { check_admin_issuer(issuer, &shop)?; } Ok(ExtensionSessionToken { - customer: verified.text("sub"), + // Only a customer's GID: the `sub` of an admin token is a staff member. + customer: verified + .text("sub") + .filter(|sub| sub.starts_with("gid://shopify/Customer/")), shop, expires_at: verified.expires_at, claims: verified.claims, @@ -1150,11 +1155,12 @@ mod tests { admin_shaped["dest"] = json!("https://store-name.myshopify.com"); admin_shaped["iss"] = json!("https://store-name.myshopify.com/admin"); assert!(verify(&admin_shaped).is_ok()); - // An admin token verifies here too: it proves its shop as well. - assert_eq!( - verify(&claims(now)).unwrap().shop().as_str(), - "my-shop.myshopify.com" - ); + // An admin token verifies here too: it proves its shop as well, but + // its staff member is not a customer. + let admin = verify(&claims(now)).unwrap(); + assert_eq!(admin.shop().as_str(), "my-shop.myshopify.com"); + assert_eq!(admin.customer(), None); + assert_eq!(admin.claims()["sub"], claims(now)["sub"]); // An `iss` is compared whole here as well. let mut prefixed = extension_claims(now); diff --git a/crates/shopify_api/tests/ui/bulk_start_not_a_query.rs b/crates/shopify_api/tests/ui/bulk_start_not_a_query.rs new file mode 100644 index 0000000..c057e9c --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_start_not_a_query.rs @@ -0,0 +1,8 @@ +// Anything but a bulk query text or a typed bulk query gets the message of +// `StartBulkQuery`, not one about `From`. +use shopify_api::{Auth, Shopify}; + +fn main() { + let shopify = Shopify::new("my-shop", Auth::access_token("shpat_x")).unwrap(); + let _ = shopify.start_bulk_query(42u32); +} diff --git a/crates/shopify_api/tests/ui/bulk_start_not_a_query.stderr b/crates/shopify_api/tests/ui/bulk_start_not_a_query.stderr new file mode 100644 index 0000000..cd0305d --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_start_not_a_query.stderr @@ -0,0 +1,31 @@ +error[E0277]: `u32` is not a bulk query to start + --> tests/ui/bulk_start_not_a_query.rs:7:21 + | +7 | let _ = shopify.start_bulk_query(42u32); + | ^^^^^^^^^^^^^^^^ ----- `u32` doesn't satisfy the trait bound + | | + | a `&str`, a `String`, `GroupObjects(…)`, or a `graphql!(bulk(…))` query or its `Variables` + | + = help: the trait `StartBulkQuery>` is not implemented for `u32` +help: the following other types implement trait `StartBulkQuery` + --> src/bulk.rs + | + | impl StartBulkQuery for &str {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&str` +... + | impl StartBulkQuery for String {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `String` +... + | impl StartBulkQuery for &String {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&String` +... + | impl> StartBulkQuery for GroupObjects {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `GroupObjects` +note: required by a bound in `bulk::::start_bulk_query` + --> src/bulk.rs + | + | pub async fn start_bulk_query( + | ---------------- required by a bound in this associated function + | &self, + | query: impl StartBulkQuery, + | ^^^^^^^^^^^^^^^^^ required by this bound in `bulk::::start_bulk_query` diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr index a08c83e..816851c 100644 --- a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -7,13 +7,13 @@ error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[Inven | | an `Option`: `None` leaves the field out | required by a bound introduced by this call | - = help: the trait `__ShopifyApiNoNull4_c2391f4b` is not implemented for `Vec>` + = help: the trait `__ShopifyApiNoNull4_c2392dae` is not implemented for `Vec>` help: this trait has no implementations, consider adding one --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c2391f4b` +note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c2392dae` --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); diff --git a/crates/shopify_api/tests/ui/literal_one_of.stderr b/crates/shopify_api/tests/ui/literal_one_of.stderr index 418d349..f0c452c 100644 --- a/crates/shopify_api/tests/ui/literal_one_of.stderr +++ b/crates/shopify_api/tests/ui/literal_one_of.stderr @@ -35,7 +35,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Optio | `Option<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2391187` is not implemented for `Option<&str>` + = help: the trait `main::__ShopifyApiExpect1_c2393afa` is not implemented for `Option<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:7:13 | @@ -52,7 +52,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Maybe | `Maybe<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2391187` is not implemented for `Maybe<&str>` + = help: the trait `main::__ShopifyApiExpect1_c2393afa` is not implemented for `Maybe<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:8:13 | diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr index adc9cbc..773ec1e 100644 --- a/crates/shopify_api/tests/ui/literal_option_in_field.stderr +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -7,7 +7,7 @@ error[E0277]: `vendor` of `ProductUpdateInput` expects a `String`, not `Option` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect1_c2393afa` is not implemented for `Option` + = help: the trait `__ShopifyApiExpect1_c23935b5` is not implemented for `Option` = note: `vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null` note: required by a bound in `Checks::build` --> tests/ui/literal_option_in_field.rs:3:13 diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr index f68771b..8e14d6a 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -9,8 +9,8 @@ error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built wit 6 | | ); | |_____- required by a bound introduced by this call | - = help: the trait `__ShopifyApiExpect2_c1d69ff9` is not implemented for `InputObject<2493993284262097346>` -help: the following other types implement trait `__ShopifyApiExpect2_c1d69ff9` + = help: the trait `__ShopifyApiExpect2_c1d69a2e` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2_c1d69a2e` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -22,7 +22,7 @@ help: the following other types implement trait `__ShopifyApiExpect2_c1d69ff9` | | | | |_____`&InputObject<960560859991546817>` | `InputObject<960560859991546817>` -note: required for `Vec>` to implement `__ShopifyApiExpect1_c1d69ff9` +note: required for `Vec>` to implement `__ShopifyApiExpect1_c1d69a2e` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr index 36229e2..db69c01 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr @@ -7,7 +7,7 @@ error[E0277]: `quantity` of `DraftOrderLineItemInput` expects an `Int`, not `&st | `&'static str` doesn't satisfy the trait bound | any integer type | - = help: the trait `main::__ShopifyApiExpect1_c1d69a2e` is not implemented for `&str` + = help: the trait `main::__ShopifyApiExpect1_c1d68407` is not implemented for `&str` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 | @@ -24,7 +24,7 @@ error[E0277]: `title` of `DraftOrderLineItemInput` expects a `String`, not `u8` | `u8` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect3_c1d69a2e` is not implemented for `u8` + = help: the trait `__ShopifyApiExpect3_c1d68407` is not implemented for `u8` = note: `title?: value` takes an `Option`, `None` leaving the field out; `title: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -42,7 +42,7 @@ error[E0277]: `requiresShipping` of `DraftOrderLineItemInput` expects a `Boolean | `{integer}` doesn't satisfy the trait bound | `bool` | - = help: the trait `__ShopifyApiExpect5_c1d69a2e` is not implemented for `{integer}` + = help: the trait `__ShopifyApiExpect5_c1d68407` is not implemented for `{integer}` = note: `requiresShipping?: value` takes an `Option`, `None` leaving the field out; `requiresShipping: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -60,8 +60,8 @@ error[E0277]: `value` of `WeightInput` expects a `Float`, not `u64` | `u64` doesn't satisfy the trait bound | `f64`, `f32`, `i32` or `u32` | - = help: the trait `main::__ShopifyApiExpect1_c1d69a2e` is not implemented for `u64` - = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c1d69a2e`, but not `main::__ShopifyApiExpect1_c1d69a2e` + = help: the trait `main::__ShopifyApiExpect1_c1d68407` is not implemented for `u64` + = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c1d68407`, but not `main::__ShopifyApiExpect1_c1d68407` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:4:13 | From c8243747276d79afb5a6583b5cf5205146c56e49 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:54:49 +0100 Subject: [PATCH 131/135] release: 1.0.0-rc.1 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++++ Cargo.lock | 6 +++--- Cargo.toml | 8 ++++---- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 21d1c02..f610e77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 1.0.0-rc.1 (2026-10-26) + +The release candidate of 1.0.0: everything under 1.0.0 below. Cargo only +takes it when asked for: `shopify_api = "=1.0.0-rc.1"`. + ## 1.0.0 (Unreleased) A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATION.md). diff --git a/Cargo.lock b/Cargo.lock index ba3055a..18d09e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1431,7 +1431,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "shopify_api" -version = "1.0.0" +version = "1.0.0-rc.1" dependencies = [ "base64", "chrono", @@ -1454,7 +1454,7 @@ dependencies = [ [[package]] name = "shopify_api_graphql" -version = "1.0.0" +version = "1.0.0-rc.1" dependencies = [ "graphql-parser", "proc-macro2", @@ -1467,7 +1467,7 @@ dependencies = [ [[package]] name = "shopify_api_macros" -version = "1.0.0" +version = "1.0.0-rc.1" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index d32e0da..2b57f01 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ members = [ ] [workspace.package] -version = "1.0.0" +version = "1.0.0-rc.1" edition = "2024" rust-version = "1.88" license = "MIT" @@ -17,9 +17,9 @@ authors = ["Thomas Tastet"] [workspace.dependencies] # The three crates are released together: each one requires the exact # version of the others, since the macro emits code for that runtime. -shopify_api = { path = "crates/shopify_api", version = "=1.0.0" } -shopify_api_graphql = { path = "crates/shopify_api_graphql", version = "=1.0.0" } -shopify_api_macros = { path = "crates/shopify_api_macros", version = "=1.0.0" } +shopify_api = { path = "crates/shopify_api", version = "=1.0.0-rc.1" } +shopify_api_graphql = { path = "crates/shopify_api_graphql", version = "=1.0.0-rc.1" } +shopify_api_macros = { path = "crates/shopify_api_macros", version = "=1.0.0-rc.1" } base64 = "0.23" chrono = { version = "0.4.39", default-features = false, features = ["clock", "serde", "std"] } From a5d5b3d9e1b8e2ccb91caad15e542624e592c3e9 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:04:56 +0100 Subject: [PATCH 132/135] fix(oauth): an app proxy signature sorts the name=value strings, not the names Shopify sorts the whole `name=value` strings of an app proxy request. Sorting by name differs when one name extends another by a byte below `=` (`page`/`page2`, `filter`/`filter.v.price.gte`), so a request Shopify signed was refused. Admin queries keep sorting by name. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +++ crates/shopify_api/src/oauth.rs | 60 ++++++++++++++++++++++++++++----- 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f610e77..d0b3b6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ takes it when asked for: `shopify_api = "=1.0.0-rc.1"`. A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATION.md). +### Since 1.0.0-rc.1 + +- Fixed: `verify_app_proxy` and `sign_app_proxy` sort the `name=value` strings, as Shopify does, not the names. A request with a parameter whose name extends another one by a byte that sorts before `=` (`page` and `page2`, `filter` and `filter.v.price.gte`) was refused though Shopify signed it. + ### Added - `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`) or read from a file (`file("…graphql")`). diff --git a/crates/shopify_api/src/oauth.rs b/crates/shopify_api/src/oauth.rs index d38bb38..f90cb50 100644 --- a/crates/shopify_api/src/oauth.rs +++ b/crates/shopify_api/src/oauth.rs @@ -546,6 +546,12 @@ impl ShopifyApp { /// Verifies the `signature` of an app proxy request. Its `timestamp` /// must be within 90 seconds of now. + /// + /// The message signed is the one Shopify computes: for each parameter but + /// `signature`, the string `name=value` (decoded, the values of a repeated + /// one joined with commas), these strings sorted and joined with nothing. + /// The whole strings are sorted, not the names: `page2=x` comes before + /// `page=1`. pub fn verify_app_proxy(&self, query: &str) -> Result { self.verify_app_proxy_at(query, Utc::now()) } @@ -807,8 +813,8 @@ fn check_timestamp(params: &[(String, String)], now: DateTime) -> Result<() } /// The parameters signed: every one but the signature, the values of a -/// repeated one joined with commas, in the order of the names. -fn signed_params(params: &[(String, String)]) -> Vec<(String, String)> { +/// repeated one joined with commas, in the order they first appear. +fn grouped_params(params: &[(String, String)]) -> Vec<(String, String)> { let mut grouped: Vec<(String, String)> = Vec::new(); for (name, value) in params { if name == "hmac" || name == "signature" { @@ -822,24 +828,31 @@ fn signed_params(params: &[(String, String)]) -> Vec<(String, String)> { None => grouped.push((name.clone(), value.clone())), } } - grouped.sort_by(|left, right| left.0.cmp(&right.0)); grouped } -/// What Shopify admin signs: `name=value` pairs, form-encoded with `%20` -/// for spaces, joined with `&`. +/// What Shopify admin signs: `name=value` pairs sorted by name, +/// form-encoded with `%20` for spaces, joined with `&`. fn admin_message(params: &[(String, String)]) -> String { - serde_urlencoded::to_string(signed_params(params)) + let mut grouped = grouped_params(params); + grouped.sort_by(|left, right| left.0.cmp(&right.0)); + serde_urlencoded::to_string(grouped) .unwrap_or_default() .replace('+', "%20") } -/// What an app proxy signs: `name=value` pairs, as received, joined with nothing. +/// What an app proxy signs: the `name=value` strings, as received, sorted +/// as whole strings and joined with nothing. +/// +/// Not sorted by name: Shopify sorts the strings, so `page2=x` comes before +/// `page=1` (`2` sorts before `=`), where a sort by name puts `page` first. fn proxy_message(params: &[(String, String)]) -> String { - signed_params(params) + let mut pairs: Vec = grouped_params(params) .into_iter() .map(|(name, value)| format!("{name}={value}")) - .collect() + .collect(); + pairs.sort_unstable(); + pairs.concat() } fn signed(params: Vec<(String, String)>) -> SignedQuery { @@ -983,6 +996,35 @@ mod tests { ); } + #[test] + fn app_proxy_signs_the_sorted_name_value_strings() { + // Shopify sorts `name=value` whole: `page2=x` before `page=1` + // ('2' < '='), `filter.v.price.gte=10` before `filter=red` ('.' < '='). + // The signature below is HMAC-SHA256("hush", message), computed + // outside the crate (`openssl dgst -sha256 -hmac hush`). + let query = "page=1&page2=x&filter=red&filter.v.price.gte=10\ + &shop=a.myshopify.com&path_prefix=%2Fapps%2Fx×tamp=1700000000"; + let message = "filter.v.price.gte=10filter=redpage2=xpage=1\ + path_prefix=/apps/xshop=a.myshopify.comtimestamp=1700000000"; + let signature = "e640778c56c80f8a92904d2b740665f8dd3b3d2d0f30095aa325bf576074f0f9"; + assert_eq!(proxy_message(&parse_query(query).unwrap()), message); + assert_eq!(app().sign_app_proxy(query).unwrap(), signature); + let verified = app() + .verify_app_proxy_at(&format!("{query}&signature={signature}"), at(1_700_000_000)) + .unwrap(); + assert_eq!(verified.get("page2"), Some("x")); + + // `-` sorts before `=` as well. + assert_eq!( + proxy_message(&parse_query("filter=red&filter-x=1").unwrap()), + "filter-x=1filter=red" + ); + assert_eq!( + app().sign_app_proxy("filter=red&filter-x=1").unwrap(), + "31d2d42ad3281aaaf8ca1a9b40f2b21387aee62103e43c3b1564938817b26205" + ); + } + fn claims(now: i64) -> Value { json!({ "iss": "https://my-shop.myshopify.com/admin", From ffcc8618c14add06c4fc6b38734dfcdcb5d1dc97 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:08:18 +0100 Subject: [PATCH 133/135] feat(auth): Error::Auth carries the status and OAuth code of a refusal A caller that tells a lasting refusal (4xx with an OAuth code) from a passing one (5xx, 408, 429, no code) had to parse the message. Error::Auth now has `status`, `oauth_code` (OAuthErrorCode) and `held` (the failure of a renewal another request ran), with accessors, filled for client credentials, refresh, code exchange, token exchange and the held copies. The Display text is unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + README.md | 7 ++ crates/shopify_api/src/auth.rs | 58 ++++----- crates/shopify_api/src/error.rs | 154 +++++++++++++++++++++++- crates/shopify_api/src/lib.rs | 2 +- crates/shopify_api/tests/auth.rs | 188 +++++++++++++++++++++++++++++- crates/shopify_api/tests/oauth.rs | 68 +++++++++++ 7 files changed, 448 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d0b3b6e..7cb14e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO ### Since 1.0.0-rc.1 - Fixed: `verify_app_proxy` and `sign_app_proxy` sort the `name=value` strings, as Shopify does, not the names. A request with a parameter whose name extends another one by a byte that sorts before `=` (`page` and `page2`, `filter` and `filter.v.price.gte`) was refused though Shopify signed it. +- Added: `Error::Auth` has `status` and `oauth_code` (`OAuthErrorCode`), the HTTP status and OAuth `error` code of the token endpoint's refusal, and `held`, set when the failure is that of a renewal another request ran; `Error::token_endpoint_status`, `Error::oauth_code` and `Error::is_held_auth_failure` read them. They are filled for client credentials, refresh, code exchange and token exchange, and `None` for an Auth error that is not a refusal (an answer that does not read as a token, no refresh token). The text of the errors does not change. ### Added diff --git a/README.md b/README.md index 017c9b4..1f82bb6 100644 --- a/README.md +++ b/README.md @@ -268,6 +268,13 @@ let shopify = Shopify::builder("my-shop") Clones of a client share its token: one renewal serves them all, however many requests wait for it. +When Shopify refuses a token, `Error::Auth` says how, without a message to +parse: `error.token_endpoint_status()` (`Some(400)`), `error.oauth_code()` +(`Some(OAuthErrorCode::InvalidClient)`, `None` when the body has no code) and +`error.is_held_auth_failure()` (the failure of a renewal another request ran). +A `4xx` other than `408` and `429` with a code will not pass by itself; a +`5xx`, `408`, `429` or no code may. + ## Rate limits and retries A request Shopify throttles is sent again when the bucket holds its cost again, diff --git a/crates/shopify_api/src/auth.rs b/crates/shopify_api/src/auth.rs index f84048f..e43f0ea 100644 --- a/crates/shopify_api/src/auth.rs +++ b/crates/shopify_api/src/auth.rs @@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize}; use tokio::sync::{Mutex, OwnedMutexGuard}; use crate::transport::{BoxFuture, HttpRequest, Method, Transport}; -use crate::{Error, Result, ShopDomain}; +use crate::{Error, OAuthErrorCode, Result, ShopDomain}; /// How a [`Shopify`](crate::Shopify) client gets its access token. /// @@ -362,7 +362,7 @@ pub(crate) async fn request_token( // What the endpoint wrote is kept apart: it may echo what it was sent. let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap_or_default(); let error = body.get("error").and_then(serde_json::Value::as_str); - let code = error.map(oauth_error_code); + let code = error.map(OAuthErrorCode::parse); let description = body .get("error_description") .and_then(serde_json::Value::as_str); @@ -378,7 +378,7 @@ pub(crate) async fn request_token( ), None => format!("the token endpoint of {shop} answered {}", response.status), }; - return Err(Error::auth_with_detail(message, detail)); + return Err(Error::auth_refused(message, detail, response.status, code)); } let parsed: TokenResponse = crate::decode::from_slice(&response.body).map_err(|failure| { Error::auth_with_detail( @@ -426,7 +426,7 @@ pub(crate) struct Tokens { struct State { token: Option, /// When the last renewal failed, and why. - failure: Option<(Instant, String)>, + failure: Option<(Instant, Failure)>, /// The token was renewed, and the store has not saved it yet. unsaved: bool, } @@ -442,9 +442,32 @@ impl State { /// The last failure, if it is recent enough to be the answer. fn held_failure(&self) -> Option { - let (at, message) = self.failure.as_ref()?; - (at.elapsed() < FAILURE_HOLD) - .then(|| Error::auth(format!("{message} (asked again in a few seconds)"))) + let (at, failure) = self.failure.as_ref()?; + (at.elapsed() < FAILURE_HOLD).then(|| Error::Auth { + message: format!("{} (asked again in a few seconds)", failure.message), + detail: None, + status: failure.status, + oauth_code: failure.oauth_code, + held: true, + }) + } +} + +/// What a failed renewal hands to the requests that come while it is held. +struct Failure { + /// The `Display` of the error. + message: String, + status: Option, + oauth_code: Option, +} + +impl Failure { + fn of(error: &Error) -> Self { + Self { + message: error.to_string(), + status: error.token_endpoint_status(), + oauth_code: error.oauth_code(), + } } } @@ -567,7 +590,7 @@ impl Tokens { let token = match obtain(&kind, &state, &endpoint).await { Ok(token) => token, Err(error) => { - state.failure = Some((Instant::now(), error.to_string())); + state.failure = Some((Instant::now(), Failure::of(&error))); return Err(error); } }; @@ -603,25 +626,6 @@ fn stopped(error: tokio::task::JoinError) -> Error { }) } -/// An OAuth error code (RFC 6749, 5.2, and Shopify's) as an error shows it. -fn oauth_error_code(code: &str) -> &'static str { - const CODES: [&str; 8] = [ - "shop_not_permitted", - "invalid_request", - "invalid_client", - "invalid_grant", - "unauthorized_client", - "unsupported_grant_type", - "invalid_scope", - "invalid_subject_token", - ]; - CODES - .iter() - .find(|known| **known == code) - .copied() - .unwrap_or("an error code this crate does not know") -} - /// Asks Shopify for a new token, as `kind` does. async fn obtain(kind: &Kind, state: &State, endpoint: &Endpoint) -> Result { let transport = endpoint.transport.as_ref(); diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs index d583372..d9230e8 100644 --- a/crates/shopify_api/src/error.rs +++ b/crates/shopify_api/src/error.rs @@ -160,12 +160,42 @@ pub enum Error { }, /// A token could not be obtained or renewed. + /// + /// When the token endpoint refused the request, `status` and + /// `oauth_code` say how, so that a caller can tell a refusal that will + /// last (a `4xx` with an OAuth error code, `invalid_client`, + /// `shop_not_permitted`…) from one that passes (a `5xx`, `408`, `429`, or + /// no code) without reading the message: + /// + /// ``` + /// # use shopify_api::Error; + /// fn lasts(error: &Error) -> bool { + /// matches!( + /// (error.token_endpoint_status(), error.oauth_code()), + /// (Some(status @ 400..=499), Some(_)) if status != 408 && status != 429 + /// ) + /// } + /// ``` #[non_exhaustive] Auth { message: String, /// What the token endpoint said, or serde's message about its /// answer. See [`Error::sensitive_detail`]. detail: Option, + /// The HTTP status of the token endpoint's refusal. `None` when the + /// error is not a refusal: an answer that does not read as a token, + /// a network failure, no refresh token, a renewal that panicked. + status: Option, + /// The OAuth `error` code of the token endpoint's refusal, when its + /// body has one. `None` when the body has none (a `5xx` page, text) + /// or the error is not a refusal. + oauth_code: Option, + /// `true` when the renewal that failed was another request's: this + /// request waited for it, or came within the few seconds a failure + /// is the answer of every request instead of asking Shopify again. + /// `status` and `oauth_code` are those of that renewal; `detail` is + /// `None`. + held: bool, }, /// A mutation that this crate runs for you returned `userErrors`. @@ -344,10 +374,19 @@ impl fmt::Debug for Error { .field("reason", reason) .field("detail", detail) .finish(), - Self::Auth { message, detail } => formatter + Self::Auth { + message, + detail, + status, + oauth_code, + held, + } => formatter .debug_struct("Auth") .field("message", message) .field("detail", detail) + .field("status", status) + .field("oauth_code", oauth_code) + .field("held", held) .finish(), Self::UserErrors { mutation, errors } => formatter .debug_struct("UserErrors") @@ -481,6 +520,31 @@ impl Error { } } + /// The HTTP status of the token endpoint's refusal, for [`Error::Auth`]. + /// `None` for an [`Error::Auth`] that is not a refusal, and for any + /// other variant (the status of [`Error::Http`] is its `status` field). + pub fn token_endpoint_status(&self) -> Option { + match self { + Self::Auth { status, .. } => *status, + _ => None, + } + } + + /// The OAuth `error` code of the token endpoint's refusal, for + /// [`Error::Auth`], when its body has one. + pub fn oauth_code(&self) -> Option { + match self { + Self::Auth { oauth_code, .. } => *oauth_code, + _ => None, + } + } + + /// Whether this [`Error::Auth`] is the failure of a renewal another + /// request ran, handed to this one (see the `held` field). + pub fn is_held_auth_failure(&self) -> bool { + matches!(self, Self::Auth { held: true, .. }) + } + /// The errors Shopify returned, for [`Error::Graphql`]. pub fn graphql_errors(&self) -> &[GraphqlError] { match self { @@ -561,6 +625,9 @@ impl Error { Self::Auth { message: message.into(), detail: None, + status: None, + oauth_code: None, + held: false, } } @@ -568,8 +635,93 @@ impl Error { Self::Auth { message: message.into(), detail: Some(SensitiveDetail(detail)), + status: None, + oauth_code: None, + held: false, } } + + /// The token endpoint refused the request with `status`. + pub(crate) fn auth_refused( + message: String, + detail: String, + status: u16, + oauth_code: Option, + ) -> Self { + Self::Auth { + message, + detail: Some(SensitiveDetail(detail)), + status: Some(status), + oauth_code, + held: false, + } + } +} + +/// The OAuth `error` code of a token endpoint's refusal: those of RFC 6749 +/// (5.2) and Shopify's, in [`Error::Auth`]. +/// +/// A code this crate does not know is [`Other`](Self::Other), without its +/// text: the endpoint wrote it, and it is in [`Error::sensitive_detail`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum OAuthErrorCode { + /// `shop_not_permitted`: the app may not ask this shop for a token + /// (client credentials on a shop of another organization). + ShopNotPermitted, + /// `invalid_request` + InvalidRequest, + /// `invalid_client`: the client ID or secret is wrong. + InvalidClient, + /// `invalid_grant`: the code, refresh token or credentials do not hold. + InvalidGrant, + /// `unauthorized_client` + UnauthorizedClient, + /// `unsupported_grant_type` + UnsupportedGrantType, + /// `invalid_scope` + InvalidScope, + /// `invalid_subject_token`: the session token of a token exchange. + InvalidSubjectToken, + /// A code this crate does not know. + Other, +} + +impl OAuthErrorCode { + const KNOWN: [(&'static str, Self); 8] = [ + ("shop_not_permitted", Self::ShopNotPermitted), + ("invalid_request", Self::InvalidRequest), + ("invalid_client", Self::InvalidClient), + ("invalid_grant", Self::InvalidGrant), + ("unauthorized_client", Self::UnauthorizedClient), + ("unsupported_grant_type", Self::UnsupportedGrantType), + ("invalid_scope", Self::InvalidScope), + ("invalid_subject_token", Self::InvalidSubjectToken), + ]; + + /// The code as the endpoint writes it; `None` for [`Other`](Self::Other). + pub fn as_str(self) -> Option<&'static str> { + Self::KNOWN + .iter() + .find(|(_, code)| *code == self) + .map(|(text, _)| *text) + } + + pub(crate) fn parse(text: &str) -> Self { + Self::KNOWN + .iter() + .find(|(known, _)| *known == text) + .map_or(Self::Other, |(_, code)| *code) + } +} + +impl fmt::Display for OAuthErrorCode { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str( + self.as_str() + .unwrap_or("an error code this crate does not know"), + ) + } } /// A GraphQL name: what a variable is called in an operation. diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs index 7f27479..c45e085 100644 --- a/crates/shopify_api/src/lib.rs +++ b/crates/shopify_api/src/lib.rs @@ -85,7 +85,7 @@ pub mod webhooks; pub use auth::{AssociatedUser, Auth, TokenData, TokenStore}; pub use client::{RetryPolicy, Shopify, ShopifyBuilder, USER_AGENT}; -pub use error::{Error, GraphqlErrors, RawBody, Result, SensitiveDetail}; +pub use error::{Error, GraphqlErrors, OAuthErrorCode, RawBody, Result, SensitiveDetail}; pub use graphql::{ Cost, GraphqlError, InputObject, IntoVariable, InvalidValueReason, Location, Maybe, Operation, OperationKind, RawResponse, Response, ThrottleStatus, UserError, VariableType, diff --git a/crates/shopify_api/tests/auth.rs b/crates/shopify_api/tests/auth.rs index 5bff0df..2943089 100644 --- a/crates/shopify_api/tests/auth.rs +++ b/crates/shopify_api/tests/auth.rs @@ -7,7 +7,9 @@ use std::time::Duration; use serde_json::json; use shopify_api::testing::MockTransport; use shopify_api::transport::{BoxFuture, HttpRequest, HttpResponse}; -use shopify_api::{Auth, Error, RetryPolicy, ShopDomain, Shopify, TokenData, TokenStore}; +use shopify_api::{ + Auth, Error, OAuthErrorCode, RetryPolicy, ShopDomain, Shopify, TokenData, TokenStore, +}; const TOKEN_URL: &str = "https://test-shop.myshopify.com/admin/oauth/access_token"; @@ -258,6 +260,9 @@ async fn an_expired_refresh_token_says_what_to_do() { .contains("refresh token is missing or expired"), "{error}" ); + // Not a refusal of the token endpoint: nothing was asked. + assert_eq!(error.token_endpoint_status(), None); + assert_eq!(error.oauth_code(), None); assert!(mock.requests().is_empty()); } @@ -284,9 +289,106 @@ async fn a_refused_grant_says_what_shopify_answered_and_never_the_secret() { error.sensitive_detail(), Some("shop_not_permitted: Client credentials cannot be performed on this shop.") ); + // And how it refused, without reading the message. + assert_eq!(error.token_endpoint_status(), Some(400)); + assert_eq!(error.oauth_code(), Some(OAuthErrorCode::ShopNotPermitted)); + assert!(!error.is_held_auth_failure()); + assert!(matches!( + error, + Error::Auth { + status: Some(400), + oauth_code: Some(OAuthErrorCode::ShopNotPermitted), + held: false, + .. + } + )); assert!(!format!("{error:?}").contains("top-secret")); } +/// The client credentials grant of a client that answers `status` and `body`. +async fn grant_refused_with(status: u16, body: &str) -> Error { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(status, body.to_string())); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap_err() +} + +#[tokio::test] +async fn a_refusal_without_an_oauth_code_has_its_status_only() { + for (status, body) in [ + (503, "Service Unavailable"), + (429, "{\"errors\": \"Too many requests\"}"), + (500, ""), + ] { + let error = grant_refused_with(status, body).await; + assert_eq!( + error.to_string(), + format!( + "authentication failed: the token endpoint of test-shop.myshopify.com answered {status}" + ) + ); + assert_eq!(error.token_endpoint_status(), Some(status)); + assert_eq!(error.oauth_code(), None); + assert!(!error.is_held_auth_failure()); + } +} + +#[tokio::test] +async fn an_unknown_oauth_code_is_a_code_without_its_text() { + let error = grant_refused_with(400, r#"{"error": "shpat_LOOKS_LIKE_A_TOKEN"}"#).await; + assert_eq!( + error.to_string(), + "authentication failed: the token endpoint of test-shop.myshopify.com answered 400 \ + (an error code this crate does not know)" + ); + assert_eq!(error.token_endpoint_status(), Some(400)); + assert_eq!(error.oauth_code(), Some(OAuthErrorCode::Other)); + assert_eq!(OAuthErrorCode::Other.as_str(), None); + assert!(!format!("{error:?}").contains("LOOKS_LIKE")); +} + +#[tokio::test] +async fn a_token_answer_that_does_not_read_is_not_a_refusal() { + let mock = MockTransport::new(); + mock.push_json(json!({ "access_token": 1 })); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(error.to_string().contains("invalid token"), "{error}"); + assert_eq!(error.token_endpoint_status(), None); + assert_eq!(error.oauth_code(), None); +} + +#[tokio::test] +async fn a_refused_refresh_has_its_status_and_code() { + let mock = MockTransport::new(); + mock.push(HttpResponse::json( + 400, + &json!({ "error": "invalid_grant", "error_description": "The refresh token is revoked." }), + )); + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + let shopify = builder(&mock) + .auth(Auth::expiring_token("id", "secret", stored)) + .build() + .unwrap(); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert_eq!( + error.to_string(), + "authentication failed: the token endpoint of test-shop.myshopify.com answered 400 (invalid_grant)" + ); + assert_eq!(error.token_endpoint_status(), Some(400)); + assert_eq!(error.oauth_code(), Some(OAuthErrorCode::InvalidGrant)); + assert_eq!(OAuthErrorCode::InvalidGrant.as_str(), Some("invalid_grant")); +} + #[tokio::test] async fn a_token_answer_that_does_not_parse_shows_no_token() { for answer in [ @@ -449,6 +551,90 @@ async fn a_failed_grant_answers_the_requests_that_wait_for_it() { assert_eq!(token_requests(&mock).len(), 1); } +#[tokio::test] +async fn the_requests_that_wait_for_a_refused_grant_get_its_status_and_code() { + let mock = MockTransport::new(); + mock.respond_with(|request: &HttpRequest| { + if request.url == TOKEN_URL { + return Ok(HttpResponse::json( + 401, + &json!({ "error": "invalid_client", "error_description": "Client authentication failed" }), + )); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + let calls: Vec<_> = (0..5) + .map(|_| { + let shopify = shopify.clone(); + tokio::spawn(async move { shopify.graphql("{ shop { name } }", ()).await }) + }) + .collect(); + let mut held = 0; + for call in calls { + let error = call.await.unwrap().unwrap_err(); + assert_eq!(error.token_endpoint_status(), Some(401), "{error:?}"); + assert_eq!(error.oauth_code(), Some(OAuthErrorCode::InvalidClient)); + let refusal = "the token endpoint of test-shop.myshopify.com answered 401 (invalid_client)"; + if error.is_held_auth_failure() { + held += 1; + assert_eq!( + error.to_string(), + format!( + "authentication failed: authentication failed: {refusal} (asked again in a few seconds)" + ) + ); + assert_eq!(error.sensitive_detail(), None); + } else { + assert_eq!( + error.to_string(), + format!("authentication failed: {refusal}") + ); + } + } + // One request asked Shopify; the four others were handed its failure. + assert_eq!(token_requests(&mock).len(), 1); + assert_eq!(held, 4); +} + +#[tokio::test] +async fn a_held_failure_that_is_not_a_refusal_has_no_status() { + let mock = MockTransport::new(); + mock.respond_with(|request: &HttpRequest| { + if request.url == TOKEN_URL { + return Ok(HttpResponse::json( + 200, + &json!({ "scope": "read_products" }), + )); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + let first = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + let second = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(!first.is_held_auth_failure()); + assert!(second.is_held_auth_failure()); + for error in [first, second] { + assert_eq!(error.token_endpoint_status(), None); + assert_eq!(error.oauth_code(), None); + } + assert_eq!(token_requests(&mock).len(), 1); +} + #[tokio::test] async fn a_token_that_never_expires_in_practice_is_read() { let mock = MockTransport::new(); diff --git a/crates/shopify_api/tests/oauth.rs b/crates/shopify_api/tests/oauth.rs index 144054f..3572cc2 100644 --- a/crates/shopify_api/tests/oauth.rs +++ b/crates/shopify_api/tests/oauth.rs @@ -5,6 +5,7 @@ use serde_json::json; use shopify_api::oauth::{RequestedToken, ShopifyApp}; use shopify_api::testing::MockTransport; use shopify_api::transport::HttpResponse; +use shopify_api::{Error, OAuthErrorCode}; fn app(mock: &MockTransport) -> ShopifyApp { ShopifyApp::new("client-id", "client-secret").with_transport(mock.clone()) @@ -249,3 +250,70 @@ async fn the_clients_of_an_app_save_their_renewed_tokens() { assert_eq!(saved[0].0, "my-shop.myshopify.com"); assert_eq!(saved[0].1.refresh_token.as_deref(), Some("shprt_2")); } + +#[tokio::test] +async fn a_refused_code_exchange_has_its_status_and_code() { + let mock = MockTransport::new(); + mock.push(HttpResponse::json( + 400, + &json!({ "error": "invalid_request", "error_description": "The authorization code was not found or was already used" }), + )); + let app = app(&mock); + let query = format!( + "code=abc&shop=my-shop.myshopify.com&state=s1×tamp={}", + now() + ); + let signature = app.sign_query(&query).unwrap(); + let callback = app + .verify_query(&format!("{query}&hmac={signature}")) + .unwrap(); + + let error = app.exchange_code(&callback).await.unwrap_err(); + assert_eq!( + error.to_string(), + "authentication failed: the token endpoint of my-shop.myshopify.com answered 400 (invalid_request)" + ); + assert!(matches!( + error, + Error::Auth { + status: Some(400), + oauth_code: Some(OAuthErrorCode::InvalidRequest), + held: false, + .. + } + )); +} + +#[tokio::test] +async fn a_refused_token_exchange_has_its_status_and_code() { + for (status, body, code) in [ + ( + 400, + r#"{"error": "invalid_subject_token"}"#, + Some(OAuthErrorCode::InvalidSubjectToken), + ), + (502, "Bad Gateway", None), + ] { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(status, body.to_string())); + let app = app(&mock); + let now = now(); + let bearer = app.sign_session_token(&json!({ + "iss": "https://my-shop.myshopify.com/admin", + "dest": "https://my-shop.myshopify.com", + "aud": "client-id", + "sub": "42", + "exp": now + 60, + "nbf": now, + })); + let session = app.verify_session_token(&bearer).unwrap(); + + let error = app + .exchange_session_token(&session, RequestedToken::Offline) + .await + .unwrap_err(); + assert_eq!(error.token_endpoint_status(), Some(status), "{error:?}"); + assert_eq!(error.oauth_code(), code); + assert!(!error.is_held_auth_failure()); + } +} From d511689b1517e300229ba187ec280083f63f8a7a Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:14:25 +0100 Subject: [PATCH 134/135] feat(macros): crate = path names shopify_api in the generated code graphql! (inline, modules, bulk) and input! take `crate = path` first, so a crate that uses them through a framework re-exporting shopify_api needs no shopify_api in its own Cargo.toml. The default stays ::shopify_api. The path must be absolute; `$crate` is refused, since serde's derive reads it as text. The schema and API version are still those of the calling crate. The trybuild crate names shift with the new UI case, which moves the crate-name hash in five expected outputs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + README.md | 12 ++ crates/shopify_api/docs/graphql.md | 39 ++++ crates/shopify_api/docs/input.md | 5 + crates/shopify_api/tests/facade.rs | 135 +++++++++--- .../tests/ui/crate_path_dollar_crate.rs | 12 ++ .../tests/ui/crate_path_dollar_crate.stderr | 10 + ...literal_maybe_non_null_with_default.stderr | 4 +- .../tests/ui/literal_one_of.stderr | 4 +- .../tests/ui/literal_option_in_field.stderr | 2 +- .../tests/ui/literal_wrong_input_type.stderr | 6 +- .../tests/ui/literal_wrong_scalar.stderr | 10 +- crates/shopify_api_macros/README.md | 3 +- crates/shopify_api_macros/src/lib.rs | 200 ++++++++++++++++-- 14 files changed, 377 insertions(+), 66 deletions(-) create mode 100644 crates/shopify_api/tests/ui/crate_path_dollar_crate.rs create mode 100644 crates/shopify_api/tests/ui/crate_path_dollar_crate.stderr diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cb14e7..ca69e14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATIO - Fixed: `verify_app_proxy` and `sign_app_proxy` sort the `name=value` strings, as Shopify does, not the names. A request with a parameter whose name extends another one by a byte that sorts before `=` (`page` and `page2`, `filter` and `filter.v.price.gte`) was refused though Shopify signed it. - Added: `Error::Auth` has `status` and `oauth_code` (`OAuthErrorCode`), the HTTP status and OAuth `error` code of the token endpoint's refusal, and `held`, set when the failure is that of a renewal another request ran; `Error::token_endpoint_status`, `Error::oauth_code` and `Error::is_held_auth_failure` read them. They are filled for client credentials, refresh, code exchange and token exchange, and `None` for an Auth error that is not a refusal (an answer that does not read as a token, no refresh token). The text of the errors does not change. +- Added: `crate = path` as the first argument of `graphql!` (`graphql!(crate = ::my_framework::shopify_api, "…", x = 1)`, `graphql! { crate = …; pub mod a = "…"; }`) and `input!` (`input!(crate = …, TypeName { … })`): the path of `shopify_api` in the generated code, `::shopify_api` by default, for a crate that uses the macros through a framework re-exporting them without depending on `shopify_api` itself. The path is absolute; `$crate` is refused. The schema is still that of the calling crate. ### Added diff --git a/README.md b/README.md index 1f82bb6..1e67d3f 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,18 @@ graphql! { } ``` +### Through a framework + +A crate that reaches `shopify_api` through a crate re-exporting it, and does +not list it in its own `Cargo.toml`, gives the path with `crate =`; the schema +is still that crate's `graphql/admin.schema.json`: + +```rust,ignore +let op = my_framework::graphql!(crate = ::my_framework::shopify_api, "{ shop { name } }"); +my_framework::graphql! { crate = ::my_framework::shopify_api; pub mod shop = "{ shop { name } }"; } +let m = my_framework::input!(crate = ::my_framework::shopify_api, SEOInput { title: title }); +``` + ### Untyped For an operation built at run time, `shopify.graphql(query, variables)` diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md index b2884bf..5b89c9a 100644 --- a/crates/shopify_api/docs/graphql.md +++ b/crates/shopify_api/docs/graphql.md @@ -624,6 +624,45 @@ first mismatch: `` Shopify's answer does not match the operation at `orders.node That happens when a shop runs another version than the schema, or when a test scripts an answer that leaves out a non-null field. +# Through a crate that re-exports `shopify_api` + +The generated code reaches `shopify_api` through `::shopify_api`. A crate +that uses `graphql!` and `input!` through a framework that re-exports them, +without `shopify_api` in its own `Cargo.toml`, names the path with `crate =`, +before anything else: + +```rust,ignore +use my_framework::{graphql, input}; + +// Inline, `,` after the path. +let operation = graphql!(crate = ::my_framework::shopify_api, "query($first: Int!) { products(first: $first) { nodes { id } } }", first = 10); +let bulk = graphql!(crate = ::my_framework::shopify_api, bulk("{ orders { edges { node { id } } } }")); + +// Modules, `;` after the path: it applies to every module of the block. +graphql! { + crate = ::my_framework::shopify_api; + pub mod products = "query($first: Int!) { products(first: $first) { nodes { id } } }"; + pub mod shop = "{ shop { name } }"; +} + +let metafield = input!(crate = ::my_framework::shopify_api, MetafieldsSetInput { + ownerId: product_id, namespace: "custom", key: "color", type: "single_line_text_field", value: color, +}); +``` + +The path is absolute, `::my_framework::shopify_api` or +`crate::path::to::shopify_api`: the generated code sits in modules of its +own, where a relative path or a name brought in by `use` does not resolve. It +cannot start with `$crate`, since serde's derive reads it as text: a +framework's `macro_rules!` wrapper writes `::my_framework::shopify_api`. +`extern crate my_framework as shopify_api;` at the root of the crate works +too, without `crate =`. + +The schema and the API version are those of the crate that writes the +operation, as always: its `graphql/admin.schema.json` and its +`[package.metadata.shopify_api]`, downloaded on the same terms, whether or not +it depends on `shopify_api` itself. + # Limits - Subscriptions are refused, and one inline `graphql!` takes one operation. diff --git a/crates/shopify_api/docs/input.md b/crates/shopify_api/docs/input.md index d744a55..a935a53 100644 --- a/crates/shopify_api/docs/input.md +++ b/crates/shopify_api/docs/input.md @@ -62,3 +62,8 @@ refused: the operation that holds it fails with The fields are checked against the schema of the crate where `input!` is written. A value built in another crate, against another schema or version, has the same Rust type as long as the GraphQL name is the same. + +Through a framework that re-exports `shopify_api`, without it in the crate's +own `Cargo.toml`, the path comes first: +`input!(crate = ::my_framework::shopify_api, MetafieldsSetInput { … })` (see +[`graphql!`](crate::graphql!#through-a-crate-that-re-exports-shopify_api)). diff --git a/crates/shopify_api/tests/facade.rs b/crates/shopify_api/tests/facade.rs index 0bdd213..7ca165c 100644 --- a/crates/shopify_api/tests/facade.rs +++ b/crates/shopify_api/tests/facade.rs @@ -1,17 +1,18 @@ //! The code `graphql!` and `input!` generate reaches `shopify_api` through -//! `::shopify_api::__private` only: an app that depends on a crate -//! re-exporting it, `extern crate facade as shopify_api`, compiles, even -//! when that crate has a `Result`, an `Operation` or a `bulk` of its own. +//! `::shopify_api::__private` only, or `crate = path`: an app that depends +//! on a crate re-exporting it, and not on `shopify_api`, compiles, even when +//! that crate has a `Result`, an `Operation` or a `bulk` of its own. //! //! Builds a small workspace with cargo, offline, in `CARGO_TARGET_TMPDIR`. use std::path::Path; use std::process::Command; -#[test] -fn the_generated_code_compiles_through_a_facade_with_names_of_its_own() { +/// Builds and runs `app`, which depends on `probe_facade` only, whose +/// `lib.rs` is `facade`: what the app printed. +fn run_app(name: &str, facade: &str, app: &str) -> String { let tmp = Path::new(env!("CARGO_TARGET_TMPDIR")); - let root = tmp.join("facade"); + let root = tmp.join(name); let _ = std::fs::remove_dir_all(&root); let shopify_api = Path::new(env!("CARGO_MANIFEST_DIR")); let write = |path: &str, contents: &str| { @@ -33,17 +34,8 @@ fn the_generated_code_compiles_through_a_facade_with_names_of_its_own() { shopify_api.display() ), ); - write( - "facade/src/lib.rs", - "pub use shopify_api::*;\n\ - // Names of its own, which shadow those of the glob.\n\ - pub type Result = std::result::Result;\n\ - pub struct Operation;\n\ - pub struct OperationKind;\n\ - pub struct InputObject;\n\ - pub struct Maybe;\n\ - pub mod bulk {}\n", - ); + write("facade/src/lib.rs", facade); + // No `shopify_api` here: the app reaches it through the facade only. write( "app/Cargo.toml", "[package]\nname = \"probe_facade_app\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ @@ -54,8 +46,36 @@ fn the_generated_code_compiles_through_a_facade_with_names_of_its_own() { "app/graphql/admin.schema.json", &std::fs::read_to_string(shopify_api.join("graphql/admin.schema.json")).unwrap(), ); - write( - "app/src/main.rs", + write("app/src/main.rs", app); + + let output = Command::new(std::env::var_os("CARGO").unwrap_or("cargo".into())) + .args(["run", "--offline", "--quiet", "-p", "probe_facade_app"]) + .arg("--manifest-path") + .arg(root.join("Cargo.toml")) + .env("CARGO_TARGET_DIR", tmp.join(format!("{name}_target"))) + .env_remove("CARGO_PRIMARY_PACKAGE") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout).into_owned() +} + +#[test] +fn the_generated_code_compiles_through_a_facade_with_names_of_its_own() { + let printed = run_app( + "facade", + "pub use shopify_api::*;\n\ + // Names of its own, which shadow those of the glob.\n\ + pub type Result = std::result::Result;\n\ + pub struct Operation;\n\ + pub struct OperationKind;\n\ + pub struct InputObject;\n\ + pub struct Maybe;\n\ + pub mod bulk {}\n", r#"extern crate probe_facade as shopify_api; shopify_api::graphql! { @@ -95,19 +115,70 @@ fn main() { } "#, ); + assert_eq!(printed, "ok"); +} - let output = Command::new(std::env::var_os("CARGO").unwrap_or("cargo".into())) - .args(["run", "--offline", "--quiet", "-p", "probe_facade_app"]) - .arg("--manifest-path") - .arg(root.join("Cargo.toml")) - .env("CARGO_TARGET_DIR", tmp.join("facade_target")) - .env_remove("CARGO_PRIMARY_PACKAGE") - .output() - .unwrap(); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) +#[test] +fn crate_names_the_path_of_shopify_api_in_a_crate_that_does_not_depend_on_it() { + // A framework that re-exports the crate and its macros, with names of + // its own at its root that the generated code must not take. + let printed = run_app( + "facade_crate_path", + "pub use shopify_api;\n\ + pub use shopify_api::{graphql, input};\n\ + pub type Result = std::result::Result;\n\ + pub struct Operation;\n\ + pub mod __private {}\n", + r#"use probe_facade::{graphql, input}; + +graphql! { + crate = ::probe_facade::shopify_api; + mod products = "query($first: Int!) { products(first: $first) { nodes { id title } } }"; + pub(crate) mod set = "mutation($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { userErrors { message } } + }"; + mod catalog = bulk("{ products { edges { node { + id + variants { edges { node { id } } } + } } } }"); + mod tags = bulk("mutation($id: ID!, $tags: [String!]!) { + tagsAdd(id: $id, tags: $tags) { userErrors { message } } + }"); +} + +mod nested { + // A path from the root of the crate works too, from any module. + pub use probe_facade::shopify_api as sa; + probe_facade::graphql! { crate = crate::nested::sa; pub mod shop = "{ shop { name } }"; } +} + +fn main() { + let note: Option = None; + let metafield = input!(crate = ::probe_facade::shopify_api, MetafieldsSetInput { + ownerId: "gid://shopify/Product/1", + namespace: "a", + key: "b", + type: "single_line_text_field", + value: "c", + }); + let set = probe_facade::shopify_api::Operation::from(set::Variables { metafields: vec![metafield] }); + let update = graphql!( + crate = ::probe_facade::shopify_api, + "mutation($p: ProductUpdateInput!) { productUpdate(product: $p) { userErrors { message } } }", + p = { id: "gid://shopify/Product/1", descriptionHtml?: note, status: ACTIVE }, + ); + let _ = products::operation(products::Variables { first: 1 }); + let _ = catalog::operation(); + let _ = graphql!(crate = ::probe_facade::shopify_api, bulk("{ orders { edges { node { id } } } }")); + let _ = tags::Variables { id: String::new(), tags: Vec::new() }; + let _ = nested::shop::operation(); + print!("{}\n{}", set.variable_json("metafields").unwrap().unwrap(), update.variable_json("p").unwrap().unwrap()); +} +"#, + ); + assert_eq!( + printed, + "[{\"ownerId\":\"gid://shopify/Product/1\",\"namespace\":\"a\",\"key\":\"b\",\"type\":\"single_line_text_field\",\"value\":\"c\"}]\n\ + {\"id\":\"gid://shopify/Product/1\",\"status\":\"ACTIVE\"}" ); - assert_eq!(String::from_utf8_lossy(&output.stdout), "ok"); } diff --git a/crates/shopify_api/tests/ui/crate_path_dollar_crate.rs b/crates/shopify_api/tests/ui/crate_path_dollar_crate.rs new file mode 100644 index 0000000..828f1b0 --- /dev/null +++ b/crates/shopify_api/tests/ui/crate_path_dollar_crate.rs @@ -0,0 +1,12 @@ +// `$crate` means nothing in the text serde's derive reads the path from. +pub use shopify_api as runtime; + +macro_rules! shop_id { + () => { + shopify_api::graphql!(crate = $crate::runtime, "{ shop { id } }") + }; +} + +fn main() { + let _ = shop_id!(); +} diff --git a/crates/shopify_api/tests/ui/crate_path_dollar_crate.stderr b/crates/shopify_api/tests/ui/crate_path_dollar_crate.stderr new file mode 100644 index 0000000..9381187 --- /dev/null +++ b/crates/shopify_api/tests/ui/crate_path_dollar_crate.stderr @@ -0,0 +1,10 @@ +error: `crate = $crate::…` cannot reach serde's derive: write the absolute path, `crate = ::my_framework::shopify_api` + --> tests/ui/crate_path_dollar_crate.rs:6:39 + | + 6 | shopify_api::graphql!(crate = $crate::runtime, "{ shop { id } }") + | ^^^^^^ +... +11 | let _ = shop_id!(); + | ---------- in this macro invocation + | + = note: this error originates in the macro `shop_id` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr index 816851c..509134e 100644 --- a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -7,13 +7,13 @@ error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[Inven | | an `Option`: `None` leaves the field out | required by a bound introduced by this call | - = help: the trait `__ShopifyApiNoNull4_c2392dae` is not implemented for `Vec>` + = help: the trait `__ShopifyApiNoNull4_c2392f79` is not implemented for `Vec>` help: this trait has no implementations, consider adding one --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c2392dae` +note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c2392f79` --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 | 6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); diff --git a/crates/shopify_api/tests/ui/literal_one_of.stderr b/crates/shopify_api/tests/ui/literal_one_of.stderr index f0c452c..26bd76e 100644 --- a/crates/shopify_api/tests/ui/literal_one_of.stderr +++ b/crates/shopify_api/tests/ui/literal_one_of.stderr @@ -35,7 +35,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Optio | `Option<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2393afa` is not implemented for `Option<&str>` + = help: the trait `main::__ShopifyApiExpect1_c23935b5` is not implemented for `Option<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:7:13 | @@ -52,7 +52,7 @@ error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Maybe | `Maybe<&str>` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `main::__ShopifyApiExpect1_c2393afa` is not implemented for `Maybe<&str>` + = help: the trait `main::__ShopifyApiExpect1_c23935b5` is not implemented for `Maybe<&str>` note: required by a bound in `main::Checks::build` --> tests/ui/literal_one_of.rs:8:13 | diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr index 773ec1e..9b3c698 100644 --- a/crates/shopify_api/tests/ui/literal_option_in_field.stderr +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -7,7 +7,7 @@ error[E0277]: `vendor` of `ProductUpdateInput` expects a `String`, not `Option` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect1_c23935b5` is not implemented for `Option` + = help: the trait `__ShopifyApiExpect1_c1d682ad` is not implemented for `Option` = note: `vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null` note: required by a bound in `Checks::build` --> tests/ui/literal_option_in_field.rs:3:13 diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr index 8e14d6a..8073484 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -9,8 +9,8 @@ error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built wit 6 | | ); | |_____- required by a bound introduced by this call | - = help: the trait `__ShopifyApiExpect2_c1d69a2e` is not implemented for `InputObject<2493993284262097346>` -help: the following other types implement trait `__ShopifyApiExpect2_c1d69a2e` + = help: the trait `__ShopifyApiExpect2_c1d68407` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2_c1d68407` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( @@ -22,7 +22,7 @@ help: the following other types implement trait `__ShopifyApiExpect2_c1d69a2e` | | | | |_____`&InputObject<960560859991546817>` | `InputObject<960560859991546817>` -note: required for `Vec>` to implement `__ShopifyApiExpect1_c1d69a2e` +note: required for `Vec>` to implement `__ShopifyApiExpect1_c1d68407` --> tests/ui/literal_wrong_input_type.rs:3:13 | 3 | let _ = shopify_api::graphql!( diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr index db69c01..2a69e54 100644 --- a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr @@ -7,7 +7,7 @@ error[E0277]: `quantity` of `DraftOrderLineItemInput` expects an `Int`, not `&st | `&'static str` doesn't satisfy the trait bound | any integer type | - = help: the trait `main::__ShopifyApiExpect1_c1d68407` is not implemented for `&str` + = help: the trait `main::__ShopifyApiExpect1_c1d69cb4` is not implemented for `&str` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 | @@ -24,7 +24,7 @@ error[E0277]: `title` of `DraftOrderLineItemInput` expects a `String`, not `u8` | `u8` doesn't satisfy the trait bound | `String`, `&str`, `&String` or `Cow` | - = help: the trait `__ShopifyApiExpect3_c1d68407` is not implemented for `u8` + = help: the trait `__ShopifyApiExpect3_c1d69cb4` is not implemented for `u8` = note: `title?: value` takes an `Option`, `None` leaving the field out; `title: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -42,7 +42,7 @@ error[E0277]: `requiresShipping` of `DraftOrderLineItemInput` expects a `Boolean | `{integer}` doesn't satisfy the trait bound | `bool` | - = help: the trait `__ShopifyApiExpect5_c1d68407` is not implemented for `{integer}` + = help: the trait `__ShopifyApiExpect5_c1d69cb4` is not implemented for `{integer}` = note: `requiresShipping?: value` takes an `Option`, `None` leaving the field out; `requiresShipping: null` sends `null` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:3:13 @@ -60,8 +60,8 @@ error[E0277]: `value` of `WeightInput` expects a `Float`, not `u64` | `u64` doesn't satisfy the trait bound | `f64`, `f32`, `i32` or `u32` | - = help: the trait `main::__ShopifyApiExpect1_c1d68407` is not implemented for `u64` - = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c1d68407`, but not `main::__ShopifyApiExpect1_c1d68407` + = help: the trait `main::__ShopifyApiExpect1_c1d69cb4` is not implemented for `u64` + = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c1d69cb4`, but not `main::__ShopifyApiExpect1_c1d69cb4` note: required by a bound in `main::Checks::build` --> tests/ui/literal_wrong_scalar.rs:4:13 | diff --git a/crates/shopify_api_macros/README.md b/crates/shopify_api_macros/README.md index e2f876e..2b13b08 100644 --- a/crates/shopify_api_macros/README.md +++ b/crates/shopify_api_macros/README.md @@ -2,5 +2,6 @@ The `graphql!` and `input!` procedural macros of [`shopify_api`](https://crates.io/crates/shopify_api). Use them through `shopify_api::graphql!` and `shopify_api::input!`, which -document them: the generated code refers to `shopify_api` and does not compile +document them: the generated code refers to `::shopify_api`, or to the path +given with `crate = ::my_framework::shopify_api`, and does not compile without it. diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs index 7ff73d7..3f34a81 100644 --- a/crates/shopify_api_macros/src/lib.rs +++ b/crates/shopify_api_macros/src/lib.rs @@ -93,8 +93,81 @@ impl Parse for Source { } } +/// `crate = path` before the rest of a macro's input: where the generated +/// code finds `shopify_api`, `::shopify_api` when it is not given. +struct Krate(TokenStream); + +impl Krate { + /// Reads `crate = path` and its separator, `,` or `;`, when the input starts with it. + fn parse(input: ParseStream) -> syn::Result { + if !input.peek(Token![crate]) || !input.peek2(Token![=]) { + return Ok(Self(quote!(::shopify_api))); + } + input.parse::()?; + input.parse::()?; + let path: syn::Path = input.parse().map_err(|error| { + syn::Error::new( + error.span(), + "expected the path of `shopify_api` after `crate =`: `crate = ::my_framework::shopify_api`", + ) + })?; + let first = &path.segments[0].ident; + if path.leading_colon.is_none() && first != "crate" && first != "$crate" { + // The generated code sits in modules of its own, where a relative + // path, or a name brought in by `use`, does not resolve. + return Err(syn::Error::new( + first.span(), + "the path of `crate =` must be absolute: `crate = ::my_framework::shopify_api` or `crate = crate::shopify_api`", + )); + } + if let Some(segment) = path.segments.first() + && segment.ident == "$crate" + { + // serde's derive takes the path as text, where `$crate` means nothing. + return Err(syn::Error::new( + segment.ident.span(), + "`crate = $crate::…` cannot reach serde's derive: write the absolute path, `crate = ::my_framework::shopify_api`", + )); + } + if let Some(arguments) = path + .segments + .iter() + .find(|segment| !segment.arguments.is_none()) + { + return Err(syn::Error::new( + arguments.arguments.span(), + "the path of `crate =` takes no generic arguments", + )); + } + if input.peek(Token![,]) { + input.parse::()?; + } else if input.peek(Token![;]) { + input.parse::()?; + } else { + return Err(input.error("expected `,` or `;` after `crate = path`")); + } + Ok(Self(quote!(#path))) + } +} + /// `graphql!(SOURCE, name = value, …)`, or modules: -/// `graphql! { pub mod name = SOURCE; mod other = SOURCE }`. +/// `graphql! { pub mod name = SOURCE; mod other = SOURCE }`, after an +/// optional `crate = path`. +struct Invocation { + krate: TokenStream, + input: Input, +} + +impl Parse for Invocation { + fn parse(input: ParseStream) -> syn::Result { + let Krate(krate) = Krate::parse(input)?; + Ok(Self { + krate, + input: input.parse()?, + }) + } +} + enum Input { Expression { source: Source, @@ -177,14 +250,16 @@ impl Parse for Input { } } -/// `input!(TypeName { field: value, … })`. +/// `input!(TypeName { field: value, … })`, after an optional `crate = path`. struct InputObject { + krate: TokenStream, name: Ident, object: Value, } impl Parse for InputObject { fn parse(input: ParseStream) -> syn::Result { + let Krate(krate) = Krate::parse(input)?; const FORM: &str = "expected an input object of the schema: `input!(TypeName { field: value, … })`"; let name: Ident = input @@ -199,7 +274,11 @@ impl Parse for InputObject { if !input.is_empty() { return Err(input.error("expected the end of `input!`")); } - Ok(Self { name, object }) + Ok(Self { + krate, + name, + object, + }) } } @@ -558,21 +637,19 @@ impl Flavor { } } -/// The path of the runtime crate in the generated code, its only one: every -/// item is reached through `#krate::__private`, so that a crate re-exporting -/// `shopify_api` (`extern crate it as shopify_api`, or a future `crate = …`) -/// needs nothing but that module. -fn krate() -> TokenStream { - quote!(::shopify_api) -} - /// `graphql!("…", name = value)`: the operation as a value. +/// +/// `krate` is the path of the runtime crate in the generated code, its only +/// one: every item is reached through `#krate::__private`, so that a crate +/// re-exporting `shopify_api` (`extern crate it as shopify_api`, or +/// `crate = …`) needs nothing but that module. fn expand_expression( schema: &LoadedSchema, source: &Source, variables: &[(Ident, Value)], + krate: &TokenStream, ) -> syn::Result { - let krate = krate(); + let krate = krate.clone(); let text = Text::read(source)?; let (operation, flavor) = Flavor::of(schema, source, &text)?; @@ -669,14 +746,18 @@ fn expand_expression( } /// `graphql! { mod name = "…"; }`: the operation as a module that names its types. -fn expand_module(schema: &LoadedSchema, module: &Module) -> syn::Result { +fn expand_module( + schema: &LoadedSchema, + module: &Module, + krate: &TokenStream, +) -> syn::Result { let Module { attributes, visibility, name, source, } = module; - let krate = krate(); + let krate = krate.clone(); let text = Text::read(source)?; let (operation, flavor) = Flavor::of(schema, source, &text)?; let target = flavor.target(&krate); @@ -738,14 +819,20 @@ fn expand_module(schema: &LoadedSchema, module: &Module) -> syn::Result) -> syn::Result { +fn expand( + invocation: Invocation, + schema: Result, +) -> syn::Result { let schema = schema.map_err(|message| syn::Error::new(Span::call_site(), message))?; + let Invocation { krate, input } = invocation; match input { - Input::Expression { source, variables } => expand_expression(&schema, &source, &variables), + Input::Expression { source, variables } => { + expand_expression(&schema, &source, &variables, &krate) + } Input::Modules(modules) => { let mut expanded = TokenStream::new(); for module in &modules { - expanded.extend(expand_module(&schema, module)?); + expanded.extend(expand_module(&schema, module, &krate)?); } Ok(expanded) } @@ -761,7 +848,7 @@ fn expand_input( let Value::Object(object) = &input.object else { unreachable!("`input!` reads an object"); }; - let mut literals = Literals::new(schema.schema(), krate()); + let mut literals = Literals::new(schema.schema(), input.krate.clone()); let value = literals .input_object(&input.name.to_string(), input.name.span(), object) .map_err(|error| schema.literal_error(error))?; @@ -777,7 +864,7 @@ fn expand_input( /// See `shopify_api::graphql!`. #[proc_macro] pub fn graphql(input: proc_macro::TokenStream) -> proc_macro::TokenStream { - let input = syn::parse_macro_input!(input as Input); + let input = syn::parse_macro_input!(input as Invocation); expand(input, LoadedSchema::load()) .unwrap_or_else(syn::Error::into_compile_error) .into() @@ -797,7 +884,7 @@ pub fn input(input: proc_macro::TokenStream) -> proc_macro::TokenStream { #[doc(hidden)] #[proc_macro] pub fn __graphql_internal(input: proc_macro::TokenStream) -> proc_macro::TokenStream { - let input = syn::parse_macro_input!(input as Input); + let input = syn::parse_macro_input!(input as Invocation); expand(input, LoadedSchema::internal()) .unwrap_or_else(syn::Error::into_compile_error) .into() @@ -881,6 +968,54 @@ mod tests { assert!(error.starts_with("cannot read it: "), "{error}"); } + #[test] + fn parses_the_path_of_the_runtime_crate() { + let krate = |text: &str| { + syn::parse_str::(text) + .unwrap() + .krate + .to_string() + .replace(' ', "") + }; + assert_eq!(krate(r#""{ shop { id } }", first = 1"#), "::shopify_api"); + assert_eq!( + krate(r#"crate = ::openshop::shopify_api, "{ shop { id } }", first = 1"#), + "::openshop::shopify_api" + ); + assert_eq!( + krate(r#"crate = crate::shopify_api; pub mod a = "{ shop { id } }";"#), + "crate::shopify_api" + ); + let Invocation { input, .. } = syn::parse_str( + r#"crate = ::openshop::shopify_api; #[doc = "A."] pub mod a = "{ shop { id } }"; mod b = "{ shop { name } }""#, + ) + .unwrap(); + let Input::Modules(modules) = input else { + panic!("modules"); + }; + assert_eq!(modules.len(), 2); + let Invocation { input, .. } = + syn::parse_str(r#"crate = ::openshop::shopify_api, bulk("{ shop { id } }")"#).unwrap(); + assert!(matches!( + input, + Input::Expression { + source: Source::Bulk(_), + .. + } + )); + + let object: InputObject = + syn::parse_str("crate = ::openshop::shopify_api, MetafieldsSetInput { key: k }") + .unwrap(); + assert_eq!( + object.krate.to_string().replace(' ', ""), + "::openshop::shopify_api" + ); + assert_eq!(object.name, "MetafieldsSetInput"); + let object: InputObject = syn::parse_str("MetafieldsSetInput { key: k }").unwrap(); + assert_eq!(object.krate.to_string().replace(' ', ""), "::shopify_api"); + } + #[test] fn parses_both_forms_and_both_sources() { let expression: Input = @@ -961,6 +1096,31 @@ mod tests { matches!(&modules[1].source, Source::Bulk(inner) if matches!(**inner, Source::Literal(_))) ); + for (source, message) in [ + ( + "crate = shopify_api, \"{ shop { id } }\"", + "the path of `crate =` must be absolute: `crate = ::my_framework::shopify_api` or `crate = crate::shopify_api`", + ), + ( + "crate = ::a::b, \"{ shop { id } }\"", + "the path of `crate =` takes no generic arguments", + ), + ( + "crate = ::a::b \"{ shop { id } }\"", + "expected `,` or `;` after `crate = path`", + ), + ( + "crate = , \"{ shop { id } }\"", + "expected the path of `shopify_api` after `crate =`: `crate = ::my_framework::shopify_api`", + ), + ] { + let error = syn::parse_str::(source) + .err() + .expect(source) + .to_string(); + assert_eq!(error, message, "{source}"); + } + for (source, message) in [ ("first = 1", SOURCE_FORM), (r#"path("x.graphql")"#, SOURCE_FORM), From 0d98b3cb1f078e571867314a7f996415a0d4eff6 Mon Sep 17 00:00:00 2001 From: Thomas <31560900+0xtlt@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:33:35 +0100 Subject: [PATCH 135/135] release: 1.0.0-rc.2 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++++ Cargo.lock | 6 +++--- Cargo.toml | 8 ++++---- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca69e14..67c1273 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 1.0.0-rc.2 (2026-10-27) + +The second release candidate: rc.1 and the changes under "Since 1.0.0-rc.1" +below. Cargo only takes it when asked for: `shopify_api = "=1.0.0-rc.2"`. + ## 1.0.0-rc.1 (2026-10-26) The release candidate of 1.0.0: everything under 1.0.0 below. Cargo only diff --git a/Cargo.lock b/Cargo.lock index 18d09e2..394b747 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1431,7 +1431,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "shopify_api" -version = "1.0.0-rc.1" +version = "1.0.0-rc.2" dependencies = [ "base64", "chrono", @@ -1454,7 +1454,7 @@ dependencies = [ [[package]] name = "shopify_api_graphql" -version = "1.0.0-rc.1" +version = "1.0.0-rc.2" dependencies = [ "graphql-parser", "proc-macro2", @@ -1467,7 +1467,7 @@ dependencies = [ [[package]] name = "shopify_api_macros" -version = "1.0.0-rc.1" +version = "1.0.0-rc.2" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 2b57f01..0a6d32d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ members = [ ] [workspace.package] -version = "1.0.0-rc.1" +version = "1.0.0-rc.2" edition = "2024" rust-version = "1.88" license = "MIT" @@ -17,9 +17,9 @@ authors = ["Thomas Tastet"] [workspace.dependencies] # The three crates are released together: each one requires the exact # version of the others, since the macro emits code for that runtime. -shopify_api = { path = "crates/shopify_api", version = "=1.0.0-rc.1" } -shopify_api_graphql = { path = "crates/shopify_api_graphql", version = "=1.0.0-rc.1" } -shopify_api_macros = { path = "crates/shopify_api_macros", version = "=1.0.0-rc.1" } +shopify_api = { path = "crates/shopify_api", version = "=1.0.0-rc.2" } +shopify_api_graphql = { path = "crates/shopify_api_graphql", version = "=1.0.0-rc.2" } +shopify_api_macros = { path = "crates/shopify_api_macros", version = "=1.0.0-rc.2" } base64 = "0.23" chrono = { version = "0.4.39", default-features = false, features = ["clock", "serde", "std"] }